Atlas › Test

claudeElicitation.test|title=claudeElicitation elicitationResultFromAnswers coerces text answers to the field schema type|occurrence=1

Exact test identity: mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node/claudeElicitation.test|title=claudeElicitation elicitationResultFromAnswers coerces text answers to the field schema type|occurrence=1

Package
mocha:v1|namespace=vscode@05c208e9e28d8c1c723fa08f85e2b7a96092e8e5|file=vs/platform/agentHost/test/node
Suite / test hierarchy
claudeElicitation.test|title=claudeElicitation elicitationResultFromAnswers coerces text answers to the field schema type|occurrence=1
Test
claudeElicitation.test|title=claudeElicitation elicitationResultFromAnswers coerces text answers to the field schema type|occurrence=1
Introduced at
claudeElicitation.ts ×3 Frontier kind: Joint frontier
Covered ranges
737
Covered lines
10683
Covered files
39

Covered source

Expand a file to inspect source; the > gutter marks covered lines.

src/vs/platform/agentHost/common/state/protocol/channels-chat/state.ts 1557 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { ModelSelection } from '../channels-root/state.js';
10 > import type { AgentSelection, McpAuthRequirement, SessionStatus } from '../channels-session/state.js';
11 > import type { ContentRef, ErrorInfo, FileEdit, StringOrMarkdown, TextRange, TextSelection, URI, UsageInfo } from '../common/state.js';
12 >
13 > // ─── Chat State ──────────────────────────────────────────────────────────────
14 >
15 > /**
16 > * Full state for a single chat, loaded when a client subscribes to the chat's
17 > * URI.
18 > *
19 > * The lightweight catalog representation of a chat is {@link ChatSummary},
20 > * carried in {@link SessionState.chats | `SessionState.chats`}. `ChatState`
21 > * **denormalizes** every {@link ChatSummary} field directly onto itself so
22 > * subscribers receive one flat object instead of having to merge a nested
23 > * `summary` sub-object. Producers MUST keep the two representations
24 > * consistent: any change to the inlined fields below SHOULD also be
25 > * announced on the parent session via the matching
26 > * {@link SessionChatUpdatedAction | `session/chatUpdated`} action.
27 > *
28 > * @category Chat State
29 > */
30 > export interface ChatState {
31 > // ── Summary fields (denormalized from ChatSummary) ─────────────────
32 > /** Chat URI */
33 > resource: URI;
34 > /** Chat title */
35 > title: string;
36 > /** Current chat status (reuses SessionStatus shape) */
37 > status: SessionStatus;
38 > /** Human-readable description of what the chat is currently doing */
39 > activity?: string;
40 > /** Last modification timestamp (ISO 8601, e.g. `"2025-03-10T18:42:03.123Z"`) */
41 > modifiedAt: string;
42 > /** How this chat came into existence */
43 > origin?: ChatOrigin;
44 > /**
45 > * How the user can interact with this chat. See {@link ChatInteractivity}.
46 > *
47 > * Supports agent-team patterns where worker chats are read-only or hidden.
48 > * Absence defaults to {@link ChatInteractivity.Full} for backward
49 > * compatibility.
50 > */
51 > interactivity?: ChatInteractivity;
52 > /**
53 > * The subset of the session's
54 > * {@link SessionState.workingDirectories | `workingDirectories`} that this
55 > * chat's agent has tool access to. Every entry MUST be present in the owning
56 > * session's `workingDirectories`; servers MUST reject a
57 > * `chat/workingDirectorySet` action that violates this constraint.
58 > *
59 > * When absent, the chat inherits the full session set. When present but empty
60 > * (not recommended), the chat has no working-directory tool access at all.
61 > *
62 > * Dispatch `chat/workingDirectorySet` / `chat/workingDirectoryRemoved` to
63 > * update the subset on a running chat.
64 > */
65 > workingDirectories?: URI[];
66 > /**
67 > * The chat's primary working directory — the distinguished root this chat is
68 > * centered on (e.g. the agent's process root for this chat, the default
69 > * location for relative paths). MUST be one of this chat's effective working
70 > * directories ({@link workingDirectories}, or the session's set when that is
71 > * absent). Present when the agent advertises
72 > * {@link MultipleWorkingDirectoriesCapability.requiresPrimary}.
73 > *
74 > * **Read-only and fixed at creation.** It is set from
75 > * {@link CreateChatParams.primaryWorkingDirectory} (or, for the session's
76 > * default chat, {@link CreateSessionParams.primaryWorkingDirectory}) and does
77 > * not change over the chat's lifetime — there is no action to mutate it, and
78 > * it does not participate in `session/chatUpdated`.
79 > */
80 > primaryWorkingDirectory?: URI;
81 >
82 > // ── Conversation contents ──────────────────────────────────────────
83 > /** Completed turns */
84 > turns: Turn[];
85 > /**
86 > * Cursor for loading older completed turns into this chat state.
87 > *
88 > * Presence means `turns` is a tail window and more historical turns are
89 > * available. Pass this opaque cursor to `fetchTurns`; the host MUST insert
90 > * the loaded turns into state and update or clear this cursor before
91 > * responding. Absence means the state contains all retained turns.
92 > */
93 > turnsNextCursor?: string;
94 > /** Currently in-progress turn */
95 > activeTurn?: ActiveTurn;
96 > /** Message to inject into the current turn at a convenient point */
97 > steeringMessage?: PendingMessage;
98 > /** Messages to send automatically as new turns after the current turn finishes */
99 > queuedMessages?: PendingMessage[];
100 > /**
101 > * The user's in-progress draft input for this chat — the message they are
102 > * composing but have not sent yet, including its
103 > * {@link Message.model | model} / {@link Message.agent | agent} selection
104 > * and attachments.
105 > *
106 > * Clients MAY periodically sync their local input state into this field so
107 > * a draft survives reloads and is visible to other clients viewing the same
108 > * chat. Eager syncing is **not** required — clients SHOULD debounce and MAY
109 > * sync only at convenient points. When presenting input UI for an existing
110 > * chat, clients SHOULD use any `draft` to initialize their input state.
111 > * Cleared (set to `undefined`) once the message is sent.
112 > */
113 > draft?: Message;
114 > /**
115 > * Additional provider-specific metadata for this chat.
116 > */
117 > _meta?: Record<string, unknown>;
118 > }
119 >
120 > /**
121 > * Lightweight catalog entry for a chat, carried in
122 > * {@link SessionState.chats | `SessionState.chats`}. The full conversation
123 > * lives in {@link ChatState}, which inlines (denormalizes) every field below.
124 > *
125 > * @category Chat State
126 > */
127 > export interface ChatSummary {
128 > /** Chat URI */
129 > resource: URI;
130 > /** Chat title */
131 > title: string;
132 > /** Current chat status (reuses SessionStatus shape) */
133 > status: SessionStatus;
134 > /** Human-readable description of what the chat is currently doing */
135 > activity?: string;
136 > /** Last modification timestamp (ISO 8601, e.g. `"2025-03-10T18:42:03.123Z"`) */
137 > modifiedAt: string;
138 > /** How this chat came into existence */
139 > origin?: ChatOrigin;
140 > /**
141 > * How the user can interact with this chat. See {@link ChatInteractivity}.
142 > *
143 > * Supports agent-team patterns where worker chats are read-only or hidden.
144 > * Absence defaults to {@link ChatInteractivity.Full} for backward
145 > * compatibility.
146 > */
147 > interactivity?: ChatInteractivity;
148 > /**
149 > * The subset of the session's working directories this chat uses.
150 > * See {@link ChatState.workingDirectories} for the full semantics.
151 > */
152 > workingDirectories?: URI[];
153 > /**
154 > * The chat's primary working directory.
155 > * See {@link ChatState.primaryWorkingDirectory} for the full semantics.
156 > */
157 > primaryWorkingDirectory?: URI;
158 > }
159 >
160 > /**
161 > * Discriminant for {@link ChatOrigin} — how a chat came into existence.
162 > *
163 > * @category Chat State
164 > */
165 > export const enum ChatOriginKind {
166 > /** User created the chat explicitly (e.g. via the host UI). */
167 > User = 'user',
168 > /** Forked from an existing chat at a specific turn. */
169 > Fork = 'fork',
170 > /** Created as an independent side conversation from a specific turn. */
171 > SideChat = 'sideChat',
172 > /** Spawned by a tool call running in another chat (e.g. a sub-agent delegation). */
173 > Tool = 'tool',
174 > }
175 >
176 > /**
177 > * Immutable selected-text snapshot captured when a side chat is created.
178 > *
179 > * The host records this exact text when it accepts `createChat`; later changes
180 > * to the source chat do not alter it.
181 > *
182 > * @category Chat State
183 > */
184 > export interface SideChatSelection {
185 > /**
186 > * Exact selected-text snapshot captured at `createChat` acceptance.
187 > *
188 > * MUST be non-empty.
189 > */
190 > text: string;
191 > /**
192 > * Optional provenance for the response part that contained {@link text} when
193 > * the host took the snapshot.
194 > *
195 > * Advisory only: this is not a live range or offset and MUST NOT be used to
196 > * recompute `text`.
197 > */
198 > responsePartId?: string;
199 > }
200 >
201 > /**
202 > * How a chat came into existence. Clients MAY use it to render
203 > * contextual UI (parent indicators, fork markers, "spawned by tool" badges).
204 > *
205 > * Fork and side-chat origins both carry a stable top-level `turnId` alongside
206 > * their discriminated `kind` value instead of snapshotting whether that turn
207 > * was active or historical at creation time. Consumers resolve the identifier
208 > * against the
209 > * source chat's current `activeTurn` or retained `turns` as needed.
210 > *
211 > * When a host accepts side-chat creation from the source chat's current active
212 > * turn, it snapshots the retained history plus that turn's current user
213 > * message and any partial assistant response already available. Later
214 > * source-turn deltas do not retroactively change the created side chat's
215 > * starting context, and once the source turn completes it is still referenced
216 > * by the same `turnId`. Side-chat origins MAY also retain an immutable
217 > * {@link SideChatSelection | selected-text snapshot} captured at acceptance
218 > * time; any `responsePartId` there is provenance only, not a range.
219 > *
220 > * The `tool` variant records a tool-spawned worker from the worker's side: its
221 > * `chat`/`toolCallId` identify the spawning tool call in the parent chat. This
222 > * is the canonical record of the spawn relationship. The same edge is surfaced
223 > * from the parent's side by {@link ToolResultSubagentContent}, whose `resource`
224 > * is this chat's URI; hosts MUST keep the two consistent.
225 > *
226 > * @category Chat State
227 > */
228 > export type ChatOrigin =
229 > | { kind: ChatOriginKind.User }
230 > | { kind: ChatOriginKind.Fork; chat: URI; turnId: string }
231 > | { kind: ChatOriginKind.SideChat; chat: URI; turnId: string; selection?: SideChatSelection }
232 > | { kind: ChatOriginKind.Tool; chat: URI; toolCallId: string };
233 >
234 > /**
235 > * How a user can interact with a chat.
236 > *
237 > * - `Full` — user can send messages and watch (default when absent)
238 > * - `ReadOnly` — user can watch but not send messages (e.g. agent team workers)
239 > * - `Hidden` — internal worker not shown in UI at all
240 > *
241 > * Supports the agent-team pattern where a lead chat is fully interactive and
242 > * worker chats are read-only (visible for observability) or hidden (internal
243 > * implementation detail). The harness sets this based on the chat's role;
244 > * the UI uses it to show appropriate controls.
245 > *
246 > * @category Chat State
247 > */
248 > export const enum ChatInteractivity {
249 > /** User can send messages and watch (default when absent) */
250 > Full = 'full',
251 > /** User can watch but not send messages */
252 > ReadOnly = 'read-only',
253 > /** Internal worker not shown in UI at all */
254 > Hidden = 'hidden',
255 > }
256 >
257 > // ─── Pending Message Types ───────────────────────────────────────────────────
258 >
259 > /**
260 > * Discriminant for pending message kinds.
261 > *
262 > * @category Pending Message Types
263 > */
264 > export const enum PendingMessageKind {
265 > /** Injected into the current turn at a convenient point */
266 > Steering = 'steering',
267 > /** Sent automatically as a new turn after the current turn finishes */
268 > Queued = 'queued',
269 > }
270 >
271 > /**
272 > * A message queued for future delivery to the agent.
273 > *
274 > * Steering messages are injected into the current turn mid-flight.
275 > * Queued messages are automatically started as new turns after the
276 > * current turn naturally finishes.
277 > *
278 > * @category Pending Message Types
279 > */
280 > export interface PendingMessage {
281 > /** Unique identifier for this pending message */
282 > id: string;
283 > /** The message that will start the next turn */
284 > message: Message;
285 > }
286 >
287 >
288 > // ─── Chat Input Types ────────────────────────────────────────────────────
289 >
290 > /**
291 > * How a client completed an input request.
292 > *
293 > * @category Chat Input Types
294 > */
295 > export const enum ChatInputResponseKind {
296 > Accept = 'accept',
297 > Decline = 'decline',
298 > Cancel = 'cancel',
299 > }
300 >
301 > /**
302 > * Question/input control kind.
303 > *
304 > * @category Chat Input Types
305 > */
306 > export const enum ChatInputQuestionKind {
307 > Text = 'text',
308 > Number = 'number',
309 > Integer = 'integer',
310 > Boolean = 'boolean',
311 > SingleSelect = 'single-select',
312 > MultiSelect = 'multi-select',
313 > }
314 >
315 > /**
316 > * A choice in a select-style question.
317 > *
318 > * @category Chat Input Types
319 > */
320 > export interface ChatInputOption {
321 > /** Stable option identifier; for MCP enum values this is the enum string */
322 > id: string;
323 > /** Display label */
324 > label: string;
325 > /** Optional secondary text */
326 > description?: string;
327 > /** Whether this option is the recommended/default choice */
328 > recommended?: boolean;
329 > }
330 >
331 > interface ChatInputQuestionBase {
332 > /** Stable question identifier used as the key in `answers` */
333 > id: string;
334 > /** Short display title */
335 > title?: string;
336 > /** Prompt shown to the user */
337 > message: string;
338 > /** Whether the user must answer this question to accept the request */
339 > required?: boolean;
340 > }
341 >
342 > /** Text question within a chat input request. */
343 > export interface ChatInputTextQuestion extends ChatInputQuestionBase {
344 > kind: ChatInputQuestionKind.Text;
345 > /** Format hint for text questions, such as `email`, `uri`, `date`, or `date-time` */
346 > format?: string;
347 > /** Minimum string length */
348 > min?: number;
349 > /** Maximum string length */
350 > max?: number;
351 > /** Default text */
352 > defaultValue?: string;
353 > }
354 >
355 > /** Numeric question within a chat input request. */
356 > export interface ChatInputNumberQuestion extends ChatInputQuestionBase {
357 > kind: ChatInputQuestionKind.Number | ChatInputQuestionKind.Integer;
358 > /**
359 > * Minimum value
360 > * @format float
361 > */
362 > min?: number;
363 > /**
364 > * Maximum value
365 > * @format float
366 > */
367 > max?: number;
368 > /**
369 > * Default numeric value
370 > * @format float
371 > */
372 > defaultValue?: number;
373 > }
374 >
375 > /** Boolean question within a chat input request. */
376 > export interface ChatInputBooleanQuestion extends ChatInputQuestionBase {
377 > kind: ChatInputQuestionKind.Boolean;
378 > /** Default boolean value */
379 > defaultValue?: boolean;
380 > }
381 >
382 > /** Single-select question within a chat input request. */
383 > export interface ChatInputSingleSelectQuestion extends ChatInputQuestionBase {
384 > kind: ChatInputQuestionKind.SingleSelect;
385 > /** Options the user may select from */
386 > options: ChatInputOption[];
387 > /** Whether the user may enter text instead of selecting an option */
388 > allowFreeformInput?: boolean;
389 > }
390 >
391 > /** Multi-select question within a chat input request. */
392 > export interface ChatInputMultiSelectQuestion extends ChatInputQuestionBase {
393 > kind: ChatInputQuestionKind.MultiSelect;
394 > /** Options the user may select from */
395 > options: ChatInputOption[];
396 > /** Whether the user may enter text in addition to selecting options */
397 > allowFreeformInput?: boolean;
398 > /** Minimum selected item count */
399 > min?: number;
400 > /** Maximum selected item count */
401 > max?: number;
402 > }
403 >
404 > /**
405 > * One question within a chat input request.
406 > *
407 > * @category Chat Input Types
408 > */
409 > export type ChatInputQuestion = ChatInputTextQuestion
410 > | ChatInputNumberQuestion
411 > | ChatInputBooleanQuestion
412 > | ChatInputSingleSelectQuestion
413 > | ChatInputMultiSelectQuestion;
414 >
415 > /**
416 > * The request payload carried by an {@link InputRequestResponsePart}.
417 > *
418 > * The server creates or replaces the containing response part with
419 > * `chat/inputRequested`. Clients sync drafts with `chat/inputAnswerChanged`
420 > * and submit responses with `chat/inputCompleted`.
421 > *
422 > * @category Chat Input Types
423 > */
424 > export interface ChatInputRequest {
425 > /** Stable request identifier */
426 > id: string;
427 > /** Display message for the request as a whole */
428 > message?: string;
429 > /** URL the user should review or open, for URL-style elicitations */
430 > url?: URI;
431 > /** Ordered questions to ask the user */
432 > questions?: ChatInputQuestion[];
433 > /** Current draft or submitted answers, keyed by question ID */
434 > answers?: Record<string, ChatInputAnswer>;
435 > }
436 >
437 > /**
438 > * Answer value kind.
439 > *
440 > * @category Chat Input Types
441 > */
442 > export const enum ChatInputAnswerValueKind {
443 > Text = 'text',
444 > Number = 'number',
445 > Boolean = 'boolean',
446 > Selected = 'selected',
447 > SelectedMany = 'selected-many',
448 > }
449 >
450 > /**
451 > * Value captured for one answer.
452 > *
453 > * @category Chat Input Types
454 > */
455 > export interface ChatInputTextAnswerValue {
456 > kind: ChatInputAnswerValueKind.Text;
457 > value: string;
458 > }
459 >
460 > export interface ChatInputNumberAnswerValue {
461 > kind: ChatInputAnswerValueKind.Number;
462 > /** @format float */
463 > value: number;
464 > }
465 >
466 > export interface ChatInputBooleanAnswerValue {
467 > kind: ChatInputAnswerValueKind.Boolean;
468 > value: boolean;
469 > }
470 >
471 > export interface ChatInputSelectedAnswerValue {
472 > kind: ChatInputAnswerValueKind.Selected;
473 > value: string;
474 > /** Free-form text entered instead of selecting an option */
475 > freeformValues?: string[];
476 > }
477 >
478 > export interface ChatInputSelectedManyAnswerValue {
479 > kind: ChatInputAnswerValueKind.SelectedMany;
480 > value: string[];
481 > /** Free-form text entered in addition to selected options */
482 > freeformValues?: string[];
483 > }
484 >
485 > export type ChatInputAnswerValue = ChatInputTextAnswerValue
486 > | ChatInputNumberAnswerValue
487 > | ChatInputBooleanAnswerValue
488 > | ChatInputSelectedAnswerValue
489 > | ChatInputSelectedManyAnswerValue;
490 >
491 > export interface ChatInputAnswered {
492 > /** Answer state */
493 > state: ChatInputAnswerState.Draft | ChatInputAnswerState.Submitted;
494 > /** Answer value */
495 > value: ChatInputAnswerValue;
496 > }
497 >
498 > export interface ChatInputSkipped {
499 > /** Answer state */
500 > state: ChatInputAnswerState.Skipped;
501 > /** Free-form reason or value captured while skipping, if any */
502 > freeformValues?: string[];
503 > }
504 >
505 > /**
506 > * Answer lifecycle state.
507 > *
508 > * @category Chat Input Types
509 > */
510 > export const enum ChatInputAnswerState {
511 > Draft = 'draft',
512 > Submitted = 'submitted',
513 > Skipped = 'skipped',
514 > }
515 >
516 > /**
517 > * Draft, submitted, or skipped answer for one question.
518 > *
519 > * @category Chat Input Types
520 > */
521 > export type ChatInputAnswer = ChatInputAnswered | ChatInputSkipped;
522 >
523 >
524 > // ─── Turn Types ──────────────────────────────────────────────────────────────
525 >
526 > /**
527 > * How a turn ended.
528 > *
529 > * @category Turn Types
530 > */
531 > export const enum TurnState {
532 > Complete = 'complete',
533 > Cancelled = 'cancelled',
534 > Error = 'error',
535 > }
536 >
537 > /**
538 > * Discriminant for {@link MessageAttachment} variants.
539 > *
540 > * @category Turn Types
541 > */
542 > export const enum MessageAttachmentKind {
543 > /** A simple, opaque attachment whose representation is described by the producer. */
544 > Simple = 'simple',
545 > /** An attachment whose data is embedded inline as a base64 string. */
546 > EmbeddedResource = 'embeddedResource',
547 > /** An attachment that references a resource by URI. */
548 > Resource = 'resource',
549 > /** An attachment that references annotations on an annotations channel. */
550 > Annotations = 'annotations',
551 > /** An attachment that references a bounded transcript from another chat. */
552 > Chat = 'chat',
553 > }
554 >
555 > /**
556 > * A completed request/response cycle.
557 > *
558 > * @category Turn Types
559 > */
560 > export interface Turn {
561 > /** Turn identifier */
562 > id: string;
563 > /** ISO 8601 timestamp when this turn started. */
564 > startedAt?: string;
565 > /** Turn duration in milliseconds. */
566 > duration?: number;
567 > /** The message that initiated the turn */
568 > message: Message;
569 > /**
570 > * All response content in stream order: text, tool calls, reasoning, and content refs.
571 > *
572 > * Consumers should derive display text by concatenating markdown parts,
573 > * and find tool calls by filtering for `ToolCall` parts.
574 > */
575 > responseParts: ResponsePart[];
576 > /** Token usage info */
577 > usage: UsageInfo | undefined;
578 > /** How the turn ended */
579 > state: TurnState;
580 > /** Error details if state is `'error'` */
581 > error?: ErrorInfo;
582 > }
583 >
584 > /**
585 > * An in-progress turn — the assistant is actively streaming.
586 > *
587 > * @category Turn Types
588 > */
589 > export interface ActiveTurn {
590 > /** Turn identifier */
591 > id: string;
592 > /** ISO 8601 timestamp when this turn started. */
593 > startedAt: string;
594 > /** The message that initiated the turn */
595 > message: Message;
596 > /**
597 > * All response content in stream order: text, tool calls, reasoning, and content refs.
598 > *
599 > * Tool call parts include `pendingPermissions` when permissions are awaiting user approval.
600 > */
601 > responseParts: ResponsePart[];
602 > /** Token usage info */
603 > usage: UsageInfo | undefined;
604 > }
605 >
606 > /**
607 > * Discriminant for {@link MessageOrigin} — identifies who produced a message.
608 > *
609 > * @category Turn Types
610 > */
611 > export enum MessageKind {
612 > /** Sent directly by the user. */
613 > User = 'user',
614 > /**
615 > * Produced by the agent itself rather than the user — for example, an agent
616 > * that seeds the first message of a chat it spawned.
617 > */
618 > Agent = 'agent',
619 > /**
620 > * Produced by a tool rather than the user — for example, a tool that spawns a
621 > * worker chat whose first message carries a seed prompt.
622 > */
623 > Tool = 'tool',
624 > /** A system-generated notification rather than a direct user message. */
625 > SystemNotification = 'systemNotification',
626 > }
627 >
628 > /**
629 > * Identifies the origin of a {@link Message} — who produced it. For the message
630 > * that initiates a turn ({@link Turn.message}), this is also the origin of the
631 > * turn; for steering or queued messages it is just the origin of that message.
632 > *
633 > * @category Turn Types
634 > */
635 > export interface MessageOrigin {
636 > /** The kind of actor that produced the message. */
637 > kind: MessageKind;
638 > }
639 >
640 > /**
641 > * A message that initiates or steers a turn. Messages can originate from the
642 > * user, the agent, a tool, or be system-generated (see {@link MessageOrigin}).
643 > *
644 > * Attachments MAY be referenced inside {@link Message.text} via their
645 > * {@link MessageAttachmentBase.range} field. Attachments without a range are
646 > * still associated with the message but do not correspond to a specific span
647 > * in the text.
648 > *
649 > * @category Turn Types
650 > */
651 > export interface Message {
652 > /** Message text */
653 > text: string;
654 > /** The origin of the message */
655 > origin: MessageOrigin;
656 > /** File/selection attachments */
657 > attachments?: MessageAttachment[];
658 > /**
659 > * The model this message was, or will be, sent with.
660 > *
661 > * For historic user/agent messages this records the model actually used, so
662 > * a client editing or resending the message can retain that selection. For a
663 > * {@link ChatState.draft | draft} it carries the model the user picked for
664 > * the message they are composing. Absent means the agent host's default
665 > * model applies.
666 > */
667 > model?: ModelSelection;
668 > /**
669 > * The custom agent this message was, or will be, sent with.
670 > *
671 > * For historic messages this records the agent actually used; for a
672 > * {@link ChatState.draft | draft} it carries the agent the user picked.
673 > * Absent means no custom agent — the provider's default behavior applies.
674 > */
675 > agent?: AgentSelection;
676 > /**
677 > * Additional provider-specific metadata for this message.
678 > *
679 > * Clients MAY look for well-known keys here to provide enhanced UI, and
680 > * agent hosts MAY use it to carry context that does not fit any other
681 > * field. Mirrors the MCP `_meta` convention.
682 > */
683 > _meta?: Record<string, unknown>;
684 > }
685 >
686 > /**
687 > * Common fields shared by all {@link MessageAttachment} variants.
688 > *
689 > * @category Turn Types
690 > */
691 > export interface MessageAttachmentBase {
692 > /**
693 > * A human-readable label for the attachment (e.g. the filename of a file
694 > * attachment). Used for display in UI.
695 > */
696 > label: string;
697 >
698 > /**
699 > * If defined, the range in {@link Message.text} that references this
700 > * attachment. This is a text range, not a byte range.
701 > */
702 > range?: TextRange;
703 >
704 > /**
705 > * Advisory display hint for clients rendering this attachment. Recognized
706 > * values include:
707 > *
708 > * - `'image'`: the attachment is an image
709 > * - `'document'`: the attachment is a textual document
710 > * - `'symbol'`: the attachment is a code symbol (e.g. a function or class)
711 > * - `'directory'`: the attachment is a folder
712 > * - `'selection'`: the attachment is a selection within a document
713 > *
714 > * Implementations MAY provide additional values; clients SHOULD fall back
715 > * to a reasonable default when an unknown value is encountered.
716 > */
717 > displayKind?: string;
718 >
719 > /**
720 > * Additional implementation-defined metadata for the attachment.
721 > *
722 > * If the attachment was produced by the `completions` command, the client
723 > * MUST preserve every property of `_meta` originally returned by the agent
724 > * host when sending the user message containing the accepted completion.
725 > */
726 > _meta?: Record<string, unknown>;
727 > }
728 >
729 > /**
730 > * A simple, opaque attachment whose model representation is described by
731 > * the producer.
732 > *
733 > * @category Turn Types
734 > */
735 > export interface SimpleMessageAttachment extends MessageAttachmentBase {
736 > /** Discriminant */
737 > type: MessageAttachmentKind.Simple;
738 >
739 > /**
740 > * Representation of the attachment as it should be shown to the model.
741 > *
742 > * If the attachment was produced by the client, this property MUST be
743 > * defined so the agent host can correctly interpret the attachment. This
744 > * property MAY be omitted when the attachment originated from a
745 > * `completions` response.
746 > */
747 > modelRepresentation?: string;
748 > }
749 >
750 > /**
751 > * An attachment whose data is embedded inline as a base64 string.
752 > *
753 > * Use this for small binary payloads (e.g. a pasted image) that should be
754 > * delivered with the user message itself rather than fetched separately.
755 > *
756 > * @category Turn Types
757 > */
758 > export interface MessageEmbeddedResourceAttachment extends MessageAttachmentBase {
759 > /** Discriminant */
760 > type: MessageAttachmentKind.EmbeddedResource;
761 > /** Base64-encoded binary data */
762 > data: string;
763 > /** Content MIME type (e.g. `"image/png"`, `"application/pdf"`) */
764 > contentType: string;
765 > /**
766 > * Optional selection within the attached textual resource.
767 > *
768 > * Only meaningful for textual resources.
769 > */
770 > selection?: TextSelection;
771 > }
772 >
773 > /**
774 > * An attachment that references a resource by URI. The content is not
775 > * delivered inline; consumers can fetch it via `resourceRead` when needed.
776 > *
777 > * @category Turn Types
778 > */
779 > export interface MessageResourceAttachment extends MessageAttachmentBase, ContentRef {
780 > /** Discriminant */
781 > type: MessageAttachmentKind.Resource;
782 > /**
783 > * Optional selection within the referenced textual resource.
784 > *
785 > * Only meaningful for textual resources.
786 > */
787 > selection?: TextSelection;
788 > }
789 >
790 > /**
791 > * An attachment that references annotations on a session's annotations
792 > * channel (see {@link AnnotationsState}).
793 > *
794 > * When {@link annotationIds} is omitted the attachment references every
795 > * annotation on the channel; when present it references only the listed
796 > * {@link Annotation.id | annotation ids}.
797 > *
798 > * @category Turn Types
799 > */
800 > export interface MessageAnnotationsAttachment extends MessageAttachmentBase {
801 > /** Discriminant */
802 > type: MessageAttachmentKind.Annotations;
803 > /**
804 > * The annotations channel URI (typically `ahp-session:/<uuid>/annotations`).
805 > * Matches {@link AnnotationsSummary.resource}.
806 > */
807 > resource: URI;
808 > /**
809 > * Specific {@link Annotation.id | annotation ids} to reference. When
810 > * omitted, the attachment references all annotations on the channel.
811 > */
812 > annotationIds?: string[];
813 > }
814 >
815 > /**
816 > * An attachment that references a chat transcript through a fixed completed
817 > * turn.
818 > *
819 > * The referenced chat MUST belong to the same session as the message's chat.
820 > * The host resolves the transcript from its first retained turn through
821 > * `endTurn`, inclusive, when accepting the message. Later turns do not
822 > * change the context represented by an already-sent attachment.
823 > *
824 > * Hosts MUST NOT recursively expand chat attachments found inside the
825 > * referenced transcript. Clients SHOULD keep rendering `label` if the
826 > * referenced chat is later pruned, and treat opening `resource` as best-effort.
827 > *
828 > * @category Turn Types
829 > */
830 > export interface MessageChatAttachment extends MessageAttachmentBase {
831 > /** Discriminant */
832 > type: MessageAttachmentKind.Chat;
833 > /** URI of the referenced chat. */
834 > resource: URI;
835 > /** Last completed turn included in the referenced transcript. */
836 > endTurn: string;
837 > }
838 >
839 > /**
840 > * An attachment associated with a {@link Message}.
841 > *
842 > * @category Turn Types
843 > */
844 > export type MessageAttachment =
845 > | SimpleMessageAttachment
846 > | MessageEmbeddedResourceAttachment
847 > | MessageResourceAttachment
848 > | MessageAnnotationsAttachment
849 > | MessageChatAttachment;
850 >
851 > // ─── Response Parts ──────────────────────────────────────────────────────────
852 >
853 > /**
854 > * Discriminant for response part types.
855 > *
856 > * @category Response Parts
857 > */
858 > export const enum ResponsePartKind {
859 > Markdown = 'markdown',
860 > ContentRef = 'contentRef',
861 > ToolCall = 'toolCall',
862 > Reasoning = 'reasoning',
863 > SystemNotification = 'systemNotification',
864 > InputRequest = 'inputRequest',
865 > }
866 >
867 > /**
868 > * @category Response Parts
869 > */
870 > export interface MarkdownResponsePart {
871 > /** Discriminant */
872 > kind: ResponsePartKind.Markdown;
873 > /** Part identifier, used by `chat/delta` to target this part for content appends */
874 > id: string;
875 > /** Markdown content */
876 > content: string;
877 > }
878 >
879 > /**
880 > * A content part that's a reference to large content stored outside the state tree.
881 > *
882 > * @category Response Parts
883 > */
884 > export interface ResourceReponsePart extends ContentRef {
885 > /** Discriminant */
886 > kind: ResponsePartKind.ContentRef;
887 > }
888 >
889 > /**
890 > * A tool call represented as a response part.
891 > *
892 > * Tool calls are part of the response stream, interleaved with text and
893 > * reasoning. The `toolCall.toolCallId` serves as the part identifier for
894 > * actions that target this part.
895 > *
896 > * @category Response Parts
897 > */
898 > export interface ToolCallResponsePart {
899 > /** Discriminant */
900 > kind: ResponsePartKind.ToolCall;
901 > /** Full tool call lifecycle state */
902 > toolCall: ToolCallState;
903 > }
904 >
905 > /**
906 > * Reasoning/thinking content from the model.
907 > *
908 > * @category Response Parts
909 > */
910 > export interface ReasoningResponsePart {
911 > /** Discriminant */
912 > kind: ResponsePartKind.Reasoning;
913 > /** Part identifier, used by `chat/reasoning` to target this part for content appends */
914 > id: string;
915 > /** Accumulated reasoning text */
916 > content: string;
917 > }
918 >
919 > /**
920 > * @category Response Parts
921 > */
922 > export type ResponsePart =
923 > | MarkdownResponsePart
924 > | ResourceReponsePart
925 > | ToolCallResponsePart
926 > | ReasoningResponsePart
927 > | SystemNotificationResponsePart
928 > | InputRequestResponsePart;
929 >
930 > /**
931 > * A live or resolved input request (elicitation) in the turn response stream.
932 > *
933 > * The server inserts the part with `chat/inputRequested`. While
934 > * {@link response} is absent, clients can update answer drafts with
935 > * `chat/inputAnswerChanged` and submit a response with `chat/inputCompleted`.
936 > * Completion updates this part in place so its stream position is stable and
937 > * the full interaction remains durable and backfillable via `fetchTurns`.
938 > *
939 > * If the turn ends without a submitted response, the unresolved part remains
940 > * in the completed turn transcript with {@link response} absent.
941 > *
942 > * @category Response Parts
943 > */
944 > export interface InputRequestResponsePart {
945 > /** Discriminant */
946 > kind: ResponsePartKind.InputRequest;
947 > /**
948 > * The request, carrying its `id`, `message`, `url`, `questions`, and current
949 > * draft or submitted `answers`.
950 > */
951 > request: ChatInputRequest;
952 > /**
953 > * How the request was resolved. Absent until a client submits `accept`,
954 > * `decline`, or `cancel` with `chat/inputCompleted`.
955 > */
956 > response?: ChatInputResponseKind;
957 > }
958 >
959 > /**
960 > * A system notification surfaced as part of the response stream.
961 > *
962 > * System notifications are messages authored by the agent harness
963 > * that need to be visible to both the agent (for situational awareness) and
964 > * the user (for transcript continuity). Examples include "background subagent
965 > * X completed" or "task Y was cancelled".
966 > *
967 > * @category Response Parts
968 > */
969 > export interface SystemNotificationResponsePart {
970 > /** Discriminant */
971 > kind: ResponsePartKind.SystemNotification;
972 > /** The text of the system notification */
973 > content: StringOrMarkdown;
974 > /**
975 > * Additional provider-specific metadata for this notification.
976 > *
977 > * A host MAY attach a machine-readable descriptor of what triggered the
978 > * notification so clients can categorize, icon, group, filter, or localize
979 > * it without parsing `content`. Clients MAY look for well-known keys here to
980 > * provide enhanced UI, and MUST render coherently from `content` alone when
981 > * `_meta` is absent or unrecognized.
982 > */
983 > _meta?: Record<string, unknown>;
984 > }
985 >
986 >
987 > // ─── Tool Call Types ─────────────────────────────────────────────────────────
988 >
989 > /**
990 > * Status of a tool call in the lifecycle state machine.
991 > *
992 > * @category Tool Call Types
993 > */
994 > export const enum ToolCallStatus {
995 > Streaming = 'streaming',
996 > PendingConfirmation = 'pending-confirmation',
997 > Running = 'running',
998 > /**
999 > * Running paused because the MCP server backing this call needs
1000 > * authentication (typically step-up auth for insufficient scope,
1001 > * surfacing mid-execution). See {@link ToolCallAuthRequiredState}.
1002 > */
1003 > AuthRequired = 'auth-required',
1004 > PendingResultConfirmation = 'pending-result-confirmation',
1005 > Completed = 'completed',
1006 > Cancelled = 'cancelled',
1007 > }
1008 >
1009 > /**
1010 > * How a tool call was confirmed for execution.
1011 > *
1012 > * - `NotNeeded` — No confirmation required (auto-approved)
1013 > * - `UserAction` — User explicitly approved
1014 > * - `Setting` — Approved by a persistent user setting
1015 > *
1016 > * @category Tool Call Types
1017 > */
1018 > export const enum ToolCallConfirmationReason {
1019 > NotNeeded = 'not-needed',
1020 > UserAction = 'user-action',
1021 > Setting = 'setting',
1022 > }
1023 >
1024 > /**
1025 > * Identifies a model judge as the source of a confirmation requirement.
1026 > *
1027 > * @category Tool Call Types
1028 > */
1029 > export const enum ToolCallRiskAssessmentKind {
1030 > Judge = 'judge',
1031 > }
1032 >
1033 > /**
1034 > * Lifecycle status of an asynchronous model-judge confirmation decision.
1035 > *
1036 > * @category Tool Call Types
1037 > */
1038 > export const enum ToolCallRiskAssessmentStatus {
1039 > Loading = 'loading',
1040 > Complete = 'complete',
1041 > }
1042 >
1043 > interface ToolCallRiskAssessmentBase {
1044 > kind: ToolCallRiskAssessmentKind;
1045 > }
1046 >
1047 > /**
1048 > * The model judge is still evaluating the tool call.
1049 > *
1050 > * @category Tool Call Types
1051 > */
1052 > export interface ToolCallRiskAssessmentLoadingState extends ToolCallRiskAssessmentBase {
1053 > status: ToolCallRiskAssessmentStatus.Loading;
1054 > }
1055 >
1056 > /**
1057 > * The model judge has completed its evaluation.
1058 > *
1059 > * @category Tool Call Types
1060 > */
1061 > export interface ToolCallRiskAssessmentCompleteState extends ToolCallRiskAssessmentBase {
1062 > status: ToolCallRiskAssessmentStatus.Complete;
1063 > reason: StringOrMarkdown;
1064 > /**
1065 > * The judge's normalized safety score, where `0` is unsafe and `1` is safe.
1066 > * @format float
1067 > */
1068 > safety: number;
1069 > }
1070 >
1071 > export type ToolCallRiskAssessment =
1072 > | ToolCallRiskAssessmentLoadingState
1073 > | ToolCallRiskAssessmentCompleteState;
1074 >
1075 > /**
1076 > * Why a tool call was cancelled.
1077 > *
1078 > * @category Tool Call Types
1079 > */
1080 > export const enum ToolCallCancellationReason {
1081 > Denied = 'denied',
1082 > Skipped = 'skipped',
1083 > ResultDenied = 'result-denied',
1084 > }
1085 >
1086 > /**
1087 > * Whether a confirmation option represents an approval or denial action.
1088 > *
1089 > * @category Tool Call Types
1090 > */
1091 > export const enum ConfirmationOptionKind {
1092 > Approve = 'approve',
1093 > Deny = 'deny',
1094 > }
1095 >
1096 > /**
1097 > * A confirmation option that the server offers for a tool call awaiting
1098 > * approval. Allows richer choices beyond simple approve/deny — for example,
1099 > * "Approve in this Session" or "Deny with reason."
1100 > *
1101 > * @category Tool Call Types
1102 > */
1103 > export interface ConfirmationOption {
1104 > /** Unique identifier for the option, returned in the confirmed action */
1105 > id: string;
1106 > /** Human-readable label displayed to the user */
1107 > label: string;
1108 > /** Whether this option represents an approval or denial */
1109 > kind: ConfirmationOptionKind;
1110 > /**
1111 > * Logical group number for visual categorisation.
1112 > *
1113 > * Clients SHOULD display options in the order they are defined and MAY
1114 > * use differing group numbers to insert dividers between logical clusters
1115 > * of options.
1116 > */
1117 > group?: number;
1118 > }
1119 >
1120 > export const enum ToolCallContributorKind {
1121 > Client = 'client',
1122 > MCP = 'mcp',
1123 > }
1124 >
1125 > export interface ToolCallClientContributor {
1126 > kind: ToolCallContributorKind.Client;
1127 > /**
1128 > * If this tool is provided by a client, the `clientId` of the owning client.
1129 > * Absent for server-side tools.
1130 > *
1131 > * When set, the identified client is responsible for executing the tool and
1132 > * dispatching `chat/toolCallComplete` with the result.
1133 > */
1134 > clientId: string;
1135 > }
1136 >
1137 > export interface ToolCallMcpContributor {
1138 > kind: ToolCallContributorKind.MCP;
1139 > /**
1140 > * Customization ID of the corresponding MCP server in {@link SessionState.customizations}.
1141 > */
1142 > customizationId: string;
1143 > }
1144 >
1145 > export type ToolCallContributor = ToolCallClientContributor | ToolCallMcpContributor;
1146 >
1147 > /**
1148 > * Metadata common to all tool call states.
1149 > *
1150 > * @category Tool Call Types
1151 > * @remarks
1152 > * Fields like `toolName` carry agent-specific identifiers on the wire despite the
1153 > * agent-agnostic design principle. These exist for debugging and logging purposes.
1154 > * A future version may move these to a separate diagnostic channel or namespace them
1155 > * more clearly.
1156 > */
1157 > interface ToolCallBase {
1158 > /** Unique tool call identifier */
1159 > toolCallId: string;
1160 > /** Internal tool name (for debugging/logging) */
1161 > toolName: string;
1162 > /** Human-readable tool name */
1163 > displayName: string;
1164 > /** Human-readable description of what the tool invocation intends to do */
1165 > intention?: string;
1166 > /**
1167 > * Reference to the contributor of the tool being called.
1168 > */
1169 > contributor?: ToolCallContributor;
1170 > /**
1171 > * Additional provider-specific metadata for this tool call.
1172 > *
1173 > * This MAY include a `ui` field corresponding to the MCP Apps (SEP-1865)
1174 > * `McpUiToolMeta` found in MCP tool calls, which may be used in combination
1175 > * with the {@link contributor} to serve MCP Apps.
1176 > */
1177 > _meta?: Record<string, unknown>;
1178 > }
1179 >
1180 > /**
1181 > * Properties available once tool call parameters are fully received.
1182 > *
1183 > * @category Tool Call Types
1184 > */
1185 > interface ToolCallParameterFields {
1186 > /** Message describing what the tool will do */
1187 > invocationMessage: StringOrMarkdown;
1188 > /** Raw tool input */
1189 > toolInput?: string;
1190 > }
1191 >
1192 > /**
1193 > * Tool execution result details, available after execution completes.
1194 > *
1195 > * @category Tool Call Types
1196 > */
1197 > export interface ToolCallResult {
1198 > /** Whether the tool succeeded */
1199 > success: boolean;
1200 > /** Past-tense description of what the tool did */
1201 > pastTenseMessage: StringOrMarkdown;
1202 > /**
1203 > * Unstructured result content blocks.
1204 > *
1205 > * This mirrors the `content` field of MCP `CallToolResult`.
1206 > */
1207 > content?: ToolResultContent[];
1208 > /**
1209 > * Optional structured result object.
1210 > *
1211 > * This mirrors the `structuredContent` field of MCP `CallToolResult`.
1212 > */
1213 > structuredContent?: Record<string, unknown>;
1214 > /** Error details if the tool failed */
1215 > error?: { message: string; code?: string };
1216 > }
1217 >
1218 > /**
1219 > * LM is streaming the tool call parameters.
1220 > *
1221 > * @category Tool Call Types
1222 > */
1223 > export interface ToolCallStreamingState extends ToolCallBase {
1224 > status: ToolCallStatus.Streaming;
1225 > /** Partial parameters accumulated so far */
1226 > partialInput?: string;
1227 > /** Progress message shown while parameters are streaming */
1228 > invocationMessage?: StringOrMarkdown;
1229 > }
1230 >
1231 > /**
1232 > * Parameters are complete, or a running tool requires re-confirmation
1233 > * (e.g. a mid-execution permission check).
1234 > *
1235 > * @category Tool Call Types
1236 > */
1237 > export interface ToolCallPendingConfirmationState extends ToolCallBase, ToolCallParameterFields {
1238 > status: ToolCallStatus.PendingConfirmation;
1239 > /** Short title for the confirmation prompt (e.g. `"Run in terminal"`, `"Write file"`) */
1240 > confirmationTitle?: StringOrMarkdown;
1241 > /** Risk assessment that informed the confirmation requirement. */
1242 > riskAssessment?: ToolCallRiskAssessment;
1243 > /** File edits that this tool call will perform, for preview before confirmation */
1244 > edits?: { items: FileEdit[] };
1245 > /** Whether the agent host allows the client to edit the tool's input parameters before confirming */
1246 > editable?: boolean;
1247 > /**
1248 > * Options the server offers for this confirmation. When present, the client
1249 > * SHOULD render these instead of a plain approve/deny UI. Each option
1250 > * belongs to a {@link ConfirmationOptionGroup} so the client can still
1251 > * categorise the choices.
1252 > */
1253 > options?: ConfirmationOption[];
1254 > }
1255 >
1256 > /**
1257 > * Fields present on every tool call state that exists **after** confirmation
1258 > * has been resolved: {@link ToolCallRunningState}, {@link ToolCallAuthRequiredState},
1259 > * {@link ToolCallPendingResultConfirmationState}, and {@link ToolCallCompletedState}.
1260 > * `ToolCallPendingConfirmationState` (not yet confirmed) and
1261 > * `ToolCallCancelledState` (the denial path — never ran) don't satisfy this
1262 > * invariant, so they keep their own `selectedOption` field independently
1263 > * rather than extending this one.
1264 > *
1265 > * @category Tool Call Types
1266 > */
1267 > interface ToolCallPostConfirmationFields {
1268 > /** How the tool was confirmed for execution */
1269 > confirmed: ToolCallConfirmationReason;
1270 > /** The confirmation option the user selected, if confirmation options were provided */
1271 > selectedOption?: ConfirmationOption;
1272 > }
1273 >
1274 > /**
1275 > * Tool is actively executing.
1276 > *
1277 > * @category Tool Call Types
1278 > */
1279 > export interface ToolCallRunningState extends ToolCallBase, ToolCallParameterFields, ToolCallPostConfirmationFields {
1280 > status: ToolCallStatus.Running;
1281 > /**
1282 > * Partial content produced while the tool is still executing.
1283 > *
1284 > * For example, a terminal content block lets clients subscribe to live
1285 > * output before the tool completes.
1286 > */
1287 > content?: ToolResultContent[];
1288 > }
1289 >
1290 > /**
1291 > * A running tool call is paused because the MCP server backing it needs
1292 > * authentication — most commonly {@link McpAuthRequirement.reason |
1293 > * `insufficientScope`} step-up auth triggered by the `tools/call` request
1294 > * itself. Only ever reached from {@link ToolCallRunningState}, and normally
1295 > * returns there once authenticated: `running` → `auth-required` → `running`
1296 > * → …. A client MAY instead cancel the invocation without authenticating by
1297 > * dispatching a `chat/toolCallComplete` with a **failed** result, always
1298 > * moving straight to {@link ToolCallCompletedState} —
1299 > * `requiresResultConfirmation` is ignored on this path, so it can never
1300 > * enter {@link ToolCallPendingResultConfirmationState}. A **successful**
1301 > * result dispatched from this state is invalid and MUST be rejected/ignored
1302 > * as a no-op by the reducer, since execution never resumed after the
1303 > * challenge.
1304 > *
1305 > * This is the tool-call-level counterpart to
1306 > * {@link McpServerAuthRequiredState} — that state means the MCP *server*
1307 > * cannot serve any request; this one means *this specific invocation* is
1308 > * waiting on the same kind of challenge. The two are dispatched
1309 > * independently and MAY be true at the same time, or not: an
1310 > * `insufficientScope` challenge triggered by a single tool call, for
1311 > * example, need not block the whole server.
1312 > *
1313 > * Because the challenge is always resolved by pushing a token via the
1314 > * existing `authenticate` command, this state can only originate from a
1315 > * tool call {@link ToolCallContributorKind.MCP | contributed by an MCP
1316 > * server} — `contributor` is narrowed accordingly (unlike the optional,
1317 > * multi-kind `contributor` on other tool call states).
1318 > *
1319 > * @category Tool Call Types
1320 > */
1321 > export interface ToolCallAuthRequiredState extends ToolCallBase, ToolCallParameterFields, ToolCallPostConfirmationFields {
1322 > status: ToolCallStatus.AuthRequired;
1323 > /** The MCP server that contributed this tool call — always MCP, never a client tool. */
1324 > contributor: ToolCallMcpContributor;
1325 > /** The authentication challenge blocking this invocation. */
1326 > auth: McpAuthRequirement;
1327 > /** Partial content produced before the call paused for authentication. */
1328 > content?: ToolResultContent[];
1329 > }
1330 >
1331 > /**
1332 > * Tool finished executing, waiting for client to approve the result.
1333 > *
1334 > * @category Tool Call Types
1335 > */
1336 > export interface ToolCallPendingResultConfirmationState extends ToolCallBase, ToolCallParameterFields, ToolCallResult, ToolCallPostConfirmationFields {
1337 > status: ToolCallStatus.PendingResultConfirmation;
1338 > }
1339 >
1340 > /**
1341 > * Tool completed successfully or with an error.
1342 > *
1343 > * @category Tool Call Types
1344 > */
1345 > export interface ToolCallCompletedState extends ToolCallBase, ToolCallParameterFields, ToolCallResult, ToolCallPostConfirmationFields {
1346 > status: ToolCallStatus.Completed;
1347 > }
1348 >
1349 > /**
1350 > * Tool call was cancelled before execution.
1351 > *
1352 > * @category Tool Call Types
1353 > */
1354 > export interface ToolCallCancelledState extends ToolCallBase, ToolCallParameterFields {
1355 > status: ToolCallStatus.Cancelled;
1356 > /** Why the tool was cancelled */
1357 > reason: ToolCallCancellationReason;
1358 > /** Optional message explaining the cancellation */
1359 > reasonMessage?: StringOrMarkdown;
1360 > /** What the user suggested doing instead */
1361 > userSuggestion?: Message;
1362 > /** The confirmation option the user selected, if confirmation options were provided */
1363 > selectedOption?: ConfirmationOption;
1364 > }
1365 >
1366 > /**
1367 > * Discriminated union of all tool call lifecycle states.
1368 > *
1369 > * See the [state model guide](/guide/state-model.html#tool-call-lifecycle)
1370 > * for the full state machine diagram.
1371 > *
1372 > * @category Tool Call Types
1373 > */
1374 > export type ToolCallState =
1375 > | ToolCallStreamingState
1376 > | ToolCallPendingConfirmationState
1377 > | ToolCallRunningState
1378 > | ToolCallAuthRequiredState
1379 > | ToolCallPendingResultConfirmationState
1380 > | ToolCallCompletedState
1381 > | ToolCallCancelledState;
1382 >
1383 > /**
1384 > * The two tool-call states that block on a client confirmation: parameter
1385 > * confirmation before execution ({@link ToolCallPendingConfirmationState}) and
1386 > * result confirmation after execution
1387 > * ({@link ToolCallPendingResultConfirmationState}).
1388 > *
1389 > * {@link ToolCallAuthRequiredState} is intentionally **not** part of this
1390 > * union: it doesn't block on a `chat/toolCallConfirmed`-style client
1391 > * decision, it blocks on the client completing an OAuth flow and calling
1392 > * `authenticate`. See {@link SessionToolAuthenticationRequest} for its
1393 > * session-level surfacing.
1394 > *
1395 > * Surfaced at the session level by {@link SessionToolConfirmationRequest}.
1396 > *
1397 > * @category Tool Call Types
1398 > */
1399 > export type ToolCallConfirmationState =
1400 > | ToolCallPendingConfirmationState
1401 > | ToolCallPendingResultConfirmationState;
1402 >
1403 >
1404 > // ─── Tool Result Content ─────────────────────────────────────────────────────
1405 >
1406 > /**
1407 > * Discriminant for tool result content types.
1408 > *
1409 > * @category Tool Result Content
1410 > */
1411 > export const enum ToolResultContentType {
1412 > Text = 'text',
1413 > EmbeddedResource = 'embeddedResource',
1414 > Resource = 'resource',
1415 > FileEdit = 'fileEdit',
1416 > Terminal = 'terminal',
1417 > Subagent = 'subagent',
1418 > }
1419 >
1420 > /**
1421 > * Text content in a tool result.
1422 > *
1423 > * Mirrors MCP `TextContent`.
1424 > *
1425 > * @category Tool Result Content
1426 > */
1427 > export interface ToolResultTextContent {
1428 > type: ToolResultContentType.Text;
1429 > /** The text content */
1430 > text: string;
1431 > }
1432 >
1433 > /**
1434 > * Base64-encoded binary content embedded in a tool result.
1435 > *
1436 > * Mirrors MCP `EmbeddedResource` for inline binary data.
1437 > *
1438 > * @category Tool Result Content
1439 > */
1440 > export interface ToolResultEmbeddedResourceContent {
1441 > type: ToolResultContentType.EmbeddedResource;
1442 > /** Base64-encoded data */
1443 > data: string;
1444 > /** Content type (e.g. `"image/png"`, `"application/pdf"`) */
1445 > contentType: string;
1446 > }
1447 >
1448 > /**
1449 > * A reference to a resource stored outside the tool result.
1450 > *
1451 > * Wraps {@link ContentRef} for lazy-loading large results.
1452 > *
1453 > * @category Tool Result Content
1454 > */
1455 > export interface ToolResultResourceContent extends ContentRef {
1456 > type: ToolResultContentType.Resource;
1457 > }
1458 >
1459 > /**
1460 > * Describes a file modification performed by a tool.
1461 > *
1462 > * @category Tool Result Content
1463 > */
1464 > export interface ToolResultFileEditContent extends FileEdit {
1465 > type: ToolResultContentType.FileEdit;
1466 > }
1467 >
1468 > /**
1469 > * A reference to a terminal whose output is relevant to this tool result.
1470 > *
1471 > * Clients can subscribe to the terminal's URI to stream its output in real
1472 > * time, providing live feedback while a tool is executing.
1473 > *
1474 > * When the command exits, {@link result} is filled in on the completed
1475 > * result, retaining the outcome for clients that did not subscribe. This
1476 > * records the command's exit, not the terminal's — the terminal may keep
1477 > * running afterwards.
1478 > *
1479 > * @category Tool Result Content
1480 > */
1481 > export interface ToolResultTerminalContent {
1482 > type: ToolResultContentType.Terminal;
1483 > /** Terminal URI (subscribable for full terminal state) */
1484 > resource: URI;
1485 > /** Display title for the terminal content */
1486 > title: string;
1487 > /**
1488 > * Whether this terminal-style resource is backed by a pseudoterminal.
1489 > * When `false`, output is plain text and clients do not need to parse
1490 > * VT sequences.
1491 > */
1492 > isPty?: boolean;
1493 > /** Outcome of the command, present once it has exited. */
1494 > result?: TerminalCommandResult;
1495 > }
1496 >
1497 > /**
1498 > * Outcome of a command run in a terminal-style tool, filled in on
1499 > * {@link ToolResultTerminalContent.result} once the command exits.
1500 > *
1501 > * @category Tool Result Content
1502 > */
1503 > export interface TerminalCommandResult {
1504 > /** Exit code from the completed command, if reported by the runtime */
1505 > exitCode?: number;
1506 > /**
1507 > * Preview of the command's output, for clients that are not subscribed
1508 > * to the terminal or that arrive after it is disposed. When `isPty` is
1509 > * `true` the preview may contain VT sequences; when `false` it is plain
1510 > * text.
1511 > */
1512 > preview?: string;
1513 > /** Whether `preview` is known to be incomplete or truncated */
1514 > truncated?: boolean;
1515 > }
1516 >
1517 > /**
1518 > * A reference, embedded in a tool result, to a worker chat spawned by the tool
1519 > * call (a sub-agent delegation), referenced by a chat URI (`ahp-chat:/...`).
1520 > *
1521 > * This is the spawning tool call's forward view of the worker. The worker chat
1522 > * records the same edge in reverse via its {@link ChatOrigin} (`kind: 'tool'`),
1523 > * whose `toolCallId` identifies the tool call that emitted this content.
1524 > *
1525 > * @category Tool Result Content
1526 > */
1527 > export interface ToolResultSubagentContent {
1528 > type: ToolResultContentType.Subagent;
1529 > /** Worker chat URI (subscribable for full chat state) */
1530 > resource: URI;
1531 > /** Display title for the subagent */
1532 > title: string;
1533 > /** Internal agent name */
1534 > agentName?: string;
1535 > /** Human-readable description of the subagent's task */
1536 > description?: string;
1537 > }
1538 >
1539 > /**
1540 > * Content block in a tool result.
1541 > *
1542 > * Mirrors the content blocks in MCP `CallToolResult.content`, plus
1543 > * `ToolResultResourceContent` for lazy-loading large results,
1544 > * `ToolResultFileEditContent` for file edit diffs,
1545 > * `ToolResultTerminalContent` for live terminal output and
1546 > * command completion metadata, and
1547 > * `ToolResultSubagentContent` for tool-spawned worker chats (AHP extensions).
1548 > *
1549 > * @category Tool Result Content
1550 > */
1551 > export type ToolResultContent =
1552 > | ToolResultTextContent
1553 > | ToolResultEmbeddedResourceContent
1554 > | ToolResultResourceContent
1555 > | ToolResultFileEditContent
1556 > | ToolResultTerminalContent
1557 > | ToolResultSubagentContent;
src/vs/platform/agentHost/common/state/protocol/channels-session/state.ts 1351 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { Changeset } from '../channels-changeset/state.js';
10 > import type { AnnotationsSummary } from '../channels-annotations/state.js';
11 > import type { ChatSummary, ChatInputRequest, ToolCallConfirmationState, ToolCallState, ToolCallAuthRequiredState } from '../channels-chat/state.js';
12 > import type { ConfigPropertySchema, ErrorInfo, Icon, ProtectedResourceMetadata, TextRange, URI } from '../common/state.js';
13 >
14 > // ─── Session State ───────────────────────────────────────────────────────────
15 >
16 > /**
17 > * Session initialization state.
18 > *
19 > * @category Session State
20 > */
21 > export const enum SessionLifecycle {
22 > Creating = 'creating',
23 > Ready = 'ready',
24 > CreationFailed = 'creationFailed',
25 > }
26 >
27 > /**
28 > * Bitset of summary-level session status flags.
29 > *
30 > * Use bitwise checks instead of equality for non-terminal activity. For example,
31 > * `status & SessionStatus.InProgress` matches both ordinary in-progress turns
32 > * and turns that are paused waiting for input.
33 > *
34 > * @category Session State
35 > */
36 > export const enum SessionStatus {
37 > /** Session is idle — no turn is active. */
38 > Idle = 1,
39 > /** Session ended with an error. */
40 > Error = 1 << 1,
41 > /** A turn is actively streaming. */
42 > InProgress = 1 << 3,
43 > /** A turn is in progress but blocked waiting for user input or tool confirmation. */
44 > InputNeeded = (1 << 3) | (1 << 4),
45 > /** The client has viewed this session since its last modification. */
46 > IsRead = 1 << 5,
47 > /** The session has been archived by the client. */
48 > IsArchived = 1 << 6,
49 > }
50 >
51 > /**
52 > * Metadata shared between the full {@link SessionState} (delivered when a
53 > * client subscribes to a session's URI) and the lightweight
54 > * {@link SessionSummary} (carried in the root-channel session catalog).
55 > *
56 > * These fields describe the session at a glance and appear in both places.
57 > * `SessionState` owns the authoritative values for a subscribed session;
58 > * `SessionSummary` mirrors them into the catalog so clients that only render a
59 > * session list don't have to subscribe to every session URI. The host keeps
60 > * the catalog in sync via `root/sessionSummaryChanged`.
61 > *
62 > * @category Session State
63 > */
64 > export interface SessionMetadata {
65 > /** Agent provider ID */
66 > provider: string;
67 > /** Session title */
68 > title: string;
69 > /** Current session status */
70 > status: SessionStatus;
71 > /** Human-readable description of what the session is currently doing */
72 > activity?: string;
73 > /** Server-owned project for this session */
74 > project?: ProjectInfo;
75 > /**
76 > * The working directories the session's agent has tool access to, as
77 > * maintained by the `session/workingDirectorySet` /
78 > * `session/workingDirectoryRemoved` actions. Directories are **equal peers** —
79 > * the session has no primary. Individual chats MAY restrict to a subset via
80 > * {@link ChatSummary.workingDirectories | their own `workingDirectories`} and
81 > * designate one of their own directories as primary (see
82 > * {@link ChatState.primaryWorkingDirectory}); a chat that sets no subset
83 > * operates against this full set.
84 > */
85 > workingDirectories?: URI[];
86 > /**
87 > * Lightweight summary of this session's inline annotations channel
88 > * (`ahp-session:/<uuid>/annotations`). Surfaced so badge UI can render
89 > * annotation / entry counts without subscribing. Absent when the session
90 > * does not expose an annotations channel.
91 > */
92 > annotations?: AnnotationsSummary;
93 > }
94 >
95 > /**
96 > * Full state for a single session, loaded when a client subscribes to the session's URI.
97 > *
98 > * Inlines (denormalizes) every {@link SessionMetadata} field directly onto
99 > * itself so subscribers receive one flat object instead of a nested summary.
100 > * The lightweight catalog representation is {@link SessionSummary}, surfaced on
101 > * the root channel; the host keeps the two in sync via
102 > * `root/sessionSummaryChanged`.
103 > *
104 > * @category Session State
105 > */
106 > export interface SessionState extends SessionMetadata {
107 > /** Session initialization state */
108 > lifecycle: SessionLifecycle;
109 > /** Error details if creation failed */
110 > creationError?: ErrorInfo;
111 > /** Tools provided by the server (agent host) for this session */
112 > serverTools?: ToolDefinition[];
113 > /**
114 > * The clients currently providing tools and interactive capabilities to this
115 > * session. If multiple tools or customizations are provided by the same
116 > * active client, an agent host MAY deduplicate them when exposed to a model,
117 > * with a preference given to the client that started the turn.
118 > *
119 > * Membership is host-managed: clients add (or refresh) themselves with
120 > * `session/activeClientSet`, and the host removes them with
121 > * `session/activeClientRemoved` when they unsubscribe, disconnect without
122 > * reconnecting in time, or reconnect without resubscribing to the session.
123 > */
124 > activeClients: SessionActiveClient[];
125 > /** Catalog of chats in this session. */
126 > chats: ChatSummary[];
127 > /**
128 > * The chat that receives input when the user addresses the session without
129 > * selecting a specific chat. This is a UI routing hint, not a hierarchy
130 > * marker — chats remain equal peers at the protocol level. Hosts MAY change
131 > * this over the session's lifetime.
132 > */
133 > defaultChat?: URI;
134 > /** Session configuration schema and current values */
135 > config?: SessionConfigState;
136 > /**
137 > * Top-level customizations active in this session.
138 > *
139 > * Always one of the {@link Customization} variants:
140 > *
141 > * - Container customizations ({@link PluginCustomization},
142 > * {@link DirectoryCustomization}) whose children — agents, skills,
143 > * prompts, rules, hooks, MCP servers — live in each container's
144 > * {@link ContainerCustomizationBase.children | `children`} array.
145 > * - Top-level {@link McpServerCustomization} entries the host
146 > * surfaces directly (for example a globally-configured MCP server
147 > * that isn't bundled in a plugin or directory). MCP servers may
148 > * also appear as children of a container.
149 > *
150 > * Client-published plugins arrive via
151 > * {@link SessionActiveClient.customizations | `activeClients[].customizations`}
152 > * and the host propagates them into this list (typically with the
153 > * container's `clientId` set and `children` populated). Clients
154 > * publish in container shape only; bare MCP servers at the top level
155 > * are server-originated.
156 > */
157 > customizations?: Customization[];
158 > /**
159 > * Catalogue of changesets the server can produce for this session. Each
160 > * entry advertises a subscribable view of file changes (uncommitted,
161 > * session-wide, per-turn, etc.) and the URI template the client expands
162 > * before subscribing. See {@link Changeset} for the full shape and
163 > * {@link /guide/changesets | Changesets} for an overview of the model.
164 > */
165 > changesets?: Changeset[];
166 > /**
167 > * Outstanding input the session is blocked on, aggregated across every chat
168 > * so a client can discover and answer it from the session channel alone,
169 > * without subscribing to individual chats.
170 > *
171 > * Each entry is self-sufficient: it carries the owning chat's URI plus every
172 > * identifier the client needs to respond. A client answers by dispatching the
173 > * ordinary `chat/*` action to that chat's channel — see
174 > * {@link SessionInputRequest} for the per-variant response path. A present,
175 > * non-empty list implies {@link SessionStatus.InputNeeded} on
176 > * {@link SessionSummary.status}.
177 > *
178 > * Host-managed: the host upserts entries with `session/inputNeededSet` as
179 > * chats raise requests and removes them with `session/inputNeededRemoved`
180 > * once the underlying request resolves.
181 > */
182 > inputNeeded?: SessionInputRequest[];
183 > /**
184 > * Additional provider-specific metadata for this session.
185 > *
186 > * Clients MAY look for well-known keys here to provide enhanced UI.
187 > * For example, a `git` key may provide extra git metadata about the session's
188 > * working directories.
189 > */
190 > _meta?: Record<string, unknown>;
191 > }
192 >
193 > /**
194 > * A client currently providing tools and interactive capabilities to a session.
195 > *
196 > * A session MAY have several active clients at once; entries in
197 > * {@link SessionState.activeClients} are keyed by `clientId`. The server SHOULD
198 > * automatically remove an active client when that client disconnects.
199 > *
200 > * @category Session State
201 > */
202 > export interface SessionActiveClient {
203 > /** Client identifier (matches `clientId` from `initialize`) */
204 > clientId: string;
205 > /** Human-readable client name (e.g. `"VS Code"`) */
206 > displayName?: string;
207 > /** Tools this client provides to the session */
208 > tools: ToolDefinition[];
209 > /**
210 > * Plugin customizations this client contributes to the session.
211 > *
212 > * Clients publish in [Open Plugins](https://open-plugins.com/) format
213 > * — i.e. always container-shaped plugins. They MAY synthesize virtual
214 > * plugins in memory and rely on the host to expand them into concrete
215 > * children inside {@link SessionState.customizations}.
216 > */
217 > customizations?: ClientPluginCustomization[];
218 > }
219 >
220 > // ─── Session Input Requests ──────────────────────────────────────────────────
221 >
222 > /**
223 > * Discriminant for the kinds of outstanding input a session can surface in
224 > * {@link SessionState.inputNeeded}.
225 > *
226 > * This is a general/typological union (not a lifecycle), so the discriminant is
227 > * a `*Kind`.
228 > *
229 > * @category Session Input Types
230 > */
231 > export const enum SessionInputRequestKind {
232 > /** A user-facing elicitation mirrored from an unresolved chat response part. */
233 > ChatInput = 'chatInput',
234 > /** A tool call awaiting parameter- or result-confirmation. */
235 > ToolConfirmation = 'toolConfirmation',
236 > /** A running tool the session wants an active client to execute. */
237 > ToolClientExecution = 'toolClientExecution',
238 > /** A tool call blocked on MCP authentication mid-execution. */
239 > ToolAuthentication = 'toolAuthentication',
240 > }
241 >
242 > /**
243 > * Fields common to every {@link SessionInputRequest} variant.
244 > *
245 > * @category Session Input Types
246 > */
247 > interface SessionInputRequestBase {
248 > /**
249 > * Stable key for this entry, unique within the session's
250 > * {@link SessionState.inputNeeded} list. The host derives it however it likes
251 > * (for example from the chat URI plus the underlying request or tool-call
252 > * id); consumers MUST treat it as opaque. It is the key for the
253 > * `session/inputNeededSet` / `session/inputNeededRemoved` upsert convention.
254 > */
255 > id: string;
256 > /**
257 > * The chat the underlying request lives in. This is the channel a client
258 > * dispatches its response to — it does not need to have subscribed to that
259 > * chat first.
260 > */
261 > chat: URI;
262 > }
263 >
264 > /**
265 > * A user-input elicitation surfaced at the session level, mirroring the request
266 > * from an unresolved {@link InputRequestResponsePart} in the owning chat.
267 > *
268 > * Respond by dispatching `chat/inputCompleted` (or syncing drafts with
269 > * `chat/inputAnswerChanged`) to {@link SessionInputRequestBase.chat | `chat`},
270 > * keyed by {@link ChatInputRequest.id | `request.id`}.
271 > *
272 > * @category Session Input Types
273 > */
274 > export interface SessionChatInputRequest extends SessionInputRequestBase {
275 > kind: SessionInputRequestKind.ChatInput;
276 > /** The mirrored chat input request. */
277 > request: ChatInputRequest;
278 > }
279 >
280 > /**
281 > * A tool call blocked on confirmation — either parameter confirmation before
282 > * execution or result confirmation after — surfaced at the session level.
283 > *
284 > * Respond by dispatching `chat/toolCallConfirmed` (for
285 > * {@link ToolCallPendingConfirmationState}) or `chat/toolCallResultConfirmed`
286 > * (for {@link ToolCallPendingResultConfirmationState}) to
287 > * {@link SessionInputRequestBase.chat | `chat`}, keyed by `turnId` and
288 > * `toolCall.toolCallId`.
289 > *
290 > * @category Session Input Types
291 > */
292 > export interface SessionToolConfirmationRequest extends SessionInputRequestBase {
293 > kind: SessionInputRequestKind.ToolConfirmation;
294 > /** The turn the tool call belongs to. */
295 > turnId: string;
296 > /** The tool call awaiting confirmation. */
297 > toolCall: ToolCallConfirmationState;
298 > }
299 >
300 > /**
301 > * A running tool whose execution is delegated to an active client. Surfaced so
302 > * a client that provides the tool can pick up the work without subscribing to
303 > * the owning chat.
304 > *
305 > * The {@link toolCall} is always a {@link ToolCallRunningState} (a
306 > * {@link ToolCallState} in `running` status) whose
307 > * {@link ToolCallRunningState.contributor | `contributor`} is a client
308 > * {@link ToolCallClientContributor} whose `clientId` matches the denormalized
309 > * {@link clientId} here. Execute and report the result by dispatching
310 > * `chat/toolCallComplete` (and optionally streaming with
311 > * `chat/toolCallContentChanged`) to {@link SessionInputRequestBase.chat |
312 > * `chat`}, keyed by `turnId` and `toolCall.toolCallId`.
313 > *
314 > * @category Session Input Types
315 > */
316 > export interface SessionToolClientExecutionRequest extends SessionInputRequestBase {
317 > kind: SessionInputRequestKind.ToolClientExecution;
318 > /** The turn the tool call belongs to. */
319 > turnId: string;
320 > /**
321 > * The `clientId` expected to execute the tool. Matches the `clientId` of the
322 > * tool call's client {@link ToolCallContributor}.
323 > */
324 > clientId: string;
325 > /**
326 > * The running tool call the session wants the owning client to execute. The
327 > * host only ever populates this with a {@link ToolCallRunningState} (i.e. a
328 > * {@link ToolCallState} in `running` status).
329 > */
330 > toolCall: ToolCallState;
331 > }
332 >
333 > /**
334 > * A tool call blocked on MCP authentication mid-execution, surfaced at the
335 > * session level.
336 > *
337 > * The {@link toolCall} is always a {@link ToolCallAuthRequiredState} (a
338 > * {@link ToolCallState} in `auth-required` status). Unlike
339 > * {@link SessionToolConfirmationRequest}, this is **not** answered by
340 > * dispatching a `chat/*` action directly: the client obtains a token for
341 > * {@link ToolCallAuthRequiredState.auth | `toolCall.auth`}`.resource` and
342 > * pushes it via the existing `authenticate` command (see
343 > * {@link /specification/authentication | Authentication}). The host resumes
344 > * the tool call and dispatches `chat/toolCallAuthResolved` once the token is
345 > * accepted, at which point it also removes this entry with
346 > * `session/inputNeededRemoved`.
347 > *
348 > * @category Session Input Types
349 > */
350 > export interface SessionToolAuthenticationRequest extends SessionInputRequestBase {
351 > kind: SessionInputRequestKind.ToolAuthentication;
352 > /** The turn the tool call belongs to. */
353 > turnId: string;
354 > /** The tool call awaiting authentication. */
355 > toolCall: ToolCallAuthRequiredState;
356 > }
357 >
358 > /**
359 > * One outstanding piece of input a session is blocked on, aggregated across all
360 > * chats in {@link SessionState.inputNeeded}.
361 > *
362 > * Each entry is self-sufficient: it carries the owning
363 > * {@link SessionInputRequestBase.chat | `chat`} URI plus every identifier needed
364 > * to construct the response, so a client can answer by dispatching the ordinary
365 > * `chat/*` action (`chat/inputCompleted`, `chat/toolCallConfirmed`,
366 > * `chat/toolCallComplete`, …) to that chat's channel **without having subscribed
367 > * to the chat** — except {@link SessionToolAuthenticationRequest}, which is
368 > * resolved via the `authenticate` command instead. The host removes the entry
369 > * with `session/inputNeededRemoved` once the underlying request resolves.
370 > *
371 > * @category Session Input Types
372 > */
373 > export type SessionInputRequest =
374 > | SessionChatInputRequest
375 > | SessionToolConfirmationRequest
376 > | SessionToolClientExecutionRequest
377 > | SessionToolAuthenticationRequest;
378 >
379 > /**
380 > * Server-owned project metadata for a session.
381 > *
382 > * @category Session State
383 > */
384 > export interface ProjectInfo {
385 > /** Project URI */
386 > uri: URI;
387 > /** Human-readable project name */
388 > displayName: string;
389 > }
390 >
391 > /**
392 > * Lightweight catalog entry summarizing one session. Surfaced via
393 > * {@link RootChannelCommands.listSessions | `root/listSessions`} and
394 > * `root/sessionAdded`/`root/sessionSummaryChanged` notifications.
395 > *
396 > * **Aggregation across chats.** Once a session contains more than one chat,
397 > * several `SessionSummary` fields are derived from the underlying
398 > * {@link SessionState.chats | chat catalog}. Producers SHOULD follow these
399 > * rules so clients that only consume the session summary (e.g. a session
400 > * list) still see meaningful state:
401 > *
402 > * - `status`: take the activity bits (`Idle` / `InProgress` / `InputNeeded` /
403 > * `Error` — bits 0–4) from the
404 > * {@link SessionState.defaultChat | default chat} when present, else from
405 > * the most recently modified chat. **Promote** `InputNeeded` whenever any
406 > * chat in the session needs input, and **promote** `Error` whenever any
407 > * chat is in an error state — both override the default-chat bits. The
408 > * orthogonal flag bits (`IsRead`, `IsArchived`) remain session-scoped.
409 > * - `activity`: mirror the activity string of the default chat, or of the
410 > * chat currently driving the promoted status bits when a non-default chat
411 > * wins (e.g. the chat that raised `InputNeeded`).
412 > * - `modifiedAt`: the max of all chats' `modifiedAt`.
413 > * - `workingDirectories`: the session-level set. Individual chats MAY restrict
414 > * to a subset via {@link ChatSummary.workingDirectories}; aggregating these
415 > * up is meaningless and SHOULD NOT be attempted.
416 > * - `changes`: optional roll-up across all chats. Producers MAY sum the
417 > * per-chat changeset stats or report the most expensive chat's stats —
418 > * whichever is cheaper for the host to compute.
419 > *
420 > * Sessions with a single chat trivially satisfy all of the above (the chat's
421 > * values pass through unchanged). The rules only matter once a session
422 > * carries multiple chats.
423 > *
424 > * @category Session State
425 > */
426 > export interface SessionSummary extends SessionMetadata {
427 > /** Session URI */
428 > resource: URI;
429 > /** Creation timestamp (ISO 8601, e.g. `"2025-03-10T18:42:03.123Z"`) */
430 > createdAt: string;
431 > /** Last modification timestamp (ISO 8601, e.g. `"2025-03-10T18:42:03.123Z"`) */
432 > modifiedAt: string;
433 > /**
434 > * Aggregate summary of file changes associated with this session. Servers
435 > * may populate this to give clients a quick at-a-glance view of the
436 > * session's footprint (e.g., for list rendering) without requiring the
437 > * client to subscribe to a changeset.
438 > */
439 > changes?: ChangesSummary;
440 > /**
441 > * Lightweight server-defined metadata clients may use for the session
442 > * presentation. The protocol does not interpret these values; producers
443 > * SHOULD keep the payload small because summaries appear in session lists
444 > * and session notifications.
445 > */
446 > _meta?: Record<string, unknown>;
447 > }
448 >
449 > /**
450 > * Aggregate counts describing the file changes associated with a session.
451 > *
452 > * All fields are optional so servers can populate only the metrics they
453 > * cheaply have available.
454 > *
455 > * @category Session State
456 > */
457 > export interface ChangesSummary {
458 > /** Total number of inserted lines across all changed files. */
459 > additions?: number;
460 > /** Total number of deleted lines across all changed files. */
461 > deletions?: number;
462 > /** Number of files that have changes. */
463 > files?: number;
464 > }
465 >
466 > // ─── Agent Selection ─────────────────────────────────────────────────────────
467 >
468 > /**
469 > * A selected custom agent for a session.
470 > *
471 > * The `uri` identifies a specific custom agent (matching an
472 > * {@link AgentCustomization.uri | `AgentCustomization.uri`} exposed via
473 > * the session's effective customizations). Consumers resolve the agent's
474 > * display name by looking up `uri` in the session's customization tree.
475 > *
476 > * A message with no `agent` selected uses the provider's default behavior.
477 > *
478 > * @category Session State
479 > */
480 > export interface AgentSelection {
481 > /** Stable agent URI (matches an {@link AgentCustomization.uri}). */
482 > uri: URI;
483 > }
484 >
485 > // ─── Session Config Types ────────────────────────────────────────────────────
486 >
487 > /**
488 > * A session configuration property descriptor.
489 > *
490 > * Extends the generic {@link ConfigPropertySchema} with session-specific
491 > * display extensions.
492 > *
493 > * @category Session Config Types
494 > */
495 > export interface SessionConfigPropertySchema extends ConfigPropertySchema {
496 > /**
497 > * Display extension: when `true`, the full set of allowed values is too large
498 > * to enumerate statically. The client SHOULD use `sessionConfigCompletions`
499 > * to fetch matching values based on user input. Any values in `enum` are
500 > * seed/recent values for initial display.
501 > */
502 > enumDynamic?: boolean;
503 > /** When `true`, the user may change this property after session creation */
504 > sessionMutable?: boolean;
505 > }
506 >
507 > /**
508 > * A JSON Schema object describing available session configuration metadata.
509 > *
510 > * @category Session Config Types
511 > */
512 > export interface SessionConfigSchema {
513 > /** JSON Schema: always `'object'` */
514 > type: 'object';
515 > /** JSON Schema: property descriptors keyed by property id */
516 > properties: Record<string, SessionConfigPropertySchema>;
517 > /** JSON Schema: list of required property ids */
518 > required?: string[];
519 > }
520 >
521 > /**
522 > * Live session configuration metadata.
523 > *
524 > * The schema describes the available configuration properties and the values
525 > * contain the current value for each resolved property.
526 > *
527 > * @category Session Config Types
528 > */
529 > export interface SessionConfigState {
530 > /** JSON Schema describing available configuration properties */
531 > schema: SessionConfigSchema;
532 > /** Current configuration values */
533 > values: Record<string, unknown>;
534 > }
535 >
536 > // ─── Tool Definition Types ───────────────────────────────────────────────────
537 >
538 > /**
539 > * Describes a tool available in a session, provided by either the server or the active client.
540 > *
541 > * @category Tool Definition Types
542 > */
543 > export interface ToolDefinition {
544 > /** Unique tool identifier */
545 > name: string;
546 > /** Human-readable display name */
547 > title?: string;
548 > /** Description of what the tool does */
549 > description?: string;
550 > /**
551 > * JSON Schema defining the expected input parameters.
552 > *
553 > * Optional because client-provided tools may not have formal schemas.
554 > * Mirrors MCP `Tool.inputSchema`.
555 > */
556 > inputSchema?: {
557 > type: 'object';
558 > properties?: Record<string, object>;
559 > required?: string[];
560 > };
561 > /**
562 > * JSON Schema defining the structure of the tool's output.
563 > *
564 > * Mirrors MCP `Tool.outputSchema`.
565 > */
566 > outputSchema?: {
567 > type: 'object';
568 > properties?: Record<string, object>;
569 > required?: string[];
570 > };
571 > /** Behavioral hints about the tool. All properties are advisory. */
572 > annotations?: ToolAnnotations;
573 > /**
574 > * Additional provider-specific metadata.
575 > *
576 > * Mirrors the MCP `_meta` convention.
577 > */
578 > _meta?: Record<string, unknown>;
579 > }
580 >
581 > /**
582 > * Behavioral hints about a tool. All properties are advisory and not
583 > * guaranteed to faithfully describe tool behavior.
584 > *
585 > * Mirrors MCP `ToolAnnotations` from the Model Context Protocol specification.
586 > *
587 > * @category Tool Definition Types
588 > */
589 > export interface ToolAnnotations {
590 > /** Alternate human-readable title */
591 > title?: string;
592 > /** Tool does not modify its environment (default: false) */
593 > readOnlyHint?: boolean;
594 > /** Tool may perform destructive updates (default: true) */
595 > destructiveHint?: boolean;
596 > /** Repeated calls with the same arguments have no additional effect (default: false) */
597 > idempotentHint?: boolean;
598 > /** Tool may interact with external entities (default: true) */
599 > openWorldHint?: boolean;
600 > }
601 >
602 > // ─── Customization Types ─────────────────────────────────────────────────────
603 >
604 > /**
605 > * Discriminant for the kind of customization.
606 > *
607 > * Top-level entries in {@link SessionState.customizations} and
608 > * {@link AgentInfo.customizations} are either container customizations
609 > * ({@link CustomizationType.Plugin | `Plugin`} or
610 > * {@link CustomizationType.Directory | `Directory`}) or
611 > * {@link CustomizationType.McpServer | `McpServer`} entries surfaced
612 > * directly by the host. The remaining types appear only as children of
613 > * a container.
614 > *
615 > * @category Customization Types
616 > */
617 > export const enum CustomizationType {
618 > Plugin = 'plugin',
619 > Directory = 'directory',
620 > Agent = 'agent',
621 > Skill = 'skill',
622 > Prompt = 'prompt',
623 > Rule = 'rule',
624 > Hook = 'hook',
625 > McpServer = 'mcpServer',
626 > }
627 >
628 > /**
629 > * Customization types that appear as children of a
630 > * {@link PluginCustomization} or {@link DirectoryCustomization}.
631 > *
632 > * @category Customization Types
633 > */
634 > export type ChildCustomizationType =
635 > | CustomizationType.Agent
636 > | CustomizationType.Skill
637 > | CustomizationType.Prompt
638 > | CustomizationType.Rule
639 > | CustomizationType.Hook
640 > | CustomizationType.McpServer;
641 >
642 > /**
643 > * Fields shared by every customization variant.
644 > *
645 > * @category Customization Types
646 > */
647 > interface CustomizationBase {
648 > /**
649 > * Session-unique opaque identifier. Used by every action that targets a
650 > * specific customization. Minted by whoever publishes the customization
651 > * (typically the agent host).
652 > */
653 > id: string;
654 > /**
655 > * Source URI for this customization. A plugin URL, a file URI, or a
656 > * directory URI.
657 > *
658 > * For declarations that live inside a larger file — e.g. an MCP
659 > * server declared inline in a `plugins.json` manifest — `uri` points
660 > * to the containing file and {@link CustomizationBase.range | `range`}
661 > * narrows it to the declaration's span.
662 > */
663 > uri: URI;
664 > /** Human-readable name. */
665 > name: string;
666 > /** Icons for UI display. */
667 > icons?: Icon[];
668 > /**
669 > * Optional span within {@link CustomizationBase.uri | `uri`} when this
670 > * customization is a subset of a larger file (for example, one entry
671 > * in an inline `mcpServers` block of a `plugins.json` manifest).
672 > * Absent when the customization covers the whole resource.
673 > */
674 > range?: TextRange;
675 > /**
676 > * Additional provider-specific metadata for this customization.
677 > *
678 > * Mirrors the MCP `_meta` convention. Optional and opaque to the
679 > * protocol; producers and consumers agree on its contents
680 > * out-of-band.
681 > */
682 > _meta?: Record<string, unknown>;
683 > }
684 >
685 > /**
686 > * Discriminant values for {@link CustomizationLoadState}.
687 > *
688 > * @category Customization Types
689 > */
690 > export const enum CustomizationLoadStatus {
691 > Loading = 'loading',
692 > Loaded = 'loaded',
693 > Degraded = 'degraded',
694 > Error = 'error',
695 > }
696 >
697 > /**
698 > * Container is being loaded by the host.
699 > *
700 > * @category Customization Types
701 > */
702 > export interface CustomizationLoadingState {
703 > kind: CustomizationLoadStatus.Loading;
704 > }
705 >
706 > /**
707 > * Container loaded successfully.
708 > *
709 > * @category Customization Types
710 > */
711 > export interface CustomizationLoadedState {
712 > kind: CustomizationLoadStatus.Loaded;
713 > }
714 >
715 > /**
716 > * Container partially loaded but has warnings.
717 > *
718 > * @category Customization Types
719 > */
720 > export interface CustomizationDegradedState {
721 > kind: CustomizationLoadStatus.Degraded;
722 > /** Human-readable description of the warning. */
723 > message: string;
724 > }
725 >
726 > /**
727 > * Container failed to load.
728 > *
729 > * @category Customization Types
730 > */
731 > export interface CustomizationErrorState {
732 > kind: CustomizationLoadStatus.Error;
733 > /** Human-readable error message. */
734 > message: string;
735 > }
736 >
737 > /**
738 > * Discriminated load state for a container customization
739 > * ({@link PluginCustomization} or {@link DirectoryCustomization}).
740 > *
741 > * @category Customization Types
742 > */
743 > export type CustomizationLoadState =
744 > | CustomizationLoadingState
745 > | CustomizationLoadedState
746 > | CustomizationDegradedState
747 > | CustomizationErrorState;
748 >
749 > /**
750 > * Fields shared by container customizations.
751 > *
752 > * @category Customization Types
753 > */
754 > interface ContainerCustomizationBase extends CustomizationBase {
755 > /** Whether this container is currently enabled. */
756 > enabled: boolean;
757 > /**
758 > * `clientId` of the client that contributed this container. Absent for
759 > * server-originated entries.
760 > */
761 > clientId?: string;
762 > /**
763 > * Host-reported load state. Absent means the host has not yet reported
764 > * a load state for this container.
765 > */
766 > load?: CustomizationLoadState;
767 > /**
768 > * Children discovered inside this container.
769 > *
770 > * Absent means the host has not parsed this container yet. An empty
771 > * array means the host parsed the container and it contributes
772 > * nothing.
773 > */
774 > children?: ChildCustomization[];
775 > }
776 >
777 > /**
778 > * An [Open Plugins](https://open-plugins.com/) plugin.
779 > *
780 > * @category Customization Types
781 > */
782 > export interface PluginCustomization extends ContainerCustomizationBase {
783 > type: CustomizationType.Plugin;
784 > /**
785 > * Version of the plugin, sourced from the
786 > * [Open Plugins](https://open-plugins.com/) manifest's optional
787 > * `version` field (semver, e.g. `"1.2.0"`). Absent when the manifest
788 > * declares no version — the field is optional there — or the source
789 > * has no version concept. Provenance / display only: the host neither
790 > * parses nor enforces it.
791 > */
792 > version?: string;
793 > }
794 >
795 > /**
796 > * A {@link PluginCustomization} as published by a client. Extends the
797 > * server-facing shape with an opaque `nonce` so the host can detect when
798 > * the client's view of a plugin has changed and re-parse only as needed.
799 > *
800 > * Clients SHOULD include a `nonce`. Server-side fields like
801 > * {@link ContainerCustomizationBase.children | `children`} and
802 > * {@link ContainerCustomizationBase.load | `load`} are typically left
803 > * absent on publication and populated by the host when the resolved
804 > * plugin appears in {@link SessionState.customizations}.
805 > *
806 > * @category Customization Types
807 > */
808 > export interface ClientPluginCustomization extends PluginCustomization {
809 > /** Opaque version token used by the host to detect changes. */
810 > nonce?: string;
811 > }
812 >
813 > /**
814 > * A directory the host watches for this session.
815 > *
816 > * Presence in the customization list signals that the host may discover
817 > * customizations from this directory. When `writable` is `true`, clients
818 > * MAY persist new customizations into the directory using
819 > * [`resourceWrite`](/reference/common#resourcewrite); the host will
820 > * then surface the resulting child via the customization actions.
821 > *
822 > * The directory may not yet exist on disk.
823 > *
824 > * @category Customization Types
825 > */
826 > export interface DirectoryCustomization extends ContainerCustomizationBase {
827 > type: CustomizationType.Directory;
828 > /** Which child customization type this directory holds. */
829 > contents: ChildCustomizationType;
830 > /** Whether clients may write into this directory. */
831 > writable: boolean;
832 > }
833 >
834 > /**
835 > * Fields shared by the leaf child customizations that live inside a
836 > * container — {@link AgentCustomization}, {@link SkillCustomization},
837 > * {@link PromptCustomization}, {@link RuleCustomization}, and
838 > * {@link HookCustomization}.
839 > *
840 > * {@link McpServerCustomization} is also a child but does not extend this
841 > * base: it always carries an explicit {@link McpServerCustomization.enabled}
842 > * because it can appear as a top-level customization too.
843 > *
844 > * @category Customization Types
845 > */
846 > interface ChildCustomizationBase extends CustomizationBase {
847 > /**
848 > * Whether this child is individually enabled. Absent means enabled, so a
849 > * producer only needs to set it to surface a child that exists but is
850 > * turned off on its own.
851 > *
852 > * This flag is independent of the parent container's: the **effective**
853 > * enabled state of a child is
854 > * `container.enabled && (child.enabled ?? true)`, so a disabled container
855 > * disables every child regardless of each child's own flag.
856 > *
857 > * A child is turned on or off by id with
858 > * {@link SessionCustomizationToggledAction | `session/customizationToggled`}.
859 > */
860 > enabled?: boolean;
861 > }
862 >
863 > /**
864 > * A custom agent contributed by a plugin or directory.
865 > *
866 > * Mirrors the [Open Plugins agent](https://open-plugins.com/agent-builders/components/agents)
867 > * format: a markdown file with YAML frontmatter, where the body is the
868 > * agent's system prompt.
869 > *
870 > * @category Customization Types
871 > */
872 > export interface AgentCustomization extends ChildCustomizationBase {
873 > type: CustomizationType.Agent;
874 > /**
875 > * Short description of what the agent specializes in and when to
876 > * invoke it. Sourced from the agent file's frontmatter `description`.
877 > */
878 > description?: string;
879 > /**
880 > * Model the agent is pinned to, sourced from the agent file's
881 > * frontmatter `model`. Absent means the agent inherits the session's
882 > * default model.
883 > */
884 > model?: string;
885 > /**
886 > * Allowlist of tool names the agent is scoped to, sourced from the
887 > * agent file's frontmatter `tools`. A non-empty list restricts the
888 > * agent to exactly those tools. Absent — or an empty list — imposes no
889 > * restriction beyond the session default: the agent may use any
890 > * available tool. Producers express "no restriction" by omitting the
891 > * field rather than sending an empty array, so an empty list carries no
892 > * meaning distinct from absence.
893 > */
894 > tools?: string[];
895 > /**
896 > * When `true`, the agent will not auto-delegate to this custom agent
897 > * as a sub-agent; it can only be selected by the user. Absent or
898 > * `false` means the agent may delegate to it.
899 > */
900 > disableModelInvocation?: boolean;
901 > /**
902 > * When `true`, the user cannot select this custom agent (for example,
903 > * in a picker); it remains available for the agent to auto-delegate
904 > * to. Absent or `false` means the user may select it.
905 > */
906 > disableUserInvocation?: boolean;
907 > }
908 >
909 > /**
910 > * A skill contributed by a plugin or directory.
911 > *
912 > * Covers both [Open Plugins skill formats](https://open-plugins.com/agent-builders/components/skills)
913 > * — the `skills/` directory layout (one subdirectory per skill, each with
914 > * a `SKILL.md`) and the flatter `commands/` directory of slash-command
915 > * skills.
916 > *
917 > * @category Customization Types
918 > */
919 > export interface SkillCustomization extends ChildCustomizationBase {
920 > type: CustomizationType.Skill;
921 > /**
922 > * Short description used for help text and auto-invocation matching.
923 > * Sourced from the skill's frontmatter `description`.
924 > */
925 > description?: string;
926 > /**
927 > * When `true`, only the user can invoke this skill — the agent will not
928 > * auto-invoke it. Sourced from the command skill's frontmatter
929 > * `disable-model-invocation` flag.
930 > */
931 > disableModelInvocation?: boolean;
932 > /**
933 > * When `true`, the user cannot directly invoke this skill (for example,
934 > * as a slash command); it remains available for the agent to
935 > * auto-invoke. Absent or `false` means the user may invoke it.
936 > */
937 > disableUserInvocation?: boolean;
938 > }
939 >
940 > /**
941 > * A prompt contributed by a plugin or directory.
942 > *
943 > * @category Customization Types
944 > */
945 > export interface PromptCustomization extends ChildCustomizationBase {
946 > type: CustomizationType.Prompt;
947 > /** Short description of what the prompt does. */
948 > description?: string;
949 > }
950 >
951 > /**
952 > * A rule contributed by a plugin or directory.
953 > *
954 > * Mirrors the [Open Plugins rule](https://open-plugins.com/agent-builders/components/rules)
955 > * format: a markdown file (e.g. `.mdc`) whose body is injected into
956 > * context while the rule is active. This type also covers tool-specific
957 > * "instruction" formats (e.g. VS Code Copilot's
958 > * `.github/instructions/*.md`), which differ only in naming — they
959 > * share the same semantics of `description`, optional always-on
960 > * activation, and optional glob scoping.
961 > *
962 > * @category Customization Types
963 > */
964 > export interface RuleCustomization extends ChildCustomizationBase {
965 > type: CustomizationType.Rule;
966 > /**
967 > * Description of what the rule enforces.
968 > */
969 > description?: string;
970 > /**
971 > * When `true`, the rule is always active (subject to `globs` if any).
972 > * When `false` or absent, the agent or user decides whether to apply
973 > * the rule.
974 > */
975 > alwaysApply?: boolean;
976 > /**
977 > * Glob patterns the rule applies to. When present, the rule is only
978 > * active for matching files.
979 > */
980 > globs?: string[];
981 > }
982 >
983 > /**
984 > * A hook manifest contributed by a plugin or directory.
985 > *
986 > * @category Customization Types
987 > */
988 > export interface HookCustomization extends ChildCustomizationBase {
989 > type: CustomizationType.Hook;
990 > }
991 >
992 > /**
993 > * An MCP server contributed by a plugin or directory.
994 > *
995 > * When the server is declared inline in the containing plugin manifest,
996 > * `uri` points at the manifest file and
997 > * {@link CustomizationBase.range | `range`} narrows it to the
998 > * declaration's span.
999 > *
1000 > * The MCP server customization also reflects its current status.
1001 > *
1002 > * @category Customization Types
1003 > */
1004 > export interface McpServerCustomization extends CustomizationBase {
1005 > type: CustomizationType.McpServer;
1006 > /**
1007 > * Whether this MCP server is currently enabled.
1008 > */
1009 > enabled: boolean;
1010 > /**
1011 > * Current lifecycle state of the MCP server.
1012 > */
1013 > state: McpServerState;
1014 > /**
1015 > * An `mcp://`-protocol channel the client uses to side-channel traffic
1016 > * into the upstream MCP server itself. The channel is NOT a fresh raw MCP
1017 > * connection: it piggybacks on the AHP transport
1018 > * and skips the MCP `initialize` sequence.
1019 > *
1020 > * The agent host MAY only serve a subset of MCP on this
1021 > * channel; the served subset is described by domain-specific
1022 > * capabilities such as those in
1023 > * {@link McpServerCustomizationApps.capabilities}.
1024 > *
1025 > * The channel URI SHOULD be stable across the server's lifetime, but
1026 > * the agent host MAY change it (for example across a restart) and
1027 > * MAY only expose it while the server is in
1028 > * {@link McpServerStatus.Ready | `Ready`}. Absence means no
1029 > * side-channel is currently available.
1030 > */
1031 > channel?: URI;
1032 > /**
1033 > * MCP App support. This property SHOULD be advertised for MCP servers
1034 > * which support apps.
1035 > */
1036 > mcpApp?: McpServerCustomizationApps;
1037 > }
1038 >
1039 > /**
1040 > * Information from the agent host needed to render MCP Apps served
1041 > * by this MCP server.
1042 > *
1043 > * @category MCP Server State
1044 > */
1045 > export interface McpServerCustomizationApps {
1046 > /**
1047 > * The subset of MCP App
1048 > * [`HostCapabilities`](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx)
1049 > * the AHP host can satisfy for Views backed by this server. The
1050 > * client feeds these straight through into the `hostCapabilities` of
1051 > * the `ui/initialize` response delivered to the View.
1052 > */
1053 > capabilities: AhpMcpUiHostCapabilities;
1054 > }
1055 >
1056 > /**
1057 > * The subset of MCP App
1058 > * [`HostCapabilities`](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx)
1059 > * an AHP host can derive from the upstream MCP server (and from AHP's own
1060 > * forwarding plumbing). Advertised on
1061 > * {@link McpServerCustomizationApps.capabilities} so clients can pass it
1062 > * through into the `hostCapabilities` of the `ui/initialize` response
1063 > * delivered to an MCP App View.
1064 > *
1065 > * Field names mirror the MCP Apps spec exactly, so the AHP-side producer
1066 > * can pass them straight through into the `hostCapabilities` of the
1067 > * `ui/initialize` response delivered to the View.
1068 > *
1069 > * Capabilities outside this set (`openLinks`, `downloadFile`, `sandbox`,
1070 > * `experimental`) are decided locally by whichever AHP client renders the
1071 > * View and are NOT part of this AHP-level advertisement — only the
1072 > * server-derived subset is.
1073 > *
1074 > * An agent host MUST only advertise a capability when it actually accepts the
1075 > * corresponding methods/notifications on the `mcp://` channel:
1076 > *
1077 > * - {@link serverTools}: host proxies `tools/list` and `tools/call` to
1078 > * the MCP server. When `listChanged` is `true`, the host also forwards
1079 > * `notifications/tools/list_changed`.
1080 > * - {@link serverResources}: host proxies `resources/read`,
1081 > * `resources/list`, and `resources/templates/list` to the MCP server.
1082 > * When `listChanged` is `true`, the host also forwards
1083 > * `notifications/resources/list_changed`.
1084 > * - {@link logging}: host accepts `notifications/message` log entries
1085 > * from the App and forwards them via `mcpNotification` (and forwards
1086 > * `logging/setLevel` calls to the server).
1087 > * - {@link sampling}: host serves `sampling/createMessage` via
1088 > * `mcpMethodCall`. When `sampling.tools` is present, the host also
1089 > * accepts SEP-1577 `tools` / `toolChoice` / `tool_use` content blocks
1090 > * inside `CreateMessageRequest`.
1091 > *
1092 > * @category MCP Server State
1093 > * @see {@link https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx | MCP Apps spec (SEP-1865)}
1094 > */
1095 > export interface AhpMcpUiHostCapabilities {
1096 > /** Producer proxies the MCP `tools/*` methods to the upstream server. */
1097 > serverTools?: {
1098 > /** Producer forwards `notifications/tools/list_changed` from the server. */
1099 > listChanged?: boolean;
1100 > };
1101 > /** Producer proxies the MCP `resources/*` methods to the upstream server. */
1102 > serverResources?: {
1103 > /** Producer forwards `notifications/resources/list_changed` from the server. */
1104 > listChanged?: boolean;
1105 > };
1106 > /** Producer accepts `notifications/message` log entries from the App via `mcpNotification`. */
1107 > logging?: Record<string, never>;
1108 > /** Producer serves `sampling/createMessage` via `mcpMethodCall`. */
1109 > sampling?: {
1110 > /**
1111 > * Producer accepts SEP-1577 `tools` / `toolChoice` / `tool_use` content
1112 > * blocks inside `CreateMessageRequest`.
1113 > */
1114 > tools?: Record<string, never>;
1115 > };
1116 > }
1117 >
1118 > /**
1119 > * Child customizations that live inside a {@link PluginCustomization} or
1120 > * {@link DirectoryCustomization}.
1121 > *
1122 > * @category Customization Types
1123 > */
1124 > export type ChildCustomization =
1125 > | AgentCustomization
1126 > | SkillCustomization
1127 > | PromptCustomization
1128 > | RuleCustomization
1129 > | HookCustomization
1130 > | McpServerCustomization;
1131 >
1132 > /**
1133 > * A top-level customization active in a session. Either a container
1134 > * ({@link PluginCustomization} or {@link DirectoryCustomization}) whose
1135 > * leaf customizations live in its
1136 > * {@link ContainerCustomizationBase.children | `children`} array, or a
1137 > * bare {@link McpServerCustomization} surfaced directly by the host.
1138 > *
1139 > * @category Customization Types
1140 > */
1141 > export type Customization =
1142 > | PluginCustomization
1143 > | DirectoryCustomization
1144 > | McpServerCustomization;
1145 >
1146 >
1147 > // ─── MCP Server State ────────────────────────────────────────────────────────
1148 >
1149 > /**
1150 > * Discriminant for the {@link McpServerState} union.
1151 > *
1152 > * @category MCP Server State
1153 > */
1154 > export const enum McpServerStatus {
1155 > /** Server has been registered but is not yet running. */
1156 > Starting = 'starting',
1157 > /** Server is running and serving requests. */
1158 > Ready = 'ready',
1159 > /**
1160 > * Server is reachable but requires additional authentication before it
1161 > * can start, or before it can serve a particular request. Carries the
1162 > * RFC 9728 Protected Resource Metadata the client needs to obtain a
1163 > * token; the client then pushes the token via the existing
1164 > * `authenticate` command.
1165 > */
1166 > AuthRequired = 'authRequired',
1167 > /** Server failed to start, crashed, or otherwise transitioned to a fatal error. */
1168 > Error = 'error',
1169 > /** Server has been shut down. */
1170 > Stopped = 'stopped',
1171 > }
1172 >
1173 > /**
1174 > * Why an MCP server is currently in the {@link McpServerStatus.AuthRequired}
1175 > * state. Mirrors the three failure modes defined by the
1176 > * [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization.md).
1177 > *
1178 > * @category MCP Server State
1179 > */
1180 > export const enum McpAuthRequiredReason {
1181 > /** No token has been provided yet (HTTP 401, no prior token). */
1182 > Required = 'required',
1183 > /** A previously valid token expired or was revoked (HTTP 401). */
1184 > Expired = 'expired',
1185 > /**
1186 > * Step-up auth: a token is present but its scopes are insufficient for
1187 > * the requested operation (HTTP 403 with
1188 > * `WWW-Authenticate: Bearer error="insufficient_scope"`).
1189 > *
1190 > * Unlike {@link Required} and {@link Expired} — which typically surface
1191 > * before any tool work is in flight — `InsufficientScope` is almost
1192 > * always triggered by an MCP request issued mid-turn (a `tools/call`,
1193 > * `resources/read`, etc.). The host SHOULD pair the
1194 > * {@link McpServerAuthRequiredState} transition with
1195 > * {@link SessionStatus.InputNeeded} on
1196 > * {@link SessionSummary.status | the session} so the activity becomes
1197 > * visible at the session-summary level, and clients SHOULD watch for
1198 > * this kind on any
1199 > * {@link McpServerCustomization | MCP server} backing a running tool
1200 > * call so they can present an explicit "grant more access" affordance
1201 > * tied to the blocked tool call.
1202 > */
1203 > InsufficientScope = 'insufficientScope',
1204 > }
1205 >
1206 > /**
1207 > * Server is registered with the host but has not yet started.
1208 > *
1209 > * @category MCP Server State
1210 > */
1211 > export interface McpServerStartingState {
1212 > kind: McpServerStatus.Starting;
1213 > }
1214 >
1215 > /**
1216 > * Server is running and serving requests.
1217 > *
1218 > * @category MCP Server State
1219 > */
1220 > export interface McpServerReadyState {
1221 > kind: McpServerStatus.Ready;
1222 > }
1223 >
1224 > /**
1225 > * A pre-registered OAuth client that clients use instead of dynamic client
1226 > * registration when resolving an MCP authentication challenge.
1227 > *
1228 > * @category MCP Server State
1229 > */
1230 > export interface McpOAuthClient {
1231 > /** OAuth client identifier registered with the authorization server. */
1232 > clientId: string;
1233 > /**
1234 > * OAuth client secret for a confidential client. Absence means the client is
1235 > * public and uses a secretless flow such as authorization code with PKCE.
1236 > */
1237 > clientSecret?: string;
1238 > }
1239 >
1240 > /**
1241 > * Reusable MCP authentication challenge — the RFC 9728 discovery info a
1242 > * client needs to obtain a token and push it via the `authenticate` command.
1243 > * Deliberately carries **no token**: this describes what is being asked for,
1244 > * never the ****** itself.
1245 > *
1246 > * Shared by two independent state machines that describe the same OAuth
1247 > * challenge from different vantage points:
1248 > *
1249 > * - {@link McpServerAuthRequiredState} — the MCP server itself cannot serve
1250 > * *any* request until the client authenticates.
1251 > * - {@link ToolCallAuthRequiredState} — a specific in-flight tool call is
1252 > * paused pending authentication (typically
1253 > * {@link McpAuthRequiredReason.InsufficientScope} step-up auth
1254 > * mid-execution). The server state and the tool-call state remain
1255 > * separate on purpose: the server saying "I need auth" and a tool
1256 > * invocation saying "I am waiting on that auth" are different facts that
1257 > * can be true independently.
1258 > *
1259 > * @category MCP Server State
1260 > */
1261 > export interface McpAuthRequirement {
1262 > /** Why authentication is required. */
1263 > reason: McpAuthRequiredReason;
1264 > /**
1265 > * Pre-registered OAuth client to use for authorization. When present, clients
1266 > * MUST use these credentials instead of dynamic client registration.
1267 > */
1268 > oauthClient?: McpOAuthClient;
1269 > /**
1270 > * RFC 9728 Protected Resource Metadata. The `resource` field is the
1271 > * canonical MCP server URI per RFC 8707, used as the OAuth `resource`
1272 > * indicator. `authorization_servers` is REQUIRED by the MCP
1273 > * authorization spec.
1274 > */
1275 > resource: ProtectedResourceMetadata;
1276 > /**
1277 > * Scopes required for the current challenge, parsed from the
1278 > * `WWW-Authenticate: ******"…"` header (or `scopes_supported`
1279 > * fallback). Authoritative for the next authorization request — clients
1280 > * MUST NOT assume any subset/superset relationship to
1281 > * `resource.scopes_supported`.
1282 > */
1283 > requiredScopes?: string[];
1284 > /** Human-readable hint, typically from the OAuth `error_description`. */
1285 > description?: string;
1286 > }
1287 >
1288 > /**
1289 > * Server is reachable but cannot serve requests until the client
1290 > * authenticates. Mirrors the discovery flow defined by
1291 > * [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728)
1292 > * (Protected Resource Metadata) and the OAuth 2.1 / RFC 6750 challenge
1293 > * semantics required by the MCP authorization spec.
1294 > *
1295 > * Clients react to this state by calling the existing `authenticate`
1296 > * command with the {@link ProtectedResourceMetadata.resource | resource}
1297 > * carried here. There is **no** `notify/authRequired` notification for
1298 > * MCP servers — the action stream is the single source of truth.
1299 > *
1300 > * When the transition is triggered by a request issued during a turn
1301 > * — most commonly
1302 > * {@link McpAuthRequiredReason.InsufficientScope | `InsufficientScope`}
1303 > * surfacing mid-tool-call — the host SHOULD also raise
1304 > * {@link SessionStatus.InputNeeded} on the session so the block is
1305 > * visible at the summary level. Clients SHOULD watch this status on
1306 > * any MCP server backing a running tool call and surface an explicit
1307 > * affordance (e.g. a "grant additional access" prompt) tied to that
1308 > * tool call, rather than relying on the user to notice the
1309 > * customization’s status badge.
1310 > *
1311 > * @category MCP Server State
1312 > */
1313 > export interface McpServerAuthRequiredState extends McpAuthRequirement {
1314 > kind: McpServerStatus.AuthRequired;
1315 > }
1316 >
1317 > /**
1318 > * Server failed to start, crashed, or otherwise transitioned to a
1319 > * non-recoverable error. Use {@link McpServerStatus.AuthRequired}
1320 > * for authentication failures.
1321 > *
1322 > * @category MCP Server State
1323 > */
1324 > export interface McpServerErrorState {
1325 > kind: McpServerStatus.Error;
1326 > /** Error details. */
1327 > error: ErrorInfo;
1328 > }
1329 >
1330 > /**
1331 > * Server has been shut down. The host MAY remove the server from the
1332 > * session entirely shortly after this state.
1333 > *
1334 > * @category MCP Server State
1335 > */
1336 > export interface McpServerStoppedState {
1337 > kind: McpServerStatus.Stopped;
1338 > }
1339 >
1340 > /**
1341 > * Discriminated union of all MCP server lifecycle states.
1342 > * Discriminated by `kind` (a {@link McpServerStatus} value).
1343 > *
1344 > * @category MCP Server State
1345 > */
1346 > export type McpServerState =
1347 > | McpServerStartingState
1348 > | McpServerReadyState
1349 > | McpServerAuthRequiredState
1350 > | McpServerErrorState
1351 > | McpServerStoppedState;
src/vs/platform/agentHost/common/state/protocol/common/commands.ts 1071 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commands.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI, Snapshot } from './state.js';
10 > import type { ActionEnvelope, StateAction } from './actions.js';
11 > import type { TelemetryCapabilities } from '../channels-otlp/state.js';
12 >
13 > // ─── BaseParams ──────────────────────────────────────────────────────────────
14 >
15 > /**
16 > * Base shape every command's params extends.
17 > *
18 > * `channel` identifies the channel the command targets, mirroring the
19 > * `channel` field on every protocol notification. For commands that operate
20 > * on a specific channel (a session, terminal, or changeset), `channel` is
21 > * that channel's URI. For commands that are connection-level rather than
22 > * channel-scoped (e.g. {@link InitializeParams | `initialize`},
23 > * {@link PingParams | `ping`}, {@link ListSessionsParams | `listSessions`},
24 > * the `resource*` filesystem commands, and {@link AuthenticateParams |
25 > * `authenticate`}), the params type narrows `channel` to the literal
26 > * root URI `'ahp-root://'`.
27 > *
28 > * This invariant lets implementations route every incoming message —
29 > * request, response, or notification — by inspecting `params.channel`
30 > * without needing to know the per-method param shape.
31 > *
32 > * @category Commands
33 > */
34 > export interface BaseParams {
35 > /** Channel URI this command targets. */
36 > channel: URI;
37 > }
38 >
39 > // ─── Pagination ──────────────────────────────────────────────────────────────
40 >
41 > /**
42 > * Cursor-based pagination inputs, mixed into the params of any list command
43 > * that can page a large result set (e.g. {@link ListSessionsParams |
44 > * `listSessions`}). The paired output is {@link PaginatedResult}.
45 > *
46 > * Pagination is **opaque and cursor-based**, mirroring the shape `fetchTurns`
47 > * already uses for chat history: the server owns the ordering and keyset, and
48 > * the client walks pages by echoing the cursor from the previous
49 > * {@link PaginatedResult.nextCursor} back on the next request.
50 > *
51 > * The contract every paginated command shares:
52 > *
53 > * - To fetch the first page, omit `cursor`. Supply `limit` to bound the page.
54 > * - If the result carries a {@link PaginatedResult.nextCursor}, more entries
55 > * exist — pass it back as `cursor` to fetch the following page. A missing
56 > * `nextCursor` signals the end of the collection.
57 > * - Cursors are **server-defined and opaque**: clients MUST NOT parse, modify,
58 > * or persist them across connections. An unrecognised cursor SHOULD be
59 > * rejected with an `InvalidParams` error.
60 > * - Pagination is **fully additive**: a client that omits `limit`/`cursor` and
61 > * ignores `nextCursor` sees the pre-pagination behaviour (subject to any
62 > * server-imposed cap), and a server that does not paginate ignores the inputs
63 > * and returns everything in a single page.
64 > *
65 > * @category Commands
66 > */
67 > export interface PaginatedParams {
68 > /**
69 > * Maximum number of entries to return in this page. The server SHOULD respect
70 > * this bound but MAY return fewer entries and MAY impose its own upper cap.
71 > * Omit to let the server choose the page size.
72 > */
73 > limit?: number;
74 > /**
75 > * Opaque pagination cursor from a previous {@link PaginatedResult.nextCursor}.
76 > * Omit to fetch the first page. Cursors are server-defined and MUST be treated
77 > * as opaque — do not parse, modify, or persist them across connections. An
78 > * unrecognised cursor SHOULD be rejected with an `InvalidParams` error.
79 > */
80 > cursor?: string;
81 > }
82 >
83 > /**
84 > * Cursor-based pagination output, extended by the result of any list command
85 > * that can page a large result set (e.g. {@link ListSessionsResult |
86 > * `listSessions`}). See {@link PaginatedParams} for the full pagination
87 > * contract shared by every paginated command.
88 > *
89 > * @category Commands
90 > */
91 > export interface PaginatedResult {
92 > /**
93 > * Opaque cursor for the next page. Present when more entries exist beyond the
94 > * returned page; absent signals the end of the collection. Pass it back as
95 > * {@link PaginatedParams.cursor} to fetch the following page.
96 > */
97 > nextCursor?: string;
98 > }
99 >
100 > // ─── initialize ──────────────────────────────────────────────────────────────
101 >
102 > /**
103 > * Identifies a protocol implementation — the software (and build) on one end
104 > * of the connection, as distinct from the {@link AgentInfo | agent persona} it
105 > * hosts. Carried as {@link InitializeParams.clientInfo | `clientInfo`} on the
106 > * client side and {@link InitializeResult.serverInfo | `serverInfo`} on the
107 > * server side, mirroring LSP's `clientInfo`/`serverInfo` and MCP's
108 > * `Implementation`.
109 > *
110 > * This is **informational only**: it exists for logging, telemetry, an
111 > * about/status affordance, and — as a last resort — a known-issue workaround
112 > * for a specific buggy build. It is **not** a feature-detection mechanism.
113 > * Feature availability stays with the capability model
114 > * ({@link ClientCapabilities} and the various `*.capabilities` declarations);
115 > * implementations SHOULD NOT gate protocol behaviour on parsing
116 > * {@link Implementation.version | `version`}.
117 > *
118 > * @category Commands
119 > */
120 > export interface Implementation {
121 > /** Implementation name, e.g. a product or package identifier. */
122 > name: string;
123 > /**
124 > * Implementation version. A [SemVer](https://semver.org) string is
125 > * recommended but not required.
126 > */
127 > version?: string;
128 > /** Optional human-readable display name. */
129 > title?: string;
130 > }
131 >
132 > /**
133 > * Establishes a new connection and negotiates the protocol version.
134 > * This MUST be the first message sent by the client.
135 > *
136 > * @category Commands
137 > * @method initialize
138 > * @direction Client → Server
139 > * @messageType Request
140 > * @version 1
141 > * @see {@link /specification/lifecycle | Lifecycle} for the full handshake flow.
142 > */
143 > export interface InitializeParams extends BaseParams {
144 > channel: 'ahp-root://';
145 > /**
146 > * Protocol versions the client is willing to speak, ordered from most
147 > * preferred to least preferred. Each entry is a [SemVer](https://semver.org)
148 > * `MAJOR.MINOR.PATCH` string (e.g. `"0.1.0"`).
149 > *
150 > * The server selects one entry and returns it as `InitializeResult.protocolVersion`.
151 > * If the server cannot speak any of the offered versions, it MUST return
152 > * error code `-32005` (`UnsupportedProtocolVersion`).
153 > */
154 > protocolVersions: string[];
155 > /** Unique client identifier */
156 > clientId: string;
157 > /**
158 > * Optional identity of the client implementation (name and version).
159 > * Informational only — see {@link Implementation} for how it may and may not
160 > * be used. Distinct from {@link InitializeParams.clientId | `clientId`},
161 > * which is an opaque per-connection identifier used for reconnection, not a
162 > * human-readable implementation name.
163 > */
164 > clientInfo?: Implementation;
165 > /** URIs to subscribe to during handshake */
166 > initialSubscriptions?: URI[];
167 > /**
168 > * IETF BCP 47 language tag indicating the client's preferred locale
169 > * (e.g. `"en-US"`, `"ja"`). The server SHOULD use this to localise
170 > * user-facing strings such as confirmation option labels.
171 > */
172 > locale?: string;
173 > /**
174 > * Optional client capability declarations.
175 > *
176 > * Servers SHOULD only advertise features whose corresponding client
177 > * capability is set here. Absent means "not declared" — the server
178 > * MUST assume the client does not support the feature.
179 > */
180 > capabilities?: ClientCapabilities;
181 > }
182 >
183 > /**
184 > * Optional capabilities a client declares during `initialize`.
185 > *
186 > * Each field is a presence flag: an empty object `{}` means "supported",
187 > * absence means "not supported". Sub-fields on individual capabilities
188 > * are reserved for future per-capability options.
189 > *
190 > * @category Commands
191 > */
192 > export interface ClientCapabilities {
193 > /**
194 > * Client can render
195 > * [MCP Apps](https://github.com/modelcontextprotocol/ext-apps) — i.e.
196 > * it can host the View sandbox, run the `ui/*` protocol against it,
197 > * and forward `mcp://`-channel traffic on the App's behalf.
198 > *
199 > * Hosts SHOULD only populate
200 > * {@link McpServerCustomization.mcpApp | `McpServerCustomization.mcpApp`}
201 > * (and expose the corresponding
202 > * {@link McpServerCustomization.channel | `mcp://` channel}) when this
203 > * capability is declared. Clients that omit it MUST treat
204 > * App-bearing tool calls as ordinary MCP tool calls.
205 > */
206 > mcpApps?: Record<string, never>;
207 > }
208 >
209 > /**
210 > * Result of the `initialize` command.
211 > *
212 > * `protocolVersion` is the version the server has selected from the client's
213 > * `protocolVersions` list. The client and server MUST use this version for
214 > * the rest of the connection. If the server cannot speak any of the offered
215 > * versions it MUST return error code `-32005` (`UnsupportedProtocolVersion`)
216 > * instead of a result.
217 > */
218 > export interface InitializeResult {
219 > /**
220 > * Protocol version selected by the server. MUST be one of the entries in
221 > * `InitializeParams.protocolVersions`. Formatted as a [SemVer](https://semver.org)
222 > * `MAJOR.MINOR.PATCH` string (e.g. `"0.1.0"`).
223 > */
224 > protocolVersion: string;
225 > /** Current server sequence number */
226 > serverSeq: number;
227 > /**
228 > * Optional identity of the server implementation (name and version).
229 > * Informational only — see {@link Implementation} for how it may and may not
230 > * be used. Whereas {@link InitializeResult.protocolVersion | `protocolVersion`}
231 > * identifies the negotiated protocol, `serverInfo` identifies the host
232 > * software behind it.
233 > */
234 > serverInfo?: Implementation;
235 > /** Snapshots for each `initialSubscriptions` URI */
236 > snapshots: Snapshot[];
237 > /** Suggested default directory for remote filesystem browsing */
238 > defaultDirectory?: URI;
239 > /**
240 > * Characters that, when typed in a {@link Message} input, SHOULD cause
241 > * the client to issue a `completions` request with
242 > * {@link CompletionItemKind.UserMessage}. Typically includes characters like
243 > * `'@'` or `'/'`.
244 > */
245 > completionTriggerCharacters?: string[];
246 > /**
247 > * Prefix that the host recognizes at the start of a user {@link Message.text}
248 > * as a shorthand for executing the remainder as a terminal command. Currently
249 > * the standardized convention is `"!"`; absence means the host does not
250 > * support command prefixes.
251 > */
252 > terminalCommandPrefix?: string;
253 > /**
254 > * OTLP telemetry channels the host emits, if any. Each populated field is
255 > * either a literal `ahp-otlp:` channel URI or an RFC 6570 URI template a
256 > * client expands before subscribing (currently only the `logs` channel
257 > * defines a template variable, `{level}`, for subscriber-side severity
258 > * filtering). Clients MAY ignore signals they cannot process.
259 > *
260 > * @see {@link /specification/telemetry-channel | Telemetry Channel}
261 > */
262 > telemetry?: TelemetryCapabilities;
263 > }
264 >
265 > // ─── ping ────────────────────────────────────────────────────────────────────
266 >
267 > /**
268 > * Verifies that the AHP connection is still alive and keeps it from being
269 > * closed by idle-timeout intermediaries (proxies, load balancers, etc.).
270 > *
271 > * The server MUST respond regardless of whether the client has completed
272 > * `initialize` or holds any subscriptions. Ping carries no payload in either
273 > * direction; the response itself is the signal.
274 > *
275 > * @category Commands
276 > * @method ping
277 > * @direction Client → Server
278 > * @messageType Request
279 > * @version 1
280 > */
281 > export interface PingParams extends BaseParams {
282 > channel: 'ahp-root://';
283 > }
284 >
285 > // ─── reconnect ───────────────────────────────────────────────────────────────
286 >
287 > /**
288 > * Discriminant for reconnect result types.
289 > *
290 > * @category Commands
291 > */
292 > export const enum ReconnectResultType {
293 > Replay = 'replay',
294 > Snapshot = 'snapshot',
295 > }
296 >
297 > /**
298 > * Re-establishes a dropped connection. The server replays missed actions or
299 > * provides fresh snapshots.
300 > *
301 > * @category Commands
302 > * @method reconnect
303 > * @direction Client → Server
304 > * @messageType Request
305 > * @version 1
306 > * @see {@link /specification/lifecycle | Lifecycle} for details.
307 > */
308 > export interface ReconnectParams extends BaseParams {
309 > channel: 'ahp-root://';
310 > /** Client identifier from the original connection */
311 > clientId: string;
312 > /** Last `serverSeq` the client received */
313 > lastSeenServerSeq: number;
314 > /** URIs the client was subscribed to */
315 > subscriptions: URI[];
316 > }
317 >
318 > /**
319 > * Reconnect result when the server can replay from the requested sequence.
320 > *
321 > * The server MUST include all replayed data in the response.
322 > */
323 > export interface ReconnectReplayResult {
324 > /** Discriminant */
325 > type: ReconnectResultType.Replay;
326 > /** Missed action envelopes since `lastSeenServerSeq` */
327 > actions: ActionEnvelope[];
328 > /**
329 > * URIs from `ReconnectParams.subscriptions` that the server cannot resume.
330 > * This includes resources that no longer exist (e.g. disposed sessions or
331 > * terminals) as well as resources the client is no longer permitted to
332 > * observe. Clients SHOULD drop these from their local subscription set.
333 > */
334 > missing: URI[];
335 > }
336 >
337 > /**
338 > * Reconnect result when the gap exceeds the replay buffer.
339 > */
340 > export interface ReconnectSnapshotResult {
341 > /** Discriminant */
342 > type: ReconnectResultType.Snapshot;
343 > /** Fresh snapshots for each subscription */
344 > snapshots: Snapshot[];
345 > }
346 >
347 > /** Result of the `reconnect` command. */
348 > export type ReconnectResult = ReconnectReplayResult | ReconnectSnapshotResult;
349 >
350 > // ─── subscribe ───────────────────────────────────────────────────────────────
351 >
352 > /**
353 > * Subscribe to a URI-identified channel.
354 > *
355 > * A channel MAY have state associated with it (e.g. root, sessions,
356 > * terminals) or be stateless (pure pub/sub for streaming data). For
357 > * state-bearing channels the result includes a snapshot; for stateless
358 > * channels `snapshot` is omitted.
359 > *
360 > * @category Commands
361 > * @method subscribe
362 > * @direction Client → Server
363 > * @messageType Request
364 > * @version 1
365 > * @see {@link /specification/subscriptions | Subscriptions}
366 > */
367 > export interface SubscribeParams extends BaseParams {
368 > /**
369 > * Optional delivery preferences for this subscription.
370 > *
371 > * Servers MAY use these preferences to buffer and coalesce high-frequency
372 > * updates while preserving the same reduced state. Omit this field for the
373 > * server's default delivery behavior.
374 > */
375 > delivery?: SubscriptionDeliveryOptions;
376 > /**
377 > * Optional client-requested shape for the returned snapshot.
378 > *
379 > * Servers that do not understand a requested view ignore it and return their
380 > * default snapshot. Clients MUST tolerate receiving more state than requested.
381 > */
382 > view?: SubscribeView;
383 > }
384 >
385 > /**
386 > * Optional client-requested shape for a subscription snapshot.
387 > *
388 > * @category Commands
389 > */
390 > export interface SubscribeView {
391 > /**
392 > * Advisory number of most-recent completed turns to expose in a chat
393 > * snapshot.
394 > *
395 > * Servers MAY return more or fewer turns than requested. When omitted, the
396 > * host MUST return all retained turns. When older turns remain available, the
397 > * returned {@link ChatState} carries `turnsNextCursor`; clients pass that
398 > * cursor to `fetchTurns` to ask the host to page more turns into the chat
399 > * state.
400 > */
401 > turns?: number;
402 > }
403 >
404 > /**
405 > * Advisory delivery preferences for a single subscription.
406 > *
407 > * @category Commands
408 > */
409 > export interface SubscriptionDeliveryOptions {
410 > /**
411 > * Maximum time, in milliseconds, that the server may intentionally delay
412 > * delivery while buffering/coalescing updates for this subscription.
413 > *
414 > * A value of `0` requests immediate delivery with no intentional coalescing.
415 > */
416 > maxLatencyMs?: number;
417 > }
418 >
419 > /**
420 > * Result of the `subscribe` command.
421 > *
422 > * `snapshot` is present when the subscribed channel has associated state, and
423 > * absent for stateless channels.
424 > */
425 > export interface SubscribeResult {
426 > /** Snapshot of the subscribed channel's state (omitted for stateless channels) */
427 > snapshot?: Snapshot;
428 > }
429 >
430 > // ─── unsubscribe ─────────────────────────────────────────────────────────────
431 >
432 > /**
433 > * Stop receiving updates for a channel.
434 > *
435 > * @category Commands
436 > * @method unsubscribe
437 > * @direction Client → Server
438 > * @messageType Notification
439 > * @version 1
440 > * @see {@link /specification/subscriptions | Subscriptions}
441 > */
442 > export interface UnsubscribeParams {
443 > /** Channel URI to unsubscribe from */
444 > channel: URI;
445 > }
446 >
447 > // ─── dispatchAction ──────────────────────────────────────────────────────────
448 >
449 > /**
450 > * Fire-and-forget action dispatch (write-ahead). The client applies actions
451 > * optimistically to local state and the server echoes them back as an
452 > * {@link ActionEnvelope} once accepted.
453 > *
454 > * The client → server method is named `dispatchAction`; the server's reply
455 > * arrives on the server → client `action` notification (params:
456 > * {@link ActionEnvelope}).
457 > *
458 > * @category Commands
459 > * @method dispatchAction
460 > * @direction Client → Server
461 > * @messageType Notification
462 > * @version 1
463 > * @see {@link /guide/actions | Actions} for the full list of client-dispatchable actions.
464 > */
465 > export interface DispatchActionParams {
466 > /** Channel URI this action targets */
467 > channel: URI;
468 > /** Client sequence number */
469 > clientSeq: number;
470 > /** The action to dispatch */
471 > action: StateAction;
472 > }
473 >
474 > // ─── resourceRead ────────────────────────────────────────────────────────
475 >
476 > /**
477 > * Encoding of fetched content data.
478 > *
479 > * @category Commands
480 > */
481 > export const enum ContentEncoding {
482 > Base64 = 'base64',
483 > Utf8 = 'utf-8',
484 > }
485 >
486 > /**
487 > * Reads the content of a resource by URI.
488 > *
489 > * Content references keep the state tree small by storing large data (images,
490 > * long tool outputs) by reference rather than inline.
491 > *
492 > * Binary content (images, etc.) MUST use `base64` encoding. Text content MAY
493 > * use `utf-8` encoding.
494 > *
495 > * Like all `resource*` methods, `resourceRead` is symmetrical and MAY be
496 > * sent in either direction. Hosts use it to fetch content from a
497 > * client-published URI (e.g. `virtual://my-client/...` plugins); clients
498 > * use it to read host-side files. The receiver enforces access via the
499 > * same permission/`resourceRequest` flow regardless of which peer initiated.
500 > *
501 > * @category Commands
502 > * @method resourceRead
503 > * @direction Client ↔ Server
504 > * @messageType Request
505 > * @version 1
506 > * @throws `NotFound` (`-32008`) if the URI does not exist.
507 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to read the URI.
508 > * @example
509 > * ```jsonc
510 > * // Client → Server
511 > * { "jsonrpc": "2.0", "id": 10, "method": "resourceRead",
512 > * "params": { "uri": "ahp-session:/<uuid>/content/img-1" } }
513 > *
514 > * // Server → Client
515 > * { "jsonrpc": "2.0", "id": 10, "result": {
516 > * "data": "iVBORw0KGgo...",
517 > * "encoding": "base64",
518 > * "contentType": "image/png"
519 > * }}
520 > * ```
521 > */
522 > export interface ResourceReadParams extends BaseParams {
523 > channel: 'ahp-root://';
524 > /** Content URI from a `ContentRef` */
525 > uri: string;
526 > /** Preferred encoding for the returned data (default: server-chosen) */
527 > encoding?: ContentEncoding;
528 > }
529 >
530 > /**
531 > * Result of the `resourceRead` command.
532 > *
533 > * The server SHOULD honor the `encoding` requested in the params. If the
534 > * server cannot provide the requested encoding, it MUST fall back to either
535 > * `base64` or `utf-8`.
536 > */
537 > export interface ResourceReadResult {
538 > /** Content encoded as a string */
539 > data: string;
540 > /** How `data` is encoded */
541 > encoding: ContentEncoding;
542 > /** Content type (e.g. `"image/png"`, `"text/plain"`) */
543 > contentType?: string;
544 > }
545 >
546 > // ─── resourceWrite ───────────────────────────────────────────────────────────
547 >
548 > /**
549 > * How {@link ResourceWriteParams.data} is placed within the target file.
550 > *
551 > * Each mode interprets {@link ResourceWriteParams.position} differently:
552 > *
553 > * - `truncate` (default): rooted at the **start** of the file. The file is
554 > * truncated at `position` (0 by default) and `data` is written from that
555 > * offset, so the resulting file is `existing[0..position] + data`. With
556 > * `position` omitted this is a full overwrite.
557 > * - `append`: rooted at the **end** of the file. `position` counts bytes
558 > * backwards from EOF, so `position: 0` (the default) writes at EOF —
559 > * POSIX append — and `position: 5` inserts `data` 5 bytes before the
560 > * current EOF, shifting those trailing 5 bytes after the inserted region.
561 > * The server MUST evaluate the effective EOF and write atomically with
562 > * respect to other appenders so concurrent `append` writes do not
563 > * clobber each other.
564 > * - `insert`: rooted at the **start** of the file. `position` (0 by default)
565 > * is the byte offset at which `data` is spliced in; bytes at or after
566 > * `position` are shifted right by `data.length`. `insert` always grows
567 > * the file — use `truncate` to overwrite bytes in place.
568 > *
569 > * @category Commands
570 > */
571 > export const enum ResourceWriteMode {
572 > Truncate = 'truncate',
573 > Append = 'append',
574 > Insert = 'insert',
575 > }
576 >
577 > /**
578 > * Writes content to a file on the server's filesystem.
579 > *
580 > * Binary content (images, etc.) MUST use `base64` encoding. Text content MAY
581 > * use `utf-8` encoding.
582 > *
583 > * If the file does not exist, it is created. If the file already exists, the
584 > * effect on existing bytes depends on {@link ResourceWriteParams.mode}:
585 > * `truncate` (default) overwrites from the chosen offset onward, `append`
586 > * preserves all existing bytes and adds `data` at a position rooted at EOF,
587 > * and `insert` preserves all existing bytes and splices `data` in at an
588 > * offset rooted at the start of the file.
589 > *
590 > * Like all `resource*` methods, `resourceWrite` is symmetrical and MAY be
591 > * sent in either direction.
592 > *
593 > * @category Commands
594 > * @method resourceWrite
595 > * @direction Client ↔ Server
596 > * @messageType Request
597 > * @version 1
598 > * @throws `NotFound` (`-32008`) if the parent directory does not exist.
599 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to write to the path.
600 > * @throws `AlreadyExists` (`-32010`) if `createOnly` is set and the file already exists.
601 > * @throws `Conflict` (`-32011`) if `ifMatch` is set and the current `etag` does not match.
602 > * @example
603 > * ```jsonc
604 > * // Client → Server
605 > * { "jsonrpc": "2.0", "id": 11, "method": "resourceWrite",
606 > * "params": { "uri": "file:///workspace/hello.txt", "data": "SGVsbG8=",
607 > * "encoding": "base64", "contentType": "text/plain" } }
608 > *
609 > * // Server → Client
610 > * { "jsonrpc": "2.0", "id": 11, "result": {} }
611 > * ```
612 > */
613 > export interface ResourceWriteParams extends BaseParams {
614 > channel: 'ahp-root://';
615 > /** Target file URI on the server filesystem */
616 > uri: URI;
617 > /** Content encoded as a string */
618 > data: string;
619 > /** How `data` is encoded */
620 > encoding: ContentEncoding;
621 > /** Content type (e.g. `"text/plain"`, `"image/png"`) */
622 > contentType?: string;
623 > /**
624 > * If `true`, the server MUST fail if the file already exists instead of
625 > * overwriting it. Useful for safe creation of new files.
626 > */
627 > createOnly?: boolean;
628 > /**
629 > * How `data` is placed within the target file. Defaults to `'truncate'`
630 > * (full overwrite) when omitted. See {@link ResourceWriteMode} for the
631 > * meaning of each mode and how it interprets {@link position}.
632 > */
633 > mode?: ResourceWriteMode;
634 > /**
635 > * Byte offset interpreted according to {@link mode}. Defaults to `0`.
636 > * - `truncate`: offset from the start of the file at which to truncate
637 > * before writing.
638 > * - `append`: bytes back from EOF at which to insert `data`.
639 > * - `insert`: offset from the start of the file at which to splice in
640 > * `data`.
641 > */
642 > position?: number;
643 > /**
644 > * Optimistic-concurrency token previously returned by
645 > * {@link ResourceResolveResult.etag}. When set, the server MUST fail with
646 > * `Conflict` if the current `etag` does not match — preventing lost
647 > * updates between a `resourceResolve` and a subsequent `resourceWrite`.
648 > */
649 > ifMatch?: string;
650 > }
651 >
652 > /**
653 > * Result of the `resourceWrite` command.
654 > *
655 > * An empty object on success.
656 > */
657 > export interface ResourceWriteResult {
658 > }
659 >
660 > // ─── resourceList ────────────────────────────────────────────────────────
661 >
662 > /**
663 > * Lists directory entries at a file URI on the server's filesystem.
664 > *
665 > * This is intended for remote folder pickers and similar UI that needs to let
666 > * users navigate the server's local filesystem.
667 > *
668 > * The server MUST return success only if the target exists and is a directory.
669 > * If the target does not exist, is not a directory, or cannot be accessed, the
670 > * server MUST return a JSON-RPC error.
671 > *
672 > * Like all `resource*` methods, `resourceList` is symmetrical and MAY be
673 > * sent in either direction.
674 > *
675 > * @category Commands
676 > * @method resourceList
677 > * @direction Client ↔ Server
678 > * @messageType Request
679 > * @version 1
680 > * @throws `NotFound` (`-32008`) if the directory does not exist.
681 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to browse the directory.
682 > */
683 > export interface ResourceListParams extends BaseParams {
684 > channel: 'ahp-root://';
685 > /** Directory URI on the server filesystem */
686 > uri: URI;
687 > }
688 >
689 > /**
690 > * Directory entry returned by `resourceList`.
691 > */
692 > export interface DirectoryEntry {
693 > /** Base name of the entry */
694 > name: string;
695 > /** Whether the entry is a file or directory */
696 > type: 'file' | 'directory';
697 > }
698 >
699 > /**
700 > * Result of the `resourceList` command.
701 > */
702 > export interface ResourceListResult {
703 > /** Entries directly contained in the requested directory */
704 > entries: DirectoryEntry[];
705 > }
706 >
707 > // ─── resourceCopy ────────────────────────────────────────────────────────────
708 >
709 > /**
710 > * Copies a resource from one URI to another on the server's filesystem.
711 > *
712 > * If the destination already exists, it is overwritten unless `failIfExists`
713 > * is set.
714 > *
715 > * Like all `resource*` methods, `resourceCopy` is symmetrical and MAY be
716 > * sent in either direction.
717 > *
718 > * @category Commands
719 > * @method resourceCopy
720 > * @direction Client ↔ Server
721 > * @messageType Request
722 > * @version 1
723 > * @throws `NotFound` (`-32008`) if the source does not exist.
724 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to read the source or write to the destination.
725 > * @throws `AlreadyExists` (`-32010`) if `failIfExists` is set and the destination already exists.
726 > */
727 > export interface ResourceCopyParams extends BaseParams {
728 > channel: 'ahp-root://';
729 > /** Source URI to copy from */
730 > source: URI;
731 > /** Destination URI to copy to */
732 > destination: URI;
733 > /**
734 > * If `true`, the server MUST fail if the destination already exists instead
735 > * of overwriting it.
736 > */
737 > failIfExists?: boolean;
738 > }
739 >
740 > /**
741 > * Result of the `resourceCopy` command.
742 > *
743 > * An empty object on success.
744 > */
745 > export interface ResourceCopyResult {
746 > }
747 >
748 > // ─── resourceDelete ──────────────────────────────────────────────────────────
749 >
750 > /**
751 > * Deletes a resource at a URI on the server's filesystem.
752 > *
753 > * Like all `resource*` methods, `resourceDelete` is symmetrical and MAY be
754 > * sent in either direction.
755 > *
756 > * @category Commands
757 > * @method resourceDelete
758 > * @direction Client ↔ Server
759 > * @messageType Request
760 > * @version 1
761 > * @throws `NotFound` (`-32008`) if the resource does not exist.
762 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to delete the resource.
763 > */
764 > export interface ResourceDeleteParams extends BaseParams {
765 > channel: 'ahp-root://';
766 > /** URI of the resource to delete */
767 > uri: URI;
768 > /**
769 > * If `true` and the target is a directory, delete it and all its contents
770 > * recursively. If `false` (default), deleting a non-empty directory MUST fail.
771 > */
772 > recursive?: boolean;
773 > }
774 >
775 > /**
776 > * Result of the `resourceDelete` command.
777 > *
778 > * An empty object on success.
779 > */
780 > export interface ResourceDeleteResult {
781 > }
782 >
783 > // ─── resourceRequest ─────────────────────────────────────────────────────────
784 >
785 > /**
786 > * Requests permission to access a resource on the receiver's filesystem.
787 > *
788 > * `resourceRequest` is symmetrical and MAY be sent in either direction: a
789 > * client asks the server to grant access to a server-side resource, or a
790 > * server asks the client to grant access to a client-side resource. The
791 > * receiver decides whether to allow, deny, or prompt the user for the
792 > * requested access.
793 > *
794 > * If the receiver denies access, it MUST respond with `PermissionDenied`
795 > * (-32009). The error data MAY include a `ResourceRequestParams` value
796 > * describing the access the caller would need to be granted for the
797 > * operation to succeed; see `PermissionDeniedErrorData` in
798 > * `types/errors.ts`.
799 > *
800 > * After a successful `resourceRequest`, the caller MAY use the corresponding
801 > * `resource*` commands (e.g. `resourceRead`, `resourceWrite`) to perform the
802 > * operation. Receivers MAY rescind access at any time by returning
803 > * `PermissionDenied` on subsequent operations.
804 > *
805 > * Either `read`, `write`, or both SHOULD be set to `true`. A request with
806 > * neither flag set is treated as `read: true` by receivers.
807 > *
808 > * @category Commands
809 > * @method resourceRequest
810 > * @direction Client ↔ Server
811 > * @messageType Request
812 > * @version 1
813 > * @throws `PermissionDenied` (`-32009`) if access is denied.
814 > */
815 > export interface ResourceRequestParams extends BaseParams {
816 > channel: 'ahp-root://';
817 > /**
818 > * Resource URI being requested. Typically a `file:` URI on the receiver's
819 > * filesystem, but any URI scheme that the receiver mediates access to is
820 > * allowed.
821 > */
822 > uri: URI;
823 > /** Whether the caller needs read access to the resource. */
824 > read?: boolean;
825 > /** Whether the caller needs write access to the resource. */
826 > write?: boolean;
827 > }
828 >
829 > /**
830 > * Result of the `resourceRequest` command.
831 > *
832 > * An empty object on success.
833 > */
834 > export interface ResourceRequestResult {
835 > }
836 >
837 > // ─── resourceMove ────────────────────────────────────────────────────────────
838 >
839 > /**
840 > * Moves (renames) a resource from one URI to another on the server's filesystem.
841 > *
842 > * If the destination already exists, it is overwritten unless `failIfExists`
843 > * is set.
844 > *
845 > * Like all `resource*` methods, `resourceMove` is symmetrical and MAY be
846 > * sent in either direction.
847 > *
848 > * @category Commands
849 > * @method resourceMove
850 > * @direction Client ↔ Server
851 > * @messageType Request
852 > * @version 1
853 > * @throws `NotFound` (`-32008`) if the source does not exist.
854 > * @throws `PermissionDenied` (`-32009`) if the client is not permitted to move the resource.
855 > * @throws `AlreadyExists` (`-32010`) if `failIfExists` is set and the destination already exists.
856 > */
857 > export interface ResourceMoveParams extends BaseParams {
858 > channel: 'ahp-root://';
859 > /** Source URI to move from */
860 > source: URI;
861 > /** Destination URI to move to */
862 > destination: URI;
863 > /**
864 > * If `true`, the server MUST fail if the destination already exists instead
865 > * of overwriting it.
866 > */
867 > failIfExists?: boolean;
868 > }
869 >
870 > /**
871 > * Result of the `resourceMove` command.
872 > *
873 > * An empty object on success.
874 > */
875 > export interface ResourceMoveResult {
876 > }
877 >
878 > // ─── resourceResolve ─────────────────────────────────────────────────────────
879 >
880 > /**
881 > * Discriminant for {@link ResourceResolveResult.type}.
882 > *
883 > * @category Commands
884 > */
885 > export const enum ResourceType {
886 > File = 'file',
887 > Directory = 'directory',
888 > Symlink = 'symlink',
889 > }
890 >
891 > /**
892 > * Resolves a resource — the combination of POSIX `stat` and `realpath`.
893 > *
894 > * `resourceResolve` returns metadata about the resource together with its
895 > * canonical URI after symlink resolution. Use this in place of any
896 > * `resourceExists` shim: a missing resource MUST surface as a `NotFound`
897 > * JSON-RPC error rather than a success with a sentinel value. Callers that
898 > * truly need a boolean check should attempt `resourceResolve` and treat
899 > * `NotFound` as "does not exist".
900 > *
901 > * Like all `resource*` methods, `resourceResolve` is symmetrical and MAY be
902 > * sent in either direction.
903 > *
904 > * @category Commands
905 > * @method resourceResolve
906 > * @direction Client ↔ Server
907 > * @messageType Request
908 > * @version 1
909 > * @throws `NotFound` (`-32008`) if the resource does not exist.
910 > * @throws `PermissionDenied` (`-32009`) if the caller is not permitted to stat the URI.
911 > * @example
912 > * ```jsonc
913 > * // Client → Server
914 > * { "jsonrpc": "2.0", "id": 20, "method": "resourceResolve",
915 > * "params": { "channel": "ahp-root://", "uri": "file:///workspace/hello.txt" } }
916 > *
917 > * // Server → Client
918 > * { "jsonrpc": "2.0", "id": 20, "result": {
919 > * "uri": "file:///workspace/hello.txt",
920 > * "type": "file",
921 > * "size": 5,
922 > * "mtime": "2026-01-15T12:34:56.789Z",
923 > * "etag": "W/\"5-abc123\""
924 > * }}
925 > * ```
926 > */
927 > export interface ResourceResolveParams extends BaseParams {
928 > channel: 'ahp-root://';
929 > /** URI to resolve */
930 > uri: URI;
931 > /**
932 > * When `true` (default), follow symlinks and report the metadata of the
933 > * link target — and set `uri` in the result to the canonical (realpath)
934 > * URI. When `false`, stat the link itself (lstat semantics) and report
935 > * `type: 'symlink'`.
936 > */
937 > followSymlinks?: boolean;
938 > }
939 >
940 > /**
941 > * Result of the `resourceResolve` command.
942 > */
943 > export interface ResourceResolveResult {
944 > /**
945 > * Canonical URI after symlink resolution. Equal to the requested URI when
946 > * `followSymlinks` is `false` or the URI does not traverse a symlink.
947 > */
948 > uri: URI;
949 > /** Resource kind. */
950 > type: ResourceType;
951 > /**
952 > * Size in bytes. Omitted for directories when the provider cannot
953 > * cheaply compute it.
954 > */
955 > size?: number;
956 > /** Last-modified time in ISO 8601 format, when known. */
957 > mtime?: string;
958 > /** Creation time in ISO 8601 format, when known. */
959 > ctime?: string;
960 > /** Sniffed MIME type, when known (e.g. `"text/plain"`, `"image/png"`). */
961 > contentType?: string;
962 > /**
963 > * Opaque per-provider version token. When present, pass it as
964 > * {@link ResourceWriteParams.ifMatch} on a subsequent `resourceWrite` to
965 > * detect concurrent modifications.
966 > */
967 > etag?: string;
968 > }
969 >
970 > // ─── resourceMkdir ───────────────────────────────────────────────────────────
971 >
972 > /**
973 > * Creates a directory on the server's filesystem with `mkdir -p` semantics.
974 > *
975 > * The server MUST create any missing parent directories. Creating a
976 > * directory that already exists is a no-op success. If `uri` already
977 > * exists but is **not** a directory, the server MUST fail with
978 > * `AlreadyExists`.
979 > *
980 > * Like all `resource*` methods, `resourceMkdir` is symmetrical and MAY be
981 > * sent in either direction.
982 > *
983 > * @category Commands
984 > * @method resourceMkdir
985 > * @direction Client ↔ Server
986 > * @messageType Request
987 > * @version 1
988 > * @throws `PermissionDenied` (`-32009`) if the caller is not permitted to create the directory.
989 > * @throws `AlreadyExists` (`-32010`) if `uri` already exists as a non-directory.
990 > */
991 > export interface ResourceMkdirParams extends BaseParams {
992 > channel: 'ahp-root://';
993 > /** Directory URI to create (parents created as needed). */
994 > uri: URI;
995 > }
996 >
997 > /**
998 > * Result of the `resourceMkdir` command.
999 > *
1000 > * An empty object on success.
1001 > */
1002 > export interface ResourceMkdirResult {
1003 > }
1004 >
1005 > // ─── authenticate ────────────────────────────────────────────────────────────
1006 >
1007 > /**
1008 > * Pushes a ****** for a protected resource. The `resource` field MUST
1009 > * match a protected-resource identifier the client has discovered from the
1010 > * server — whether declared statically in `AgentInfo.protectedResources`,
1011 > * or discovered dynamically from a live `McpServerAuthRequiredState.resource`
1012 > * or `ToolCallAuthRequiredState.auth.resource` (both surfaced only once the
1013 > * corresponding MCP server or tool call actually challenges for auth).
1014 > * Servers MUST accept any `resource` value they have themselves advertised
1015 > * through one of these three mechanisms.
1016 > *
1017 > * Tokens are delivered using [RFC 6750](https://datatracker.ietf.org/doc/html/rfc6750)
1018 > * (****** Usage) semantics. The client obtains the token from the
1019 > * authorization server(s) listed in the resource's metadata and pushes it
1020 > * to the server via this command.
1021 > *
1022 > * @category Commands
1023 > * @method authenticate
1024 > * @direction Client → Server
1025 > * @messageType Request
1026 > * @version 1
1027 > * @see {@link /specification/authentication | Authentication}
1028 > * @example
1029 > * ```jsonc
1030 > * // Client → Server
1031 > * { "jsonrpc": "2.0", "id": 3, "method": "authenticate",
1032 > * "params": { "channel": "ahp-root://", "resource": "https://api.github.com", "token": "gho_xxxx" } }
1033 > *
1034 > * // Server → Client (success)
1035 > * { "jsonrpc": "2.0", "id": 3, "result": {} }
1036 > *
1037 > * // Server → Client (failure — invalid token)
1038 > * { "jsonrpc": "2.0", "id": 3, "error": { "code": -32007, "message": "Invalid token" } }
1039 > * ```
1040 > */
1041 > export interface AuthenticateParams extends BaseParams {
1042 > channel: 'ahp-root://';
1043 > /**
1044 > * The protected resource identifier. MUST match a `resource` value the
1045 > * server has advertised — via `ProtectedResourceMetadata` in
1046 > * `AgentInfo.protectedResources`, or via a live
1047 > * `McpServerAuthRequiredState.resource` / `ToolCallAuthRequiredState.auth.resource`.
1048 > */
1049 > resource: string;
1050 > /** ****** obtained from the resource's authorization server */
1051 > token: string;
1052 > /**
1053 > * OAuth scopes the token grants, when known. Lets the server determine
1054 > * whether a specific challenge — e.g. the `requiredScopes` on a live
1055 > * `McpServerAuthRequiredState` or `ToolCallAuthRequiredState.auth` — is
1056 > * satisfied without decoding the (opaque, server-specific) token itself.
1057 > * Omit when the client doesn't track granted scopes separately from the
1058 > * token.
1059 > */
1060 > scopes?: string[];
1061 > }
1062 >
1063 > /**
1064 > * Result of the `authenticate` command.
1065 > *
1066 > * An empty object on success. If the token is invalid or the resource is
1067 > * unrecognized, the server MUST return a JSON-RPC error (e.g. `AuthRequired`
1068 > * `-32007` or `InvalidParams` `-32602`).
1069 > */
1070 > export interface AuthenticateResult {
1071 > }
src/vs/platform/agentHost/common/state/sessionState.ts 822 covered LOC · 57 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- sessionState.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // Immutable state types for the sessions process protocol.
7 > // See protocol.md for the full design rationale.
8 > //
9 > // Most types are imported from the auto-generated protocol layer
10 > // (synced from the agent-host-protocol repo). This file adds VS Code-specific
11 > // helpers and re-exports.
12 >
13 > import { decodeBase64, encodeBase64, VSBuffer } from '../../../../base/common/buffer.js';
14 > import { hasKey, type Mutable } from '../../../../base/common/types.js';
15 > import { URI as ResourceURI } from '../../../../base/common/uri.js';
16 > import type { IProductService } from '../../../product/common/productService.js';
17 > import { readToolCallMeta } from '../meta/agentToolCallMeta.js';
18 > import {
19 > ResponsePartKind,
20 > SessionStatus,
21 > ToolCallStatus,
22 > SessionLifecycle,
23 > TerminalState,
24 > ToolResultContentType,
25 > ToolResultFileEditContent,
26 > ChatOriginKind,
27 > ChatInteractivity,
28 > type ActiveTurn,
29 > type ChangesetState,
30 > type ChatState,
31 > type ChatSummary,
32 > type PendingMessage,
33 > type Turn,
34 > type AnnotationsState,
35 > type URI as ProtocolURI,
36 > type RootState,
37 > type SessionState,
38 > type SessionSummary,
39 > type TextRange,
40 > type ToolCallCancelledState,
41 > type ToolCallCompletedState,
42 > type ToolCallResult,
43 > type ToolCallState,
44 > type ToolResultContent,
45 > type ToolResultSubagentContent,
46 > type ToolResultTextContent,
47 > type UsageInfo,
48 > type Message,
49 > } from './protocol/state.js';
50 >
51 > // Re-export everything from the protocol state module
52 > export {
53 > ChangesetOperationScope, ChangesetOperationStatus, ChangesetStatus, CustomizationLoadStatus,
54 > CustomizationType, MessageAttachmentKind, MessageKind,
55 > PendingMessageKind,
56 > PolicyState,
57 > ResponsePartKind,
58 > ChatInputAnswerState as SessionInputAnswerState,
59 > ChatInputAnswerValueKind as SessionInputAnswerValueKind,
60 > ChatInputQuestionKind as SessionInputQuestionKind,
61 > ChatInputResponseKind as SessionInputResponseKind,
62 > ChatInteractivity,
63 > ChatOriginKind,
64 > SessionLifecycle,
65 > SessionStatus, ToolCallCancellationReason, ToolCallConfirmationReason, ToolCallContributorKind, ToolCallRiskAssessmentKind, ToolCallRiskAssessmentStatus, ToolCallStatus,
66 > ToolResultContentType,
67 > TurnState, type ActiveTurn, type AgentCustomization, type AgentCapabilities, type AgentInfo, type AgentSelection, type Annotation, type AnnotationEntry, type AnnotationsState, type AnnotationsSummary, type Changeset, type ChangesetFile,
68 > type ChangesetOperation, type ChangesetState, type ChatState, type ChatSummary, type ChatOrigin, type ChildCustomization, type ClientPluginCustomization, type ConfigPropertySchema,
69 > type ConfigSchema,
70 > type ContentRef, type Customization, type CustomizationDegradedState,
71 > type CustomizationErrorState, type CustomizationLoadedState, type CustomizationLoadingState, type CustomizationLoadState, type DirectoryCustomization, type ErrorInfo, type HookCustomization, type FileEdit as ISessionFileDiff, type ToolResultEmbeddedResourceContent as IToolResultBinaryContent, type MarkdownResponsePart, type McpServerCustomization, type MessageAttachment,
72 > type MessageResourceAttachment, type MessageEmbeddedResourceAttachment, type MessageAnnotationsAttachment, type ModelSelection, type PendingMessage, type PluginCustomization, type ProjectInfo, type PromptCustomization, type ReasoningResponsePart,
73 > type ResponsePart,
74 > type RootState, type RuleCustomization, type SessionActiveClient,
75 > type SessionConfigState, type ChatInputAnswer as SessionInputAnswer,
76 > type ChatInputOption as SessionInputOption, type ChatInputQuestion as SessionInputQuestion, type ChatInputRequest as SessionInputRequest, type SessionModelInfo,
77 > type SessionState,
78 > type SessionSummary, type SkillCustomization, type Snapshot, type StringOrMarkdown, type TerminalState, type TextRange,
79 > type ToolAnnotations,
80 > type ToolCallCancelledState,
81 > type ToolCallCompletedState,
82 > type ToolCallPendingConfirmationState,
83 > type ToolCallPendingResultConfirmationState,
84 > type ToolCallResponsePart,
85 > type ToolCallResult,
86 > type ToolCallRiskAssessment,
87 > type ToolCallRiskAssessmentCompleteState,
88 > type ToolCallRiskAssessmentLoadingState,
89 > type ToolCallRunningState,
90 > type ToolCallState,
91 > type ToolCallStreamingState,
92 > type ToolCallContributor,
93 > type ToolDefinition, type ToolResultContent,
94 > type ToolResultFileEditContent,
95 > type TerminalCommandResult,
96 > type ToolResultSubagentContent,
97 > type ToolResultTerminalContent,
98 > type ToolResultTextContent,
99 > type Turn, type URI, type UsageInfo,
100 > type Message
101 > } from './protocol/state.js';
102 >
103 > /**
104 > * Well-known keys that may appear on {@link UsageInfo._meta}.
105 > * Clients MAY read these to provide enhanced UI (e.g. credit cost display).
106 > */
107 > export interface UsageInfoMeta {
108 > /** Per-turn credit cost reported by the backend. */
109 > cost?: number;
110 > /** The concrete model selected by Copilot Auto and the routing explanation. */
111 > autoModeResolved?: IAutoModeResolvedInfo;
112 > /** Copilot-specific usage breakdown, including nano-AIU totals. */
113 > copilotUsage?: {
114 > totalNanoAiu?: number;
115 > [key: string]: unknown;
116 > };
117 > /**
118 > * Per-category account quota snapshots reported by the backend on the
119 > * model-call usage event, keyed by quota type (e.g. `chat`,
120 > * `premium_interactions`). Clients MAY use these to keep the account quota
121 > * UI current without a separate quota fetch.
122 > */
123 > quotaSnapshots?: {
124 > [quotaType: string]: {
125 > readonly isUnlimitedEntitlement?: boolean;
126 > readonly entitlementRequests?: number;
127 > readonly usedRequests?: number;
128 > readonly remainingPercentage?: number;
129 > readonly overage?: number;
130 > readonly overageAllowedWithExhaustedQuota?: boolean;
131 > /** ISO 8601 date when the quota resets, if applicable. */
132 > readonly resetDate?: string;
133 > } | undefined;
134 > };
135 > /**
136 > * Per-source context-window attribution breakdown reported by the SDK's
137 > * `session.rpc.metadata.getContextAttribution()`. Populated asynchronously
138 > * after each usage event and piped to the context-usage widget as
139 > * `promptTokenDetails`.
140 > */
141 > contextAttribution?: IContextAttributionData;
142 > [key: string]: unknown;
143 > }
144 >
145 > export interface IAutoModeResolvedInfo {
146 > readonly chosenModel: string;
147 > readonly reasoningBucket?: 'low' | 'medium' | 'high';
148 > readonly categoryScores?: Readonly<Record<string, number | undefined>>;
149 > readonly predictedLabel?: string;
150 > readonly confidence?: number;
151 > readonly candidateModels?: readonly string[];
152 > }
153 >
154 > /**
155 > * Mirrors the SDK's `SessionContextAttribution` shape — a flat list of
156 > * per-source entries describing what occupies the session's context window.
157 > */
158 > export interface IContextAttributionData {
159 > readonly totalTokens: number;
160 > readonly entries: readonly IContextAttributionEntry[];
161 > readonly compactions: { readonly count: number };
162 > }
163 >
164 > export interface IContextAttributionEntry {
165 > readonly kind: string;
166 > readonly id: string;
167 > readonly label: string;
168 > readonly tokens: number;
169 > readonly parentId?: string;
170 > readonly attributes?: Readonly<Record<string, string | undefined>>;
171 > }
172 >
173 > type AccountQuotaSnapshot = NonNullable<NonNullable<UsageInfoMeta['quotaSnapshots']>[string]>;
174 >
175 function readAccountQuotaSnapshot(value: unknown): AccountQuotaSnapshot | undefined {
176 if (!value || typeof value !== 'object' || Array.isArray(value)) {
188 return snapshot;
189 }
191 > /**
192 > * Reads the well-known {@link UsageInfoMeta} keys from a usage report's open
193 > * `_meta` bag, ignoring unrelated provider-specific keys and validating each
194 > * field's type. Always read {@link UsageInfo._meta} through this helper rather
195 > * than casting the bag to {@link UsageInfoMeta}, so a malformed or partial bag
196 > * degrades to absent fields instead of producing values of the wrong runtime
197 > * type. Returns an empty object when the bag is absent.
198 > */
199 > export function readUsageInfoMeta(usage: UsageInfo | undefined): UsageInfoMeta {
200 const meta = usage?._meta;
201 if (!meta) {
227 return result;
228 }
230 function readAutoModeResolvedInfo(value: unknown): IAutoModeResolvedInfo | undefined {
231 if (!value || typeof value !== 'object' || Array.isArray(value)) {
258 return result;
259 }
261 function readContextAttribution(value: unknown): IContextAttributionData | undefined {
262 if (!value || typeof value !== 'object' || Array.isArray(value)) {
295 return { totalTokens: raw['totalTokens'] as number, entries, compactions };
296 }
298 function filterStringAttributes(raw: Record<string, unknown>): Record<string, string | undefined> {
299 const result: Record<string, string | undefined> = {};
305 return result;
306 }
308 > export {
309 > ChangesetOperationTargetKind, type ChangesetOperationFollowUp, type ChangesetOperationTarget
310 > } from './protocol/commands.js';
311 >
312 > // Canonical chat-input type names (the protocol renamed the former
313 > // `SessionInput*` types to `ChatInput*` when input requests moved onto the
314 > // chat channel). Re-exported here so consumers can import them from the glue
315 > // layer alongside the legacy `SessionInput*` aliases above.
316 > export {
317 > ChatInputAnswerState,
318 > ChatInputAnswerValueKind,
319 > ChatInputQuestionKind,
320 > ChatInputResponseKind,
321 > type ChatInputAnswer,
322 > type ChatInputOption,
323 > type ChatInputQuestion,
324 > type ChatInputRequest,
325 > type InputRequestResponsePart,
326 > } from './protocol/state.js';
327 >
328 > // ---- File edit kind ---------------------------------------------------------
329 >
330 > /**
331 > * The kind of file edit operation. Derived from the presence/absence of
332 > * `before`/`after` in {@link ToolResultFileEditContent}.
333 > */
334 > export const enum FileEditKind {
335 > /** Content edit (same file URI, different content). */
336 > Edit = 'edit',
337 > /** File creation (no before state). */
338 > Create = 'create',
339 > /** File deletion (no after state). */
340 > Delete = 'delete',
341 > /** File rename/move (different before and after URIs). */
342 > Rename = 'rename',
343 > }
344 >
345 > // ---- Well-known URIs --------------------------------------------------------
346 >
347 > /** URI for the root state subscription. */
348 > export const ROOT_STATE_URI = 'ahp-root://';
349 >
350 > /** Scheme used by {@link ROOT_STATE_URI}. */
351 > export const AHP_ROOT_SCHEME = 'ahp-root';
352 >
353 > /** Scheme used by resource-watch channel URIs (`ahp-resource-watch:/<encoded>`). */
354 > export const AHP_RESOURCE_WATCH_SCHEME = 'ahp-resource-watch';
355 >
356 > /**
357 > * Encode a resource-watch descriptor into its canonical channel URI. The
358 > * descriptor is serialised into the URI path so the receiver can recover
359 > * the watch parameters without any server-side bookkeeping — subscribe is
360 > * the only point where state is materialised (an `IFileService` watcher
361 > * is attached on the first subscriber and held through a grace window
362 > * after the last drops).
363 > */
364 > export function buildResourceWatchChannelUri(descriptor: {
365 readonly root: string;
366 readonly recursive?: boolean;
380 return `${AHP_RESOURCE_WATCH_SCHEME}://r/${json}`;
381 }
383 > /**
384 > * Inverse of {@link buildResourceWatchChannelUri}. Returns `undefined` if
385 > * `uri` is not a well-formed `ahp-resource-watch:` URI — callers should
386 > * surface that as a not-found error to the client.
387 > */
388 > export function parseResourceWatchChannelUri(uri: string): {
389 root: string;
390 recursive: boolean;
421 }
422 }
424 > /** Returns `true` when `uri` identifies a resource-watch channel. */
425 > export function isAhpResourceWatchChannel(uri: string): boolean {
426 try {
427 return ResourceURI.parse(uri).scheme === AHP_RESOURCE_WATCH_SCHEME;
430 }
431 }
433 > /**
434 > * Returns `true` when `uri` identifies the root channel, regardless of
435 > * whether the caller passes the canonical wire form (`'ahp-root://'`) or a
436 > * variant that has been round-tripped through the workbench {@link URI} class
437 > * (which normalizes the authority-less form to `'ahp-root:'`). Always prefer
438 > * this helper over a direct `=== ROOT_STATE_URI` comparison so the two
439 > * spellings stay interchangeable.
440 > */
441 > export function isAhpRootChannel(uri: string): boolean {
442 if (uri === ROOT_STATE_URI) {
443 return true;
449 }
450 }
452 > /**
453 > * Mints a session-unique opaque id for a customization, derived from its
454 > * source URI and (when present) its `range` within the source. Plugins MAY
455 > * declare multiple children (e.g. MCP servers, hooks) inside the same
456 > * manifest file; including the range disambiguates them without an extra
457 > * mapping table.
458 > *
459 > * The range is appended as a reserved `#range=` query-style suffix; any
460 > * existing `#` in the URI is percent-encoded first so a source URI that
461 > * already contains a fragment cannot collide with a ranged id.
462 > */
463 > export function customizationId(uri: string, range?: TextRange): string {
464 if (!range) {
465 return uri;
468 return `${safeUri}#range=${range.start.line}:${range.start.character}-${range.end.line}:${range.end.character}`;
469 }
471 > // ---- VS Code-specific derived types -----------------------------------------
472 >
473 > /**
474 > * A tool call in a terminal state, stored in completed turns.
475 > */
476 > export type ICompletedToolCall = ToolCallCompletedState | ToolCallCancelledState;
477 >
478 > /**
479 > * Derived status type for the tool call lifecycle.
480 > */
481 > export type ToolCallStatusString = ToolCallState['status'];
482 >
483 > // ---- Tool output helper -----------------------------------------------------
484 >
485 > /**
486 > * Extracts a plain-text tool output string from a tool call result's `content`
487 > * array. Joins all text-type content parts into a single string.
488 > *
489 > * Returns `undefined` if there are no text content parts.
490 > */
491 > export function getToolOutputText(result: ToolCallResult): string | undefined {
492 if (!result.content || result.content.length === 0) {
493 return undefined;
504 return textParts.map(p => p.text).join('\n');
505 }
507 > /**
508 > * Extracts file edit content entries from a tool call result's `content` array.
509 > * Returns an empty array if there are no file edit content parts.
510 > */
511 > export function getToolFileEdits(result: ToolCallResult): ToolResultFileEditContent[] {
512 if (!result.content || result.content.length === 0) {
513 return [];
521 return edits;
522 }
524 > /**
525 > * Extracts the first subagent content entry from a tool call's `content` array.
526 > * Works with both completed tool call results and running tool call states.
527 > * Returns `undefined` if there are no subagent content parts.
528 > */
529 > export function getToolSubagentContent(result: { content?: readonly ToolResultContent[] }): ToolResultSubagentContent | undefined {
530 if (!result.content || result.content.length === 0) {
531 return undefined;
538 return undefined;
539 }
541 > // ---- Subagent URI helpers ---------------------------------------------------
542 >
543 > const SUBAGENT_URI_SEGMENT = 'subagent';
544 > const SUBAGENT_URI_MARKER = `/${SUBAGENT_URI_SEGMENT}/`;
545 > const SUBAGENT_URI_PATH_REGEX = /^(?<parentPath>.+)\/subagent\/(?<toolCallId>.+)$/;
546 >
547 function asResourceUri(uri: ProtocolURI | ResourceURI): ResourceURI {
548 return typeof uri === 'string' ? ResourceURI.parse(uri) : uri;
549 }
551 function getSubagentBasePath(parentSession: ProtocolURI | ResourceURI): { parent: ResourceURI; path: string } {
552 const parent = asResourceUri(parentSession);
554 return { parent, path: `${parentPath}${SUBAGENT_URI_MARKER}` };
555 }
557 > /**
558 > * Builds a subagent session URI from a parent session URI and tool call ID.
559 > * Convention: `{parentSessionUri}/subagent/{toolCallId}`
560 > */
561 > export function buildSubagentSessionUri(parentSession: ProtocolURI | ResourceURI, toolCallId: string): string {
562 const { parent, path } = getSubagentBasePath(parentSession);
563 return parent.with({ path: `${path}${toolCallId}` }).toString();
564 }
566 > /**
567 > * Parses a subagent session URI into its parent session URI and tool call ID.
568 > * Returns `undefined` if the URI does not follow the subagent convention.
569 > */
570 > export function parseSubagentSessionUri(uri: ProtocolURI | ResourceURI): { parentSession: ResourceURI; toolCallId: string } | undefined {
571 const resource = asResourceUri(uri);
572 const match = SUBAGENT_URI_PATH_REGEX.exec(resource.path);
579 };
580 }
582 > /**
583 > * Returns whether a session URI represents a subagent session.
584 > */
585 > export function isSubagentSession(uri: ProtocolURI | ResourceURI): boolean {
586 return parseSubagentSessionUri(uri) !== undefined;
587 }
589 > /**
590 > * Builds the string prefix used by the state manager for cached subagent sessions.
591 > */
592 > export function buildSubagentSessionUriPrefix(parentSession: ProtocolURI | ResourceURI): string {
593 const { parent, path } = getSubagentBasePath(parentSession);
594 return parent.with({ path }).toString();
595 }
597 > // ---- Factory helpers --------------------------------------------------------
598 >
599 > export function createRootState(): RootState {
600 return {
601 agents: [],
603 };
604 }
606 > /**
607 > * Creates the initial flat {@link SessionState} for a session from its
608 > * root-channel {@link SessionSummary} catalog entry. Session metadata
609 > * ({@link SessionMetadata}) — and the shared `_meta` bag — are inlined directly
610 > * onto the state.
611 > */
612 > export function createSessionState(summary: SessionSummary): SessionState {
613 const state: SessionState = {
614 provider: summary.provider,
627 return state;
628 }
630 > /**
631 > * Creates an empty {@link ChatState} for a chat. The summary fields are
632 > * denormalized onto the chat state per the protocol contract; callers pass
633 > * the chat's catalog summary and this seeds an empty conversation.
634 > */
635 > export function createChatState(summary: ChatSummary): ChatState {
636 return {
637 resource: summary.resource,
648 };
649 }
651 > /**
652 > * Derives the default-chat {@link ChatSummary} for a session from its
653 > * {@link SessionSummary}. The default chat inherits the session's title,
654 > * status, activity and working directory, and is marked as a
655 > * {@link ChatOriginKind.User | user-originated} chat. Both the session and
656 > * chat `modifiedAt` are ISO-8601 strings, so it is carried over directly.
657 > */
658 > export function createDefaultChatSummary(session: SessionSummary, chatUri: ProtocolURI): ChatSummary {
659 const summary: ChatSummary = {
660 resource: chatUri,
675 return summary;
676 }
678 > /** Activity bits (0-4) of {@link SessionStatus}; the high bits carry orthogonal flags (IsRead / IsArchived). */
679 > const STATUS_ACTIVITY_MASK = (1 << 5) - 1;
680 >
681 > /** Whether the active turn has a `PendingConfirmation` tool call auto-approved by the session's bypass setting. */
682 function hasAutoApprovedPendingConfirmation(state: ChatState): boolean {
683 return !!state.activeTurn?.responseParts.some(part =>
687 );
688 }
690 > /** Whether the chat is genuinely blocked on user input (an open input request, an auth-required tool, or a non-auto-approved confirmation gate). */
691 function chatAwaitsUserInput(state: ChatState): boolean {
692 return !!state.activeTurn?.responseParts.some(part => {
708 });
709 }
711 > /**
712 > * Projects a chat's status for session-summary aggregation, demoting an
713 > * `InputNeeded` back to `InProgress` only when it is caused solely by an
714 > * auto-approved confirmation — otherwise a session with bypass approvals flashes
715 > * "input needed" in the sessions list while an auto-approved tool runs.
716 > */
717 function chatSummaryStatus(state: ChatState): SessionStatus {
718 const status = state.status;
728 return status;
729 }
731 > /**
732 > * Derives a {@link ChatSummary} from a fully-populated {@link ChatState} by
733 > * projecting out the denormalized summary fields. Used to keep the parent
734 > * session's `chats` catalog in sync with a chat's denormalized state.
735 > */
736 > export function chatSummaryFromState(state: ChatState): ChatSummary {
737 const summary: ChatSummary = {
738 resource: state.resource,
748 return summary;
749 }
751 > /**
752 > * The effective interactivity of a chat given its session's archived state.
753 > *
754 > * `interactivity` is the general read-only mechanism (e.g. subagent worker
755 > * chats are `ReadOnly`). An archived session is read-only too, so its
756 > * interactive chats are downgraded to `ReadOnly`. `Hidden` chats stay hidden —
757 > * archiving only downgrades `Full` chats. Absent interactivity defaults to
758 > * `Full` for backward compatibility.
759 > *
760 > * The host uses this to enforce read-only turns off a single signal
761 > * ({@link isChatReadOnly}) rather than special-casing archived; the same rule
762 > * is mirrored client-side to hide the composer.
763 > */
764 > export function effectiveChatInteractivity(interactivity: ChatInteractivity | undefined, sessionArchived: boolean): ChatInteractivity {
765 if (interactivity === ChatInteractivity.Hidden) {
766 return ChatInteractivity.Hidden;
771 return interactivity ?? ChatInteractivity.Full;
772 }
774 > /**
775 > * Whether a chat rejects user-dispatched turns, given its own interactivity and
776 > * its session's archived state. `true` for `ReadOnly` chats (including archived
777 > * sessions' interactive chats). See {@link effectiveChatInteractivity}.
778 > */
779 > export function isChatReadOnly(interactivity: ChatInteractivity | undefined, sessionArchived: boolean): boolean {
780 return effectiveChatInteractivity(interactivity, sessionArchived) === ChatInteractivity.ReadOnly;
781 }
783 > export function createActiveTurn(id: string, message: Message, startedAt: string): ActiveTurn {
784 return {
785 id,
790 };
791 }
793 > export const enum StateComponents {
794 > Root,
795 > Session,
796 > Chat,
797 > Terminal,
798 > Changeset,
799 > Annotations,
800 > }
801 >
802 > export type ComponentToState = {
803 > [StateComponents.Root]: RootState;
804 > [StateComponents.Session]: SessionState;
805 > [StateComponents.Chat]: ChatState;
806 > [StateComponents.Terminal]: TerminalState;
807 > [StateComponents.Changeset]: ChangesetState;
808 > [StateComponents.Annotations]: AnnotationsState;
809 > };
810 >
811 > // ---- Default chat URI helpers ----------------------------------------------
812 >
813 > /** Scheme used by chat channel URIs (`ahp-chat://...`). */
814 > export const AHP_CHAT_SCHEME = 'ahp-chat';
815 >
816 > /** Chat id of the default chat that every session owns. */
817 > export const DEFAULT_CHAT_ID = 'default';
818 >
819 > /**
820 > * Derives the deterministic channel URI for a chat within a session. Every chat
821 > * — the default chat and any additional peer chats — encodes its owning session
822 > * URI into the path so producers and consumers can recover the session without a
823 > * lookup table (see {@link parseChatUri}). The chat id is carried in the URI
824 > * authority.
825 > *
826 > * `ahp-chat://<chatId>/<base64(sessionUri)>`
827 > */
828 > export function buildChatUri(sessionUri: ProtocolURI | ResourceURI, chatId: string): string {
829 const session = typeof sessionUri === 'string' ? sessionUri : sessionUri.toString();
830 const encoded = encodeBase64(VSBuffer.fromString(session), false, true);
831 return `${AHP_CHAT_SCHEME}://${chatId}/${encoded}`;
832 }
834 > /**
835 > * Derives the deterministic default-chat channel URI for a session. While the
836 > * protocol allows a session to contain many chats, every session always owns a
837 > * default chat whose URI is derived from the owning session URI so producers and
838 > * consumers can compute it without a lookup table.
839 > *
840 > * The session URI is encoded into the path so {@link parseChatUri} can recover
841 > * it.
842 > */
843 > export function buildDefaultChatUri(sessionUri: ProtocolURI | ResourceURI): string {
844 return buildChatUri(sessionUri, DEFAULT_CHAT_ID);
845 }
847 > const SUBAGENT_CHAT_ID = 'subagent';
848 >
849 > export function isSubagentChatUri(uri: ProtocolURI | ResourceURI): boolean {
850 const parsed = typeof uri === 'string' ? ResourceURI.parse(uri) : uri;
851 return parsed.scheme === AHP_CHAT_SCHEME && parsed.authority === SUBAGENT_CHAT_ID;
852 }
854 > export function buildSubagentChatUri(sessionUri: ProtocolURI | ResourceURI, toolCallId: string): string {
855 const session = typeof sessionUri === 'string' ? sessionUri : sessionUri.toString();
856 const encoded = encodeBase64(VSBuffer.fromString(session), false, true);
857 return `${AHP_CHAT_SCHEME}://${SUBAGENT_CHAT_ID}/${encoded}/${encodeURIComponent(toolCallId)}`;
858 }
860 > /**
861 > * Inverse of {@link buildChatUri}: recovers the owning session URI and chat id
862 > * from any chat channel URI. Returns `undefined` when `uri` is not a well-formed
863 > * chat URI.
864 > */
865 > export function parseChatUri(uri: ProtocolURI | ResourceURI): { session: string; chatId: string } | undefined {
866 let parsed: ResourceURI;
867 try {
891 }
892 }
894 > /**
895 > * Inverse of {@link buildDefaultChatUri}: recovers the owning session URI from a
896 > * chat channel URI. Returns `undefined` when `uri` is not a well-formed chat URI.
897 > * Accepts any chat URI (default or additional) so callers that only need the
898 > * parent session can use it uniformly.
899 > */
900 > export function parseDefaultChatUri(uri: ProtocolURI | ResourceURI): string | undefined {
901 return parseChatUri(uri)?.session;
902 }
904 > export function parseRequiredSessionUriFromChatUri(uri: ProtocolURI | ResourceURI): string {
905 const session = parseDefaultChatUri(uri);
906 if (session === undefined) {
909 return session;
910 }
912 > /** Returns `true` when `uri` is the default chat of its session. */
913 > export function isDefaultChatUri(uri: ProtocolURI | ResourceURI): boolean {
914 return parseChatUri(uri)?.chatId === DEFAULT_CHAT_ID;
915 }
917 > /**
918 > * Resolves a feature-level `(session, chat)` pair to the single chat URI used by
919 > * the agent session/chat surface. A session always owns a DEFAULT chat addressed
920 > * by the session URI itself; additional (peer) chats are addressed by their own
921 > * chat channel URIs. This is the one place default-chat resolution lives so
922 > * agents never re-derive "is this the default chat?".
923 > */
924 > export function resolveChatUri(session: ResourceURI, chat: ResourceURI): ResourceURI {
925 return isDefaultChatUri(chat) ? session : chat;
926 }
928 > /** Returns `true` when `uri` identifies a chat channel. */
929 > export function isAhpChatChannel(uri: string): boolean {
930 try {
931 return ResourceURI.parse(uri).scheme === AHP_CHAT_SCHEME;
934 }
935 }
937 > // ---- Session + default-chat composite --------------------------------------
938 >
939 > /**
940 > * A single chat's effective session context: the shared {@link SessionState}
941 > * (working directories, active clients, config, customizations/MCP scope, …)
942 > * resolved for one chat and merged with that chat's conversation contents.
943 > *
944 > * The protocol moved turns and pending state off the session and onto a
945 > * per-chat channel, and lets a chat override the session's working directories
946 > * with a subset (e.g. {@link ChatState.workingDirectories}) and carry its own
947 > * read-only {@link ChatState.primaryWorkingDirectory | primary} (fixed at chat
948 > * creation — the session has no primary). This composite recombines the session
949 > * with one of its chats — default or peer — so consumers read the chat's
950 > * effective context and conversation through one object without walking back to
951 > * the session to re-derive shared state. The {@link ISessionWithDefaultChat.workingDirectories}
952 > * carry the chat's *effective* working directories (its own subset override when
953 > * present, else the session's full set); {@link ISessionWithDefaultChat.primaryWorkingDirectory}
954 > * is the chat's own primary.
955 > */
956 > export interface ISessionWithDefaultChat extends SessionState {
957 > /** The chat's read-only primary working directory (fixed at chat creation). */
958 > primaryWorkingDirectory?: ProtocolURI;
959 > /** Completed turns of this chat. */
960 > turns: Turn[];
961 > /** Currently in-progress turn of this chat. */
962 > activeTurn?: ActiveTurn;
963 > /** Steering message pending on this chat. */
964 > steeringMessage?: PendingMessage;
965 > /** Queued messages pending on this chat. */
966 > queuedMessages?: PendingMessage[];
967 > /** Draft input of this chat. */
968 > draft?: Message;
969 > }
970 >
971 > /**
972 > * Projects a {@link SessionState} and one of its {@link ChatState | chats}
973 > * (default or peer) into that chat's {@link ISessionWithDefaultChat | effective
974 > * session context}. Per-chat overrides (the working-directories subset and the
975 > * chat's own primary) are layered over the session defaults, and the
976 > * conversation fields are taken from the chat. When the chat state is absent
977 > * (e.g. not yet hydrated) the conversation fields default to empty and the
978 > * session defaults apply.
979 > */
980 > export function mergeSessionWithDefaultChat(session: SessionState, chat: ChatState | undefined): ISessionWithDefaultChat {
981 return {
982 ...session,
990 };
991 }
993 > /**
994 > * Resolves the active turn of a session's default chat, if any.
995 > */
996 > export function getActiveTurn(chat: ChatState | undefined): ActiveTurn | undefined {
997 return chat?.activeTurn;
998 }
1000 > /**
1001 > * Resolves the default chat's catalog summary from a session, if present.
1002 > */
1003 > export function getDefaultChat(session: SessionState): ChatSummary | undefined {
1004 if (session.defaultChat !== undefined) {
1005 const match = session.chats.find(c => c.resource === session.defaultChat);
1010 return session.chats[0];
1011 }
1013 > // ---- SessionMeta accessors -------------------------------------------------
1014 >
1015 > /**
1016 > * VS Code-side alias for the protocol's open `_meta` property bag on
1017 > * {@link SessionState}. Keys SHOULD be namespaced (e.g. `git`, `vscode.foo`)
1018 > * to avoid collisions; values MUST be JSON-serializable.
1019 > */
1020 > export type SessionMeta = Record<string, unknown>;
1021 >
1022 > /**
1023 > * VS Code-side alias for the protocol's open `_meta` property bag on
1024 > * {@link SessionSummary}. Keys SHOULD be namespaced (e.g. `git`, `vscode.foo`)
1025 > * to avoid collisions; values MUST be JSON-serializable.
1026 > */
1027 > export type SessionSummaryMeta = Record<string, unknown>;
1028 >
1029 > /**
1030 > * Reserved key under {@link SessionMeta} for the well-known git-state
1031 > * payload. Value at this key, when present, MUST be shaped like
1032 > * {@link ISessionGitState}. This is a VS Code-specific convention layered
1033 > * on top of the protocol's generic `_meta` bag — the protocol itself does
1034 > * not know about git state.
1035 > */
1036 > export const SESSION_META_GIT_KEY = 'git';
1037 >
1038 > /**
1039 > * Reserved key under {@link SessionMeta} for the well-known GitHub-state
1040 > * payload. Value at this key, when present, MUST be shaped like
1041 > * {@link ISessionGitHubState}. This is a VS Code-specific convention layered
1042 > * on top of the protocol's generic `_meta` bag — the protocol itself does
1043 > * not know about GitHub state.
1044 > */
1045 > export const SESSION_META_GITHUB_KEY = 'github';
1046 >
1047 > export const SESSION_META_PROMPT_CACHE_KEY = 'vscode.promptCache';
1048 >
1049 > /** Latest known prompt-cache state for the model active in an agent session. */
1050 > export interface ISessionPromptCacheState {
1051 > readonly modelId: string;
1052 > readonly cacheExpiresAt: string;
1053 > }
1054 >
1055 > /** Reads the latest known prompt-cache state from session metadata. */
1056 > export function readSessionPromptCacheState(meta: SessionMeta | undefined): ISessionPromptCacheState | undefined {
1057 const value = meta?.[SESSION_META_PROMPT_CACHE_KEY];
1058 if (!value || typeof value !== 'object' || Array.isArray(value)) {
1064 : undefined;
1065 }
1067 > /** Returns session metadata with the prompt-cache slot updated or removed. */
1068 > export function withSessionPromptCacheState(meta: SessionMeta | undefined, promptCache: ISessionPromptCacheState | undefined): SessionMeta | undefined {
1069 const next: SessionMeta = { ...meta };
1070 if (promptCache) {
1075 return Object.keys(next).length > 0 ? next : undefined;
1076 }
1078 > /**
1079 > * Git state of a session's working directory, carried under
1080 > * {@link SessionMeta} at {@link SESSION_META_GIT_KEY}. Used by clients to
1081 > * drive source-control affordances (e.g. PR/merge buttons in the Agents
1082 > * app).
1083 > *
1084 > * All fields are optional — agents that do not track a particular field
1085 > * should omit it rather than send a placeholder, so clients can distinguish
1086 > * "unknown" from "known to be zero".
1087 > */
1088 > export interface ISessionGitState {
1089 > /** Whether the working directory has a `github.com` git remote. */
1090 > readonly hasGitHubRemote?: boolean;
1091 > /** Current branch name. */
1092 > readonly branchName?: string;
1093 > /** Base branch the work targets (e.g. `main`). */
1094 > readonly baseBranchName?: string;
1095 > /** Upstream tracking branch (e.g. `origin/feature`). */
1096 > readonly upstreamBranchName?: string;
1097 > /** Number of commits the upstream branch has ahead of the local branch. */
1098 > readonly incomingChanges?: number;
1099 > /** Number of commits the local branch has ahead of the upstream branch. */
1100 > readonly outgoingChanges?: number;
1101 > /** Number of files with uncommitted changes. */
1102 > readonly uncommittedChanges?: number;
1103 > /** GitHub repository owner parsed from the working copy's GitHub remote (preferring `origin`, falling back to the first GitHub remote). */
1104 > readonly githubOwner?: string;
1105 > /** GitHub repository name parsed from the working copy's GitHub remote (preferring `origin`, falling back to the first GitHub remote). */
1106 > readonly githubRepo?: string;
1107 > }
1108 >
1109 > /**
1110 > * GitHub state of a session, carried under {@link SessionMeta} at
1111 > * {@link SESSION_META_GITHUB_KEY}. Used by clients to drive GitHub-specific
1112 > * affordances (e.g. PR/merge buttons in the Agents app).
1113 > *
1114 > * All fields are optional — agents that do not track a particular field
1115 > * should omit it rather than send a placeholder, so clients can distinguish
1116 > * "unknown" from "known to be zero".
1117 > */
1118 > export interface ISessionGitHubState {
1119 > /** The owner of the GitHub repository. */
1120 > readonly owner?: string;
1121 > /** The name of the GitHub repository. */
1122 > readonly repo?: string;
1123 > /** The URL of the GitHub pull request. */
1124 > readonly pullRequestUrl?: string;
1125 > }
1126 >
1127 > /**
1128 > * Reads the well-known git-state payload from {@link SessionMeta}, if
1129 > * present. Returns `undefined` when the meta bag is absent or the value at
1130 > * the git key is not a plain object (e.g. an array or a primitive).
1131 > * Individual fields with wrong types are silently dropped so partial state
1132 > * still propagates.
1133 > *
1134 > * Unlike the other typed readers, this takes the raw {@link SessionMeta} value
1135 > * rather than its parent {@link SessionState}: the sessions provider stores and
1136 > * reads a detached meta snapshot without retaining the owning state.
1137 > */
1138 > export function readSessionGitState(meta: SessionMeta | undefined): ISessionGitState | undefined {
1139 const value = meta?.[SESSION_META_GIT_KEY];
1140 if (!value || typeof value !== 'object' || Array.isArray(value)) {
1164 return result;
1165 }
1167 > /**
1168 > * Returns a new {@link SessionMeta} with the git-state payload set to
1169 > * `gitState`, or with the git slot removed if `gitState` is `undefined`.
1170 > * Returns `undefined` if the result would be empty.
1171 > */
1172 > export function withSessionGitState(meta: SessionMeta | undefined, gitState: ISessionGitState | undefined): SessionMeta | undefined {
1173 const next: { [key: string]: unknown } = { ...meta };
1174 if (gitState !== undefined) {
1179 return Object.keys(next).length > 0 ? next : undefined;
1180 }
1182 > /**
1183 > * Reads the well-known GitHub state payload from {@link SessionSummaryMeta}, if
1184 > * present. Returns `undefined` when the meta bag is absent or the value at the
1185 > * GitHub key is not a plain object (e.g. an array or a primitive).
1186 > * Individual fields with wrong types are silently dropped so partial state
1187 > * still propagates.
1188 > *
1189 > * Unlike the other typed readers, this takes the raw {@link SessionSummaryMeta}
1190 > * value rather than its parent {@link SessionState}: the sessions provider stores and
1191 > * reads a detached meta snapshot without retaining the owning state.
1192 > */
1193 > export function readSessionGitHubState(meta: SessionSummaryMeta | undefined): ISessionGitHubState | undefined {
1194 const value = meta?.[SESSION_META_GITHUB_KEY];
1195 if (!value || typeof value !== 'object' || Array.isArray(value)) {
1208 return result;
1209 }
1211 > /**
1212 > * Returns a new {@link SessionSummaryMeta} with the GitHub-state payload set to
1213 > * `gitHubState`, or with the GitHub slot removed if `gitHubState` is `undefined`.
1214 > * Returns `undefined` if the result would be empty.
1215 > */
1216 > export function withSessionGitHubState(meta: SessionSummaryMeta | undefined, gitHubState: ISessionGitHubState | undefined): SessionSummaryMeta | undefined {
1217 const next: { [key: string]: unknown } = { ...meta };
1218 if (gitHubState !== undefined) {
1223 return Object.keys(next).length > 0 ? next : undefined;
1224 }
1226 > /**
1227 > * Reserved key under {@link SessionSummaryMeta} recording how deeply a session
1228 > * was spawned via the `create_session` host tool (0 for a top-level, user-created
1229 > * session). Used to bound recursive session creation. VS Code-specific convention
1230 > * layered on top of the protocol's generic `_meta` bag.
1231 > */
1232 > export const SESSION_META_SPAWN_DEPTH_KEY = 'agentHost/sessionSpawnDepth';
1233 >
1234 > /**
1235 > * Reads the `create_session` spawn depth from a {@link SessionSummaryMeta} bag,
1236 > * returning `0` when the key is absent or not a finite number.
1237 > */
1238 > export function readSessionSpawnDepth(meta: SessionSummaryMeta | undefined): number {
1239 const value = meta?.[SESSION_META_SPAWN_DEPTH_KEY];
1240 return typeof value === 'number' && Number.isFinite(value) ? value : 0;
1241 }
1243 > /**
1244 > * Returns a new {@link SessionSummaryMeta} with the `create_session` spawn depth
1245 > * set to `depth`, preserving any other keys in the bag.
1246 > */
1247 > export function withSessionSpawnDepth(meta: SessionSummaryMeta | undefined, depth: number): SessionSummaryMeta {
1248 return { ...meta, [SESSION_META_SPAWN_DEPTH_KEY]: depth };
1249 }
1251 > /**
1252 > * Reserved key under {@link SessionSummaryMeta} marking a session as
1253 > * workspace-less: a session with no workspace/folder binding (surfaced in the
1254 > * UI as a "Quick Chat"). Carried on the summary bag (not the full state) so
1255 > * clients can group/style such sessions in session lists without subscribing to
1256 > * full session state. VS Code-specific convention layered on the protocol's
1257 > * generic `_meta` bag.
1258 > */
1259 > export const SESSION_META_WORKSPACELESS_KEY = 'workspaceless';
1260 >
1261 > /**
1262 > * Session-database metadata key recording whether a session is workspace-less (a
1263 > * workspace-less chat). Owned by the AH service: `AgentService` writes it centrally at
1264 > * create/materialize and overlays it onto every agent's summary `_meta` in
1265 > * `listSessions`; agents only read it (e.g. to pick the workspace-less system prompt
1266 > * on resume) and never persist it themselves.
1267 > */
1268 > export const AH_META_WORKSPACELESS_DB_KEY = 'agentHost.workspaceless';
1269 >
1270 > /**
1271 > * Session-database metadata key recording whether a session is archived. Written by
1272 > * the AH orchestrator (`AgentSideEffects` on `SessionIsArchivedChanged`) and read by
1273 > * both the orchestrator (`AgentService` restore/list) and agents (e.g. `CopilotAgent`
1274 > * decides whether to recreate a missing worktree vs. resume read-only for history).
1275 > * {@link AH_META_IS_DONE_DB_KEY} is the legacy name kept for sessions persisted before
1276 > * the rename; readers fall back to it when {@link AH_META_IS_ARCHIVED_DB_KEY} is absent.
1277 > */
1278 > export const AH_META_IS_ARCHIVED_DB_KEY = 'isArchived';
1279 >
1280 > /** Legacy metadata key for the archived flag; see {@link AH_META_IS_ARCHIVED_DB_KEY}. */
1281 > export const AH_META_IS_DONE_DB_KEY = 'isDone';
1282 >
1283 > /**
1284 > * Reads the workspace-less marker from {@link SessionSummaryMeta}. Returns
1285 > * `true` only when the well-known key is present and set to boolean `true`.
1286 > */
1287 > export function readSessionWorkspaceless(meta: SessionSummaryMeta | undefined): boolean {
1288 return meta?.[SESSION_META_WORKSPACELESS_KEY] === true;
1289 }
1291 > /**
1292 > * Returns a new {@link SessionSummaryMeta} with the workspace-less marker set,
1293 > * or with the slot removed when `workspaceless` is `false`. Returns `undefined`
1294 > * if the result would be empty.
1295 > */
1296 > export function withSessionWorkspaceless(meta: SessionSummaryMeta | undefined, workspaceless: boolean): SessionSummaryMeta | undefined {
1297 const next: { [key: string]: unknown } = { ...meta };
1298 if (workspaceless) {
1303 return Object.keys(next).length > 0 ? next : undefined;
1304 }
1306 > // ---- RootState _meta accessors ---------------------------------------------
1307 >
1308 > /**
1309 > * VS Code-side alias for the protocol's open `_meta` property bag on
1310 > * {@link RootState}. Keys SHOULD be namespaced to avoid collisions; values MUST
1311 > * be JSON-serializable.
1312 > */
1313 > export type RootMeta = Record<string, unknown>;
1314 >
1315 > /**
1316 > * Reserved key under {@link RootMeta} for the well-known host-build payload.
1317 > * Value at this key, when present, MUST be shaped like {@link IHostBuildInfo}.
1318 > * This is a VS Code-specific convention layered on top of the protocol's
1319 > * generic `_meta` bag — the protocol itself does not know about build info.
1320 > */
1321 > export const ROOT_META_HOST_BUILD_KEY = 'hostBuild';
1322 >
1323 > /**
1324 > * Build information about the program hosting the agent host (the VS Code CLI),
1325 > * carried under {@link RootMeta} at {@link ROOT_META_HOST_BUILD_KEY}. Lets a
1326 > * client see which build is hosting it — useful when inspecting the output of a
1327 > * remote agent host.
1328 > *
1329 > * All fields except {@link version} are optional — a build that does not track
1330 > * a particular field should omit it.
1331 > */
1332 > export interface IHostBuildInfo {
1333 > /** Product version (e.g. `1.96.0`). */
1334 > readonly version: string;
1335 > /** Commit SHA of the build, if known. */
1336 > readonly commit?: string;
1337 > /** Build date (ISO 8601), if known. */
1338 > readonly date?: string;
1339 > /** Release quality (e.g. `stable`, `insider`), if known. */
1340 > readonly quality?: string;
1341 > }
1342 >
1343 > /**
1344 > * Derives {@link IHostBuildInfo} from the host's {@link IProductService}.
1345 > */
1346 > export function hostBuildInfoFromProduct(productService: IProductService): IHostBuildInfo {
1347 return {
1348 version: productService.version,
1352 };
1353 }
1355 > /**
1356 > * Reads the well-known host-build payload from {@link RootMeta}, if present.
1357 > * Returns `undefined` when the meta bag is absent or the value at the host-build
1358 > * key is not a plain object with a string `version`. Optional fields with wrong
1359 > * types are silently dropped.
1360 > */
1361 > export function readHostBuildInfo(state: RootState | undefined): IHostBuildInfo | undefined {
1362 const meta = state?._meta;
1363 const value = meta?.[ROOT_META_HOST_BUILD_KEY];
1377 return result;
1378 }
1380 > /**
1381 > * Returns a new {@link RootMeta} with the host-build payload set to
1382 > * `buildInfo`, or with the slot removed if `buildInfo` is `undefined`. Returns
1383 > * `undefined` if the result would be empty.
1384 > */
1385 > export function withHostBuildInfo(meta: RootMeta | undefined, buildInfo: IHostBuildInfo | undefined): RootMeta | undefined {
1386 const next: { [key: string]: unknown } = { ...meta };
1387 if (buildInfo !== undefined) {
1392 return Object.keys(next).length > 0 ? next : undefined;
1393 }
1395 > /**
1396 > * Formats {@link IHostBuildInfo} as a short single-line human-readable string,
1397 > * e.g. `1.96.0 (commit abc1234, 2024-01-02T03:04:05Z, insider)`.
1398 > */
1399 > export function formatHostBuildInfo(info: IHostBuildInfo): string {
1400 const details: string[] = [];
1401 if (info.commit) { details.push(`commit ${info.commit}`); }
src/vs/base/common/lifecycle.ts 479 covered LOC · 98 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- lifecycle.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { compareBy, numberComparator } from './arrays.js';
7 > import { groupBy } from './collections.js';
8 > import { SetMap, ResourceMap } from './map.js';
9 > import { URI } from './uri.js';
10 > import { createSingleCallFunction } from './functional.js';
11 > import { Iterable } from './iterator.js';
12 > import { BugIndicatingError, onUnexpectedError } from './errors.js';
13 >
14 > // #region Disposable Tracking
15 >
16 > /**
17 > * Enables logging of potentially leaked disposables.
18 > *
19 > * A disposable is considered leaked if it is not disposed or not registered as the child of
20 > * another disposable. This tracking is very simple an only works for classes that either
21 > * extend Disposable or use a DisposableStore. This means there are a lot of false positives.
22 > */
23 > const TRACK_DISPOSABLES = false;
24 > let disposableTracker: IDisposableTracker | null = null;
25 >
26 > export interface IDisposableTracker {
27 > /**
28 > * Is called on construction of a disposable.
29 > */
30 > trackDisposable(disposable: IDisposable): void;
31 >
32 > /**
33 > * Is called when a disposable is registered as child of another disposable (e.g. {@link DisposableStore}).
34 > * If parent is `null`, the disposable is removed from its former parent.
35 > */
36 > setParent(child: IDisposable, parent: IDisposable | null): void;
37 >
38 > /**
39 > * Is called after a disposable is disposed.
40 > */
41 > markAsDisposed(disposable: IDisposable): void;
42 >
43 > /**
44 > * Indicates that the given object is a singleton which does not need to be disposed.
45 > */
46 > markAsSingleton(disposable: IDisposable): void;
47 > }
48 >
49 > export class GCBasedDisposableTracker implements IDisposableTracker {
50
51 private readonly _registry = new FinalizationRegistry<string>(heldValue => {
52 console.warn(`[LEAKED DISPOSABLE] ${heldValue}`);
53 });
55 > trackDisposable(disposable: IDisposable): void {
56 const stack = new Error('CREATED via:').stack!;
57 this._registry.register(disposable, stack, disposable);
58 }
60 > setParent(child: IDisposable, parent: IDisposable | null): void {
61 if (parent) {
62 this._registry.unregister(child);
65 }
66 }
68 > markAsDisposed(disposable: IDisposable): void {
69 this._registry.unregister(disposable);
70 }
72 > markAsSingleton(disposable: IDisposable): void {
73 this._registry.unregister(disposable);
74 }
75 > } lifecycle.ts
76 >
77 > export interface DisposableInfo {
78 > value: IDisposable;
79 > source: string | null;
80 > parent: IDisposable | null;
81 > isSingleton: boolean;
82 > idx: number;
83 > }
84 >
85 > export class DisposableTracker implements IDisposableTracker {
86 > private static idx = 0; lifecycle.ts
87 >
88 > private readonly livingDisposables = new Map<IDisposable, DisposableInfo>();
90 > private getDisposableData(d: IDisposable): DisposableInfo {
91 let val = this.livingDisposables.get(d);
92 if (!val) {
96 return val;
97 }
99 > trackDisposable(d: IDisposable): void {
100 const data = this.getDisposableData(d);
101 if (!data.source) {
104 }
105 }
106 > lifecycle.ts
107 > setParent(child: IDisposable, parent: IDisposable | null): void {
108 const data = this.getDisposableData(child);
109 data.parent = parent;
110 }
111 > lifecycle.ts
112 > markAsDisposed(x: IDisposable): void {
113 > this.livingDisposables.delete(x); lifecycle.ts
114 > }
115 > lifecycle.ts
116 > markAsSingleton(disposable: IDisposable): void {
117 this.getDisposableData(disposable).isSingleton = true;
118 }
119 > lifecycle.ts
120 > private getRootParent(data: DisposableInfo, cache: Map<DisposableInfo, DisposableInfo>): DisposableInfo {
121 const cacheValue = cache.get(data);
122 if (cacheValue) {
128 return result;
129 }
130 > lifecycle.ts
131 > getTrackedDisposables(): IDisposable[] {
132 const rootParentCache = new Map<DisposableInfo, DisposableInfo>();
133
138 return leaking;
139 }
140 > lifecycle.ts
141 > computeLeakingDisposables(maxReported = 10, preComputedLeaks?: DisposableInfo[]): { leaks: DisposableInfo[]; details: string } | undefined {
142 > let uncoveredLeakingObjs: DisposableInfo[] | undefined; lifecycle.ts
143 > if (preComputedLeaks) {
144 uncoveredLeakingObjs = preComputedLeaks;
145 > } else { lifecycle.ts
146 > const rootParentCache = new Map<DisposableInfo, DisposableInfo>();
147 >
148 > const leakingObjects = [...this.livingDisposables.values()]
149 > .filter((info) => info.source !== null && !this.getRootParent(info, rootParentCache).isSingleton);
150 >
151 > if (leakingObjects.length === 0) {
152 > return; lifecycle.ts
153 > }
154 const leakingObjsSet = new Set(leakingObjects.map(o => o.value));
155
162 throw new Error('There are cyclic diposable chains!');
163 }
164 > } lifecycle.ts
165
166 if (!uncoveredLeakingObjs) {
224
225 return { leaks: uncoveredLeakingObjs, details: message };
226 > } lifecycle.ts
227 > } lifecycle.ts
228 >
229 > export function setDisposableTracker(tracker: IDisposableTracker | null): void {
230 > disposableTracker = tracker; lifecycle.ts
231 > }
232 > lifecycle.ts
233 > if (TRACK_DISPOSABLES) {
234 const __is_disposable_tracked__ = '__is_disposable_tracked__';
235 setDisposableTracker(new class implements IDisposableTracker {
268 });
269 }
270 > lifecycle.ts
271 > export function trackDisposable<T extends IDisposable>(x: T): T {
272 > disposableTracker?.trackDisposable(x); lifecycle.ts
273 > return x;
274 > }
275 > lifecycle.ts
276 > export function markAsDisposed(disposable: IDisposable): void {
277 > disposableTracker?.markAsDisposed(disposable); lifecycle.ts
278 > }
279 > lifecycle.ts
280 function setParentOfDisposable(child: IDisposable, parent: IDisposable | null): void {
281 disposableTracker?.setParent(child, parent);
282 }
283 > lifecycle.ts
284 function setParentOfDisposables(children: IDisposable[], parent: IDisposable | null): void {
285 if (!disposableTracker) {
290 }
291 }
292 > lifecycle.ts
293 > /**
294 > * Indicates that the given object is a singleton which does not need to be disposed.
295 > */
296 > export function markAsSingleton<T extends IDisposable>(singleton: T): T {
297 disposableTracker?.markAsSingleton(singleton);
298 return singleton;
299 }
300 > lifecycle.ts
301 > // #endregion
302 >
303 > /**
304 > * An object that performs a cleanup operation when `.dispose()` is called.
305 > *
306 > * Some examples of how disposables are used:
307 > *
308 > * - An event listener that removes itself when `.dispose()` is called.
309 > * - A resource such as a file system watcher that cleans up the resource when `.dispose()` is called.
310 > * - The return value from registering a provider. When `.dispose()` is called, the provider is unregistered.
311 > */
312 > export interface IDisposable {
313 > dispose(): void;
314 > }
315 >
316 > /**
317 > * Check if `thing` is {@link IDisposable disposable}.
318 > */
319 > export function isDisposable<E>(thing: E): thing is E & IDisposable {
320 // eslint-disable-next-line local/code-no-any-casts
321 return typeof thing === 'object' && thing !== null && typeof (<IDisposable><any>thing).dispose === 'function' && (<IDisposable><any>thing).dispose.length === 0;
322 }
323 > lifecycle.ts
324 > /**
325 > * Disposes of the value(s) passed in.
326 > */
327 > export function dispose<T extends IDisposable>(disposable: T): T;
328 > export function dispose<T extends IDisposable>(disposable: T | undefined): T | undefined;
329 > export function dispose<T extends IDisposable, A extends Iterable<T> = Iterable<T>>(disposables: A): A;
330 > export function dispose<T extends IDisposable>(disposables: Array<T>): Array<T>;
331 > export function dispose<T extends IDisposable>(disposables: ReadonlyArray<T>): ReadonlyArray<T>;
332 > export function dispose<T extends IDisposable>(arg: T | Iterable<T> | undefined): any {
333 if (Iterable.is(arg)) {
334 const errors: any[] = [];
356 }
357 }
358 > lifecycle.ts
359 > export function disposeIfDisposable<T extends IDisposable | object>(disposables: Array<T>): Array<T> {
360 for (const d of disposables) {
361 if (isDisposable(d)) {
365 return [];
366 }
367 > lifecycle.ts
368 > /**
369 > * Combine multiple disposable values into a single {@link IDisposable}.
370 > */
371 > export function combinedDisposable(...disposables: IDisposable[]): IDisposable {
372 const parent = toDisposable(() => dispose(disposables));
373 setParentOfDisposables(disposables, parent);
374 return parent;
375 }
376 > lifecycle.ts
377 > class FunctionDisposable implements IDisposable {
378 > private _isDisposed: boolean;
379 > private readonly _fn: () => void;
380 >
381 > constructor(fn: () => void) {
382 this._isDisposed = false;
383 this._fn = fn;
384 trackDisposable(this);
385 }
386 > lifecycle.ts
387 > dispose() {
388 if (this._isDisposed) {
389 return;
396 this._fn();
397 }
398 > } lifecycle.ts
399 >
400 > /**
401 > * Turn a function that implements dispose into an {@link IDisposable}.
402 > *
403 > * @param fn Clean up function, guaranteed to be called only **once**.
404 > */
405 > export function toDisposable(fn: () => void): IDisposable {
406 return new FunctionDisposable(fn);
407 }
408 > lifecycle.ts
409 > /**
410 > * Manages a collection of disposable values.
411 > *
412 > * This is the preferred way to manage multiple disposables. A `DisposableStore` is safer to work with than an
413 > * `IDisposable[]` as it considers edge cases, such as registering the same value multiple times or adding an item to a
414 > * store that has already been disposed of.
415 > */
416 > export class DisposableStore implements IDisposable {
417 >
418 > static DISABLE_DISPOSED_WARNING = false;
419 >
420 > private readonly _toDispose = new Set<IDisposable>();
421 > private _isDisposed = false;
422 >
423 > constructor() {
424 > trackDisposable(this); lifecycle.ts
425 > }
426 > lifecycle.ts
427 > /**
428 > * Dispose of all registered disposables and mark this object as disposed.
429 > *
430 > * Any future disposables added to this object will be disposed of on `add`.
431 > */
432 > public dispose(): void {
433 > if (this._isDisposed) { lifecycle.ts
434 return;
435 }
436 > lifecycle.ts
437 > markAsDisposed(this);
438 > this._isDisposed = true;
439 > this.clear();
440 > }
441 > lifecycle.ts
442 > /**
443 > * @return `true` if this object has been disposed of.
444 > */
445 > public get isDisposed(): boolean {
446 return this._isDisposed;
447 }
448 > lifecycle.ts
449 > /**
450 > * Dispose of all registered disposables but do not mark this object as disposed.
451 > */
452 > public clear(): void {
453 > if (this._toDispose.size === 0) { lifecycle.ts
454 > return; lifecycle.ts
455 > }
456
457 try {
460 this._toDispose.clear();
461 }
462 > } lifecycle.ts
463 > lifecycle.ts
464 > /**
465 > * Add a new {@link IDisposable disposable} to the collection.
466 > */
467 > public add<T extends IDisposable>(o: T): T {
468 if (!o || o === Disposable.None) {
469 return o;
484 return o;
485 }
486 > lifecycle.ts
487 > /**
488 > * Deletes a disposable from store and disposes of it. This will not throw or warn and proceed to dispose the
489 > * disposable even when the disposable is not part in the store.
490 > */
491 > public delete<T extends IDisposable>(o: T): void {
492 if (!o) {
493 return;
499 o.dispose();
500 }
501 > lifecycle.ts
502 > /**
503 > * Deletes the value from the store, but does not dispose it.
504 > */
505 > public deleteAndLeak<T extends IDisposable>(o: T): void {
506 if (!o) {
507 return;
511 }
512 }
513 > lifecycle.ts
514 > public assertNotDisposed(): void {
515 if (this._isDisposed) {
516 onUnexpectedError(new BugIndicatingError('Object disposed'));
517 }
518 }
519 > } lifecycle.ts
520 >
521 > /**
522 > * Abstract base class for a {@link IDisposable disposable} object.
523 > *
524 > * Subclasses can {@linkcode _register} disposables that will be automatically cleaned up when this object is disposed of.
525 > */
526 > export abstract class Disposable implements IDisposable {
527 >
528 > /**
529 > * A disposable that does nothing when it is disposed of.
530 > *
531 > * TODO: This should not be a static property.
532 > */
533 > static readonly None = Object.freeze<IDisposable>({ dispose() { } });
534 >
535 > protected readonly _store = new DisposableStore();
536 >
537 > constructor() {
538 trackDisposable(this);
539 setParentOfDisposable(this._store, this);
540 }
541 > lifecycle.ts
542 > public dispose(): void {
543 markAsDisposed(this);
544
545 this._store.dispose();
546 }
547 > lifecycle.ts
548 > /**
549 > * Adds `o` to the collection of disposables managed by this object.
550 > */
551 > protected _register<T extends IDisposable>(o: T): T {
552 if ((o as unknown as Disposable) === this) {
553 throw new Error('Cannot register a disposable on itself!');
555 return this._store.add(o);
556 }
557 > } lifecycle.ts
558 >
559 > /**
560 > * Manages the lifecycle of a disposable value that may be changed.
561 > *
562 > * This ensures that when the disposable value is changed, the previously held disposable is disposed of. You can
563 > * also register a `MutableDisposable` on a `Disposable` to ensure it is automatically cleaned up.
564 > */
565 > export class MutableDisposable<T extends IDisposable> implements IDisposable {
566 > private _value?: T;
567 > private _isDisposed = false;
568 >
569 > constructor() {
570 trackDisposable(this);
571 }
572 > lifecycle.ts
573 > /**
574 > * Get the currently held disposable value, or `undefined` if this MutableDisposable has been disposed
575 > */
576 > get value(): T | undefined {
577 return this._isDisposed ? undefined : this._value;
578 }
579 > lifecycle.ts
580 > /**
581 > * Set a new disposable value.
582 > *
583 > * Behaviour:
584 > * - If the MutableDisposable has been disposed, the setter is a no-op.
585 > * - If the new value is strictly equal to the current value, the setter is a no-op.
586 > * - Otherwise the previous value (if any) is disposed and the new value is stored.
587 > *
588 > * Related helpers:
589 > * - clear() resets the value to `undefined` (and disposes the previous value).
590 > * - clearAndLeak() returns the old value without disposing it and removes its parent.
591 > */
592 > set value(value: T | undefined) {
593 if (this._isDisposed || value === this._value) {
594 return;
601 this._value = value;
602 }
603 > lifecycle.ts
604 > /**
605 > * Resets the stored value and disposed of the previously stored value.
606 > */
607 > clear(): void {
608 this.value = undefined;
609 }
610 > lifecycle.ts
611 > dispose(): void {
612 this._isDisposed = true;
613 markAsDisposed(this);
615 this._value = undefined;
616 }
617 > lifecycle.ts
618 > /**
619 > * Clears the value, but does not dispose it.
620 > * The old value is returned.
621 > */
622 > clearAndLeak(): T | undefined {
623 const oldValue = this._value;
624 this._value = undefined;
628 return oldValue;
629 }
630 > } lifecycle.ts
631 >
632 > /**
633 > * Manages the lifecycle of a disposable value that may be changed like {@link MutableDisposable}, but the value must
634 > * exist and cannot be undefined.
635 > */
636 > export class MandatoryMutableDisposable<T extends IDisposable> implements IDisposable {
637 > private readonly _disposable = new MutableDisposable<T>();
638 > private _isDisposed = false;
639 >
640 > constructor(initialValue: T) {
641 this._disposable.value = initialValue;
642 }
643 > lifecycle.ts
644 > get value(): T {
645 return this._disposable.value!;
646 }
647 > lifecycle.ts
648 > set value(value: T) {
649 if (this._isDisposed || value === this._disposable.value) {
650 return;
652 this._disposable.value = value;
653 }
654 > lifecycle.ts
655 > dispose() {
656 this._isDisposed = true;
657 this._disposable.dispose();
658 }
659 > } lifecycle.ts
660 >
661 > export class RefCountedDisposable {
662 >
663 > private _counter: number = 1;
664 >
665 > constructor(
666 private readonly _disposable: IDisposable,
667 ) { }
668 > lifecycle.ts
669 > acquire() {
670 this._counter++;
671 return this;
672 }
673 > lifecycle.ts
674 > release() {
675 if (--this._counter === 0) {
676 this._disposable.dispose();
678 return this;
679 }
680 > } lifecycle.ts
681 >
682 > export interface IReference<T> extends IDisposable {
683 > readonly object: T;
684 > }
685 >
686 > export abstract class ReferenceCollection<T> {
687
688 private readonly references: Map<string, { readonly object: T; counter: number }> = new Map();
689 > lifecycle.ts
690 > acquire(key: string, ...args: unknown[]): IReference<T> {
691 let reference = this.references.get(key);
692
708 return { object, dispose };
709 }
710 > lifecycle.ts
711 > protected abstract createReferencedObject(key: string, ...args: unknown[]): T;
712 > protected abstract destroyReferencedObject(key: string, object: T): void;
713 > }
714 >
715 > /**
716 > * Unwraps a reference collection of promised values. Makes sure
717 > * references are disposed whenever promises get rejected.
718 > */
719 > export class AsyncReferenceCollection<T> {
720 >
721 > constructor(private referenceCollection: ReferenceCollection<Promise<T>>) { }
722 >
723 > async acquire(key: string, ...args: unknown[]): Promise<IReference<T>> {
724 const ref = this.referenceCollection.acquire(key, ...args);
725
736 }
737 }
738 > } lifecycle.ts
739 >
740 > export class ImmortalReference<T> implements IReference<T> {
741 > constructor(public object: T) { }
742 > dispose(): void { /* noop */ }
743 > }
744 >
745 > export function disposeOnReturn(fn: (store: DisposableStore) => void): void {
746 const store = new DisposableStore();
747 try {
751 }
752 }
753 > lifecycle.ts
754 > /**
755 > * A map the manages the lifecycle of the values that it stores.
756 > */
757 > export class DisposableMap<K, V extends IDisposable = IDisposable> implements IDisposable {
758 >
759 > private readonly _store: Map<K, V>;
760 > private _isDisposed = false;
761 >
762 > constructor(store: Map<K, V> = new Map<K, V>()) {
763 this._store = store;
764 trackDisposable(this);
765 }
766 > lifecycle.ts
767 > /**
768 > * Disposes of all stored values and mark this object as disposed.
769 > *
770 > * Trying to use this object after it has been disposed of is an error.
771 > */
772 > dispose(): void {
773 markAsDisposed(this);
774 this._isDisposed = true;
775 this.clearAndDisposeAll();
776 }
777 > lifecycle.ts
778 > /**
779 > * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
780 > */
781 > clearAndDisposeAll(): void {
782 if (!this._store.size) {
783 return;
790 }
791 }
792 > lifecycle.ts
793 > has(key: K): boolean {
794 return this._store.has(key);
795 }
796 > lifecycle.ts
797 > get size(): number {
798 return this._store.size;
799 }
800 > lifecycle.ts
801 > get(key: K): V | undefined {
802 return this._store.get(key);
803 }
804 > lifecycle.ts
805 > set(key: K, value: V, skipDisposeOnOverwrite = false): void {
806 if (this._isDisposed) {
807 console.warn(new Error('Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!').stack);
815 setParentOfDisposable(value, this);
816 }
817 > lifecycle.ts
818 > /**
819 > * Delete the value stored for `key` from this map and also dispose of it.
820 > */
821 > deleteAndDispose(key: K): void {
822 this._store.get(key)?.dispose();
823 this._store.delete(key);
824 }
825 > lifecycle.ts
826 > /**
827 > * Delete the value stored for `key` from this map but return it. The caller is
828 > * responsible for disposing of the value.
829 > */
830 > deleteAndLeak(key: K): V | undefined {
831 const value = this._store.get(key);
832 if (value) {
836 return value;
837 }
838 > lifecycle.ts
839 > keys(): IterableIterator<K> {
840 return this._store.keys();
841 }
842 > lifecycle.ts
843 > values(): IterableIterator<V> {
844 return this._store.values();
845 }
846 > lifecycle.ts
847 > [Symbol.iterator](): IterableIterator<[K, V]> {
848 return this._store[Symbol.iterator]();
849 }
850 > } lifecycle.ts
851 >
852 > /**
853 > * A set that manages the lifecycle of the values that it stores.
854 > */
855 > export class DisposableSet<V extends IDisposable = IDisposable> implements IDisposable {
856 >
857 > private readonly _store: Set<V>;
858 > private _isDisposed = false;
859 >
860 > constructor(store: Set<V> = new Set<V>()) {
861 this._store = store;
862 trackDisposable(this);
863 }
864 > lifecycle.ts
865 > /**
866 > * Disposes of all stored values and mark this object as disposed.
867 > *
868 > * Trying to use this object after it has been disposed of is an error.
869 > */
870 > dispose(): void {
871 markAsDisposed(this);
872 this._isDisposed = true;
873 this.clearAndDisposeAll();
874 }
875 > lifecycle.ts
876 > /**
877 > * Disposes of all stored values and clear the set, but DO NOT mark this object as disposed.
878 > */
879 > clearAndDisposeAll(): void {
880 if (!this._store.size) {
881 return;
888 }
889 }
890 > lifecycle.ts
891 > has(value: V): boolean {
892 return this._store.has(value);
893 }
894 > lifecycle.ts
895 > get size(): number {
896 return this._store.size;
897 }
898 > lifecycle.ts
899 > add(value: V): void {
900 if (this._isDisposed) {
901 console.warn(new Error('Trying to add a disposable to a DisposableSet that has already been disposed of. The added object will be leaked!').stack);
905 setParentOfDisposable(value, this);
906 }
907 > lifecycle.ts
908 > /**
909 > * Delete the value from this set and also dispose of it.
910 > */
911 > deleteAndDispose(value: V): void {
912 if (this._store.delete(value)) {
913 value.dispose();
914 }
915 }
916 > lifecycle.ts
917 > /**
918 > * Delete the value from this set but return it. The caller is
919 > * responsible for disposing of the value.
920 > */
921 > deleteAndLeak(value: V): V | undefined {
922 if (this._store.delete(value)) {
923 setParentOfDisposable(value, null);
926 return undefined;
927 }
928 > lifecycle.ts
929 > values(): IterableIterator<V> {
930 return this._store.values();
931 }
932 > lifecycle.ts
933 > [Symbol.iterator](): IterableIterator<V> {
934 return this._store[Symbol.iterator]();
935 }
936 > } lifecycle.ts
937 >
938 > /**
939 > * Call `then` on a Promise, unless the returned disposable is disposed.
940 > */
941 > export function thenIfNotDisposed<T>(promise: Promise<T>, then: (result: T) => void): IDisposable {
942 let disposed = false;
943 promise.then(result => {
951 });
952 }
953 > lifecycle.ts
954 > /**
955 > * Call `then` on a promise that resolves to a {@link IDisposable}, then either register the
956 > * disposable or register it to the {@link DisposableStore}, depending on whether the store is
957 > * disposed or not.
958 > */
959 > export function thenRegisterOrDispose<T extends IDisposable>(promise: Promise<T>, store: DisposableStore): Promise<T> {
960 return promise.then(disposable => {
961 if (store.isDisposed) {
967 });
968 }
969 > lifecycle.ts
970 > export class DisposableResourceMap<V extends IDisposable = IDisposable> extends DisposableMap<URI, V> {
971 > constructor() {
972 super(new ResourceMap());
973 }
974 > } lifecycle.ts
src/vs/base/common/charCode.ts 450 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- charCode.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/
7 >
8 > /**
9 > * An inlined enum containing useful character codes (to be used with String.charCodeAt).
10 > * Please leave the const keyword such that it gets inlined when compiled to JavaScript!
11 > */
12 > export const enum CharCode {
13 > Null = 0,
14 > /**
15 > * The `\b` character.
16 > */
17 > Backspace = 8,
18 > /**
19 > * The `\t` character.
20 > */
21 > Tab = 9,
22 > /**
23 > * The `\n` character.
24 > */
25 > LineFeed = 10,
26 > /**
27 > * The `\r` character.
28 > */
29 > CarriageReturn = 13,
30 > Space = 32,
31 > /**
32 > * The `!` character.
33 > */
34 > ExclamationMark = 33,
35 > /**
36 > * The `"` character.
37 > */
38 > DoubleQuote = 34,
39 > /**
40 > * The `#` character.
41 > */
42 > Hash = 35,
43 > /**
44 > * The `$` character.
45 > */
46 > DollarSign = 36,
47 > /**
48 > * The `%` character.
49 > */
50 > PercentSign = 37,
51 > /**
52 > * The `&` character.
53 > */
54 > Ampersand = 38,
55 > /**
56 > * The `'` character.
57 > */
58 > SingleQuote = 39,
59 > /**
60 > * The `(` character.
61 > */
62 > OpenParen = 40,
63 > /**
64 > * The `)` character.
65 > */
66 > CloseParen = 41,
67 > /**
68 > * The `*` character.
69 > */
70 > Asterisk = 42,
71 > /**
72 > * The `+` character.
73 > */
74 > Plus = 43,
75 > /**
76 > * The `,` character.
77 > */
78 > Comma = 44,
79 > /**
80 > * The `-` character.
81 > */
82 > Dash = 45,
83 > /**
84 > * The `.` character.
85 > */
86 > Period = 46,
87 > /**
88 > * The `/` character.
89 > */
90 > Slash = 47,
91 >
92 > Digit0 = 48,
93 > Digit1 = 49,
94 > Digit2 = 50,
95 > Digit3 = 51,
96 > Digit4 = 52,
97 > Digit5 = 53,
98 > Digit6 = 54,
99 > Digit7 = 55,
100 > Digit8 = 56,
101 > Digit9 = 57,
102 >
103 > /**
104 > * The `:` character.
105 > */
106 > Colon = 58,
107 > /**
108 > * The `;` character.
109 > */
110 > Semicolon = 59,
111 > /**
112 > * The `<` character.
113 > */
114 > LessThan = 60,
115 > /**
116 > * The `=` character.
117 > */
118 > Equals = 61,
119 > /**
120 > * The `>` character.
121 > */
122 > GreaterThan = 62,
123 > /**
124 > * The `?` character.
125 > */
126 > QuestionMark = 63,
127 > /**
128 > * The `@` character.
129 > */
130 > AtSign = 64,
131 >
132 > A = 65,
133 > B = 66,
134 > C = 67,
135 > D = 68,
136 > E = 69,
137 > F = 70,
138 > G = 71,
139 > H = 72,
140 > I = 73,
141 > J = 74,
142 > K = 75,
143 > L = 76,
144 > M = 77,
145 > N = 78,
146 > O = 79,
147 > P = 80,
148 > Q = 81,
149 > R = 82,
150 > S = 83,
151 > T = 84,
152 > U = 85,
153 > V = 86,
154 > W = 87,
155 > X = 88,
156 > Y = 89,
157 > Z = 90,
158 >
159 > /**
160 > * The `[` character.
161 > */
162 > OpenSquareBracket = 91,
163 > /**
164 > * The `\` character.
165 > */
166 > Backslash = 92,
167 > /**
168 > * The `]` character.
169 > */
170 > CloseSquareBracket = 93,
171 > /**
172 > * The `^` character.
173 > */
174 > Caret = 94,
175 > /**
176 > * The `_` character.
177 > */
178 > Underline = 95,
179 > /**
180 > * The ``(`)`` character.
181 > */
182 > BackTick = 96,
183 >
184 > a = 97,
185 > b = 98,
186 > c = 99,
187 > d = 100,
188 > e = 101,
189 > f = 102,
190 > g = 103,
191 > h = 104,
192 > i = 105,
193 > j = 106,
194 > k = 107,
195 > l = 108,
196 > m = 109,
197 > n = 110,
198 > o = 111,
199 > p = 112,
200 > q = 113,
201 > r = 114,
202 > s = 115,
203 > t = 116,
204 > u = 117,
205 > v = 118,
206 > w = 119,
207 > x = 120,
208 > y = 121,
209 > z = 122,
210 >
211 > /**
212 > * The `{` character.
213 > */
214 > OpenCurlyBrace = 123,
215 > /**
216 > * The `|` character.
217 > */
218 > Pipe = 124,
219 > /**
220 > * The `}` character.
221 > */
222 > CloseCurlyBrace = 125,
223 > /**
224 > * The `~` character.
225 > */
226 > Tilde = 126,
227 >
228 > /**
229 > * The &nbsp; (no-break space) character.
230 > * Unicode Character 'NO-BREAK SPACE' (U+00A0)
231 > */
232 > NoBreakSpace = 160,
233 >
234 > U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent
235 > U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent
236 > U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent
237 > U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde
238 > U_Combining_Macron = 0x0304, // U+0304 Combining Macron
239 > U_Combining_Overline = 0x0305, // U+0305 Combining Overline
240 > U_Combining_Breve = 0x0306, // U+0306 Combining Breve
241 > U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above
242 > U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis
243 > U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above
244 > U_Combining_Ring_Above = 0x030A, // U+030A Combining Ring Above
245 > U_Combining_Double_Acute_Accent = 0x030B, // U+030B Combining Double Acute Accent
246 > U_Combining_Caron = 0x030C, // U+030C Combining Caron
247 > U_Combining_Vertical_Line_Above = 0x030D, // U+030D Combining Vertical Line Above
248 > U_Combining_Double_Vertical_Line_Above = 0x030E, // U+030E Combining Double Vertical Line Above
249 > U_Combining_Double_Grave_Accent = 0x030F, // U+030F Combining Double Grave Accent
250 > U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu
251 > U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve
252 > U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above
253 > U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above
254 > U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above
255 > U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right
256 > U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below
257 > U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below
258 > U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below
259 > U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below
260 > U_Combining_Left_Angle_Above = 0x031A, // U+031A Combining Left Angle Above
261 > U_Combining_Horn = 0x031B, // U+031B Combining Horn
262 > U_Combining_Left_Half_Ring_Below = 0x031C, // U+031C Combining Left Half Ring Below
263 > U_Combining_Up_Tack_Below = 0x031D, // U+031D Combining Up Tack Below
264 > U_Combining_Down_Tack_Below = 0x031E, // U+031E Combining Down Tack Below
265 > U_Combining_Plus_Sign_Below = 0x031F, // U+031F Combining Plus Sign Below
266 > U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below
267 > U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below
268 > U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below
269 > U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below
270 > U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below
271 > U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below
272 > U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below
273 > U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla
274 > U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek
275 > U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below
276 > U_Combining_Bridge_Below = 0x032A, // U+032A Combining Bridge Below
277 > U_Combining_Inverted_Double_Arch_Below = 0x032B, // U+032B Combining Inverted Double Arch Below
278 > U_Combining_Caron_Below = 0x032C, // U+032C Combining Caron Below
279 > U_Combining_Circumflex_Accent_Below = 0x032D, // U+032D Combining Circumflex Accent Below
280 > U_Combining_Breve_Below = 0x032E, // U+032E Combining Breve Below
281 > U_Combining_Inverted_Breve_Below = 0x032F, // U+032F Combining Inverted Breve Below
282 > U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below
283 > U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below
284 > U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line
285 > U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line
286 > U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay
287 > U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay
288 > U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay
289 > U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay
290 > U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay
291 > U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below
292 > U_Combining_Inverted_Bridge_Below = 0x033A, // U+033A Combining Inverted Bridge Below
293 > U_Combining_Square_Below = 0x033B, // U+033B Combining Square Below
294 > U_Combining_Seagull_Below = 0x033C, // U+033C Combining Seagull Below
295 > U_Combining_X_Above = 0x033D, // U+033D Combining X Above
296 > U_Combining_Vertical_Tilde = 0x033E, // U+033E Combining Vertical Tilde
297 > U_Combining_Double_Overline = 0x033F, // U+033F Combining Double Overline
298 > U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark
299 > U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark
300 > U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni
301 > U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis
302 > U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos
303 > U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni
304 > U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above
305 > U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below
306 > U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below
307 > U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below
308 > U_Combining_Not_Tilde_Above = 0x034A, // U+034A Combining Not Tilde Above
309 > U_Combining_Homothetic_Above = 0x034B, // U+034B Combining Homothetic Above
310 > U_Combining_Almost_Equal_To_Above = 0x034C, // U+034C Combining Almost Equal To Above
311 > U_Combining_Left_Right_Arrow_Below = 0x034D, // U+034D Combining Left Right Arrow Below
312 > U_Combining_Upwards_Arrow_Below = 0x034E, // U+034E Combining Upwards Arrow Below
313 > U_Combining_Grapheme_Joiner = 0x034F, // U+034F Combining Grapheme Joiner
314 > U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above
315 > U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above
316 > U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata
317 > U_Combining_X_Below = 0x0353, // U+0353 Combining X Below
318 > U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below
319 > U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below
320 > U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below
321 > U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above
322 > U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right
323 > U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below
324 > U_Combining_Double_Ring_Below = 0x035A, // U+035A Combining Double Ring Below
325 > U_Combining_Zigzag_Above = 0x035B, // U+035B Combining Zigzag Above
326 > U_Combining_Double_Breve_Below = 0x035C, // U+035C Combining Double Breve Below
327 > U_Combining_Double_Breve = 0x035D, // U+035D Combining Double Breve
328 > U_Combining_Double_Macron = 0x035E, // U+035E Combining Double Macron
329 > U_Combining_Double_Macron_Below = 0x035F, // U+035F Combining Double Macron Below
330 > U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde
331 > U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve
332 > U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below
333 > U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A
334 > U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E
335 > U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I
336 > U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O
337 > U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U
338 > U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C
339 > U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D
340 > U_Combining_Latin_Small_Letter_H = 0x036A, // U+036A Combining Latin Small Letter H
341 > U_Combining_Latin_Small_Letter_M = 0x036B, // U+036B Combining Latin Small Letter M
342 > U_Combining_Latin_Small_Letter_R = 0x036C, // U+036C Combining Latin Small Letter R
343 > U_Combining_Latin_Small_Letter_T = 0x036D, // U+036D Combining Latin Small Letter T
344 > U_Combining_Latin_Small_Letter_V = 0x036E, // U+036E Combining Latin Small Letter V
345 > U_Combining_Latin_Small_Letter_X = 0x036F, // U+036F Combining Latin Small Letter X
346 >
347 > /**
348 > * Unicode Character 'LINE SEPARATOR' (U+2028)
349 > * http://www.fileformat.info/info/unicode/char/2028/index.htm
350 > */
351 > LINE_SEPARATOR = 0x2028,
352 > /**
353 > * Unicode Character 'PARAGRAPH SEPARATOR' (U+2029)
354 > * http://www.fileformat.info/info/unicode/char/2029/index.htm
355 > */
356 > PARAGRAPH_SEPARATOR = 0x2029,
357 > /**
358 > * Unicode Character 'NEXT LINE' (U+0085)
359 > * http://www.fileformat.info/info/unicode/char/0085/index.htm
360 > */
361 > NEXT_LINE = 0x0085,
362 >
363 > // http://www.fileformat.info/info/unicode/category/Sk/list.htm
364 > U_CIRCUMFLEX = 0x005E, // U+005E CIRCUMFLEX
365 > U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT
366 > U_DIAERESIS = 0x00A8, // U+00A8 DIAERESIS
367 > U_MACRON = 0x00AF, // U+00AF MACRON
368 > U_ACUTE_ACCENT = 0x00B4, // U+00B4 ACUTE ACCENT
369 > U_CEDILLA = 0x00B8, // U+00B8 CEDILLA
370 > U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02C2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD
371 > U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02C3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD
372 > U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02C4, // U+02C4 MODIFIER LETTER UP ARROWHEAD
373 > U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02C5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD
374 > U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02D2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING
375 > U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02D3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING
376 > U_MODIFIER_LETTER_UP_TACK = 0x02D4, // U+02D4 MODIFIER LETTER UP TACK
377 > U_MODIFIER_LETTER_DOWN_TACK = 0x02D5, // U+02D5 MODIFIER LETTER DOWN TACK
378 > U_MODIFIER_LETTER_PLUS_SIGN = 0x02D6, // U+02D6 MODIFIER LETTER PLUS SIGN
379 > U_MODIFIER_LETTER_MINUS_SIGN = 0x02D7, // U+02D7 MODIFIER LETTER MINUS SIGN
380 > U_BREVE = 0x02D8, // U+02D8 BREVE
381 > U_DOT_ABOVE = 0x02D9, // U+02D9 DOT ABOVE
382 > U_RING_ABOVE = 0x02DA, // U+02DA RING ABOVE
383 > U_OGONEK = 0x02DB, // U+02DB OGONEK
384 > U_SMALL_TILDE = 0x02DC, // U+02DC SMALL TILDE
385 > U_DOUBLE_ACUTE_ACCENT = 0x02DD, // U+02DD DOUBLE ACUTE ACCENT
386 > U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02DE, // U+02DE MODIFIER LETTER RHOTIC HOOK
387 > U_MODIFIER_LETTER_CROSS_ACCENT = 0x02DF, // U+02DF MODIFIER LETTER CROSS ACCENT
388 > U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02E5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR
389 > U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02E6, // U+02E6 MODIFIER LETTER HIGH TONE BAR
390 > U_MODIFIER_LETTER_MID_TONE_BAR = 0x02E7, // U+02E7 MODIFIER LETTER MID TONE BAR
391 > U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02E8, // U+02E8 MODIFIER LETTER LOW TONE BAR
392 > U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02E9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR
393 > U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02EA, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK
394 > U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02EB, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK
395 > U_MODIFIER_LETTER_UNASPIRATED = 0x02ED, // U+02ED MODIFIER LETTER UNASPIRATED
396 > U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02EF, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD
397 > U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02F0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD
398 > U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02F1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD
399 > U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02F2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD
400 > U_MODIFIER_LETTER_LOW_RING = 0x02F3, // U+02F3 MODIFIER LETTER LOW RING
401 > U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02F4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT
402 > U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02F5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT
403 > U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02F6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT
404 > U_MODIFIER_LETTER_LOW_TILDE = 0x02F7, // U+02F7 MODIFIER LETTER LOW TILDE
405 > U_MODIFIER_LETTER_RAISED_COLON = 0x02F8, // U+02F8 MODIFIER LETTER RAISED COLON
406 > U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02F9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE
407 > U_MODIFIER_LETTER_END_HIGH_TONE = 0x02FA, // U+02FA MODIFIER LETTER END HIGH TONE
408 > U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02FB, // U+02FB MODIFIER LETTER BEGIN LOW TONE
409 > U_MODIFIER_LETTER_END_LOW_TONE = 0x02FC, // U+02FC MODIFIER LETTER END LOW TONE
410 > U_MODIFIER_LETTER_SHELF = 0x02FD, // U+02FD MODIFIER LETTER SHELF
411 > U_MODIFIER_LETTER_OPEN_SHELF = 0x02FE, // U+02FE MODIFIER LETTER OPEN SHELF
412 > U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02FF, // U+02FF MODIFIER LETTER LOW LEFT ARROW
413 > U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN
414 > U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS
415 > U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS
416 > U_GREEK_KORONIS = 0x1FBD, // U+1FBD GREEK KORONIS
417 > U_GREEK_PSILI = 0x1FBF, // U+1FBF GREEK PSILI
418 > U_GREEK_PERISPOMENI = 0x1FC0, // U+1FC0 GREEK PERISPOMENI
419 > U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1FC1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI
420 > U_GREEK_PSILI_AND_VARIA = 0x1FCD, // U+1FCD GREEK PSILI AND VARIA
421 > U_GREEK_PSILI_AND_OXIA = 0x1FCE, // U+1FCE GREEK PSILI AND OXIA
422 > U_GREEK_PSILI_AND_PERISPOMENI = 0x1FCF, // U+1FCF GREEK PSILI AND PERISPOMENI
423 > U_GREEK_DASIA_AND_VARIA = 0x1FDD, // U+1FDD GREEK DASIA AND VARIA
424 > U_GREEK_DASIA_AND_OXIA = 0x1FDE, // U+1FDE GREEK DASIA AND OXIA
425 > U_GREEK_DASIA_AND_PERISPOMENI = 0x1FDF, // U+1FDF GREEK DASIA AND PERISPOMENI
426 > U_GREEK_DIALYTIKA_AND_VARIA = 0x1FED, // U+1FED GREEK DIALYTIKA AND VARIA
427 > U_GREEK_DIALYTIKA_AND_OXIA = 0x1FEE, // U+1FEE GREEK DIALYTIKA AND OXIA
428 > U_GREEK_VARIA = 0x1FEF, // U+1FEF GREEK VARIA
429 > U_GREEK_OXIA = 0x1FFD, // U+1FFD GREEK OXIA
430 > U_GREEK_DASIA = 0x1FFE, // U+1FFE GREEK DASIA
431 >
432 > U_IDEOGRAPHIC_FULL_STOP = 0x3002, // U+3002 IDEOGRAPHIC FULL STOP
433 > U_LEFT_CORNER_BRACKET = 0x300C, // U+300C LEFT CORNER BRACKET
434 > U_RIGHT_CORNER_BRACKET = 0x300D, // U+300D RIGHT CORNER BRACKET
435 > U_LEFT_BLACK_LENTICULAR_BRACKET = 0x3010, // U+3010 LEFT BLACK LENTICULAR BRACKET
436 > U_RIGHT_BLACK_LENTICULAR_BRACKET = 0x3011, // U+3011 RIGHT BLACK LENTICULAR BRACKET
437 >
438 >
439 > U_OVERLINE = 0x203E, // Unicode Character 'OVERLINE'
440 >
441 > /**
442 > * UTF-8 BOM
443 > * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
444 > * http://www.fileformat.info/info/unicode/char/feff/index.htm
445 > */
446 > UTF8_BOM = 65279,
447 >
448 > U_FULLWIDTH_SEMICOLON = 0xFF1B, // U+FF1B FULLWIDTH SEMICOLON
449 > U_FULLWIDTH_COMMA = 0xFF0C, // U+FF0C FULLWIDTH COMMA
450 > }
src/vs/base/common/arrays.ts 404 covered LOC · 72 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- arrays.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { findFirstIdxMonotonousOrArrLen } from './arraysFind.js';
7 > import { CancellationToken } from './cancellation.js';
8 > import { CancellationError } from './errors.js';
9 > import { ISplice } from './sequence.js';
10 >
11 > /**
12 > * Returns the last entry and the initial N-1 entries of the array, as a tuple of [rest, last].
13 > *
14 > * The array must have at least one element.
15 > *
16 > * @param arr The input array
17 > * @returns A tuple of [rest, last] where rest is all but the last element and last is the last element
18 > * @throws Error if the array is empty
19 > */
20 > export function tail<T>(arr: T[]): [T[], T] {
21 if (arr.length === 0) {
22 throw new Error('Invalid tail call');
25 return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
26 }
27 > arrays.ts
28 > export function equals<T>(one: ReadonlyArray<T> | undefined, other: ReadonlyArray<T> | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b): boolean {
29 if (one === other) {
30 return true;
47 return true;
48 }
49 > arrays.ts
50 > /**
51 > * Remove the element at `index` by replacing it with the last element. This is faster than `splice`
52 > * but changes the order of the array
53 > */
54 > export function removeFastWithoutKeepingOrder<T>(array: T[], index: number) {
55 const last = array.length - 1;
56 if (index < last) {
59 array.pop();
60 }
61 > arrays.ts
62 > /**
63 > * Performs a binary search algorithm over a sorted array.
64 > *
65 > * @param array The array being searched.
66 > * @param key The value we search for.
67 > * @param comparator A function that takes two array elements and returns zero
68 > * if they are equal, a negative number if the first element precedes the
69 > * second one in the sorting order, or a positive number if the second element
70 > * precedes the first one.
71 > * @return See {@link binarySearch2}
72 > */
73 > export function binarySearch<T>(array: ReadonlyArray<T>, key: T, comparator: (op1: T, op2: T) => number): number {
74 return binarySearch2(array.length, i => comparator(array[i], key));
75 }
76 > arrays.ts
77 > /**
78 > * Performs a binary search algorithm over a sorted collection. Useful for cases
79 > * when we need to perform a binary search over something that isn't actually an
80 > * array, and converting data to an array would defeat the use of binary search
81 > * in the first place.
82 > *
83 > * @param length The collection length.
84 > * @param compareToKey A function that takes an index of an element in the
85 > * collection and returns zero if the value at this index is equal to the
86 > * search key, a negative number if the value precedes the search key in the
87 > * sorting order, or a positive number if the search key precedes the value.
88 > * @return A non-negative index of an element, if found. If not found, the
89 > * result is -(n+1) (or ~n, using bitwise notation), where n is the index
90 > * where the key should be inserted to maintain the sorting order.
91 > */
92 > export function binarySearch2(length: number, compareToKey: (index: number) => number): number {
93 let low = 0,
94 high = length - 1;
107 return -(low + 1);
108 }
109 > arrays.ts
110 > type Compare<T> = (a: T, b: T) => number;
111 >
112 > /**
113 > * Finds the nth smallest element in the array using quickselect algorithm.
114 > * The data does not need to be sorted.
115 > *
116 > * @param nth The zero-based index of the element to find (0 = smallest, 1 = second smallest, etc.)
117 > * @param data The unsorted array
118 > * @param compare A comparator function that defines the sort order
119 > * @returns The nth smallest element
120 > * @throws TypeError if nth is >= data.length
121 > */
122 > export function quickSelect<T>(nth: number, data: T[], compare: Compare<T>): T {
123
124 nth = nth | 0;
152 }
153 }
154 > arrays.ts
155 > export function groupBy<T>(data: ReadonlyArray<T>, compare: (a: T, b: T) => number): T[][] {
156 const result: T[][] = [];
157 let currentGroup: T[] | undefined = undefined;
166 return result;
167 }
168 > arrays.ts
169 > /**
170 > * Splits the given items into a list of (non-empty) groups.
171 > * `shouldBeGrouped` is used to decide if two consecutive items should be in the same group.
172 > * The order of the items is preserved.
173 > */
174 > export function* groupAdjacentBy<T>(items: Iterable<T>, shouldBeGrouped: (item1: T, item2: T) => boolean): Iterable<T[]> {
175 let currentGroup: T[] | undefined;
176 let last: T | undefined;
190 }
191 }
192 > arrays.ts
193 > export function forEachAdjacent<T>(arr: T[], f: (item1: T | undefined, item2: T | undefined) => void): void {
194 for (let i = 0; i <= arr.length; i++) {
195 f(i === 0 ? undefined : arr[i - 1], i === arr.length ? undefined : arr[i]);
196 }
197 }
198 > arrays.ts
199 > export function forEachWithNeighbors<T>(arr: T[], f: (before: T | undefined, element: T, after: T | undefined) => void): void {
200 for (let i = 0; i < arr.length; i++) {
201 f(i === 0 ? undefined : arr[i - 1], arr[i], i + 1 === arr.length ? undefined : arr[i + 1]);
202 }
203 }
204 > arrays.ts
205 > export function concatArrays<T extends any[]>(...arrays: T): T[number][number][] {
206 return [].concat(...arrays);
207 }
208 > arrays.ts
209 > interface IMutableSplice<T> extends ISplice<T> {
210 > readonly toInsert: T[];
211 > deleteCount: number;
212 > }
213 >
214 > /**
215 > * Diffs two *sorted* arrays and computes the splices which apply the diff.
216 > */
217 > export function sortedDiff<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): ISplice<T>[] {
218 const result: IMutableSplice<T>[] = [];
219
266 return result;
267 }
268 > arrays.ts
269 > /**
270 > * Takes two *sorted* arrays and computes their delta (removed, added elements).
271 > * Finishes in `Math.min(before.length, after.length)` steps.
272 > */
273 > export function delta<T>(before: ReadonlyArray<T>, after: ReadonlyArray<T>, compare: (a: T, b: T) => number): { removed: T[]; added: T[] } {
274 const splices = sortedDiff(before, after, compare);
275 const removed: T[] = [];
283 return { removed, added };
284 }
285 > arrays.ts
286 > /**
287 > * Returns the top N elements from the array.
288 > *
289 > * Faster than sorting the entire array when the array is a lot larger than N.
290 > *
291 > * @param array The unsorted array.
292 > * @param compare A sort function for the elements.
293 > * @param n The number of elements to return.
294 > * @return The first n elements from array when sorted with compare.
295 > */
296 > export function top<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, n: number): T[] {
297 if (n === 0) {
298 return [];
302 return result;
303 }
304 > arrays.ts
305 > /**
306 > * Asynchronous variant of `top()` allowing for splitting up work in batches between which the event loop can run.
307 > *
308 > * Returns the top N elements from the array.
309 > *
310 > * Faster than sorting the entire array when the array is a lot larger than N.
311 > *
312 > * @param array The unsorted array.
313 > * @param compare A sort function for the elements.
314 > * @param n The number of elements to return.
315 > * @param batch The number of elements to examine before yielding to the event loop.
316 > * @return The first n elements from array when sorted with compare.
317 > */
318 > export function topAsync<T>(array: T[], compare: (a: T, b: T) => number, n: number, batch: number, token?: CancellationToken): Promise<T[]> {
319 if (n === 0) {
320 return Promise.resolve([]);
339 });
340 }
341 > arrays.ts
342 function topStep<T>(array: ReadonlyArray<T>, compare: (a: T, b: T) => number, result: T[], i: number, m: number): void {
343 for (const n = result.length; i < m; i++) {
350 }
351 }
352 > arrays.ts
353 > /**
354 > * @returns New array with all falsy values removed. The original array IS NOT modified.
355 > */
356 > export function coalesce<T>(array: ReadonlyArray<T | undefined | null>): T[] {
357 return array.filter((e): e is T => !!e);
358 }
359 > arrays.ts
360 > /**
361 > * Remove all falsy values from `array`. The original array IS modified.
362 > */
363 > export function coalesceInPlace<T>(array: Array<T | undefined | null>): asserts array is Array<T> {
364 let to = 0;
365 for (let i = 0; i < array.length; i++) {
371 array.length = to;
372 }
373 > arrays.ts
374 > /**
375 > * @deprecated Use `Array.copyWithin` instead
376 > */
377 > export function move(array: unknown[], from: number, to: number): void {
378 array.splice(to, 0, array.splice(from, 1)[0]);
379 }
380 > arrays.ts
381 > /**
382 > * @returns false if the provided object is an array and not empty.
383 > */
384 > export function isFalsyOrEmpty(obj: unknown): boolean {
385 return !Array.isArray(obj) || obj.length === 0;
386 }
387 > arrays.ts
388 > /**
389 > * @returns True if the provided object is an array and has at least one element.
390 > */
391 > export function isNonEmptyArray<T>(obj: T[] | undefined | null): obj is T[];
392 > export function isNonEmptyArray<T>(obj: readonly T[] | undefined | null): obj is readonly T[];
393 > export function isNonEmptyArray<T>(obj: T[] | readonly T[] | undefined | null): obj is T[] | readonly T[] {
394 return Array.isArray(obj) && obj.length > 0;
395 }
396 > arrays.ts
397 > /**
398 > * Removes duplicates from the given array. The optional keyFn allows to specify
399 > * how elements are checked for equality by returning an alternate value for each.
400 > */
401 > export function distinct<T>(array: ReadonlyArray<T>, keyFn: (value: T) => unknown = value => value): T[] {
402 const seen = new Set<any>();
403
411 });
412 }
413 > arrays.ts
414 > export function uniqueFilter<T, R>(keyFn: (t: T) => R): (t: T) => boolean {
415 const seen = new Set<R>();
416
426 };
427 }
428 > arrays.ts
429 > export function commonPrefixLength<T>(one: ReadonlyArray<T>, other: ReadonlyArray<T>, equals: (a: T, b: T) => boolean = (a, b) => a === b): number {
430 let result = 0;
431
436 return result;
437 }
438 > arrays.ts
439 > export function range(to: number): number[];
440 > export function range(from: number, to: number): number[];
441 > export function range(arg: number, to?: number): number[] {
442 let from = typeof to === 'number' ? arg : 0;
443
463 return result;
464 }
465 > arrays.ts
466 > export function index<T>(array: ReadonlyArray<T>, indexer: (t: T) => string): { [key: string]: T };
467 > export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper: (t: T) => R): { [key: string]: R };
468 > export function index<T, R>(array: ReadonlyArray<T>, indexer: (t: T) => string, mapper?: (t: T) => R): { [key: string]: R } {
469 return array.reduce((r, t) => {
470 r[indexer(t)] = mapper ? mapper(t) : t;
472 }, Object.create(null));
473 }
474 > arrays.ts
475 > /**
476 > * Inserts an element into an array. Returns a function which, when
477 > * called, will remove that element from the array.
478 > *
479 > * @deprecated In almost all cases, use a `Set<T>` instead.
480 > */
481 > export function insert<T>(array: T[], element: T): () => void {
482 array.push(element);
483
484 return () => remove(array, element);
485 }
486 > arrays.ts
487 > /**
488 > * Removes an element from an array if it can be found.
489 > *
490 > * @deprecated In almost all cases, use a `Set<T>` instead.
491 > */
492 > export function remove<T>(array: T[], element: T): T | undefined {
493 const index = array.indexOf(element);
494 if (index > -1) {
500 return undefined;
501 }
502 > arrays.ts
503 > /**
504 > * Insert `insertArr` inside `target` at `insertIndex`.
505 > * Please don't touch unless you understand https://jsperf.com/inserting-an-array-within-an-array
506 > */
507 > export function arrayInsert<T>(target: T[], insertIndex: number, insertArr: T[]): T[] {
508 const before = target.slice(0, insertIndex);
509 const after = target.slice(insertIndex);
510 return before.concat(insertArr, after);
511 }
512 > arrays.ts
513 > /**
514 > * Uses Fisher-Yates shuffle to shuffle the given array
515 > */
516 > export function shuffle<T>(array: T[], _seed?: number): void {
517 let rand: () => number;
518
536 }
537 }
538 > arrays.ts
539 > /**
540 > * Pushes an element to the start of the array, if found.
541 > */
542 > export function pushToStart<T>(arr: T[], value: T): void {
543 const index = arr.indexOf(value);
544
548 }
549 }
550 > arrays.ts
551 > /**
552 > * Pushes an element to the end of the array, if found.
553 > */
554 > export function pushToEnd<T>(arr: T[], value: T): void {
555 const index = arr.indexOf(value);
556
560 }
561 }
562 > arrays.ts
563 > export function pushMany<T>(arr: T[], items: ReadonlyArray<T>): void {
564 for (const item of items) {
565 arr.push(item);
566 }
567 }
568 > arrays.ts
569 > export function mapArrayOrNot<T, U>(items: T | T[], fn: (_: T) => U): U | U[] {
570 return Array.isArray(items) ?
571 items.map(fn) :
572 fn(items);
573 }
574 > arrays.ts
575 > export function mapFilter<T, U>(array: ReadonlyArray<T>, fn: (t: T) => U | undefined): U[] {
576 const result: U[] = [];
577 for (const item of array) {
583 return result;
584 }
585 > arrays.ts
586 > export function withoutDuplicates<T>(array: ReadonlyArray<T>): T[] {
587 const s = new Set(array);
588 return Array.from(s);
589 }
590 > arrays.ts
591 > export function asArray<T>(x: T | T[]): T[];
592 > export function asArray<T>(x: T | readonly T[]): readonly T[];
593 > export function asArray<T>(x: T | T[]): T[] {
594 return Array.isArray(x) ? x : [x];
595 }
596 > arrays.ts
597 > export function getRandomElement<T>(arr: T[]): T | undefined {
598 return arr[Math.floor(Math.random() * arr.length)];
599 }
600 > arrays.ts
601 > /**
602 > * Insert the new items in the array.
603 > * @param array The original array.
604 > * @param start The zero-based location in the array from which to start inserting elements.
605 > * @param newItems The items to be inserted
606 > */
607 > export function insertInto<T>(array: T[], start: number, newItems: T[]): void {
608 const startIdx = getActualStartIndex(array, start);
609 const originalLength = array.length;
619 }
620 }
621 > arrays.ts
622 > /**
623 > * Removes elements from an array and inserts new elements in their place, returning the deleted elements. Alternative to the native Array.splice method, it
624 > * can only support limited number of items due to the maximum call stack size limit.
625 > * @param array The original array.
626 > * @param start The zero-based location in the array from which to start removing elements.
627 > * @param deleteCount The number of elements to remove.
628 > * @returns An array containing the elements that were deleted.
629 > */
630 > export function splice<T>(array: T[], start: number, deleteCount: number, newItems: T[]): T[] {
631 const index = getActualStartIndex(array, start);
632 let result = array.splice(index, deleteCount);
638 return result;
639 }
640 > arrays.ts
641 > /**
642 > * Determine the actual start index (same logic as the native splice() or slice())
643 > * If greater than the length of the array, start will be set to the length of the array. In this case, no element will be deleted but the method will behave as an adding function, adding as many element as item[n*] provided.
644 > * If negative, it will begin that many elements from the end of the array. (In this case, the origin -1, meaning -n is the index of the nth last element, and is therefore equivalent to the index of array.length - n.) If array.length + start is less than 0, it will begin from index 0.
645 > * @param array The target array.
646 > * @param start The operation index.
647 > */
648 function getActualStartIndex<T>(array: T[], start: number): number {
649 return start < 0 ? Math.max(start + array.length, 0) : Math.min(start, array.length);
650 }
651 > arrays.ts
652 >
653 >
654 > /**
655 > * When comparing two values,
656 > * a negative number indicates that the first value is less than the second,
657 > * a positive number indicates that the first value is greater than the second,
658 > * and zero indicates that neither is the case.
659 > */
660 > export type CompareResult = number;
661 >
662 > export namespace CompareResult {
663 > export function isLessThan(result: CompareResult): boolean {
664 return result < 0;
665 }
666 > arrays.ts
667 > export function isLessThanOrEqual(result: CompareResult): boolean {
668 return result <= 0;
669 }
670 > arrays.ts
671 > export function isGreaterThan(result: CompareResult): boolean {
672 return result > 0;
673 }
674 > arrays.ts
675 > export function isNeitherLessOrGreaterThan(result: CompareResult): boolean {
676 return result === 0;
677 }
678 > arrays.ts
679 > export const greaterThan = 1;
680 > export const lessThan = -1;
681 > export const neitherLessOrGreaterThan = 0;
682 > }
683 >
684 > /**
685 > * A comparator `c` defines a total order `<=` on `T` as following:
686 > * `c(a, b) <= 0` iff `a` <= `b`.
687 > * We also have `c(a, b) == 0` iff `c(b, a) == 0`.
688 > */
689 > export type Comparator<T> = (a: T, b: T) => CompareResult;
690 >
691 > export function compareBy<TItem, TCompareBy>(selector: (item: TItem) => TCompareBy, comparator: Comparator<TCompareBy>): Comparator<TItem> {
692 return (a, b) => comparator(selector(a), selector(b));
693 }
694 > arrays.ts
695 > export function tieBreakComparators<TItem>(...comparators: Comparator<TItem>[]): Comparator<TItem> {
696 return (item1, item2) => {
697 for (const comparator of comparators) {
704 };
705 }
706 > arrays.ts
707 > /**
708 > * The natural order on numbers.
709 > */
710 > export const numberComparator: Comparator<number> = (a, b) => a - b;
711 >
712 > export const booleanComparator: Comparator<boolean> = (a, b) => numberComparator(a ? 1 : 0, b ? 1 : 0);
713 >
714 > export function reverseOrder<TItem>(comparator: Comparator<TItem>): Comparator<TItem> {
715 return (a, b) => -comparator(a, b);
716 }
717 > arrays.ts
718 > /**
719 > * Returns a new comparator that treats `undefined` as the smallest value.
720 > * All other values are compared using the given comparator.
721 > */
722 > export function compareUndefinedSmallest<T>(comparator: Comparator<T>): Comparator<T | undefined> {
723 return (a, b) => {
724 if (a === undefined) {
731 };
732 }
733 > arrays.ts
734 > export class ArrayQueue<T> {
735 > private readonly items: readonly T[];
736 > private firstIdx = 0;
737 > private lastIdx: number;
738 >
739 > /**
740 > * Constructs a queue that is backed by the given array. Runtime is O(1).
741 > */
742 > constructor(items: readonly T[]) {
743 this.items = items;
744 this.lastIdx = this.items.length - 1;
745 }
746 > arrays.ts
747 > get length(): number {
748 return this.lastIdx - this.firstIdx + 1;
749 }
750 > arrays.ts
751 > /**
752 > * Consumes elements from the beginning of the queue as long as the predicate returns true.
753 > * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
754 > */
755 > takeWhile(predicate: (value: T) => boolean): T[] | null {
756 // P(k) := k <= this.lastIdx && predicate(this.items[k])
757 // Find s := min { k | k >= this.firstIdx && !P(k) } and return this.data[this.firstIdx...s)
765 return result;
766 }
767 > arrays.ts
768 > /**
769 > * Consumes elements from the end of the queue as long as the predicate returns true.
770 > * If no elements were consumed, `null` is returned.
771 > * The result has the same order as the underlying array!
772 > */
773 > takeFromEndWhile(predicate: (value: T) => boolean): T[] | null {
774 // P(k) := this.firstIdx >= k && predicate(this.items[k])
775 // Find s := max { k | k <= this.lastIdx && !P(k) } and return this.data(s...this.lastIdx]
783 return result;
784 }
785 > arrays.ts
786 > peek(): T | undefined {
787 if (this.length === 0) {
788 return undefined;
790 return this.items[this.firstIdx];
791 }
792 > arrays.ts
793 > peekLast(): T | undefined {
794 if (this.length === 0) {
795 return undefined;
797 return this.items[this.lastIdx];
798 }
799 > arrays.ts
800 > dequeue(): T | undefined {
801 const result = this.items[this.firstIdx];
802 this.firstIdx++;
803 return result;
804 }
805 > arrays.ts
806 > removeLast(): T | undefined {
807 const result = this.items[this.lastIdx];
808 this.lastIdx--;
809 return result;
810 }
811 > arrays.ts
812 > takeCount(count: number): T[] {
813 const result = this.items.slice(this.firstIdx, this.firstIdx + count);
814 this.firstIdx += count;
815 return result;
816 }
817 > } arrays.ts
818 >
819 > /**
820 > * This class is faster than an iterator and array for lazy computed data.
821 > */
822 > export class CallbackIterable<T> {
823 > public static readonly empty = new CallbackIterable<never>(_callback => { });
824 >
825 > constructor(
826 > /**
827 > * Calls the callback for every item.
828 > * Stops when the callback returns false.
829 > */
830 > public readonly iterate: (callback: (item: T) => boolean) => void
831 > ) {
832 > }
833 >
834 > forEach(handler: (item: T) => void) {
835 this.iterate(item => { handler(item); return true; });
836 }
837 > arrays.ts
838 > toArray(): T[] {
839 const result: T[] = [];
840 this.iterate(item => { result.push(item); return true; });
841 return result;
842 }
843 > arrays.ts
844 > filter(predicate: (item: T) => boolean): CallbackIterable<T> {
845 return new CallbackIterable(cb => this.iterate(item => predicate(item) ? cb(item) : true));
846 }
847 > arrays.ts
848 > map<TResult>(mapFn: (item: T) => TResult): CallbackIterable<TResult> {
849 return new CallbackIterable<TResult>(cb => this.iterate(item => cb(mapFn(item))));
850 }
851 > arrays.ts
852 > some(predicate: (item: T) => boolean): boolean {
853 let result = false;
854 this.iterate(item => { result = predicate(item); return !result; });
855 return result;
856 }
857 > arrays.ts
858 > findFirst(predicate: (item: T) => boolean): T | undefined {
859 let result: T | undefined;
860 this.iterate(item => {
867 return result;
868 }
869 > arrays.ts
870 > findLast(predicate: (item: T) => boolean): T | undefined {
871 let result: T | undefined;
872 this.iterate(item => {
878 return result;
879 }
880 > arrays.ts
881 > findLastMaxBy(comparator: Comparator<T>): T | undefined {
882 let result: T | undefined;
883 let first = true;
891 return result;
892 }
893 > } arrays.ts
894 >
895 > /**
896 > * Represents a re-arrangement of items in an array.
897 > */
898 > export class Permutation {
899 > constructor(private readonly _indexMap: readonly number[]) { }
900 >
901 > /**
902 > * Returns a permutation that sorts the given array according to the given compare function.
903 > */
904 > public static createSortPermutation<T>(arr: readonly T[], compareFn: (a: T, b: T) => number): Permutation {
905 const sortIndices = Array.from(arr.keys()).sort((index1, index2) => compareFn(arr[index1], arr[index2]));
906 return new Permutation(sortIndices);
907 }
908 > arrays.ts
909 > /**
910 > * Returns a new array with the elements of the given array re-arranged according to this permutation.
911 > */
912 > apply<T>(arr: readonly T[]): T[] {
913 return arr.map((_, index) => arr[this._indexMap[index]]);
914 }
915 > arrays.ts
916 > /**
917 > * Returns a new permutation that undoes the re-arrangement of this permutation.
918 > */
919 > inverse(): Permutation {
920 const inverseIndexMap = this._indexMap.slice();
921 for (let i = 0; i < this._indexMap.length; i++) {
924 return new Permutation(inverseIndexMap);
925 }
926 > } arrays.ts
927 >
928 > /**
929 > * Asynchronous variant of `Array.find()`, returning the first element in
930 > * the array for which the predicate returns true.
931 > *
932 > * This implementation does not bail early and waits for all promises to
933 > * resolve before returning.
934 > */
935 export async function findAsync<T>(array: readonly T[], predicate: (element: T, index: number) => Promise<boolean>): Promise<T | undefined> {
936 const results = await Promise.all(array.map(
940 return results.find(r => r.ok)?.element;
941 }
942 > arrays.ts
943 > export function sum(array: readonly number[]): number {
944 return array.reduce((acc, value) => acc + value, 0);
945 }
946 > arrays.ts
947 > export function sumBy<T>(array: readonly T[], selector: (value: T) => number): number {
948 return array.reduce((acc, value) => acc + selector(value), 0);
949 }
src/vs/base/common/stream.ts 325 covered LOC · 29 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- stream.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CancellationToken } from './cancellation.js';
7 > import { onUnexpectedError } from './errors.js';
8 > import { DisposableStore, toDisposable } from './lifecycle.js';
9 >
10 > /**
11 > * The payload that flows in readable stream events.
12 > */
13 > export type ReadableStreamEventPayload<T> = T | Error | 'end';
14 >
15 > export interface ReadableStreamEvents<T> {
16 >
17 > /**
18 > * The 'data' event is emitted whenever the stream is
19 > * relinquishing ownership of a chunk of data to a consumer.
20 > *
21 > * NOTE: PLEASE UNDERSTAND THAT ADDING A DATA LISTENER CAN
22 > * TURN THE STREAM INTO FLOWING MODE. IT IS THEREFOR THE
23 > * LAST LISTENER THAT SHOULD BE ADDED AND NOT THE FIRST
24 > *
25 > * Use `listenStream` as a helper method to listen to
26 > * stream events in the right order.
27 > */
28 > on(event: 'data', callback: (data: T) => void): void;
29 >
30 > /**
31 > * Emitted when any error occurs.
32 > */
33 > on(event: 'error', callback: (err: Error) => void): void;
34 >
35 > /**
36 > * The 'end' event is emitted when there is no more data
37 > * to be consumed from the stream. The 'end' event will
38 > * not be emitted unless the data is completely consumed.
39 > */
40 > on(event: 'end', callback: () => void): void;
41 > }
42 >
43 > /**
44 > * A interface that emulates the API shape of a node.js readable
45 > * stream for use in native and web environments.
46 > */
47 > export interface ReadableStream<T> extends ReadableStreamEvents<T> {
48 >
49 > /**
50 > * Stops emitting any events until resume() is called.
51 > */
52 > pause(): void;
53 >
54 > /**
55 > * Starts emitting events again after pause() was called.
56 > */
57 > resume(): void;
58 >
59 > /**
60 > * Destroys the stream and stops emitting any event.
61 > */
62 > destroy(): void;
63 >
64 > /**
65 > * Allows to remove a listener that was previously added.
66 > */
67 > removeListener(event: string, callback: Function): void;
68 > }
69 >
70 > /**
71 > * A interface that emulates the API shape of a node.js readable
72 > * for use in native and web environments.
73 > */
74 > export interface Readable<T> {
75 >
76 > /**
77 > * Read data from the underlying source. Will return
78 > * null to indicate that no more data can be read.
79 > */
80 > read(): T | null;
81 > }
82 >
83 > export function isReadable<T>(obj: unknown): obj is Readable<T> {
84 const candidate = obj as Readable<T> | undefined;
85 if (!candidate) {
89 return typeof candidate.read === 'function';
90 }
91 > stream.ts
92 > /**
93 > * A interface that emulates the API shape of a node.js writeable
94 > * stream for use in native and web environments.
95 > */
96 > export interface WriteableStream<T> extends ReadableStream<T> {
97 >
98 > /**
99 > * Writing data to the stream will trigger the on('data')
100 > * event listener if the stream is flowing and buffer the
101 > * data otherwise until the stream is flowing.
102 > *
103 > * If a `highWaterMark` is configured and writing to the
104 > * stream reaches this mark, a promise will be returned
105 > * that should be awaited on before writing more data.
106 > * Otherwise there is a risk of buffering a large number
107 > * of data chunks without consumer.
108 > */
109 > write(data: T): void | Promise<void>;
110 >
111 > /**
112 > * Signals an error to the consumer of the stream via the
113 > * on('error') handler if the stream is flowing.
114 > *
115 > * NOTE: call `end` to signal that the stream has ended,
116 > * this DOES NOT happen automatically from `error`.
117 > */
118 > error(error: Error): void;
119 >
120 > /**
121 > * Signals the end of the stream to the consumer. If the
122 > * result is provided, will trigger the on('data') event
123 > * listener if the stream is flowing and buffer the data
124 > * otherwise until the stream is flowing.
125 > */
126 > end(result?: T): void;
127 > }
128 >
129 > /**
130 > * A stream that has a buffer already read. Returns the original stream
131 > * that was read as well as the chunks that got read.
132 > *
133 > * The `ended` flag indicates if the stream has been fully consumed.
134 > */
135 > export interface ReadableBufferedStream<T> {
136 >
137 > /**
138 > * The original stream that is being read.
139 > */
140 > stream: ReadableStream<T>;
141 >
142 > /**
143 > * An array of chunks already read from this stream.
144 > */
145 > buffer: T[];
146 >
147 > /**
148 > * Signals if the stream has ended or not. If not, consumers
149 > * should continue to read from the stream until consumed.
150 > */
151 > ended: boolean;
152 > }
153 >
154 > export function isReadableStream<T>(obj: unknown): obj is ReadableStream<T> {
155 const candidate = obj as ReadableStream<T> | undefined;
156 if (!candidate) {
160 return [candidate.on, candidate.pause, candidate.resume, candidate.destroy].every(fn => typeof fn === 'function');
161 }
162 > stream.ts
163 > export function isReadableBufferedStream<T>(obj: unknown): obj is ReadableBufferedStream<T> {
164 const candidate = obj as ReadableBufferedStream<T> | undefined;
165 if (!candidate) {
169 return isReadableStream(candidate.stream) && Array.isArray(candidate.buffer) && typeof candidate.ended === 'boolean';
170 }
171 > stream.ts
172 > export interface IReducer<T, R = T> {
173 > (data: T[]): R;
174 > }
175 >
176 > export interface IDataTransformer<Original, Transformed> {
177 > (data: Original): Transformed;
178 > }
179 >
180 > export interface IErrorTransformer {
181 > (error: Error): Error;
182 > }
183 >
184 > export interface ITransformer<Original, Transformed> {
185 > data: IDataTransformer<Original, Transformed>;
186 > error?: IErrorTransformer;
187 > }
188 >
189 > export function newWriteableStream<T>(reducer: IReducer<T> | null, options?: WriteableStreamOptions): WriteableStream<T> {
190 return new WriteableStreamImpl<T>(reducer, options);
191 }
192 > stream.ts
193 > export interface WriteableStreamOptions {
194 >
195 > /**
196 > * The number of objects to buffer before WriteableStream#write()
197 > * signals back that the buffer is full. Can be used to reduce
198 > * the memory pressure when the stream is not flowing.
199 > */
200 > highWaterMark?: number;
201 > }
202 >
203 > class WriteableStreamImpl<T> implements WriteableStream<T> {
204 >
205 > private readonly state = {
206 > flowing: false,
207 > ended: false,
208 > destroyed: false
209 > };
210 >
211 > private readonly buffer = {
212 > data: [] as T[],
213 > error: [] as Error[]
214 > };
215 >
216 > private readonly listeners = {
217 > data: [] as { (data: T): void }[],
218 > error: [] as { (error: Error): void }[],
219 > end: [] as { (): void }[]
220 > };
221 >
222 > private readonly pendingWritePromises: Function[] = [];
223 >
224 > /**
225 > * @param reducer a function that reduces the buffered data into a single object;
226 > * because some objects can be complex and non-reducible, we also
227 > * allow passing the explicit `null` value to skip the reduce step
228 > * @param options stream options
229 > */
230 > constructor(private reducer: IReducer<T> | null, private options?: WriteableStreamOptions) { }
231 >
232 > pause(): void {
233 if (this.state.destroyed) {
234 return;
237 this.state.flowing = false;
238 }
239 > stream.ts
240 > resume(): void {
241 if (this.state.destroyed) {
242 return;
252 }
253 }
254 > stream.ts
255 > write(data: T): void | Promise<void> {
256 if (this.state.destroyed) {
257 return;
273 }
274 }
275 > stream.ts
276 > error(error: Error): void {
277 if (this.state.destroyed) {
278 return;
289 }
290 }
291 > stream.ts
292 > end(result?: T): void {
293 if (this.state.destroyed) {
294 return;
312 }
313 }
314 > stream.ts
315 > private emitData(data: T): void {
316 this.listeners.data.slice(0).forEach(listener => listener(data)); // slice to avoid listener mutation from delivering event
317 }
318 > stream.ts
319 > private emitError(error: Error): void {
320 if (this.listeners.error.length === 0) {
321 onUnexpectedError(error); // nobody listened to this error so we log it as unexpected
324 }
325 }
326 > stream.ts
327 > private emitEnd(): void {
328 this.listeners.end.slice(0).forEach(listener => listener()); // slice to avoid listener mutation from delivering event
329 }
330 > stream.ts
331 > on(event: 'data', callback: (data: T) => void): void;
332 > on(event: 'error', callback: (err: Error) => void): void;
333 > on(event: 'end', callback: () => void): void;
334 > on(event: 'data' | 'error' | 'end', callback: ((data: T) => void) | ((err: Error) => void) | (() => void)): void {
335 if (this.state.destroyed) {
336 return;
372 }
373 }
374 > stream.ts
375 > removeListener(event: string, callback: Function): void {
376 if (this.state.destroyed) {
377 return;
401 }
402 }
403 > stream.ts
404 > private flowData(): void {
405 // if buffer is empty, nothing to do
406 if (this.buffer.data.length === 0) {
428 pendingWritePromises.forEach(pendingWritePromise => pendingWritePromise());
429 }
430 > stream.ts
431 > private flowErrors(): void {
432 if (this.listeners.error.length > 0) {
433 for (const error of this.buffer.error) {
438 }
439 }
440 > stream.ts
441 > private flowEnd(): boolean {
442 if (this.state.ended) {
443 this.emitEnd();
448 return false;
449 }
450 > stream.ts
451 > destroy(): void {
452 if (!this.state.destroyed) {
453 this.state.destroyed = true;
464 }
465 }
466 > } stream.ts
467 >
468 > /**
469 > * Helper to fully read a T readable into a T.
470 > */
471 > export function consumeReadable<T>(readable: Readable<T>, reducer: IReducer<T>): T {
472 const chunks: T[] = [];
473
479 return reducer(chunks);
480 }
481 > stream.ts
482 > /**
483 > * Helper to read a T readable up to a maximum of chunks. If the limit is
484 > * reached, will return a readable instead to ensure all data can still
485 > * be read.
486 > */
487 > export function peekReadable<T>(readable: Readable<T>, reducer: IReducer<T>, maxChunks: number): T | Readable<T> {
488 const chunks: T[] = [];
489
527 };
528 }
529 > stream.ts
530 > /**
531 > * Helper to fully read a T stream into a T or consuming
532 > * a stream fully, awaiting all the events without caring
533 > * about the data.
534 > */
535 > export function consumeStream<T, R = T>(stream: ReadableStreamEvents<T>, reducer: IReducer<T, R>): Promise<R>;
536 > export function consumeStream(stream: ReadableStreamEvents<unknown>): Promise<undefined>;
537 > export function consumeStream<T, R = T>(stream: ReadableStreamEvents<T>, reducer?: IReducer<T, R>): Promise<R | undefined> {
538 return new Promise((resolve, reject) => {
539 const chunks: T[] = [];
562 });
563 }
564 > stream.ts
565 > export interface IStreamListener<T> {
566 >
567 > /**
568 > * The 'data' event is emitted whenever the stream is
569 > * relinquishing ownership of a chunk of data to a consumer.
570 > */
571 > onData(data: T): void;
572 >
573 > /**
574 > * Emitted when any error occurs.
575 > */
576 > onError(err: Error): void;
577 >
578 > /**
579 > * The 'end' event is emitted when there is no more data
580 > * to be consumed from the stream. The 'end' event will
581 > * not be emitted unless the data is completely consumed.
582 > */
583 > onEnd(): void;
584 > }
585 >
586 > /**
587 > * Helper to listen to all events of a T stream in proper order.
588 > */
589 > export function listenStream<T>(stream: ReadableStreamEvents<T>, listener: IStreamListener<T>, token?: CancellationToken): void {
590
591 stream.on('error', error => {
610 });
611 }
612 > stream.ts
613 > /**
614 > * Helper to peek up to `maxChunks` into a stream. The return type signals if
615 > * the stream has ended or not. If not, caller needs to add a `data` listener
616 > * to continue reading.
617 > */
618 > export function peekStream<T>(stream: ReadableStream<T>, maxChunks: number): Promise<ReadableBufferedStream<T>> {
619 return new Promise((resolve, reject) => {
620 const streamListeners = new DisposableStore();
666 });
667 }
668 > stream.ts
669 > /**
670 > * Helper to create a readable stream from an existing T.
671 > */
672 > export function toStream<T>(t: T, reducer: IReducer<T>): ReadableStream<T> {
673 const stream = newWriteableStream<T>(reducer);
674
677 return stream;
678 }
679 > stream.ts
680 > /**
681 > * Helper to create an empty stream
682 > */
683 > export function emptyStream(): ReadableStream<never> {
684 const stream = newWriteableStream<never>(() => { throw new Error('not supported'); });
685 stream.end();
687 return stream;
688 }
689 > stream.ts
690 > /**
691 > * Helper to convert a T into a Readable<T>.
692 > */
693 > export function toReadable<T>(t: T): Readable<T> {
694 let consumed = false;
695
706 };
707 }
708 > stream.ts
709 > /**
710 > * Helper to transform a readable stream into another stream.
711 > */
712 > export function transform<Original, Transformed>(stream: ReadableStreamEvents<Original>, transformer: ITransformer<Original, Transformed>, reducer: IReducer<Transformed>): ReadableStream<Transformed> {
713 const target = newWriteableStream<Transformed>(reducer);
714
721 return target;
722 }
723 > stream.ts
724 > /**
725 > * Helper to take an existing readable that will
726 > * have a prefix injected to the beginning.
727 > */
728 > export function prefixedReadable<T>(prefix: T, readable: Readable<T>, reducer: IReducer<T>): Readable<T> {
729 let prefixHandled = false;
730
751 };
752 }
753 > stream.ts
754 > /**
755 > * Helper to take an existing stream that will
756 > * have a prefix injected to the beginning.
757 > */
758 > export function prefixedStream<T>(prefix: T, stream: ReadableStream<T>, reducer: IReducer<T>): ReadableStream<T> {
759 let prefixHandled = false;
760
src/vs/platform/agentHost/common/state/protocol/channels-session/commands.ts 323 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commands.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI } from '../common/state.js';
10 > import type { BaseParams } from '../common/commands.js';
11 > import type { SessionActiveClient } from './state.js';
12 > import type { MessageAttachment } from '../channels-chat/state.js';
13 >
14 > // ─── createSession ───────────────────────────────────────────────────────────
15 >
16 > /**
17 > * Creates a new session with the specified agent provider.
18 > *
19 > * If the session URI already exists, the server MUST return an error with code
20 > * `-32003` (`SessionAlreadyExists`).
21 > *
22 > * After creation, the client should subscribe to the session URI to receive state
23 > * updates. The server also broadcasts a `root/sessionAdded` notification to all
24 > * clients.
25 > *
26 > * @category Commands
27 > * @method createSession
28 > * @direction Client → Server
29 > * @messageType Request
30 > * @version 1
31 > * @example
32 > * ```jsonc
33 > * // Client → Server
34 > * { "jsonrpc": "2.0", "id": 2, "method": "createSession",
35 > * "params": { "channel": "ahp-session:/<uuid>", "provider": "copilot" } }
36 > *
37 > * // Server → Client (success)
38 > * { "jsonrpc": "2.0", "id": 2, "result": null }
39 > *
40 > * // Server → Client (failure — provider not found)
41 > * { "jsonrpc": "2.0", "id": 2, "error": { "code": -32002, "message": "No agent for provider" } }
42 > *
43 > * // Server → Client (failure — session already exists)
44 > * { "jsonrpc": "2.0", "id": 2, "error": { "code": -32003, "message": "Session already exists" } }
45 > * ```
46 > */
47 > /**
48 > * Identifies a source session and turn to fork from.
49 > *
50 > * When provided in `createSession`, the server populates the new session with
51 > * content from the source session up to and including the response of the
52 > * specified turn.
53 > */
54 > export interface SessionForkSource {
55 > /** URI of the existing session to fork from */
56 > session: URI;
57 > /** Turn ID in the source session; content up to and including this turn's response is copied */
58 > turnId: string;
59 > }
60 >
61 > export interface CreateSessionParams extends BaseParams {
62 > /** Session URI (client-chosen, e.g. `ahp-session:/<uuid>`) */
63 > channel: URI;
64 > /** Agent provider ID */
65 > provider?: string;
66 > /**
67 > * The working directories the session's agent is granted tool access to.
68 > * A session may span multiple directories; they are equal peers except when
69 > * the agent advertises
70 > * {@link MultipleWorkingDirectoriesCapability.requiresPrimary}, in which case
71 > * one of them should be designated the primary via
72 > * {@link primaryWorkingDirectory}.
73 > *
74 > * A client MUST NOT supply more than one entry unless the agent advertises
75 > * {@link AgentCapabilities.multipleWorkingDirectories}; a server without that
76 > * capability treats only the first entry as the session's working directory
77 > * and ignores the rest. Dispatch `session/workingDirectorySet` /
78 > * `session/workingDirectoryRemoved` to change the set after the session has
79 > * started.
80 > *
81 > * Ignored for forked sessions — a fork inherits its working directories
82 > * from the source session identified by `fork`.
83 > */
84 > workingDirectories?: URI[];
85 > /**
86 > * The primary working directory for the session's **default chat**.
87 > *
88 > * A session has no primary of its own — primary is a per-chat notion (see
89 > * {@link ChatState.primaryWorkingDirectory}). But `createSession` implicitly
90 > * creates the session's default chat, and there is no separate `createChat`
91 > * call to carry that chat's create-time fields. This field is therefore the
92 > * only place a client can designate the **default chat's** primary at birth;
93 > * it is copied into that chat's read-only `primaryWorkingDirectory`. For any
94 > * non-default chat, pass {@link CreateChatParams.primaryWorkingDirectory}
95 > * instead.
96 > *
97 > * When set, it MUST be one of {@link workingDirectories}. A client SHOULD
98 > * supply this when the agent advertises
99 > * {@link MultipleWorkingDirectoriesCapability.requiresPrimary}; a host MAY
100 > * reject creation that omits it, or fall back to the first entry of
101 > * `workingDirectories`. Ignored for forked sessions (a fork inherits the
102 > * source session's chats and their primaries).
103 > */
104 > primaryWorkingDirectory?: URI;
105 > /**
106 > * Fork from an existing session. The new session is populated with content
107 > * from the source session up to and including the specified turn's response.
108 > */
109 > fork?: SessionForkSource;
110 > /**
111 > * Agent-specific configuration values collected via `resolveSessionConfig`.
112 > * Keys and values correspond to the schema returned by the server.
113 > */
114 > config?: Record<string, unknown>;
115 > /**
116 > * Eagerly claim an active client role for the new session.
117 > *
118 > * When provided, the server initializes the session with this client as an
119 > * active client, equivalent to dispatching a `session/activeClientSet`
120 > * action immediately after creation. The `clientId` MUST match the
121 > * `clientId` the creating client supplied in `initialize`.
122 > */
123 > activeClient?: SessionActiveClient;
124 > /**
125 > * Opt-in progress token. When set, the client is offering to receive
126 > * `progress` notifications (see `ProgressParams`) for any long-running work
127 > * the server does to bring this session up — most notably the lazy,
128 > * first-use download of the provider's native SDK. The server echoes this
129 > * exact token on every `progress` frame so the client can correlate it to
130 > * this `createSession` call (and the UI awaiting it).
131 > *
132 > * The token MUST be unique across the client's active requests. The server
133 > * MAY ignore it (e.g. when nothing long-running is needed), in which case no
134 > * `progress` notifications are emitted.
135 > */
136 > progressToken?: string;
137 > }
138 >
139 > // ─── disposeSession ──────────────────────────────────────────────────────────
140 >
141 > /**
142 > * Disposes a session and cleans up server-side resources.
143 > *
144 > * The server broadcasts a `root/sessionRemoved` notification to all clients.
145 > *
146 > * @category Commands
147 > * @method disposeSession
148 > * @direction Client → Server
149 > * @messageType Request
150 > * @version 1
151 > */
152 > export interface DisposeSessionParams extends BaseParams { }
153 >
154 > // ─── fetchTurns ──────────────────────────────────────────────────────────────
155 >
156 > /**
157 > * Requests that the host load older historical turns into a chat state.
158 > *
159 > * The command result does not carry turns. Instead, before responding, the host
160 > * MUST dispatch `chat/turnsLoaded` to insert any loaded turns into the chat
161 > * channel's `turns` state, ahead of the already-loaded window, and update or
162 > * clear `turnsNextCursor`.
163 > *
164 > * Before applying any operation that references a turn outside the currently
165 > * loaded window, the host MUST eagerly load enough older turns into state for
166 > * that operation to reduce against valid state.
167 > *
168 > * @category Commands
169 > * @method fetchTurns
170 > * @direction Client → Server
171 > * @messageType Request
172 > * @version 1
173 > * @example
174 > * ```jsonc
175 > * // Client → Server (load the next page indicated by ChatState.turnsNextCursor)
176 > * { "jsonrpc": "2.0", "id": 8, "method": "fetchTurns",
177 > * "params": { "channel": "ahp-chat:/<uuid>", "cursor": "opaque-cursor" } }
178 > *
179 > * // Server updates chat state, then responds
180 > * { "jsonrpc": "2.0", "id": 8, "result": {} }
181 > * ```
182 > */
183 > export interface FetchTurnsParams extends BaseParams {
184 > /** Chat URI */
185 > channel: URI;
186 > /**
187 > * Opaque cursor from `ChatState.turnsNextCursor`.
188 > *
189 > * The host MUST reject unrecognised cursors with `InvalidParams`. Omit only
190 > * when asking the host to opportunistically load its next older page for the
191 > * chat, if any.
192 > */
193 > cursor?: string;
194 > }
195 >
196 > /**
197 > * Result of the `fetchTurns` command.
198 > */
199 > export interface FetchTurnsResult { }
200 >
201 > // ─── completions ─────────────────────────────────────────────────────────────
202 >
203 > /**
204 > * The kind of completion items being requested.
205 > *
206 > * @category Commands
207 > */
208 > export const enum CompletionItemKind {
209 > /**
210 > * Completions for the text of a {@link Message} the user is composing.
211 > * Each returned item carries an attachment that gets associated with the
212 > * message when accepted.
213 > */
214 > UserMessage = 'userMessage',
215 > }
216 >
217 > /**
218 > * Requests completion items for a partially-typed input (e.g. a user message
219 > * the user is currently composing). Used to power `@`-mention pickers,
220 > * file/symbol references, and similar inline-completion experiences.
221 > *
222 > * Servers SHOULD treat this command as best-effort and return promptly. The
223 > * client SHOULD debounce calls to avoid flooding the server with requests on
224 > * every keystroke.
225 > *
226 > * @category Commands
227 > * @method completions
228 > * @direction Client → Server
229 > * @messageType Request
230 > * @version 1
231 > * @example
232 > * ```jsonc
233 > * // User has typed "look at @foo" and the cursor is just after "@foo".
234 > * // Client → Server
235 > * { "jsonrpc": "2.0", "id": 12, "method": "completions",
236 > * "params": { "kind": "userMessage", "channel": "ahp-chat:/<uuid>",
237 > * "text": "look at @foo", "offset": 12 } }
238 > *
239 > * // Server → Client
240 > * { "jsonrpc": "2.0", "id": 12, "result": {
241 > * "items": [
242 > * {
243 > * "insertText": "@foo.ts",
244 > * "rangeStart": 8,
245 > * "rangeEnd": 12,
246 > * "attachment": {
247 > * "type": "resource",
248 > * "label": "foo.ts",
249 > * "displayKind": "document",
250 > * "uri": "file:///workspace/foo.ts"
251 > * }
252 > * }
253 > * ]
254 > * }}
255 > * ```
256 > */
257 > export interface CompletionsParams extends BaseParams {
258 > /** What kind of completion is being requested. */
259 > kind: CompletionItemKind;
260 > /** The chat URI the completion is being requested for. */
261 > channel: URI;
262 > /**
263 > * The complete text of the input being completed (e.g. the full user
264 > * message text typed so far).
265 > */
266 > text: string;
267 > /**
268 > * The character offset within `text` at which the completion is requested,
269 > * measured in UTF-16 code units. MUST satisfy `0 <= offset <= text.length`.
270 > */
271 > offset: number;
272 > }
273 >
274 > /**
275 > * A single completion item returned by the `completions` command.
276 > *
277 > * When the user accepts an item, the client SHOULD:
278 > * 1. Replace the range `[rangeStart, rangeEnd)` in the input with `insertText`
279 > * (or insert `insertText` at the cursor when the range is omitted).
280 > * 2. Associate the item's `attachment` with the resulting {@link Message}.
281 > *
282 > * @category Commands
283 > */
284 > export interface CompletionItem {
285 > /**
286 > * The text inserted into the input when this item is accepted.
287 > */
288 > insertText: string;
289 >
290 > /**
291 > * If defined, the start of the range in the input's `text` that is replaced
292 > * by `insertText`. The range is the half-open interval
293 > * `[rangeStart, rangeEnd)` of character offsets, measured in UTF-16 code
294 > * units.
295 > *
296 > * When omitted, the client SHOULD insert `insertText` at the cursor.
297 > *
298 > * Note: this range refers to positions in the *current* input. The
299 > * attachment's own `rangeStart`/`rangeEnd` (when present) refer to
300 > * positions in the final {@link Message.text} after the item is
301 > * accepted.
302 > */
303 > rangeStart?: number;
304 >
305 > /**
306 > * The end of the range in the input's `text` that is replaced by
307 > * `insertText`. See {@link rangeStart}.
308 > */
309 > rangeEnd?: number;
310 >
311 > /**
312 > * The attachment associated with this completion item.
313 > */
314 > attachment: MessageAttachment;
315 > }
316 >
317 > /**
318 > * Result of the `completions` command.
319 > */
320 > export interface CompletionsResult {
321 > /** The completion items, in the order the server suggests displaying them. */
322 > items: CompletionItem[];
323 > }
src/vs/base/common/map.ts 313 covered LOC · 97 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- map.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { URI } from './uri.js';
7 >
8 > export function getOrSet<K, V>(map: Map<K, V>, key: K, value: V): V {
9 let result = map.get(key);
10 if (result === undefined) {
15 return result;
16 }
17 > map.ts
18 > export function mapToString<K, V>(map: Map<K, V>): string {
19 const entries: string[] = [];
20 map.forEach((value, key) => {
24 return `Map(${map.size}) {${entries.join(', ')}}`;
25 }
26 > map.ts
27 > export function setToString<K>(set: Set<K>): string {
28 const entries: K[] = [];
29 set.forEach(value => {
33 return `Set(${set.size}) {${entries.join(', ')}}`;
34 }
35 > map.ts
36 > interface ResourceMapKeyFn {
37 > (resource: URI): string;
38 > }
39 >
40 > class ResourceMapEntry<T> {
41 > constructor(readonly uri: URI, readonly value: T) { }
42 > }
43 >
44 function isEntries<T>(arg: ResourceMap<T> | ResourceMapKeyFn | readonly (readonly [URI, T])[] | undefined): arg is readonly (readonly [URI, T])[] {
45 return Array.isArray(arg);
46 }
47 > map.ts
48 > export class ResourceMap<T> implements Map<URI, T> {
49 >
50 > private static readonly defaultToKey = (resource: URI) => resource.toString();
51 >
52 > readonly [Symbol.toStringTag] = 'ResourceMap';
53 >
54 > private readonly map: Map<string, ResourceMapEntry<T>>;
55 > private readonly toKey: ResourceMapKeyFn;
56 >
57 > /**
58 > *
59 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
60 > */
61 > constructor(toKey?: ResourceMapKeyFn);
62 >
63 > /**
64 > *
65 > * @param other Another resource which this maps is created from
66 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
67 > */
68 > constructor(other?: ResourceMap<T>, toKey?: ResourceMapKeyFn);
69 >
70 > /**
71 > *
72 > * @param other Another resource which this maps is created from
73 > * @param toKey Custom uri identity function, e.g use an existing `IExtUri#getComparison`-util
74 > */
75 > constructor(entries?: readonly (readonly [URI, T])[], toKey?: ResourceMapKeyFn);
76 >
77 > constructor(arg?: ResourceMap<T> | ResourceMapKeyFn | readonly (readonly [URI, T])[], toKey?: ResourceMapKeyFn) {
78 if (arg instanceof ResourceMap) {
79 this.map = new Map(arg.map);
91 }
92 }
93 > map.ts
94 > set(resource: URI, value: T): this {
95 this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value));
96 return this;
97 }
98 > map.ts
99 > get(resource: URI): T | undefined {
100 return this.map.get(this.toKey(resource))?.value;
101 }
102 > map.ts
103 > has(resource: URI): boolean {
104 return this.map.has(this.toKey(resource));
105 }
106 > map.ts
107 > get size(): number {
108 return this.map.size;
109 }
110 > map.ts
111 > clear(): void {
112 this.map.clear();
113 }
114 > map.ts
115 > delete(resource: URI): boolean {
116 return this.map.delete(this.toKey(resource));
117 }
118 > map.ts
119 > forEach(clb: (value: T, key: URI, map: Map<URI, T>) => void, thisArg?: object): void {
120 if (typeof thisArg !== 'undefined') {
121 clb = clb.bind(thisArg);
125 }
126 }
127 > map.ts
128 > *values(): MapIterator<T> {
129 for (const entry of this.map.values()) {
130 yield entry.value;
131 }
132 }
133 > map.ts
134 > *keys(): MapIterator<URI> {
135 for (const entry of this.map.values()) {
136 yield entry.uri;
137 }
138 }
139 > map.ts
140 > *entries(): MapIterator<[URI, T]> {
141 for (const entry of this.map.values()) {
142 yield [entry.uri, entry.value];
143 }
144 }
145 > map.ts
146 > *[Symbol.iterator](): MapIterator<[URI, T]> {
147 for (const [, entry] of this.map) {
148 yield [entry.uri, entry.value];
149 }
150 }
151 > } map.ts
152 >
153 > export class ResourceSet implements Set<URI> {
154 >
155 > readonly [Symbol.toStringTag]: string = 'ResourceSet';
156 >
157 > private readonly _map: ResourceMap<URI>;
158 >
159 > constructor(toKey?: ResourceMapKeyFn);
160 > constructor(entries: readonly URI[], toKey?: ResourceMapKeyFn);
161 > constructor(entriesOrKey?: readonly URI[] | ResourceMapKeyFn, toKey?: ResourceMapKeyFn) {
162 if (!entriesOrKey || typeof entriesOrKey === 'function') {
163 this._map = new ResourceMap(entriesOrKey);
167 }
168 }
169 > map.ts
170 >
171 > get size(): number {
172 return this._map.size;
173 }
174 > map.ts
175 > add(value: URI): this {
176 this._map.set(value, value);
177 return this;
178 }
179 > map.ts
180 > clear(): void {
181 this._map.clear();
182 }
183 > map.ts
184 > delete(value: URI): boolean {
185 return this._map.delete(value);
186 }
187 > map.ts
188 > forEach(callbackfn: (value: URI, value2: URI, set: Set<URI>) => void, thisArg?: unknown): void {
189 this._map.forEach((_value, key) => callbackfn.call(thisArg, key, key, this));
190 }
191 > map.ts
192 > has(value: URI): boolean {
193 return this._map.has(value);
194 }
195 > map.ts
196 > entries(): SetIterator<[URI, URI]> {
197 return this._map.entries() as unknown as SetIterator<[URI, URI]>;
198 }
199 > map.ts
200 > keys(): SetIterator<URI> {
201 return this._map.keys() as unknown as SetIterator<URI>;
202 }
203 > map.ts
204 > values(): SetIterator<URI> {
205 return this._map.keys() as unknown as SetIterator<URI>;
206 }
207 > map.ts
208 > [Symbol.iterator](): SetIterator<URI> {
209 return this.keys();
210 }
211 > } map.ts
212 >
213 >
214 > interface Item<K, V> {
215 > previous: Item<K, V> | undefined;
216 > next: Item<K, V> | undefined;
217 > key: K;
218 > value: V;
219 > }
220 >
221 > export const enum Touch {
222 > None = 0,
223 > AsOld = 1,
224 > AsNew = 2
225 > }
226 >
227 > export class LinkedMap<K, V> implements Map<K, V> {
228 >
229 > readonly [Symbol.toStringTag] = 'LinkedMap';
230 >
231 > private _map: Map<K, Item<K, V>>;
232 > private _head: Item<K, V> | undefined;
233 > private _tail: Item<K, V> | undefined;
234 > private _size: number;
235 >
236 > private _state: number;
237 >
238 > constructor() {
239 this._map = new Map<K, Item<K, V>>();
240 this._head = undefined;
243 this._state = 0;
244 }
245 > map.ts
246 > clear(): void {
247 this._map.clear();
248 this._head = undefined;
251 this._state++;
252 }
253 > map.ts
254 > isEmpty(): boolean {
255 return !this._head && !this._tail;
256 }
257 > map.ts
258 > get size(): number {
259 return this._size;
260 }
261 > map.ts
262 > get first(): V | undefined {
263 return this._head?.value;
264 }
265 > map.ts
266 > get last(): V | undefined {
267 return this._tail?.value;
268 }
269 > map.ts
270 > has(key: K): boolean {
271 return this._map.has(key);
272 }
273 > map.ts
274 > get(key: K, touch: Touch = Touch.None): V | undefined {
275 const item = this._map.get(key);
276 if (!item) {
282 return item.value;
283 }
284 > map.ts
285 > set(key: K, value: V, touch: Touch = Touch.None): this {
286 let item = this._map.get(key);
287 if (item) {
311 return this;
312 }
313 > map.ts
314 > delete(key: K): boolean {
315 return !!this.remove(key);
316 }
317 > map.ts
318 > remove(key: K): V | undefined {
319 const item = this._map.get(key);
320 if (!item) {
326 return item.value;
327 }
328 > map.ts
329 > shift(): V | undefined {
330 if (!this._head && !this._tail) {
331 return undefined;
340 return item.value;
341 }
342 > map.ts
343 > forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
344 const state = this._state;
345 let current = this._head;
356 }
357 }
358 > map.ts
359 > keys(): MapIterator<K> {
360 const map = this;
361 const state = this._state;
381 return iterator;
382 }
383 > map.ts
384 > values(): MapIterator<V> {
385 const map = this;
386 const state = this._state;
406 return iterator;
407 }
408 > map.ts
409 > entries(): MapIterator<[K, V]> {
410 const map = this;
411 const state = this._state;
431 return iterator;
432 }
433 > map.ts
434 > [Symbol.iterator](): MapIterator<[K, V]> {
435 return this.entries();
436 }
437 > map.ts
438 > protected trimOld(newSize: number) {
439 if (newSize >= this.size) {
440 return;
458 this._state++;
459 }
460 > map.ts
461 > protected trimNew(newSize: number) {
462 if (newSize >= this.size) {
463 return;
481 this._state++;
482 }
483 > map.ts
484 > private addItemFirst(item: Item<K, V>): void {
485 // First time Insert
486 if (!this._head && !this._tail) {
495 this._state++;
496 }
497 > map.ts
498 > private addItemLast(item: Item<K, V>): void {
499 // First time Insert
500 if (!this._head && !this._tail) {
509 this._state++;
510 }
511 > map.ts
512 > private removeItem(item: Item<K, V>): void {
513 if (item === this._head && item === this._tail) {
514 this._head = undefined;
546 this._state++;
547 }
548 > map.ts
549 > private touch(item: Item<K, V>, touch: Touch): void {
550 if (!this._head || !this._tail) {
551 throw new Error('Invalid list');
608 }
609 }
610 > map.ts
611 > toJSON(): [K, V][] {
612 const data: [K, V][] = [];
613
618 return data;
619 }
620 > map.ts
621 > fromJSON(data: [K, V][]): void {
622 this.clear();
623
626 }
627 }
628 > } map.ts
629 >
630 > abstract class Cache<K, V> extends LinkedMap<K, V> {
631 >
632 > protected _limit: number;
633 > protected _ratio: number;
634 >
635 > constructor(limit: number, ratio: number = 1) {
636 super();
637 this._limit = limit;
638 this._ratio = Math.min(Math.max(0, ratio), 1);
639 }
640 > map.ts
641 > get limit(): number {
642 return this._limit;
643 }
644 > map.ts
645 > set limit(limit: number) {
646 this._limit = limit;
647 this.checkTrim();
648 }
649 > map.ts
650 > get ratio(): number {
651 return this._ratio;
652 }
653 > map.ts
654 > set ratio(ratio: number) {
655 this._ratio = Math.min(Math.max(0, ratio), 1);
656 this.checkTrim();
657 }
658 > map.ts
659 > override get(key: K, touch: Touch = Touch.AsNew): V | undefined {
660 return super.get(key, touch);
661 }
662 > map.ts
663 > peek(key: K): V | undefined {
664 return super.get(key, Touch.None);
665 }
666 > map.ts
667 > override set(key: K, value: V): this {
668 super.set(key, value, Touch.AsNew);
669 return this;
670 }
671 > map.ts
672 > protected checkTrim() {
673 if (this.size > this._limit) {
674 this.trim(Math.round(this._limit * this._ratio));
675 }
676 }
677 > map.ts
678 > protected abstract trim(newSize: number): void;
679 > }
680 >
681 > export class LRUCache<K, V> extends Cache<K, V> {
682 >
683 > constructor(limit: number, ratio: number = 1) {
684 super(limit, ratio);
685 }
686 > map.ts
687 > protected override trim(newSize: number) {
688 this.trimOld(newSize);
689 }
690 > map.ts
691 > override set(key: K, value: V): this {
692 super.set(key, value);
693 this.checkTrim();
694 return this;
695 }
696 > } map.ts
697 >
698 > export class MRUCache<K, V> extends Cache<K, V> {
699 >
700 > constructor(limit: number, ratio: number = 1) {
701 super(limit, ratio);
702 }
703 > map.ts
704 > protected override trim(newSize: number) {
705 this.trimNew(newSize);
706 }
707 > map.ts
708 > override set(key: K, value: V): this {
709 if (this._limit <= this.size && !this.has(key)) {
710 this.trim(Math.round(this._limit * this._ratio) - 1);
714 return this;
715 }
716 > } map.ts
717 >
718 > export class CounterSet<T> {
719
720 private map = new Map<T, number>();
721 > map.ts
722 > add(value: T): CounterSet<T> {
723 this.map.set(value, (this.map.get(value) || 0) + 1);
724 return this;
725 }
726 > map.ts
727 > delete(value: T): boolean {
728 let counter = this.map.get(value) || 0;
729
742 return true;
743 }
744 > map.ts
745 > has(value: T): boolean {
746 return this.map.has(value);
747 }
748 > } map.ts
749 >
750 > /**
751 > * A map that allows access both by keys and values.
752 > * **NOTE**: values need to be unique.
753 > */
754 > export class BidirectionalMap<K, V> {
755 >
756 > private readonly _m1 = new Map<K, V>();
757 > private readonly _m2 = new Map<V, K>();
758 >
759 > constructor(entries?: readonly (readonly [K, V])[]) {
760 if (entries) {
761 for (const [key, value] of entries) {
764 }
765 }
766 > map.ts
767 > clear(): void {
768 this._m1.clear();
769 this._m2.clear();
770 }
771 > map.ts
772 > set(key: K, value: V): void {
773 this._m1.set(key, value);
774 this._m2.set(value, key);
775 }
776 > map.ts
777 > get(key: K): V | undefined {
778 return this._m1.get(key);
779 }
780 > map.ts
781 > getKey(value: V): K | undefined {
782 return this._m2.get(value);
783 }
784 > map.ts
785 > delete(key: K): boolean {
786 const value = this._m1.get(key);
787 if (value === undefined) {
792 return true;
793 }
794 > map.ts
795 > forEach(callbackfn: (value: V, key: K, map: BidirectionalMap<K, V>) => void, thisArg?: unknown): void {
796 this._m1.forEach((value, key) => {
797 callbackfn.call(thisArg, value, key, this);
798 });
799 }
800 > map.ts
801 > keys(): IterableIterator<K> {
802 return this._m1.keys();
803 }
804 > map.ts
805 > values(): IterableIterator<V> {
806 return this._m1.values();
807 }
808 > } map.ts
809 >
810 > export class SetMap<K, V> {
811
812 private map = new Map<K, Set<V>>();
813 > map.ts
814 > add(key: K, value: V): void {
815 let values = this.map.get(key);
816
822 values.add(value);
823 }
824 > map.ts
825 > delete(key: K, value: V): void {
826 const values = this.map.get(key);
827
836 }
837 }
838 > map.ts
839 > forEach(key: K, fn: (value: V) => void): void {
840 const values = this.map.get(key);
841
846 values.forEach(fn);
847 }
848 > map.ts
849 > get(key: K): ReadonlySet<V> {
850 const values = this.map.get(key);
851 if (!values) {
854 return values;
855 }
856 > } map.ts
857 >
858 > export function mapsStrictEqualIgnoreOrder(a: Map<unknown, unknown>, b: Map<unknown, unknown>): boolean {
859 if (a === b) {
860 return true;
879 return true;
880 }
881 > map.ts
882 > /**
883 > * A map that is addressable with an arbitrary number of keys. This is useful in high performance
884 > * scenarios where creating a composite key whenever the data is accessed is too expensive. For
885 > * example for a very hot function, constructing a string like `first-second-third` for every call
886 > * will cause a significant hit to performance.
887 > */
888 > export class NKeyMap<TValue, TKeys extends (string | boolean | number)[]> {
889 private _data: Map<any, any> = new Map();
890 > map.ts
891 > /**
892 > * Sets a value on the map. Note that unlike a standard `Map`, the first argument is the value.
893 > * This is because the spread operator is used for the keys and must be last..
894 > * @param value The value to set.
895 > * @param keys The keys for the value.
896 > */
897 > public set(value: TValue, ...keys: [...TKeys]): void {
898 let currentMap = this._data;
899 for (let i = 0; i < keys.length - 1; i++) {
907 currentMap.set(keys[keys.length - 1], value);
908 }
909 > map.ts
910 > public get(...keys: [...TKeys]): TValue | undefined {
911 let currentMap = this._data;
912 for (let i = 0; i < keys.length - 1; i++) {
919 return currentMap.get(keys[keys.length - 1]);
920 }
921 > map.ts
922 > public delete(...keys: [...TKeys]): boolean {
923 const maps: Map<any, any>[] = [this._data];
924 let currentMap = this._data;
939 return deleted;
940 }
941 > map.ts
942 > public deleteAll(...keys: Partial<TKeys>): boolean {
943 if (keys.length === 0) {
944 const hadData = this._data.size > 0;
964 return deleted;
965 }
966 > map.ts
967 > public clear(): void {
968 this._data.clear();
969 }
970 > map.ts
971 > public *getAll(...keys: Partial<TKeys>): IterableIterator<TValue> {
972 let currentMap = this._data;
973 for (const key of keys) {
980 yield* this._values(currentMap);
981 }
982 > map.ts
983 > public *values(): IterableIterator<TValue> {
984 yield* this._values(this._data);
985 }
986 > map.ts
987 > private *_values(map: Map<any, any>): IterableIterator<TValue> {
988 for (const value of map.values()) {
989 if (value instanceof Map) {
994 }
995 }
996 > map.ts
997 > /**
998 > * Get a textual representation of the map for debugging purposes.
999 > */
1000 > public toString(): string {
1001 const printMap = (map: Map<any, any>, depth: number): string => {
1002 let result = '';
1014 return printMap(this._data, 0);
1015 }
1016 > } map.ts
src/vs/base/common/types.ts 293 covered LOC · 28 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- types.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { assert } from './assert.js';
7 >
8 > /**
9 > * @returns whether the provided parameter is a JavaScript String or not.
10 > */
11 > export function isString(str: unknown): str is string {
12 return (typeof str === 'string');
13 }
14 > types.ts
15 > /**
16 > * @returns whether the provided parameter is a JavaScript Array and each element in the array is a string.
17 > */
18 > export function isStringArray(value: unknown): value is string[] {
19 return isArrayOf(value, isString);
20 }
21 > types.ts
22 > /**
23 > * @returns whether the provided parameter is a JavaScript Array and each element in the array satisfies the provided type guard.
24 > */
25 > export function isArrayOf<T>(value: unknown, check: (item: unknown) => item is T): value is T[] {
26 return Array.isArray(value) && value.every(check);
27 }
28 > types.ts
29 > /**
30 > * @returns whether the provided parameter is of type `object` but **not**
31 > * `null`, an `array`, a `regexp`, nor a `date`.
32 > */
33 > export function isObject(obj: unknown): obj is Object {
34 > // The method can't do a type cast since there are type (like strings) which types.ts
35 > // are subclasses of any put not positvely matched by the function. Hence type
36 > // narrowing results in wrong results.
37 > return typeof obj === 'object'
38 > && obj !== null types.ts
39 > && !Array.isArray(obj)
40 > && !(obj instanceof RegExp) types.ts
41 > && !(obj instanceof Date);
42 > } types.ts
43 > types.ts
44 > /**
45 > * @returns whether the provided parameter is of type `Buffer` or Uint8Array dervived type
46 > */
47 > export function isTypedArray(obj: unknown): obj is Object {
48 const TypedArray = Object.getPrototypeOf(Uint8Array);
49 return typeof obj === 'object'
50 && obj instanceof TypedArray;
51 }
52 > types.ts
53 > /**
54 > * In **contrast** to just checking `typeof` this will return `false` for `NaN`.
55 > * @returns whether the provided parameter is a JavaScript Number or not.
56 > */
57 > export function isNumber(obj: unknown): obj is number {
58 return (typeof obj === 'number' && !isNaN(obj));
59 }
60 > types.ts
61 > /**
62 > * @returns whether the provided parameter is an Iterable, casting to the given generic
63 > */
64 > export function isIterable<T>(obj: unknown): obj is Iterable<T> {
65 // eslint-disable-next-line local/code-no-any-casts
66 return !!obj && typeof (obj as any)[Symbol.iterator] === 'function';
67 }
68 > types.ts
69 > /**
70 > * @returns whether the provided parameter is an Iterable, casting to the given generic
71 > */
72 > export function isAsyncIterable<T>(obj: unknown): obj is AsyncIterable<T> {
73 // eslint-disable-next-line local/code-no-any-casts
74 return !!obj && typeof (obj as any)[Symbol.asyncIterator] === 'function';
75 }
76 > types.ts
77 > /**
78 > * @returns whether the provided parameter is a JavaScript Boolean or not.
79 > */
80 > export function isBoolean(obj: unknown): obj is boolean {
81 return (obj === true || obj === false);
82 }
83 > types.ts
84 > /**
85 > * @returns whether the provided parameter is undefined.
86 > */
87 > export function isUndefined(obj: unknown): obj is undefined {
88 return (typeof obj === 'undefined');
89 }
90 > types.ts
91 > /**
92 > * @returns whether the provided parameter is defined.
93 > */
94 > export function isDefined<T>(arg: T | null | undefined): arg is T {
95 return !isUndefinedOrNull(arg);
96 }
97 > types.ts
98 > /**
99 > * @returns whether the provided parameter is undefined or null.
100 > */
101 > export function isUndefinedOrNull(obj: unknown): obj is undefined | null {
102 return (isUndefined(obj) || obj === null);
103 }
104 > types.ts
105 >
106 > export function assertType(condition: unknown, type?: string): asserts condition {
107 if (!condition) {
108 throw new Error(type ? `Unexpected type, expected '${type}'` : 'Unexpected type');
109 }
110 }
111 > types.ts
112 > /**
113 > * Asserts that the argument passed in is neither undefined nor null.
114 > *
115 > * @see {@link assertDefined} for a similar utility that leverages TS assertion functions to narrow down the type of `arg` to be non-nullable.
116 > */
117 > export function assertReturnsDefined<T>(arg: T | null | undefined): NonNullable<T> {
118 assert(
119 arg !== null && arg !== undefined,
123 return arg;
124 }
125 > types.ts
126 > /**
127 > * Asserts that a provided `value` is `defined` - not `null` or `undefined`,
128 > * throwing an error with the provided error or error message, while also
129 > * narrowing down the type of the `value` to be `NonNullable` using TS
130 > * assertion functions.
131 > *
132 > * @throws if the provided `value` is `null` or `undefined`.
133 > *
134 > * ## Examples
135 > *
136 > * ```typescript
137 > * // an assert with an error message
138 > * assertDefined('some value', 'String constant is not defined o_O.');
139 > *
140 > * // `throws!` the provided error
141 > * assertDefined(null, new Error('Should throw this error.'));
142 > *
143 > * // narrows down the type of `someValue` to be non-nullable
144 > * const someValue: string | undefined | null = blackbox();
145 > * assertDefined(someValue, 'Some value must be defined.');
146 > * console.log(someValue.length); // now type of `someValue` is `string`
147 > * ```
148 > *
149 > * @see {@link assertReturnsDefined} for a similar utility but without assertion.
150 > * @see {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions typescript-3-7.html#assertion-functions}
151 > */
152 > export function assertDefined<T>(value: T, error: string | NonNullable<Error>): asserts value is NonNullable<T> {
153 if (value === null || value === undefined) {
154 const errorToThrow = typeof error === 'string' ? new Error(error) : error;
157 }
158 }
159 > types.ts
160 > /**
161 > * Asserts that each argument passed in is neither undefined nor null.
162 > */
163 > export function assertReturnsAllDefined<T1, T2>(t1: T1 | null | undefined, t2: T2 | null | undefined): [T1, T2];
164 > export function assertReturnsAllDefined<T1, T2, T3>(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined): [T1, T2, T3];
165 > export function assertReturnsAllDefined<T1, T2, T3, T4>(t1: T1 | null | undefined, t2: T2 | null | undefined, t3: T3 | null | undefined, t4: T4 | null | undefined): [T1, T2, T3, T4];
166 > export function assertReturnsAllDefined(...args: (unknown | null | undefined)[]): unknown[] {
167 const result = [];
168
179 return result;
180 }
181 > types.ts
182 > /**
183 > * Checks if the provided value is one of the vales in the provided list.
184 > *
185 > * ## Examples
186 > *
187 > * ```typescript
188 > * // note! item type is a `subset of string`
189 > * type TItem = ':' | '.' | '/';
190 > *
191 > * // note! item is type of `string` here
192 > * const item: string = ':';
193 > * // list of the items to check against
194 > * const list: TItem[] = [':', '.'];
195 > *
196 > * // ok
197 > * assert(
198 > * isOneOf(item, list),
199 > * 'Must succeed.',
200 > * );
201 > *
202 > * // `item` is of `TItem` type now
203 > * ```
204 > */
205 > export const isOneOf = <TType, TSubtype extends TType>(
206 value: TType,
207 validValues: readonly TSubtype[],
211 return validValues.includes(<TSubtype>value);
212 };
213 > types.ts
214 > /**
215 > * Compile-time type check of a variable.
216 > */
217 > export function typeCheck<T = never>(_thing: NoInfer<T>): void { }
218 >
219 > const hasOwnProperty = Object.prototype.hasOwnProperty;
220 >
221 > /**
222 > * @returns whether the provided parameter is an empty JavaScript Object or not.
223 > */
224 > export function isEmptyObject(obj: unknown): obj is object {
225 if (!isObject(obj)) {
226 return false;
235 return true;
236 }
237 > types.ts
238 > /**
239 > * @returns whether the provided parameter is a JavaScript Function or not.
240 > */
241 > export function isFunction(obj: unknown): obj is Function {
242 return (typeof obj === 'function');
243 }
244 > types.ts
245 > /**
246 > * @returns whether the provided parameters is are JavaScript Function or not.
247 > */
248 > export function areFunctions(...objects: unknown[]): boolean {
249 return objects.length > 0 && objects.every(isFunction);
250 }
251 > types.ts
252 > export type TypeConstraint = string | Function;
253 >
254 > export function validateConstraints(args: unknown[], constraints: Array<TypeConstraint | undefined>): void {
255 const len = Math.min(args.length, constraints.length);
256 for (let i = 0; i < len; i++) {
258 }
259 }
260 > types.ts
261 > export function validateConstraint(arg: unknown, constraint: TypeConstraint | undefined): void {
262
263 if (isString(constraint)) {
283 }
284 }
285 > types.ts
286 > /**
287 > * Helper type assertion that safely upcasts a type to a supertype.
288 > *
289 > * This can be used to make sure the argument correctly conforms to the subtype while still being able to pass it
290 > * to contexts that expects the supertype.
291 > */
292 > export function upcast<Base, Sub extends Base = Base>(x: Sub): Base {
293 return x;
294 }
295 > types.ts
296 > type AddFirstParameterToFunction<T, TargetFunctionsReturnType, FirstParameter> = T extends (...args: any[]) => TargetFunctionsReturnType ?
297 > // Function: add param to function
298 > (firstArg: FirstParameter, ...args: Parameters<T>) => ReturnType<T> :
299 >
300 > // Else: just leave as is
301 > T;
302 >
303 > /**
304 > * Allows to add a first parameter to functions of a type.
305 > */
306 > export type AddFirstParameterToFunctions<Target, TargetFunctionsReturnType, FirstParameter> = {
307 > // For every property
308 > [K in keyof Target]: AddFirstParameterToFunction<Target[K], TargetFunctionsReturnType, FirstParameter>;
309 > };
310 >
311 > /**
312 > * Given an object with all optional properties, requires at least one to be defined.
313 > * i.e. AtLeastOne<MyObject>;
314 > */
315 > export type AtLeastOne<T, U = { [K in keyof T]: Pick<T, K> }> = Partial<T> & U[keyof U];
316 >
317 > /**
318 > * Only picks the non-optional properties of a type.
319 > */
320 > export type OmitOptional<T> = { [K in keyof T as T[K] extends Required<T>[K] ? K : never]: T[K] };
321 >
322 > /**
323 > * A type that removed readonly-less from all properties of `T`
324 > */
325 > export type Mutable<T> = {
326 > -readonly [P in keyof T]: T[P]
327 > };
328 >
329 > /**
330 > * A type that adds readonly to all properties of T, recursively.
331 > */
332 > export type DeepImmutable<T> = T extends (infer U)[]
333 > ? ReadonlyArray<DeepImmutable<U>>
334 > : T extends ReadonlyArray<infer U>
335 > ? ReadonlyArray<DeepImmutable<U>>
336 > : T extends Map<infer K, infer V>
337 > ? ReadonlyMap<K, DeepImmutable<V>>
338 > : T extends Set<infer U>
339 > ? ReadonlySet<DeepImmutable<U>>
340 > : T extends object
341 > ? {
342 > readonly [K in keyof T]: DeepImmutable<T[K]>;
343 > }
344 > : T;
345 >
346 > /**
347 > * A single object or an array of the objects.
348 > */
349 > export type SingleOrMany<T> = T | T[];
350 >
351 > /**
352 > * Given a `type X = { foo?: string }` checking that an object `satisfies X`
353 > * will ensure each property was explicitly defined, ensuring no properties
354 > * are omitted or forgotten.
355 > */
356 > export type WithDefinedProps<T> = { [K in keyof Required<T>]: T[K] };
357 >
358 >
359 > /**
360 > * A type that recursively makes all properties of `T` required
361 > */
362 > export type DeepRequiredNonNullable<T> = {
363 > [P in keyof T]-?: T[P] extends object ? DeepRequiredNonNullable<T[P]> : Required<NonNullable<T[P]>>;
364 > };
365 >
366 >
367 > /**
368 > * Represents a type that is a partial version of a given type `T`, where all properties are optional and can be deeply nested.
369 > */
370 > export type DeepPartial<T> = {
371 > [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : Partial<T[P]>;
372 > };
373 >
374 > /**
375 > * Represents a type that is a partial version of a given type `T`, except a subset.
376 > */
377 > export type PartialExcept<T, K extends keyof T> = Partial<Omit<T, K>> & Pick<T, K>;
378 >
379 >
380 > type KeysOfUnionType<T> = T extends T ? keyof T : never;
381 > type FilterType<T, TTest> = T extends TTest ? T : never;
382 > type MakeOptionalAndTrue<T extends object> = { [K in keyof T]?: true };
383 >
384 > /**
385 > * Type guard that checks if an object has specific keys and narrows the type accordingly.
386 > *
387 > * @param x - The object to check
388 > * @param key - An object with boolean values indicating which keys to check for
389 > * @returns true if all specified keys exist in the object, false otherwise
390 > *
391 > * @example
392 > * ```typescript
393 > * type A = { a: string };
394 > * type B = { b: number };
395 > * const obj: A | B = getObject();
396 > *
397 > * if (hasKey(obj, { a: true })) {
398 > * // obj is now narrowed to type A
399 > * console.log(obj.a);
400 > * }
401 > * ```
402 > */
403 > export function hasKey<T extends object, TKeys extends MakeOptionalAndTrue<T>>(x: T, key: TKeys): x is FilterType<T, { [K in KeysOfUnionType<T> & keyof TKeys]: unknown }> {
404 for (const k in key) {
405 if (!(k in x)) {
src/vs/base/common/uri.ts 283 covered LOC · 27 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uri.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { CharCode } from './charCode.js';
7 > import { MarshalledId } from './marshallingIds.js';
8 > import * as paths from './path.js';
9 > import { isWindows } from './platform.js';
10 >
11 > const _schemePattern = /^\w[\w\d+.-]*$/;
12 > const _singleSlashStart = /^\//;
13 > const _doubleSlashStart = /^\/\//;
14 >
15 function _validateUri(ret: URI, _strict?: boolean): void {
16
47 }
48 }
49 > uri.ts
50 > // for a while we allowed uris *without* schemes and this is the migration
51 > // for them, e.g. an uri without scheme and without strict-mode warns and falls
52 > // back to the file-scheme. that should cause the least carnage and still be a
53 > // clear warning
54 function _schemeFix(scheme: string, _strict: boolean): string {
55 if (!scheme && !_strict) {
58 return scheme;
59 }
60 > uri.ts
61 > // implements a bit of https://tools.ietf.org/html/rfc3986#section-5
62 function _referenceResolution(scheme: string, path: string): string {
63
79 return path;
80 }
81 > uri.ts
82 > const _empty = '';
83 > const _slash = '/';
84 > const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
85 >
86 > /**
87 > * Uniform Resource Identifier (URI) http://tools.ietf.org/html/rfc3986.
88 > * This class is a simple parser which creates the basic component parts
89 > * (http://tools.ietf.org/html/rfc3986#section-3) with minimal validation
90 > * and encoding.
91 > *
92 > * ```txt
93 > * foo://example.com:8042/over/there?name=ferret#nose
94 > * \_/ \______________/\_________/ \_________/ \__/
95 > * | | | | |
96 > * scheme authority path query fragment
97 > * | _____________________|__
98 > * / \ / \
99 > * urn:example:animal:ferret:nose
100 > * ```
101 > */
102 > export class URI implements UriComponents {
103 >
104 > static isUri(thing: unknown): thing is URI {
105 if (thing instanceof URI) {
106 return true;
118 && typeof (<URI>thing).toString === 'function';
119 }
120 > uri.ts
121 > /**
122 > * scheme is the 'http' part of 'http://www.example.com/some/path?query#fragment'.
123 > * The part before the first colon.
124 > */
125 > readonly scheme: string;
126 >
127 > /**
128 > * authority is the 'www.example.com' part of 'http://www.example.com/some/path?query#fragment'.
129 > * The part between the first double slashes and the next slash.
130 > */
131 > readonly authority: string;
132 >
133 > /**
134 > * path is the '/some/path' part of 'http://www.example.com/some/path?query#fragment'.
135 > */
136 > readonly path: string;
137 >
138 > /**
139 > * query is the 'query' part of 'http://www.example.com/some/path?query#fragment'.
140 > */
141 > readonly query: string;
142 >
143 > /**
144 > * fragment is the 'fragment' part of 'http://www.example.com/some/path?query#fragment'.
145 > */
146 > readonly fragment: string;
147 >
148 > /**
149 > * @internal
150 > */
151 > protected constructor(scheme: string, authority?: string, path?: string, query?: string, fragment?: string, _strict?: boolean);
152 >
153 > /**
154 > * @internal
155 > */
156 > protected constructor(components: UriComponents);
157 >
158 > /**
159 > * @internal
160 > */
161 > protected constructor(schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict: boolean = false) {
162
163 if (typeof schemeOrData === 'object') {
180 }
181 }
182 > uri.ts
183 > // ---- filesystem path -----------------------
184 >
185 > /**
186 > * Returns a string representing the corresponding file system path of this URI.
187 > * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
188 > * platform specific path separator.
189 > *
190 > * * Will *not* validate the path for invalid characters and semantics.
191 > * * Will *not* look at the scheme of this URI.
192 > * * The result shall *not* be used for display purposes but for accessing a file on disk.
193 > *
194 > *
195 > * The *difference* to `URI#path` is the use of the platform specific separator and the handling
196 > * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
197 > *
198 > * ```ts
199 > const u = URI.parse('file://server/c$/folder/file.txt')
200 > u.authority === 'server'
201 > u.path === '/shares/c$/file.txt'
202 > u.fsPath === '\\server\c$\folder\file.txt'
203 > ```
204 > *
205 > * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
206 > * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
207 > * with URIs that represent files on disk (`file` scheme).
208 > */
209 > get fsPath(): string {
210 // if (this.scheme !== 'file') {
211 // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`);
213 return uriToFsPath(this, false);
214 }
215 > uri.ts
216 > // ---- modify to new -------------------------
217 >
218 > with(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null }): URI {
219
220 if (!change) {
260 return new Uri(scheme, authority, path, query, fragment);
261 }
262 > uri.ts
263 > // ---- parse & validate ------------------------
264 >
265 > /**
266 > * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,
267 > * `file:///usr/home`, or `scheme:with/path`.
268 > *
269 > * @param value A string which represents an URI (see `URI#toString`).
270 > */
271 > static parse(value: string, _strict: boolean = false): URI {
272 const match = _regexp.exec(value);
273 if (!match) {
283 );
284 }
285 > uri.ts
286 > /**
287 > * Creates a new URI from a file system path, e.g. `c:\my\files`,
288 > * `/usr/home`, or `\\server\share\some\path`.
289 > *
290 > * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
291 > * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
292 > * `URI.parse('file://' + path)` because the path might contain characters that are
293 > * interpreted (# and ?). See the following sample:
294 > * ```ts
295 > const good = URI.file('/coding/c#/project1');
296 > good.scheme === 'file';
297 > good.path === '/coding/c#/project1';
298 > good.fragment === '';
299 > const bad = URI.parse('file://' + '/coding/c#/project1');
300 > bad.scheme === 'file';
301 > bad.path === '/coding/c'; // path is now broken
302 > bad.fragment === '/project1';
303 > ```
304 > *
305 > * @param path A file system path (see `URI#fsPath`)
306 > */
307 > static file(path: string): URI {
308
309 let authority = _empty;
331 return new Uri('file', authority, path, _empty, _empty);
332 }
333 > uri.ts
334 > /**
335 > * Creates new URI from uri components.
336 > *
337 > * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs
338 > * validation and should be used for untrusted uri components retrieved from storage,
339 > * user input, command arguments etc
340 > */
341 > static from(components: UriComponents, strict?: boolean): URI {
342 const result = new Uri(
343 components.scheme,
350 return result;
351 }
352 > uri.ts
353 > /**
354 > * Join a URI path with path fragments and normalizes the resulting path.
355 > *
356 > * @param uri The input URI.
357 > * @param pathFragment The path fragment to add to the URI path.
358 > * @returns The resulting URI.
359 > */
360 > static joinPath(uri: URI, ...pathFragment: string[]): URI {
361 if (!uri.path) {
362 throw new Error(`[UriError]: cannot call joinPath on URI without path: ${uri.toString()}`);
370 return uri.with({ path: newPath });
371 }
372 > uri.ts
373 > // ---- printing/externalize ---------------------------
374 >
375 > /**
376 > * Creates a string representation for this URI. It's guaranteed that calling
377 > * `URI.parse` with the result of this function creates an URI which is equal
378 > * to this URI.
379 > *
380 > * * The result shall *not* be used for display purposes but for externalization or transport.
381 > * * The result will be encoded using the percentage encoding and encoding happens mostly
382 > * ignore the scheme-specific encoding rules.
383 > *
384 > * @param skipEncoding Do not encode the result, default is `false`
385 > */
386 > toString(skipEncoding: boolean = false): string {
387 return _asFormatted(this, skipEncoding);
388 }
389 > uri.ts
390 > toJSON(): UriComponents {
391 return this;
392 }
393 > uri.ts
394 > /**
395 > * A helper function to revive URIs.
396 > *
397 > * **Note** that this function should only be used when receiving URI#toJSON generated data
398 > * and that it doesn't do any validation. Use {@link URI.from} when received "untrusted"
399 > * uri components such as command arguments or data from storage.
400 > *
401 > * @param data The URI components or URI to revive.
402 > * @returns The revived URI or undefined or null.
403 > */
404 > static revive(data: UriComponents | URI): URI;
405 > static revive(data: UriComponents | URI | undefined): URI | undefined;
406 > static revive(data: UriComponents | URI | null): URI | null;
407 > static revive(data: UriComponents | URI | undefined | null): URI | undefined | null;
408 > static revive(data: UriComponents | URI | undefined | null): URI | undefined | null {
409 if (!data) {
410 return data;
418 }
419 }
420 > uri.ts
421 > [Symbol.for('debug.description')]() {
422 return `URI(${this.toString()})`;
423 }
424 > } uri.ts
425 >
426 > export interface UriComponents {
427 > scheme: string;
428 > authority?: string;
429 > path?: string;
430 > query?: string;
431 > fragment?: string;
432 > }
433 >
434 > export function isUriComponents(thing: unknown): thing is UriComponents {
435 if (!thing || typeof thing !== 'object') {
436 return false;
442 && (typeof (<UriComponents>thing).fragment === 'string' || typeof (<UriComponents>thing).fragment === 'undefined');
443 }
444 > uri.ts
445 > interface UriState extends UriComponents {
446 > $mid: MarshalledId.Uri;
447 > external?: string;
448 > fsPath?: string;
449 > _sep?: 1;
450 > }
451 >
452 > const _pathSepMarker = isWindows ? 1 : undefined;
453 >
454 > // This class exists so that URI is compatible with vscode.Uri (API).
455 class Uri extends URI {
456
457 _formatted: string | null = null;
458 _fsPath: string | null = null;
459 > uri.ts
460 > override get fsPath(): string {
461 if (!this._fsPath) {
462 this._fsPath = uriToFsPath(this, false);
464 return this._fsPath;
465 }
466 > uri.ts
467 > override toString(skipEncoding: boolean = false): string {
468 if (!skipEncoding) {
469 if (!this._formatted) {
476 }
477 }
478 > uri.ts
479 > override toJSON(): UriComponents {
480 // eslint-disable-next-line local/code-no-dangerous-type-assertions
481 const res = <UriState>{
512 return res;
513 }
514 > } uri.ts
515 >
516 > // reserved characters: https://tools.ietf.org/html/rfc3986#section-2.2
517 > const encodeTable: { [ch: number]: string } = {
518 > [CharCode.Colon]: '%3A', // gen-delims
519 > [CharCode.Slash]: '%2F',
520 > [CharCode.QuestionMark]: '%3F',
521 > [CharCode.Hash]: '%23',
522 > [CharCode.OpenSquareBracket]: '%5B',
523 > [CharCode.CloseSquareBracket]: '%5D',
524 > [CharCode.AtSign]: '%40',
525 >
526 > [CharCode.ExclamationMark]: '%21', // sub-delims
527 > [CharCode.DollarSign]: '%24',
528 > [CharCode.Ampersand]: '%26',
529 > [CharCode.SingleQuote]: '%27',
530 > [CharCode.OpenParen]: '%28',
531 > [CharCode.CloseParen]: '%29',
532 > [CharCode.Asterisk]: '%2A',
533 > [CharCode.Plus]: '%2B',
534 > [CharCode.Comma]: '%2C',
535 > [CharCode.Semicolon]: '%3B',
536 > [CharCode.Equals]: '%3D',
537 >
538 > [CharCode.Space]: '%20',
539 > };
540 >
541 function encodeURIComponentFast(uriComponent: string, isPath: boolean, isAuthority: boolean): string {
542 let res: string | undefined = undefined;
602 return res !== undefined ? res : uriComponent;
603 }
604 > uri.ts
605 function encodeURIComponentMinimal(path: string): string {
606 let res: string | undefined = undefined;
620 return res !== undefined ? res : path;
621 }
622 > uri.ts
623 > /**
624 > * Compute `fsPath` for the given uri
625 > */
626 > export function uriToFsPath(uri: URI, keepDriveLetterCasing: boolean): string {
627
628 let value: string;
650 return value;
651 }
652 > uri.ts
653 > /**
654 > * Create the external version of a uri
655 > */
656 function _asFormatted(uri: URI, skipEncoding: boolean): string {
657
723 return res;
724 }
725 > uri.ts
726 > // --- decode
727 >
728 function decodeURIComponentGraceful(str: string): string {
729 try {
737 }
738 }
739 > uri.ts
740 > const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
741 >
742 function percentDecode(str: string): string {
743 if (!str.match(_rEncodedAsHex)) {
746 return str.replace(_rEncodedAsHex, (match) => decodeURIComponentGraceful(match));
747 }
748 > uri.ts
749 > /**
750 > * Mapped-type that replaces all occurrences of URI with UriComponents
751 > */
752 > export type UriDto<T> = { [K in keyof T]: T[K] extends URI
753 > ? UriComponents
754 > : UriDto<T[K]> };
src/vs/platform/agentHost/common/state/protocol/channels-changeset/state.ts 277 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { StringOrMarkdown, FileEdit, ErrorInfo } from '../common/state.js';
10 >
11 > // ─── Changesets ──────────────────────────────────────────────────────────────
12 >
13 > /**
14 > * Catalogue entry describing one changeset the server can produce for a
15 > * session.
16 > *
17 > * Catalogue entries are intentionally lightweight — just enough to render a
18 > * chip or list row without subscribing. Full per-changeset detail
19 > * ({@link ChangesetState}) lives on the subscribable URI obtained by
20 > * expanding {@link uriTemplate}.
21 > *
22 > * @category Changesets
23 > */
24 > export interface Changeset {
25 > /** Human-readable label, e.g. `"Uncommitted Changes"`. */
26 > label: string;
27 > /**
28 > * RFC 6570 URI template. Clients parse the variables directly out of the
29 > * template using the standard `{name}` syntax — they are not redeclared
30 > * here.
31 > *
32 > * Only the following template shapes are defined by this protocol; any
33 > * other variable name MUST be ignored by clients (there is no
34 > * protocol-defined way to obtain values for unknown variables):
35 > *
36 > * | Variables in template | Meaning |
37 > * | ------------------------------------------- | ------------------------------------------------------------------------------------ |
38 > * | _(none)_ | A static, session-wide changeset. The template is itself a subscribable URI. |
39 > * | `{turnId}` | Per-turn slice. Expand with a `Turn.id` from the session. |
40 > * | `{originalTurnId}` and `{modifiedTurnId}` | Diff between two turns. Both variables MUST be present. |
41 > *
42 > * Future protocol versions MAY add new well-known variables.
43 > */
44 > uriTemplate: string;
45 > /** Optional longer description. */
46 > description?: string;
47 > /**
48 > * Advisory hint describing what kind of changeset this is, so clients can
49 > * group, sort, or render an appropriate icon without parsing
50 > * {@link uriTemplate}. Recognized values include:
51 > *
52 > * - `'session'`: a static, session-wide changeset covering all changes the
53 > * agent has produced in this session.
54 > * - `'branch'`: changes relative to a base branch (e.g. a feature branch
55 > * diffed against `main`).
56 > * - `'uncommitted'`: the workspace's current uncommitted changes.
57 > * - `'turn'`: changes produced by a single turn. Typically paired with a
58 > * `{turnId}` variable in {@link uriTemplate}.
59 > * - `'compare-turns'`: a diff between two turns. Typically paired with
60 > * `{originalTurnId}` and `{modifiedTurnId}` variables in
61 > * {@link uriTemplate}.
62 > *
63 > * Implementations MAY provide additional values; clients SHOULD fall back
64 > * to a reasonable default when an unknown value is encountered.
65 > */
66 > changeKind: string;
67 > /**
68 > * Optional capability declarations for this changeset. Absent (or an empty
69 > * object) means the changeset advertises no optional capabilities.
70 > *
71 > * Because the catalogue entry is delivered up-front on
72 > * {@link ChangesetState | the session's changeset list}, clients can decide
73 > * whether to surface capability-gated UI (such as review checkboxes) without
74 > * first subscribing to the changeset URI. Mirrors the presence-flag
75 > * convention of `ClientCapabilities`.
76 > */
77 > capabilities?: ChangesetCapabilities;
78 > }
79 >
80 > /**
81 > * Optional capabilities a changeset advertises on its catalogue
82 > * {@link Changeset} entry.
83 > *
84 > * Each field is a presence flag: an empty object `{}` means "supported",
85 > * absence means "not supported". Sub-fields on individual capabilities are
86 > * reserved for future per-capability options.
87 > *
88 > * @category Changesets
89 > */
90 > export interface ChangesetCapabilities {
91 > /**
92 > * The changeset supports the per-file **review** workflow. When declared,
93 > * clients MAY surface a GitHub-style "Viewed" toggle per file and dispatch
94 > * {@link ChangesetFilesReviewChangedAction | `changeset/filesReviewChanged`} to
95 > * set each file's {@link ChangesetFile.reviewed} flag. Clients that omit
96 > * handling MUST treat the changeset as non-reviewable.
97 > */
98 > review?: Record<string, never>;
99 > }
100 >
101 > /**
102 > * Computation lifecycle of a {@link ChangesetState}.
103 > *
104 > * @category Changesets
105 > */
106 > export const enum ChangesetStatus {
107 > /** The server is still computing the contents of this changeset. */
108 > Computing = 'computing',
109 > /** The changeset has been fully computed and is up-to-date. */
110 > Ready = 'ready',
111 > /**
112 > * Computation failed. The cause is described by
113 > * {@link ChangesetState.error}.
114 > */
115 > Error = 'error',
116 > }
117 >
118 > /**
119 > * Full state for a single changeset, returned when a client subscribes to
120 > * an expanded changeset URI.
121 > *
122 > * The client already knows the URI it subscribed to, so this state does
123 > * not redundantly carry it (or the catalogue's `id`, `label`, etc.).
124 > * Aggregate counts (`additions`, `deletions`, `files`) are likewise
125 > * omitted: clients trivially compute them from `files[].edit.diff`.
126 > *
127 > * @category Changesets
128 > */
129 > export interface ChangesetState {
130 > /** Computation lifecycle. */
131 > status: ChangesetStatus;
132 > /** Present iff `status === ChangesetStatus.Error`. */
133 > error?: ErrorInfo;
134 > /** Files in this changeset, keyed by {@link ChangesetFile.id}. */
135 > files: ChangesetFile[];
136 > /**
137 > * Operations the client may invoke against this changeset. Omit when no
138 > * operations are available.
139 > */
140 > operations?: ChangesetOperation[];
141 > }
142 >
143 > /**
144 > * One file entry within a {@link ChangesetState}.
145 > *
146 > * @category Changesets
147 > */
148 > export interface ChangesetFile {
149 > /**
150 > * Stable identifier within the changeset. Typically `after.uri`
151 > * (or `before.uri` for deletions).
152 > */
153 > id: string;
154 > /**
155 > * Reuses the existing {@link FileEdit} shape. Clients derive line
156 > * additions, deletions, and rename/create/delete semantics from this.
157 > */
158 > edit: FileEdit;
159 > /**
160 > * Whether a reviewer has marked this file as reviewed (the GitHub-style
161 > * "Viewed" checkbox). Absent is equivalent to `false` — clients MUST treat
162 > * a missing value as not-yet-reviewed.
163 > *
164 > * Requires the changeset to advertise {@link ChangesetCapabilities.review}.
165 > * Clients toggle it by dispatching
166 > * {@link ChangesetFilesReviewChangedAction | `changeset/filesReviewChanged`};
167 > * the server MAY also originate it (e.g. an agent self-reviewing its own
168 > * output).
169 > *
170 > * There is no content version in the protocol, so review is **not** reset
171 > * automatically when a file's contents change under a stable id. The server,
172 > * which is the authority on what changed, resets review explicitly — either
173 > * by re-emitting the file (via {@link ChangesetFileSetAction} or
174 > * {@link ChangesetContentChangedAction}) without `reviewed: true`, or by
175 > * dispatching `changeset/filesReviewChanged` with `reviewed: false`.
176 > */
177 > reviewed?: boolean;
178 > /**
179 > * Server-defined opaque metadata, surfaced to operations and tooling
180 > * but not interpreted by the protocol.
181 > */
182 > _meta?: Record<string, unknown>;
183 > }
184 >
185 > /**
186 > * Execution lifecycle of a {@link ChangesetOperation}.
187 > *
188 > * An operation is invoked imperatively via `invokeChangesetOperation`, but
189 > * its progress and outcome are reflected back into changeset state so that
190 > * every subscriber observes a consistent view (e.g. a spinner on a "Create
191 > * Pull Request" button, or an inline error after a failed "revert").
192 > *
193 > * @category Changesets
194 > */
195 > export const enum ChangesetOperationStatus {
196 > /**
197 > * The operation is ready to be invoked. This is the default when
198 > * {@link ChangesetOperation.status} is omitted.
199 > */
200 > Idle = 'idle',
201 > /** An invocation of this operation is currently in flight. */
202 > Running = 'running',
203 > /**
204 > * The most recent invocation failed. The cause is described by
205 > * {@link ChangesetOperation.error}.
206 > */
207 > Error = 'error',
208 > /**
209 > * The operation is currently disabled and cannot be invoked.
210 > */
211 > Disabled = 'disabled',
212 > }
213 >
214 > /**
215 > * Where a {@link ChangesetOperation} can be invoked.
216 > *
217 > * @category Changesets
218 > */
219 > export const enum ChangesetOperationScope {
220 > /** Applies to the whole changeset. */
221 > Changeset = 'changeset',
222 > /** Applies to a single file within the changeset. */
223 > Resource = 'resource',
224 > /** Applies to a line range within a single file. */
225 > Range = 'range',
226 > }
227 >
228 > /**
229 > * A server-declared invokable verb the client can run against a
230 > * changeset, a file, or a range — `"stage"`, `"revert"`, `"create-pr"`,
231 > * and so on.
232 > *
233 > * The term "operation" is used deliberately to avoid colliding with the
234 > * protocol-level [Actions](/guide/actions) that mutate state.
235 > *
236 > * @category Changesets
237 > */
238 > export interface ChangesetOperation {
239 > /** Stable identifier, unique within this changeset. */
240 > id: string;
241 > /** Human-readable button/menu label. */
242 > label: string;
243 > /** Optional longer description shown on hover or in tooltips. */
244 > description?: string;
245 > /** Where this operation can be invoked. */
246 > scopes: ChangesetOperationScope[];
247 > /**
248 > * Optional confirmation prompt to show before invoking. When present,
249 > * the client MUST display this message to the user (typically in a
250 > * confirmation dialog) and only invoke the operation after the user
251 > * accepts. The presence of this field also signals that the operation
252 > * is destructive — clients SHOULD style the affirmative button
253 > * accordingly (e.g. with a warning colour).
254 > */
255 > confirmation?: StringOrMarkdown;
256 > /** Optional generic icon hint, e.g. `"check"`, `"trash"`. */
257 > icon?: string;
258 > /** Optional group identifier, used to group related operations together. */
259 > group?: string;
260 > /**
261 > * Current execution status. The server sets
262 > * {@link ChangesetOperationStatus.Running | Running} while an invocation
263 > * is in flight, {@link ChangesetOperationStatus.Error | Error} when the
264 > * most recent invocation failed, and
265 > * {@link ChangesetOperationStatus.Idle | Idle} otherwise.
266 > *
267 > * Clients SHOULD reflect this state in the UI — e.g. disabling the
268 > * control or showing a spinner while `Running`, and surfacing
269 > * {@link error} while `Error`.
270 > */
271 > status: ChangesetOperationStatus;
272 > /**
273 > * Cause of failure. Present iff
274 > * `status === ChangesetOperationStatus.Error`; otherwise omitted.
275 > */
276 > error?: ErrorInfo;
277 > }
src/vs/platform/agentHost/common/state/protocol/channels-root/state.ts 244 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { ConfigSchema, JsonPrimitive, ProtectedResourceMetadata } from '../common/state.js';
10 > import type { TerminalInfo } from '../channels-terminal/state.js';
11 > import type { Customization } from '../channels-session/state.js';
12 >
13 > // ─── Root State ──────────────────────────────────────────────────────────────
14 >
15 > /**
16 > * Policy configuration state for a model.
17 > *
18 > * @category Root State
19 > */
20 > export const enum PolicyState {
21 > Enabled = 'enabled',
22 > Disabled = 'disabled',
23 > Unconfigured = 'unconfigured',
24 > }
25 >
26 > /**
27 > * Global state shared with every client subscribed to `ahp-root://`.
28 > *
29 > * @category Root State
30 > */
31 > export interface RootState {
32 > /** Available agent backends and their models */
33 > agents: AgentInfo[];
34 > /** Number of active (non-disposed) sessions on the server */
35 > activeSessions?: number;
36 > /** Known terminals on the server. Subscribe to individual terminal URIs for full state. */
37 > terminals?: TerminalInfo[];
38 > /** Agent host configuration schema and current values */
39 > config?: RootConfigState;
40 > /**
41 > * Additional implementation-defined metadata about the agent host itself.
42 > *
43 > * Clients MAY look for well-known keys here to provide enhanced UI.
44 > */
45 > _meta?: Record<string, unknown>;
46 > }
47 >
48 > /**
49 > * @category Root State
50 > */
51 > export interface AgentInfo {
52 > /** Agent provider ID (e.g. `'copilot'`) */
53 > provider: string;
54 > /** Human-readable name */
55 > displayName: string;
56 > /** Description string */
57 > description: string;
58 > /** Available models for this agent */
59 > models: SessionModelInfo[];
60 > /**
61 > * Protected resources this agent requires authentication for.
62 > *
63 > * Each entry describes an OAuth 2.0 protected resource using
64 > * [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) semantics.
65 > * Clients should obtain tokens from the declared `authorization_servers`
66 > * and push them via the `authenticate` command before creating sessions
67 > * with this agent.
68 > *
69 > * @see {@link /specification/authentication | Authentication}
70 > */
71 > protectedResources?: ProtectedResourceMetadata[];
72 > /**
73 > * Customizations associated with this agent.
74 > *
75 > * Either container customizations —
76 > * {@link PluginCustomization | `PluginCustomization`} entries the agent
77 > * bundles, plus {@link DirectoryCustomization | `DirectoryCustomization`}
78 > * entries it watches in any workspace it's used with — or top-level
79 > * {@link McpServerCustomization | `McpServerCustomization`} entries
80 > * the agent host declares directly. When a session is created with
81 > * this agent, these entries are augmented (e.g. directory URIs are
82 > * resolved against the workspace, children are parsed) and propagated
83 > * into the session's `customizations` list.
84 > */
85 > customizations?: Customization[];
86 > /**
87 > * Static capabilities the agent advertises about itself. Clients use these
88 > * to gate features (multi-chat, fork) instead of switching on the provider
89 > * id.
90 > */
91 > capabilities?: AgentCapabilities;
92 > }
93 >
94 > /**
95 > * Static capabilities an {@link AgentInfo} advertises. Modelled after MCP
96 > * capabilities: each field is opt-in and its presence (an empty object `{}`)
97 > * signals support, while absence means the feature is unsupported and the
98 > * corresponding client commands MUST NOT be used. Sub-fields carry
99 > * per-capability options.
100 > *
101 > * @category Root State
102 > */
103 > export interface AgentCapabilities {
104 > /**
105 > * The agent can host more than one concurrent chat per session. When absent,
106 > * clients MUST NOT call `createChat` to open chats beyond the default one the
107 > * session starts with. An empty object `{}` advertises multi-chat without
108 > * source-based creation; set {@link MultipleChatsCapability.fork} or
109 > * {@link MultipleChatsCapability.sideChat} to allow the corresponding mode.
110 > */
111 > multipleChats?: MultipleChatsCapability;
112 > /**
113 > * The session's agent can be granted tool access to more than one working
114 > * directory. The directories are treated as equal peers except where the
115 > * agent advertises {@link MultipleWorkingDirectoriesCapability.requiresPrimary}
116 > * (some backends need one directory designated as a primary root).
117 > *
118 > * When absent, clients MUST NOT mutate a session's or chat's working-directory
119 > * set and MUST NOT set more than one entry in
120 > * {@link CreateSessionParams.workingDirectories}.
121 > */
122 > multipleWorkingDirectories?: MultipleWorkingDirectoriesCapability;
123 > }
124 >
125 > /**
126 > * Options for the {@link AgentCapabilities.multipleChats} capability.
127 > *
128 > * @category Root State
129 > */
130 > export interface MultipleChatsCapability {
131 > /**
132 > * The agent can fork a chat from a specific turn. When absent or `false`,
133 > * clients MUST NOT pass a {@link ChatSource} with `kind: "fork"` to
134 > * `createChat`.
135 > * Forking always implies multi-chat support.
136 > */
137 > fork?: boolean;
138 > /**
139 > * The agent can create a side chat from a specific turn. When absent or
140 > * `false`, clients MUST NOT pass a {@link ChatSource} with
141 > * `kind: "sideChat"` to `createChat`.
142 > *
143 > * A side chat receives the source turn as context without copying the source
144 > * transcript into its own visible history. The source is identified by a
145 > * stable `turnId`, which the host resolves against the source chat's current
146 > * `activeTurn` or retained history. When it names the current active turn,
147 > * the host snapshots the available partial assistant response at creation
148 > * time. Side-chat support always implies multi-chat support.
149 > */
150 > sideChat?: boolean;
151 > }
152 >
153 > /**
154 > * Options for the {@link AgentCapabilities.multipleWorkingDirectories} capability.
155 > *
156 > * @category Root State
157 > */
158 > export interface MultipleWorkingDirectoriesCapability {
159 > /**
160 > * The agent requires each chat to designate one of its working directories as
161 > * the **primary** — a distinguished root the chat is centered on (e.g. the
162 > * agent's process root for that chat, the default location for relative
163 > * paths). Primary is a **per-chat** notion, fixed at chat creation. When
164 > * `true`, a client SHOULD supply {@link CreateChatParams.primaryWorkingDirectory}
165 > * (and {@link CreateSessionParams.primaryWorkingDirectory}, which seeds the
166 > * session's default chat); a host MAY reject creation that omits it, or fall
167 > * back to the first entry of the chat's working directories. The chosen
168 > * primary is reported (read-only) on {@link ChatState.primaryWorkingDirectory}.
169 > *
170 > * When absent or `false`, the agent has no primary — all directories are
171 > * equal peers and clients need not designate one.
172 > */
173 > requiresPrimary?: boolean;
174 > }
175 >
176 > /**
177 > * @category Root State
178 > */
179 > export interface SessionModelInfo {
180 > /** Model identifier */
181 > id: string;
182 > /** Provider this model belongs to */
183 > provider: string;
184 > /** Human-readable model name */
185 > name: string;
186 > /** Maximum context window size */
187 > maxContextWindow?: number;
188 > /** Maximum number of output tokens the model can generate */
189 > maxOutputTokens?: number;
190 > /** Maximum number of prompt (input) tokens the model accepts */
191 > maxPromptTokens?: number;
192 > /** Whether the model supports vision */
193 > supportsVision?: boolean;
194 > /** Policy configuration state */
195 > policyState?: PolicyState;
196 > /**
197 > * Configuration schema describing model-specific options (e.g. thinking
198 > * level). Clients present this as a form and pass the resolved values in
199 > * {@link ModelSelection.config} when creating or changing sessions.
200 > */
201 > configSchema?: ConfigSchema;
202 > /**
203 > * Additional provider-specific metadata for this model.
204 > *
205 > * Clients MAY look for well-known keys here to provide enhanced UI.
206 > * For example, a `pricing` key may carry model pricing metadata.
207 > */
208 > _meta?: Record<string, unknown>;
209 > }
210 >
211 > /**
212 > * A model selection: the chosen model ID together with any model-specific
213 > * configuration values whose keys correspond to the model's
214 > * {@link SessionModelInfo.configSchema}.
215 > *
216 > * @category Root State
217 > */
218 > export interface ModelSelection {
219 > /** Model identifier */
220 > id: string;
221 > /**
222 > * Model-specific configuration values. Values are JSON primitives: most
223 > * pickers produce strings, but some (e.g. a numeric context-size picker)
224 > * produce numbers or booleans, which are carried through as-is.
225 > */
226 > config?: Record<string, JsonPrimitive>;
227 > }
228 >
229 > // ─── Root Config Types ───────────────────────────────────────────────────────
230 >
231 > /**
232 > * Live agent-host configuration metadata.
233 > *
234 > * The schema describes the available configuration properties and the values
235 > * contain the current value for each resolved property.
236 > *
237 > * @category Root State
238 > */
239 > export interface RootConfigState {
240 > /** JSON Schema describing available configuration properties */
241 > schema: ConfigSchema;
242 > /** Current configuration values */
243 > values: Record<string, unknown>;
244 > }
src/vs/base/common/validation.ts 237 covered LOC · 63 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- validation.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { mapFilter } from './arrays.js';
7 > import { IJSONSchema } from './jsonSchema.js';
8 >
9 > export interface IValidator<T> {
10 > validate(content: unknown): { content: T; error: undefined } | { content: undefined; error: ValidationError };
11 >
12 > getJSONSchema(): IJSONSchema;
13 > }
14 >
15 > export abstract class ValidatorBase<T> implements IValidator<T> {
16 > abstract validate(content: unknown): { content: T; error: undefined } | { content: undefined; error: ValidationError };
17 >
18 > abstract getJSONSchema(): IJSONSchema;
19 >
20 > validateOrThrow(content: unknown): T {
21 const result = this.validate(content);
22 if (result.error) {
25 return result.content;
26 }
27 > } validation.ts
28 >
29 > export type ValidatorType<T> = T extends IValidator<infer U> ? U : never;
30 >
31 > export interface ValidationError {
32 > message: string;
33 > }
34 >
35 > type TypeOfMap = {
36 > string: string;
37 > number: number;
38 > boolean: boolean;
39 > object: object;
40 > null: null;
41 > };
42 >
43 > class TypeofValidator<TKey extends keyof TypeOfMap> extends ValidatorBase<TypeOfMap[TKey]> {
44 > constructor(private readonly type: TKey) {
45 > super();
46 > }
47 >
48 > validate(content: unknown): { content: TypeOfMap[TKey]; error: undefined } | { content: undefined; error: ValidationError } {
49 > if (typeof content !== this.type) { validation.ts
50 return { content: undefined, error: { message: `Expected ${this.type}, but got ${typeof content}` } };
51 }
53 > return { content: content as TypeOfMap[TKey], error: undefined };
54 > }
56 > getJSONSchema(): IJSONSchema {
57 return { type: this.type };
58 }
59 > } validation.ts
60 >
61 > const vStringValidator = new TypeofValidator('string');
62 > export function vString(): ValidatorBase<string> { return vStringValidator; }
63 >
64 > const vNumberValidator = new TypeofValidator('number');
65 > export function vNumber(): ValidatorBase<number> { return vNumberValidator; }
66 >
67 > const vBooleanValidator = new TypeofValidator('boolean');
68 > export function vBoolean(): ValidatorBase<boolean> { return vBooleanValidator; }
69 >
70 > const vObjAnyValidator = new TypeofValidator('object');
71 > export function vObjAny(): ValidatorBase<object> { return vObjAnyValidator; }
72 >
73 >
74 > class UncheckedValidator<T> extends ValidatorBase<T> {
75 > validate(content: unknown): { content: T; error: undefined } {
76 return { content: content as T, error: undefined };
77 }
79 > getJSONSchema(): IJSONSchema {
80 return {};
81 }
82 > } validation.ts
83 >
84 > export function vUnchecked<T>(): ValidatorBase<T> {
85 > return new UncheckedValidator<T>(); validation.ts
86 > }
88 > class UndefinedValidator extends ValidatorBase<undefined> {
89 > validate(content: unknown): { content: undefined; error: undefined } | { content: undefined; error: ValidationError } {
90 if (content !== undefined) {
91 return { content: undefined, error: { message: `Expected undefined, but got ${typeof content}` } };
94 return { content: undefined, error: undefined };
95 }
97 > getJSONSchema(): IJSONSchema {
98 return {};
99 }
100 > } validation.ts
101 >
102 > export function vUndefined(): ValidatorBase<undefined> {
103 return new UndefinedValidator();
104 }
106 > export function vUnknown(): ValidatorBase<unknown> {
107 > return vUnchecked(); validation.ts
108 > }
110 > export type ObjectProperties = Record<string, unknown>;
111 >
112 > export class Optional<T extends IValidator<unknown>> {
113 > constructor(public readonly validator: T) { }
114 > }
115 >
116 > export function vOptionalProp<T>(validator: IValidator<T>): Optional<IValidator<T>> {
117 > return new Optional(validator); validation.ts
118 > }
120 > type ExtractOptionalKeys<T> = {
121 > [K in keyof T]: T[K] extends Optional<IValidator<unknown>> ? K : never;
122 > }[keyof T];
123 >
124 > type ExtractRequiredKeys<T> = {
125 > [K in keyof T]: T[K] extends Optional<IValidator<unknown>> ? never : K;
126 > }[keyof T];
127 >
128 > export type vObjType<T extends Record<string, IValidator<unknown> | Optional<IValidator<unknown>>>> = {
129 > [K in ExtractRequiredKeys<T>]: T[K] extends IValidator<infer U> ? U : never;
130 > } & {
131 > [K in ExtractOptionalKeys<T>]?: T[K] extends Optional<IValidator<infer U>> ? U : never;
132 > };
133 >
134 > class ObjValidator<T extends Record<string, IValidator<unknown> | Optional<IValidator<unknown>>>> extends ValidatorBase<vObjType<T>> {
135 > constructor(private readonly properties: T) {
136 > super(); validation.ts
137 > }
139 > validate(content: unknown): { content: vObjType<T>; error: undefined } | { content: undefined; error: ValidationError } {
140 > if (typeof content !== 'object' || content === null) { validation.ts
141 return { content: undefined, error: { message: 'Expected object' } };
142 }
144 > // eslint-disable-next-line local/code-no-dangerous-type-assertions
145 > const result: vObjType<T> = {} as vObjType<T>;
146 >
147 > for (const key in this.properties) {
148 > const prop = this.properties[key];
149 > // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
150 > const fieldValue = (content as any)[key];
151 >
152 > const isOptional = prop instanceof Optional;
153 > const validator: IValidator<unknown> = isOptional ? prop.validator : prop;
154 >
155 > if (isOptional && fieldValue === undefined) {
156 > // Optional field not provided, skip validation validation.ts
157 > continue;
158 > }
160 > const { content: value, error } = validator.validate(fieldValue);
161 > if (error) {
162 return { content: undefined, error: { message: `Error in property '${key}': ${error.message}` } };
163 }
165 > // eslint-disable-next-line local/code-no-any-casts, @typescript-eslint/no-explicit-any
166 > (result as any)[key] = value;
167 > }
169 > return { content: result, error: undefined };
170 > } validation.ts
172 > getJSONSchema(): IJSONSchema {
173 const requiredFields: string[] = [];
174 const schemaProperties: Record<string, IJSONSchema> = {};
191 return schema;
192 }
193 > } validation.ts
194 >
195 > export function vObj<T extends Record<string, IValidator<unknown> | Optional<IValidator<unknown>>>>(properties: T): ValidatorBase<vObjType<T>> {
196 > return new ObjValidator(properties); validation.ts
197 > }
199 > class ArrayValidator<T> extends ValidatorBase<T[]> {
200 > constructor(private readonly validator: IValidator<T>) {
201 > super(); validation.ts
202 > }
204 > validate(content: unknown): { content: T[]; error: undefined } | { content: undefined; error: ValidationError } {
205 > if (!Array.isArray(content)) { validation.ts
206 return { content: undefined, error: { message: 'Expected array' } };
207 }
209 > const result: T[] = [];
210 > for (let i = 0; i < content.length; i++) {
211 > const { content: value, error } = this.validator.validate(content[i]);
212 > if (error) {
213 return { content: undefined, error: { message: `Error in element ${i}: ${error.message}` } };
214 }
216 > result.push(value);
217 > }
218 >
219 > return { content: result, error: undefined };
220 > } validation.ts
222 > getJSONSchema(): IJSONSchema {
223 return {
224 type: 'array',
226 };
227 }
228 > } validation.ts
229 >
230 > export function vArray<T>(validator: IValidator<T>): ValidatorBase<T[]> {
231 > return new ArrayValidator(validator); validation.ts
232 > }
234 > type vTupleType<T extends IValidator<unknown>[]> = { [K in keyof T]: ValidatorType<T[K]> };
235 >
236 > class TupleValidator<T extends IValidator<unknown>[]> extends ValidatorBase<vTupleType<T>> {
237 > constructor(private readonly validators: T) {
238 super();
239 }
241 > validate(content: unknown): { content: vTupleType<T>; error: undefined } | { content: undefined; error: ValidationError } {
242 if (!Array.isArray(content)) {
243 return { content: undefined, error: { message: 'Expected array' } };
260 return { content: result, error: undefined };
261 }
263 > getJSONSchema(): IJSONSchema {
264 return {
265 type: 'array',
267 };
268 }
269 > } validation.ts
270 >
271 > export function vTuple<T extends IValidator<unknown>[]>(...validators: T): ValidatorBase<vTupleType<T>> {
272 return new TupleValidator(validators);
273 }
275 > class UnionValidator<T extends IValidator<unknown>[]> extends ValidatorBase<ValidatorType<T[number]>> {
276 > constructor(private readonly validators: T) {
277 super();
278 }
280 > validate(content: unknown): { content: ValidatorType<T[number]>; error: undefined } | { content: undefined; error: ValidationError } {
281 let lastError: ValidationError | undefined;
282 for (const validator of this.validators) {
292 return { content: undefined, error: lastError! };
293 }
295 > getJSONSchema(): IJSONSchema {
296 return {
297 oneOf: mapFilter(this.validators, validator => {
303 };
304 }
305 > } validation.ts
306 >
307 > export function vUnion<T extends IValidator<unknown>[]>(...validators: T): ValidatorBase<ValidatorType<T[number]>> {
308 return new UnionValidator(validators);
309 }
311 > class EnumValidator<T extends string[]> extends ValidatorBase<T[number]> {
312 > constructor(private readonly values: T) {
313 super();
314 }
316 > validate(content: unknown): { content: T[number]; error: undefined } | { content: undefined; error: ValidationError } {
317 if (this.values.indexOf(content as string) === -1) {
318 return { content: undefined, error: { message: `Expected one of: ${this.values.join(', ')}` } };
321 return { content: content as T[number], error: undefined };
322 }
324 > getJSONSchema(): IJSONSchema {
325 return {
326 enum: this.values,
327 };
328 }
329 > } validation.ts
330 >
331 > export function vEnum<T extends string[]>(...values: T): ValidatorBase<T[number]> {
332 return new EnumValidator(values);
333 }
335 > class LiteralValidator<T extends string> extends ValidatorBase<T> {
336 > constructor(private readonly value: T) {
337 super();
338 }
340 > validate(content: unknown): { content: T; error: undefined } | { content: undefined; error: ValidationError } {
341 if (content !== this.value) {
342 return { content: undefined, error: { message: `Expected: ${this.value}` } };
345 return { content: content as T, error: undefined };
346 }
348 > getJSONSchema(): IJSONSchema {
349 return {
350 const: this.value,
351 };
352 }
353 > } validation.ts
354 >
355 > export function vLiteral<T extends string>(value: T): ValidatorBase<T> {
356 return new LiteralValidator(value);
357 }
359 > class LazyValidator<T> extends ValidatorBase<T> {
360 > constructor(private readonly fn: () => IValidator<T>) {
361 super();
362 }
364 > validate(content: unknown): { content: T; error: undefined } | { content: undefined; error: ValidationError } {
365 return this.fn().validate(content);
366 }
368 > getJSONSchema(): IJSONSchema {
369 return this.fn().getJSONSchema();
370 }
371 > } validation.ts
372 >
373 > export function vLazy<T>(fn: () => IValidator<T>): ValidatorBase<T> {
374 return new LazyValidator(fn);
375 }
377 > class UseRefSchemaValidator<T> extends ValidatorBase<T> {
378 > constructor(
379 private readonly _ref: string,
380 private readonly _validator: IValidator<T>
382 super();
383 }
385 > validate(content: unknown): { content: T; error: undefined } | { content: undefined; error: ValidationError } {
386 return this._validator.validate(content);
387 }
389 > getJSONSchema(): IJSONSchema {
390 return { $ref: this._ref };
391 }
392 > } validation.ts
393 >
394 > export function vWithJsonSchemaRef<T>(ref: string, validator: IValidator<T>): ValidatorBase<T> {
395 return new UseRefSchemaValidator(ref, validator);
396 }
src/vs/platform/agentHost/node/claude/claudeElicitation.ts 207 covered LOC · 36 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- claudeElicitation.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { ElicitationRequest, ElicitationResult } from '@anthropic-ai/claude-agent-sdk';
7 > import type { PrimitiveSchemaDefinition } from '@modelcontextprotocol/sdk/types.js';
8 > import { isObject, isString } from '../../../../base/common/types.js';
9 > import { vArray, vNumber, vObj, vOptionalProp, vString, vUnknown, type ValidatorType } from '../../../../base/common/validation.js';
10 > import { ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputQuestionKind, ChatInputResponseKind, type ChatInputAnswer, type ChatInputOption, type ChatInputQuestion, type ChatInputRequest } from '../../common/state/sessionState.js';
11 >
12 > /**
13 > * Pure projections between the Claude SDK's MCP elicitation request/response
14 > * and the agentHost workbench protocol.
15 > *
16 > * When an MCP server calls `elicit/create`, the SDK invokes
17 > * `Options.onElicitation` with an {@link ElicitationRequest}. The agent surfaces
18 > * it as structured user input (a {@link ChatInputRequest}, the same channel
19 > * `AskUserQuestion` uses — NOT the permission gate) and translates the user's
20 > * answer back into the SDK's {@link ElicitationResult}. This module owns those
21 > * projections so they can be unit-tested without standing up an agent.
22 > *
23 > * Unlike the Codex provider — whose `requestedSchema` is a strongly-typed
24 > * generated schema — the Claude SDK delivers `requestedSchema` as an untyped
25 > * `Record<string, unknown>`. Each field is runtime-validated with the base-layer
26 > * {@link vObj} validator ({@link vElicitationField}), which drops malformed
27 > * fields instead of mis-projecting or throwing. The field type is *derived* from
28 > * that validator (not hand-rolled) and cross-checked against the MCP SDK's
29 > * authoritative {@link PrimitiveSchemaDefinition} by
30 > * {@link _assertElicitationFieldCoversSchema} (which catches an incompatible
31 > * reshape of a covered field, though not a purely additive new variant). The
32 > * base-layer validator is used rather than the SDK's own zod schema because this
33 > * module is loaded by the unit-test renderer, where a runtime
34 > * `@modelcontextprotocol/sdk` import does not resolve (all SDK runtime access
35 > * goes through `IClaudeAgentSdkService`).
36 > */
37 >
38 > /** Value the SDK accepts back for a single elicited field. */
39 > type ElicitationFieldValue = NonNullable<ElicitationResult['content']>[string];
40 >
41 > /** A `{ const, title? }` option, shared by `oneOf` and array `items.anyOf`. */
42 > const vTitledOption = vObj({ const: vString(), title: vOptionalProp(vString()) });
43 >
44 > /**
45 > * Lenient runtime validator for a single elicitation schema field. Structure is
46 > * validated (a present `enum` must be a string array, `minimum` a number, …) so
47 > * a malformed field is dropped rather than mis-projected; value-level
48 > * constraints (e.g. `format`, `type`) stay permissive so real-world schema
49 > * variation still renders. {@link IElicitationField} is derived from this, and
50 > * {@link _assertElicitationFieldCoversSchema} pins it to the MCP SDK's
51 > * {@link PrimitiveSchemaDefinition}.
52 > */
53 > const vElicitationField = vObj({
54 > type: vOptionalProp(vString()),
55 > title: vOptionalProp(vString()),
56 > description: vOptionalProp(vString()),
57 > format: vOptionalProp(vString()),
58 > default: vOptionalProp(vUnknown()),
59 > minimum: vOptionalProp(vNumber()),
60 > maximum: vOptionalProp(vNumber()),
61 > minLength: vOptionalProp(vNumber()),
62 > maxLength: vOptionalProp(vNumber()),
63 > minItems: vOptionalProp(vNumber()),
64 > maxItems: vOptionalProp(vNumber()),
65 > enum: vOptionalProp(vArray(vString())),
66 > enumNames: vOptionalProp(vArray(vString())),
67 > oneOf: vOptionalProp(vArray(vTitledOption)),
68 > items: vOptionalProp(vObj({
69 > enum: vOptionalProp(vArray(vString())),
70 > anyOf: vOptionalProp(vArray(vTitledOption)),
71 > })),
72 > });
73 >
74 > type IElicitationField = ValidatorType<typeof vElicitationField>;
75 >
76 > /**
77 > * Compile-time guard: every member of the MCP SDK's authoritative
78 > * {@link PrimitiveSchemaDefinition} union must be assignable to
79 > * {@link IElicitationField}. This catches an *incompatible reshape* of a field
80 > * we already project (e.g. the SDK retyping `enum` from `string[]` to
81 > * `number[]`) by failing to compile. It does NOT catch purely additive changes
82 > * — a brand-new union member or keyword stays structurally assignable to this
83 > * all-optional view and would be silently ignored by the projection until a
84 > * human notices the new shape. It is type-only: never called, erased at runtime.
85 > */
86 function _assertElicitationFieldCoversSchema(field: PrimitiveSchemaDefinition): IElicitationField {
87 return field;
88 }
90 > /**
91 > * Reshaped, validated view of the `form`-mode `requestedSchema`: the schema's
92 > * `properties` record flattened into ordered `[name, field]` tuples, plus its
93 > * `required` list as a set for O(1) per-field lookup during projection.
94 > */
95 > interface IParsedElicitationSchema {
96 > readonly fields: ReadonlyArray<readonly [string, IElicitationField]>;
97 > readonly required: ReadonlySet<string>;
98 > }
99 >
100 > /**
101 > * Narrow the untyped `requestedSchema` into an ordered list of runtime-validated
102 > * fields plus the required set. Fields that fail {@link vElicitationField}
103 > * validation are dropped. Returns `undefined` when the schema is absent or has no
104 > * usable `properties` object, so the caller can fall back to a message-only
105 > * request.
106 > */
107 > function parseElicitationSchema(schema: unknown): IParsedElicitationSchema | undefined { claudeElicitation.ts
108 > if (!isObject(schema)) {
109 return undefined;
110 }
111 > const properties = (schema as { properties?: unknown }).properties; claudeElicitation.ts
112 > if (!isObject(properties)) {
113 return undefined;
114 }
115 > const rawRequired = (schema as { required?: unknown }).required; claudeElicitation.ts
116 > const required = new Set<string>(Array.isArray(rawRequired) ? rawRequired.filter(isString) : []); claudeElicitation.ts
117 > const fields: Array<readonly [string, IElicitationField]> = [];
118 > for (const [name, field] of Object.entries(properties)) {
119 > const { content, error } = vElicitationField.validate(field); claudeElicitation.ts
120 > if (!error) {
121 > fields.push([name, content]); claudeElicitation.ts
122 > }
124 > return { fields, required }; claudeElicitation.ts
125 > }
127 > /**
128 > * Build the workbench {@link ChatInputRequest} for an MCP elicitation.
129 > *
130 > * - `url` mode surfaces the URL via {@link ChatInputRequest.url} with no
131 > * questions, driving the renderer's "open URL" affordance.
132 > * - `form` mode projects each field of the requested JSON schema into a
133 > * {@link ChatInputQuestion}. A missing/malformed schema falls back to a
134 > * message-only request so the user can still accept or decline.
135 > */
136 > export function buildElicitationRequest(requestId: string, request: ElicitationRequest): ChatInputRequest {
137 if (request.mode === 'url') {
138 const result: ChatInputRequest = { id: requestId, message: request.message };
149 return { id: requestId, message: request.message, questions };
150 }
152 > /**
153 > * Build the SDK {@link ElicitationResult} from the client's answers. A declined
154 > * request maps to `decline`, a cancelled/closed request to `cancel`, and an
155 > * accepted request to `accept` with a `content` object keyed by field name
156 > * (omitting skipped/missing answers). `url`-mode acceptances carry no content.
157 > */
158 > export function elicitationResultFromAnswers(
159 > request: ElicitationRequest, claudeElicitation.ts
160 > response: ChatInputResponseKind,
161 > answers: Record<string, ChatInputAnswer> | undefined,
162 > ): ElicitationResult {
163 > if (response === ChatInputResponseKind.Decline) {
164 return { action: 'decline' };
165 }
166 > if (response !== ChatInputResponseKind.Accept) { claudeElicitation.ts
167 return { action: 'cancel' };
168 }
169 > const schema = request.mode === 'url' ? undefined : parseElicitationSchema(request.requestedSchema); claudeElicitation.ts
170 > if (!schema) {
171 return { action: 'accept' };
172 }
173 > // Field names come from an untrusted schema and may be `__proto__` or another claudeElicitation.ts
174 > // inherited key, so read answers with `Object.hasOwn` and materialize the
175 > // content via `Object.fromEntries` (define semantics) so such a name lands as
176 > // an own data property instead of mutating the prototype or being dropped.
177 > const entries: [string, ElicitationFieldValue][] = [];
178 > for (const [name, field] of schema.fields) {
179 > const answer = answers && Object.hasOwn(answers, name) ? answers[name] : undefined;
180 > const value = elicitationAnswerToValue(field, answer);
181 > if (value !== undefined) {
182 > entries.push([name, value]); claudeElicitation.ts
183 > }
185 > return { action: 'accept', content: Object.fromEntries(entries) };
186 > }
188 > /** Cancel result used when there is no session to route the elicitation to. */
189 > export function cancelledElicitationResult(): ElicitationResult {
190 return { action: 'cancel' };
191 }
193 > /**
194 > * Project a single narrowed schema field into a {@link ChatInputQuestion}. The
195 > * schema's property key becomes the stable question id (the key the answer map
196 > * is later read back by). Unknown/missing types fall back to a plain text field.
197 > */
198 function elicitationFieldToQuestion(id: string, field: IElicitationField, required: boolean): ChatInputQuestion {
199 const base = { id, title: field.title ?? id, message: field.description ?? field.title ?? id, required };
256 }
257 }
259 > /**
260 > * Project a single {@link ChatInputAnswer} back into the raw value the SDK
261 > * expects for the given field, coercing to the field's declared type. This is
262 > * schema-aware because the workbench renders number/integer/boolean questions as
263 > * text inputs (no dedicated widget) and returns them as {@link ChatInputAnswer}
264 > * text values, so `"3"` / `"false"` must be coerced back to `3` / `false` to
265 > * satisfy the requested schema. Skipped/missing/uncoercible answers return
266 > * `undefined` so the caller omits them from the content object.
267 > */
268 > function elicitationAnswerToValue(field: IElicitationField, answer: ChatInputAnswer | undefined): ElicitationFieldValue | undefined { claudeElicitation.ts
269 > if (!answer || answer.state === ChatInputAnswerState.Skipped) {
270 return undefined;
271 }
272 > const { value } = answer; claudeElicitation.ts
273 > switch (field.type) {
274 > case 'boolean':
275 > if (value.kind === ChatInputAnswerValueKind.Boolean) { claudeElicitation.ts
276 return value.value;
277 }
278 > if (value.kind === ChatInputAnswerValueKind.Text) { claudeElicitation.ts
279 > if (value.value === 'true') { return true; }
280 > if (value.value === 'false') { return false; }
281 > }
282 return undefined;
283 > case 'number': claudeElicitation.ts
284 > case 'integer': {
285 > const n = value.kind === ChatInputAnswerValueKind.Number claudeElicitation.ts
286 ? value.value
287 > : value.kind === ChatInputAnswerValueKind.Text && value.value.trim() !== '' claudeElicitation.ts
288 > ? Number(value.value)
289 : undefined;
290 > if (n === undefined || !Number.isFinite(n)) { claudeElicitation.ts
291 > return undefined; claudeElicitation.ts
292 > }
293 > return field.type === 'integer' ? Math.trunc(n) : n; claudeElicitation.ts
294 > }
295 > case 'array': claudeElicitation.ts
296 if (value.kind === ChatInputAnswerValueKind.SelectedMany) {
297 return [...value.value, ...(value.freeformValues ?? [])];
src/vs/base/common/platform.ts 189 covered LOC · 12 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- platform.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import * as nls from '../../nls.js';
7 >
8 > export const LANGUAGE_DEFAULT = 'en';
9 >
10 > let _isWindows = false;
11 > let _isMacintosh = false;
12 > let _isLinux = false;
13 > let _isLinuxSnap = false;
14 > let _isNative = false;
15 > let _isWeb = false;
16 > let _isElectron = false;
17 > let _isIOS = false;
18 > let _isCI = false;
19 > let _isMobile = false;
20 > let _locale: string | undefined = undefined;
21 > let _language: string = LANGUAGE_DEFAULT;
22 > let _platformLocale: string = LANGUAGE_DEFAULT;
23 > let _translationsConfigFile: string | undefined = undefined;
24 > let _userAgent: string | undefined = undefined;
25 >
26 > export interface IProcessEnvironment {
27 > [key: string]: string | undefined;
28 > }
29 >
30 > /**
31 > * This interface is intentionally not identical to node.js
32 > * process because it also works in sandboxed environments
33 > * where the process object is implemented differently. We
34 > * define the properties here that we need for `platform`
35 > * to work and nothing else.
36 > */
37 > export interface INodeProcess {
38 > platform: string;
39 > arch: string;
40 > env: IProcessEnvironment;
41 > versions?: {
42 > node?: string;
43 > electron?: string;
44 > chrome?: string;
45 > };
46 > type?: string;
47 > cwd: () => string;
48 > }
49 >
50 > declare const process: INodeProcess;
51 >
52 > const $globalThis: any = globalThis;
53 >
54 > let nodeProcess: INodeProcess | undefined = undefined;
55 > if (typeof $globalThis.vscode !== 'undefined' && typeof $globalThis.vscode.process !== 'undefined') {
56 // Native environment (sandboxed)
57 nodeProcess = $globalThis.vscode.process;
58 > } else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') { platform.ts
59 > // Native environment (non-sandboxed)
60 > nodeProcess = process;
61 > }
62 >
63 > const isElectronProcess = typeof nodeProcess?.versions?.electron === 'string';
64 > const isElectronRenderer = isElectronProcess && nodeProcess?.type === 'renderer';
65 >
66 > interface INavigator {
67 > userAgent: string;
68 > maxTouchPoints?: number;
69 > language: string;
70 > }
71 > declare const navigator: INavigator;
72 >
73 > // Native environment
74 > if (typeof nodeProcess === 'object') {
75 > _isWindows = (nodeProcess.platform === 'win32');
76 > _isMacintosh = (nodeProcess.platform === 'darwin');
77 > _isLinux = (nodeProcess.platform === 'linux');
78 > _isLinuxSnap = _isLinux && !!nodeProcess.env['SNAP'] && !!nodeProcess.env['SNAP_REVISION'];
79 > _isElectron = isElectronProcess;
80 > _isCI = !!nodeProcess.env['CI'] || !!nodeProcess.env['BUILD_ARTIFACTSTAGINGDIRECTORY'] || !!nodeProcess.env['GITHUB_WORKSPACE'];
81 > _locale = LANGUAGE_DEFAULT;
82 > _language = LANGUAGE_DEFAULT;
83 > const rawNlsConfig = nodeProcess.env['VSCODE_NLS_CONFIG'];
84 > if (rawNlsConfig) {
85 try {
86 const nlsConfig: nls.INLSConfiguration = JSON.parse(rawNlsConfig);
113 console.error('Unable to resolve platform.');
114 }
115 > platform.ts
116 > export const enum Platform {
117 > Web,
118 > Mac,
119 > Linux,
120 > Windows
121 > }
122 > export type PlatformName = 'Web' | 'Windows' | 'Mac' | 'Linux';
123 >
124 > export function PlatformToString(platform: Platform): PlatformName {
125 switch (platform) {
126 case Platform.Web: return 'Web';
130 }
131 }
132 > platform.ts
133 > let _platform: Platform = Platform.Web;
134 > if (_isMacintosh) {
135 _platform = Platform.Mac;
136 > } else if (_isWindows) { platform.ts
137 _platform = Platform.Windows;
138 > } else if (_isLinux) { platform.ts
139 > _platform = Platform.Linux;
140 > }
141 >
142 > export const isWindows = _isWindows;
143 > export const isMacintosh = _isMacintosh;
144 > export const isLinux = _isLinux;
145 > export const isLinuxSnap = _isLinuxSnap;
146 > export const isNative = _isNative;
147 > export const isElectron = _isElectron;
148 > export const isWeb = _isWeb;
149 > export const isWebWorker = (_isWeb && typeof $globalThis.importScripts === 'function');
150 > export const webWorkerOrigin = isWebWorker ? $globalThis.origin : undefined;
151 > export const isIOS = _isIOS;
152 > export const isMobile = _isMobile;
153 > /**
154 > * Whether we run inside a CI environment, such as
155 > * GH actions or Azure Pipelines.
156 > */
157 > export const isCI = _isCI;
158 > export const platform = _platform;
159 > export const userAgent = _userAgent;
160 >
161 > /**
162 > * The language used for the user interface. The format of
163 > * the string is all lower case (e.g. zh-tw for Traditional
164 > * Chinese or de for German)
165 > */
166 > export const language = _language;
167 >
168 > export namespace Language {
169 >
170 > export function value(): string {
171 return language;
172 }
173 > platform.ts
174 > export function isDefaultVariant(): boolean {
175 if (language.length === 2) {
176 return language === 'en';
181 }
182 }
183 > platform.ts
184 > export function isDefault(): boolean {
185 return language === 'en';
186 }
187 > } platform.ts
188 >
189 > /**
190 > * Desktop: The OS locale or the locale specified by --locale or `argv.json`.
191 > * Web: matches `platformLocale`.
192 > *
193 > * The UI is not necessarily shown in the provided locale.
194 > */
195 > export const locale = _locale;
196 >
197 > /**
198 > * This will always be set to the OS/browser's locale regardless of
199 > * what was specified otherwise. The format of the string is all
200 > * lower case (e.g. zh-tw for Traditional Chinese). The UI is not
201 > * necessarily shown in the provided locale.
202 > */
203 > export const platformLocale = _platformLocale;
204 >
205 > /**
206 > * The translations that are available through language packs.
207 > */
208 > export const translationsConfigFile = _translationsConfigFile;
209 >
210 > export const setTimeout0IsFaster = (typeof $globalThis.postMessage === 'function' && !$globalThis.importScripts);
211 >
212 > /**
213 > * See https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#:~:text=than%204%2C%20then-,set%20timeout%20to%204,-.
214 > *
215 > * Works similarly to `setTimeout(0)` but doesn't suffer from the 4ms artificial delay
216 > * that browsers set when the nesting level is > 5.
217 > */
218 > export const setTimeout0 = (() => {
219 > if (setTimeout0IsFaster) {
220 interface IQueueElement {
221 id: number;
246 };
247 }
248 > return (callback: () => void) => setTimeout(callback); platform.ts
249 > })();
250 >
251 > export const enum OperatingSystem {
252 > Windows = 1,
253 > Macintosh = 2,
254 > Linux = 3
255 > }
256 > export const OS = (_isMacintosh || _isIOS ? OperatingSystem.Macintosh : (_isWindows ? OperatingSystem.Windows : OperatingSystem.Linux));
257 >
258 > let _isLittleEndian = true;
259 > let _isLittleEndianComputed = false;
260 > export function isLittleEndian(): boolean {
261 if (!_isLittleEndianComputed) {
262 _isLittleEndianComputed = true;
269 return _isLittleEndian;
270 }
271 > platform.ts
272 > export const isChrome = !!(userAgent && userAgent.indexOf('Chrome') >= 0);
273 > export const isFirefox = !!(userAgent && userAgent.indexOf('Firefox') >= 0);
274 > export const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf('Safari') >= 0));
275 > export const isEdge = !!(userAgent && userAgent.indexOf('Edg/') >= 0);
276 > export const isAndroid = !!(userAgent && userAgent.indexOf('Android') >= 0);
277 > export const hasElectronUserAgent = !!(userAgent && userAgent.indexOf('Electron') >= 0);
278 >
279 > export function isTahoeOrNewer(osVersion: string): boolean {
280 return parseFloat(osVersion) >= 25;
281 }
src/vs/nls.ts 187 covered LOC · 6 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- nls.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export function getNLSMessages(): string[] {
7 return globalThis._VSCODE_NLS_MESSAGES;
8 }
9 > nls.ts
10 > export function getNLSLanguage(): string | undefined {
11 > return globalThis._VSCODE_NLS_LANGUAGE;
12 > }
13 >
14 > declare const document: { location?: { hash?: string } } | undefined;
15 > const isPseudo = getNLSLanguage() === 'pseudo' || (typeof document !== 'undefined' && document.location && typeof document.location.hash === 'string' && document.location.hash.indexOf('pseudo=true') >= 0);
16 >
17 > export interface ILocalizeInfo {
18 > key: string;
19 > comment: string[];
20 > }
21 >
22 > export interface ILocalizedString {
23 > original: string;
24 > value: string;
25 > }
26 >
27 function _format(message: string, args: (string | number | boolean | undefined | null)[]): string {
28 let result: string;
51 return result;
52 }
53 > nls.ts
54 > /**
55 > * Marks a string to be localized. Returns the localized string.
56 > *
57 > * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string.
58 > * @param message The string to localize
59 > * @param args The arguments to the string
60 > *
61 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
62 > * @example `localize({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)`
63 > *
64 > * @returns string The localized string.
65 > */
66 > export function localize(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): string;
67 >
68 > /**
69 > * Marks a string to be localized. Returns the localized string.
70 > *
71 > * @param key The key to use for localizing the string
72 > * @param message The string to localize
73 > * @param args The arguments to the string
74 > *
75 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
76 > * @example For example, `localize('sayHello', 'hello {0}', name)`
77 > *
78 > * @returns string The localized string.
79 > */
80 > export function localize(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): string;
81 >
82 > /**
83 > * @skipMangle
84 > */
85 > export function localize(data: ILocalizeInfo | string /* | number when built */, message: string /* | null when built */, ...args: (string | number | boolean | undefined | null)[]): string {
86 if (typeof data === 'number') {
87 return _format(lookupMessage(data, message), args);
89 return _format(message, args);
90 }
91 > nls.ts
92 > /**
93 > * Only used when built: Looks up the message in the global NLS table.
94 > * This table is being made available as a global through bootstrapping
95 > * depending on the target context.
96 > */
97 function lookupMessage(index: number, fallback: string | null): string {
98 const message = getNLSMessages()?.[index];
105 return message;
106 }
107 > nls.ts
108 > /**
109 > * Marks a string to be localized. Returns an {@linkcode ILocalizedString}
110 > * which contains the localized string and the original string.
111 > *
112 > * @param info The {@linkcode ILocalizeInfo} which describes the id and comments associated with the localized string.
113 > * @param message The string to localize
114 > * @param args The arguments to the string
115 > *
116 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
117 > * @example `localize2({ key: 'sayHello', comment: ['Welcomes user'] }, 'hello {0}', name)`
118 > *
119 > * @returns ILocalizedString which contains the localized string and the original string.
120 > */
121 > export function localize2(info: ILocalizeInfo, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString;
122 >
123 > /**
124 > * Marks a string to be localized. Returns an {@linkcode ILocalizedString}
125 > * which contains the localized string and the original string.
126 > *
127 > * @param key The key to use for localizing the string
128 > * @param message The string to localize
129 > * @param args The arguments to the string
130 > *
131 > * @note `message` can contain `{n}` notation where it is replaced by the nth value in `...args`
132 > * @example `localize('sayHello', 'hello {0}', name)`
133 > *
134 > * @returns ILocalizedString which contains the localized string and the original string.
135 > */
136 > export function localize2(key: string, message: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString;
137 >
138 > /**
139 > * @skipMangle
140 > */
141 > export function localize2(data: ILocalizeInfo | string /* | number when built */, originalMessage: string, ...args: (string | number | boolean | undefined | null)[]): ILocalizedString {
142 let message: string;
143 if (typeof data === 'number') {
154 };
155 }
156 > nls.ts
157 > export interface INLSLanguagePackConfiguration {
158 >
159 > /**
160 > * The path to the translations config file that contains pointers to
161 > * all message bundles for `main` and extensions.
162 > */
163 > readonly translationsConfigFile: string;
164 >
165 > /**
166 > * The path to the file containing the translations for this language
167 > * pack as flat string array.
168 > */
169 > readonly messagesFile: string;
170 >
171 > /**
172 > * The path to the file that can be used to signal a corrupt language
173 > * pack, for example when reading the `messagesFile` fails. This will
174 > * instruct the application to re-create the cache on next startup.
175 > */
176 > readonly corruptMarkerFile: string;
177 > }
178 >
179 > export interface INLSConfiguration {
180 >
181 > /**
182 > * Locale as defined in `argv.json` or `app.getLocale()`.
183 > */
184 > readonly userLocale: string;
185 >
186 > /**
187 > * Locale as defined by the OS (e.g. `app.getPreferredSystemLanguages()`).
188 > */
189 > readonly osLocale: string;
190 >
191 > /**
192 > * The actual language of the UI that ends up being used considering `userLocale`
193 > * and `osLocale`.
194 > */
195 > readonly resolvedLanguage: string;
196 >
197 > /**
198 > * Defined if a language pack is used that is not the
199 > * default english language pack. This requires a language
200 > * pack to be installed as extension.
201 > */
202 > readonly languagePack?: INLSLanguagePackConfiguration;
203 >
204 > /**
205 > * The path to the file containing the default english messages
206 > * as flat string array. The file is only present in built
207 > * versions of the application.
208 > */
209 > readonly defaultMessagesFile: string;
210 >
211 > /**
212 > * Below properties are deprecated and only there to continue support
213 > * for `vscode-nls` module that depends on them.
214 > * Refs https://github.com/microsoft/vscode-nls/blob/main/src/node/main.ts#L36-L46
215 > */
216 > /** @deprecated */
217 > readonly locale: string;
218 > /** @deprecated */
219 > readonly availableLanguages: Record<string, string>;
220 > /** @deprecated */
221 > readonly _languagePackSupport?: boolean;
222 > /** @deprecated */
223 > readonly _languagePackId?: string;
224 > /** @deprecated */
225 > readonly _translationsConfigFile?: string;
226 > /** @deprecated */
227 > readonly _cacheRoot?: string;
228 > /** @deprecated */
229 > readonly _resolvedLanguagePackCoreLocation?: string;
230 > /** @deprecated */
231 > readonly _corruptedFile?: string;
232 > }
233 >
234 > export interface ILanguagePack {
235 > readonly hash: string;
236 > readonly label: string | undefined;
237 > readonly extensions: {
238 > readonly extensionIdentifier: { readonly id: string; readonly uuid?: string };
239 > readonly version: string;
240 > }[];
241 > readonly translations: Record<string, string | undefined>;
242 > }
243 >
244 > export type ILanguagePacks = Record<string, ILanguagePack | undefined>;
src/vs/base/common/errors.ts 183 covered LOC · 32 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- errors.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export interface ErrorListenerCallback {
7 > (error: any): void;
8 > }
9 >
10 > export interface ErrorListenerUnbind {
11 > (): void;
12 > }
13 >
14 > // Avoid circular dependency on EventEmitter by implementing a subset of the interface.
15 > export class ErrorHandler {
16 > private unexpectedErrorHandler: (e: any) => void;
17 > private listeners: ErrorListenerCallback[];
18 >
19 > constructor() {
20 >
21 > this.listeners = [];
22 >
23 > this.unexpectedErrorHandler = function (e: any) {
24 setTimeout(() => {
25 if (e.stack) {
34 }, 0);
35 };
36 > } errors.ts
37 >
38 > addListener(listener: ErrorListenerCallback): ErrorListenerUnbind {
39 this.listeners.push(listener);
40
43 };
44 }
45 > errors.ts
46 > private emit(e: any): void {
47 this.listeners.forEach((listener) => {
48 listener(e);
49 });
50 }
51 > errors.ts
52 > private _removeListener(listener: ErrorListenerCallback): void {
53 this.listeners.splice(this.listeners.indexOf(listener), 1);
54 }
55 > errors.ts
56 > setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
57 > this.unexpectedErrorHandler = newUnexpectedErrorHandler;
58 > }
59 >
60 > getUnexpectedErrorHandler(): (e: any) => void {
61 return this.unexpectedErrorHandler;
62 }
63 > errors.ts
64 > onUnexpectedError(e: any): void {
65 this.unexpectedErrorHandler(e);
66 this.emit(e);
67 }
68 > errors.ts
69 > // For external errors, we don't want the listeners to be called
70 > onUnexpectedExternalError(e: any): void {
71 this.unexpectedErrorHandler(e);
72 }
73 > } errors.ts
74 >
75 > export const errorHandler = new ErrorHandler();
76 >
77 > /** @skipMangle */
78 > export function setUnexpectedErrorHandler(newUnexpectedErrorHandler: (e: any) => void): void {
79 > errorHandler.setUnexpectedErrorHandler(newUnexpectedErrorHandler);
80 > }
81 >
82 > /**
83 > * Returns if the error is a SIGPIPE error. SIGPIPE errors should generally be
84 > * logged at most once, to avoid a loop.
85 > *
86 > * @see https://github.com/microsoft/vscode-remote-release/issues/6481
87 > */
88 > export function isSigPipeError(e: unknown): e is Error {
89 if (!e || typeof e !== 'object') {
90 return false;
94 return cast.code === 'EPIPE' && cast.syscall?.toUpperCase() === 'WRITE';
95 }
96 > errors.ts
97 > /**
98 > * This function should only be called with errors that indicate a bug in the product.
99 > * E.g. buggy extensions/invalid user-input/network issues should not be able to trigger this code path.
100 > * If they are, this indicates there is also a bug in the product.
101 > */
102 > export function onBugIndicatingError(e: any): undefined {
103 errorHandler.onUnexpectedError(e);
104 return undefined;
105 }
106 > errors.ts
107 > export function onUnexpectedError(e: any): undefined {
108 // ignore errors from cancelled promises
109 if (!isCancellationError(e)) {
112 return undefined;
113 }
114 > errors.ts
115 > export function onUnexpectedExternalError(e: any): undefined {
116 // ignore errors from cancelled promises
117 if (!isCancellationError(e)) {
120 return undefined;
121 }
122 > errors.ts
123 > type ObjectWithCode = {
124 > readonly code: unknown;
125 > };
126 >
127 function hasErrorCode(error: object): error is ObjectWithCode {
128 return Object.hasOwn(error, 'code');
129 }
130 > errors.ts
131 > export function getErrorCode(error: unknown): string | undefined {
132 if (!error || typeof error !== 'object' || !hasErrorCode(error)) {
133 return undefined;
136 return typeof code === 'string' || typeof code === 'number' ? String(code) : undefined;
137 }
138 > errors.ts
139 > export interface SerializedError {
140 > readonly $isError: true;
141 > readonly name: string;
142 > readonly message: string;
143 > readonly stack: string;
144 > readonly noTelemetry: boolean;
145 > readonly code?: string;
146 > readonly cause?: SerializedError;
147 > }
148 >
149 > type ErrorWithCode = Error & {
150 > code: string | undefined;
151 > };
152 >
153 > export function transformErrorForSerialization(error: Error): SerializedError;
154 > export function transformErrorForSerialization(error: any): any;
155 > export function transformErrorForSerialization(error: any): any {
156 if (error instanceof Error) {
157 const { name, message, cause } = error;
172 return error;
173 }
174 > errors.ts
175 > export function transformErrorFromSerialization(data: SerializedError): Error {
176 let error: Error;
177 if (data.noTelemetry) {
191 return error;
192 }
193 > errors.ts
194 > // see https://github.com/v8/v8/wiki/Stack%20Trace%20API#basic-stack-traces
195 > export interface V8CallSite {
196 > getThis(): unknown;
197 > getTypeName(): string | null;
198 > getFunction(): Function | undefined;
199 > getFunctionName(): string | null;
200 > getMethodName(): string | null;
201 > getFileName(): string | null;
202 > getLineNumber(): number | null;
203 > getColumnNumber(): number | null;
204 > getEvalOrigin(): string | undefined;
205 > isToplevel(): boolean;
206 > isEval(): boolean;
207 > isNative(): boolean;
208 > isConstructor(): boolean;
209 > toString(): string;
210 > }
211 >
212 > export const canceledName = 'Canceled';
213 >
214 > /**
215 > * Checks if the given error is a promise in canceled state
216 > */
217 > export function isCancellationError(error: any): boolean {
218 if (error instanceof CancellationError) {
219 return true;
221 return error instanceof Error && error.name === canceledName && error.message === canceledName;
222 }
223 > errors.ts
224 > // !!!IMPORTANT!!!
225 > // Do NOT change this class because it is also used as an API-type.
226 > export class CancellationError extends Error {
227 > constructor() {
228 super(canceledName);
229 this.name = this.message;
230 }
231 > } errors.ts
232 >
233 > export class PendingMigrationError extends Error {
234 >
235 > private static readonly _name = 'PendingMigrationError';
236 >
237 > static is(error: unknown): error is PendingMigrationError {
238 return error instanceof PendingMigrationError || (error instanceof Error && error.name === PendingMigrationError._name);
239 }
240 > errors.ts
241 > constructor(message: string) {
242 super(message);
243 this.name = PendingMigrationError._name;
244 }
245 > } errors.ts
246 >
247 > /**
248 > * @deprecated use {@link CancellationError `new CancellationError()`} instead
249 > */
250 > export function canceled(): Error {
251 const error = new Error(canceledName);
252 error.name = error.message;
253 return error;
254 }
255 > errors.ts
256 > export function illegalArgument(name?: string): Error {
257 if (name) {
258 return new Error(`Illegal argument: ${name}`);
261 }
262 }
263 > errors.ts
264 > export function illegalState(name?: string): Error {
265 if (name) {
266 return new Error(`Illegal state: ${name}`);
269 }
270 }
271 > errors.ts
272 > export class ReadonlyError extends TypeError {
273 > constructor(name?: string) {
274 super(name ? `${name} is read-only and cannot be changed` : 'Cannot change read-only property');
275 }
276 > } errors.ts
277 >
278 > export function getErrorMessage(err: any): string {
279 if (!err) {
280 return 'Error';
291 return String(err);
292 }
293 > errors.ts
294 > export class NotImplementedError extends Error {
295 > constructor(message?: string) {
296 super('NotImplemented');
297 if (message) {
299 }
300 }
301 > } errors.ts
302 >
303 > export class NotSupportedError extends Error {
304 > constructor(message?: string) {
305 super('NotSupported');
306 if (message) {
308 }
309 }
310 > } errors.ts
311 >
312 > export class ExpectedError extends Error {
313 readonly isExpected = true;
314 > } errors.ts
315 >
316 > /**
317 > * Error that when thrown won't be logged in telemetry as an unhandled error.
318 > */
319 > export class ErrorNoTelemetry extends Error {
320 > override readonly name: string;
321 >
322 > constructor(msg?: string) {
323 super(msg);
324 this.name = 'CodeExpectedError';
325 }
326 > errors.ts
327 > public static fromError(err: Error): ErrorNoTelemetry {
328 if (err instanceof ErrorNoTelemetry) {
329 return err;
335 return result;
336 }
337 > errors.ts
338 > public static isErrorNoTelemetry(err: Error): err is ErrorNoTelemetry {
339 return err.name === 'CodeExpectedError';
340 }
341 > } errors.ts
342 >
343 > /**
344 > * This error indicates a bug.
345 > * Do not throw this for invalid user input.
346 > * Only catch this error to recover gracefully from bugs.
347 > */
348 > export class BugIndicatingError extends Error {
349 > constructor(message?: string) {
350 super(message || 'An unexpected bug occurred.');
351 Object.setPrototypeOf(this, BugIndicatingError.prototype);
src/vs/base/common/path.ts 177 covered LOC · 31 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- path.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // NOTE: VSCode's copy of nodejs path library to be usable in common (non-node) namespace
7 > // Copied from: https://github.com/nodejs/node/commits/v22.15.0/lib/path.js
8 > // Excluding: the change that adds primordials
9 > // (https://github.com/nodejs/node/commit/187a862d221dec42fa9a5c4214e7034d9092792f and others)
10 > // Excluding: the change that adds glob matching
11 > // (https://github.com/nodejs/node/commit/57b8b8e18e5e2007114c63b71bf0baedc01936a6)
12 >
13 > /**
14 > * Copyright Joyent, Inc. and other Node contributors.
15 > *
16 > * Permission is hereby granted, free of charge, to any person obtaining a
17 > * copy of this software and associated documentation files (the
18 > * "Software"), to deal in the Software without restriction, including
19 > * without limitation the rights to use, copy, modify, merge, publish,
20 > * distribute, sublicense, and/or sell copies of the Software, and to permit
21 > * persons to whom the Software is furnished to do so, subject to the
22 > * following conditions:
23 > *
24 > * The above copyright notice and this permission notice shall be included
25 > * in all copies or substantial portions of the Software.
26 > *
27 > * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
28 > * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 > * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
30 > * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31 > * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32 > * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
33 > * USE OR OTHER DEALINGS IN THE SOFTWARE.
34 > */
35 >
36 > import * as process from './process.js';
37 >
38 > const CHAR_UPPERCASE_A = 65;/* A */
39 > const CHAR_LOWERCASE_A = 97; /* a */
40 > const CHAR_UPPERCASE_Z = 90; /* Z */
41 > const CHAR_LOWERCASE_Z = 122; /* z */
42 > const CHAR_DOT = 46; /* . */
43 > const CHAR_FORWARD_SLASH = 47; /* / */
44 > const CHAR_BACKWARD_SLASH = 92; /* \ */
45 > const CHAR_COLON = 58; /* : */
46 > const CHAR_QUESTION_MARK = 63; /* ? */
47 >
48 > class ErrorInvalidArgType extends Error {
49 > code: 'ERR_INVALID_ARG_TYPE';
50 > constructor(name: string, expected: string, actual: unknown) {
51 // determiner: 'must be' or 'must not be'
52 let determiner;
66 this.code = 'ERR_INVALID_ARG_TYPE';
67 }
68 > } path.ts
69 >
70 function validateObject(pathObject: object, name: string) {
71 if (pathObject === null || typeof pathObject !== 'object') {
73 }
74 }
75 > path.ts
76 function validateString(value: string, name: string) {
77 if (typeof value !== 'string') {
79 }
80 }
81 > path.ts
82 > const platformIsWin32 = (process.platform === 'win32');
83 >
84 function isPathSeparator(code: number | undefined) {
85 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
86 }
87 > path.ts
88 function isPosixPathSeparator(code: number | undefined) {
89 return code === CHAR_FORWARD_SLASH;
90 }
91 > path.ts
92 function isWindowsDeviceRoot(code: number) {
93 return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
94 (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z);
95 }
96 > path.ts
97 > // Resolves . and .. elements in a path with directory names
98 function normalizeString(path: string, allowAboveRoot: boolean, separator: string, isPathSeparator: (code?: number) => boolean) {
99 let res = '';
163 return res;
164 }
165 > path.ts
166 function formatExt(ext: string): string {
167 return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';
168 }
169 > path.ts
170 function _format(sep: string, pathObject: ParsedPath) {
171 validateObject(pathObject, 'pathObject');
178 return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`;
179 }
180 > path.ts
181 > export interface ParsedPath {
182 > root: string;
183 > dir: string;
184 > base: string;
185 > ext: string;
186 > name: string;
187 > }
188 >
189 > export interface IPath {
190 > normalize(path: string): string;
191 > isAbsolute(path: string): boolean;
192 > join(...paths: string[]): string;
193 > resolve(...pathSegments: string[]): string;
194 > relative(from: string, to: string): string;
195 > dirname(path: string): string;
196 > basename(path: string, suffix?: string): string;
197 > extname(path: string): string;
198 > format(pathObject: ParsedPath): string;
199 > parse(path: string): ParsedPath;
200 > toNamespacedPath(path: string): string;
201 > sep: '\\' | '/';
202 > delimiter: string;
203 > win32: IPath | null;
204 > posix: IPath | null;
205 > }
206 >
207 > export const win32: IPath = {
208 > // path.resolve([from ...], to)
209 > resolve(...pathSegments: string[]): string {
210 let resolvedDevice = '';
211 let resolvedTail = '';
343 `${resolvedDevice}${resolvedTail}` || '.';
344 },
345 > path.ts
346 > normalize(path: string): string {
347 validateString(path, 'path');
348 const len = path.length;
450 return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
451 },
452 > path.ts
453 > isAbsolute(path: string): boolean {
454 validateString(path, 'path');
455 const len = path.length;
466 isPathSeparator(path.charCodeAt(2)));
467 },
468 > path.ts
469 > join(...paths: string[]): string {
470 if (paths.length === 0) {
471 return '.';
536 return win32.normalize(joined);
537 },
538 > path.ts
539 >
540 > // It will solve the relative path from `from` to `to`, for instance:
541 > // from = 'C:\\orandea\\test\\aaa'
542 > // to = 'C:\\orandea\\impl\\bbb'
543 > // The output of the function should be: '..\\..\\impl\\bbb'
544 > relative(from: string, to: string): string {
545 validateString(from, 'from');
546 validateString(to, 'to');
699 return toOrig.slice(toStart, toEnd);
700 },
701 > path.ts
702 > toNamespacedPath(path: string): string {
703 // Note: this will *probably* throw somewhere.
704 if (typeof path !== 'string' || path.length === 0) {
730 return resolvedPath;
731 },
732 > path.ts
733 > dirname(path: string): string {
734 validateString(path, 'path');
735 const len = path.length;
818 return path.slice(0, end);
819 },
820 > path.ts
821 > basename(path: string, suffix?: string): string {
822 if (suffix !== undefined) {
823 validateString(suffix, 'suffix');
906 return path.slice(start, end);
907 },
908 > path.ts
909 > extname(path: string): string {
910 validateString(path, 'path');
911 let start = 0;
972 return path.slice(startDot, end);
973 },
974 > path.ts
975 > format: _format.bind(null, '\\'),
976 >
977 > parse(path) {
978 validateString(path, 'path');
979
1126 return ret;
1127 },
1128 > path.ts
1129 > sep: '\\',
1130 > delimiter: ';',
1131 > win32: null,
1132 > posix: null
1133 > };
1134 >
1135 > const posixCwd = (() => {
1136 > if (platformIsWin32) {
1137 // Converts Windows' backslash path separators to POSIX forward slashes
1138 // and truncates any drive indicator
1143 };
1144 }
1145 > path.ts
1146 > // We're already on POSIX, no need for any transformations
1147 > return () => process.cwd();
1148 > })();
1149 >
1150 > export const posix: IPath = {
1151 > // path.resolve([from ...], to)
1152 > resolve(...pathSegments: string[]): string {
1153 let resolvedPath = '';
1154 let resolvedAbsolute = false;
1186 return resolvedPath.length > 0 ? resolvedPath : '.';
1187 },
1188 > path.ts
1189 > normalize(path: string): string {
1190 validateString(path, 'path');
1191
1213 return isAbsolute ? `/${path}` : path;
1214 },
1215 > path.ts
1216 > isAbsolute(path: string): boolean {
1217 validateString(path, 'path');
1218 return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
1219 },
1220 > path.ts
1221 > join(...paths: string[]): string {
1222 if (paths.length === 0) {
1223 return '.';
1239 return posix.normalize(path.join('/'));
1240 },
1241 > path.ts
1242 > relative(from: string, to: string): string {
1243 validateString(from, 'from');
1244 validateString(to, 'to');
1312 return `${out}${to.slice(toStart + lastCommonSep)}`;
1313 },
1314 > path.ts
1315 > toNamespacedPath(path: string): string {
1316 // Non-op on posix systems
1317 return path;
1318 },
1319 > path.ts
1320 > dirname(path: string): string {
1321 validateString(path, 'path');
1322 if (path.length === 0) {
1346 return path.slice(0, end);
1347 },
1348 > path.ts
1349 > basename(path: string, suffix?: string): string {
1350 if (suffix !== undefined) {
1351 validateString(suffix, 'suffix');
1426 return path.slice(start, end);
1427 },
1428 > path.ts
1429 > extname(path: string): string {
1430 validateString(path, 'path');
1431 let startDot = -1;
1480 return path.slice(startDot, end);
1481 },
1482 > path.ts
1483 > format: _format.bind(null, '/'),
1484 >
1485 > parse(path: string): ParsedPath {
1486 validateString(path, 'path');
1487
1565 return ret;
1566 },
1567 > path.ts
1568 > sep: '/',
1569 > delimiter: ':',
1570 > win32: null,
1571 > posix: null
1572 > };
1573 >
1574 > posix.win32 = win32.win32 = win32;
1575 > posix.posix = win32.posix = posix;
1576 >
1577 > export const normalize = (platformIsWin32 ? win32.normalize : posix.normalize);
1578 > export const isAbsolute = (platformIsWin32 ? win32.isAbsolute : posix.isAbsolute);
1579 > export const join = (platformIsWin32 ? win32.join : posix.join);
1580 > export const resolve = (platformIsWin32 ? win32.resolve : posix.resolve);
1581 > export const relative = (platformIsWin32 ? win32.relative : posix.relative);
1582 > export const dirname = (platformIsWin32 ? win32.dirname : posix.dirname);
1583 > export const basename = (platformIsWin32 ? win32.basename : posix.basename);
1584 > export const extname = (platformIsWin32 ? win32.extname : posix.extname);
1585 > export const format = (platformIsWin32 ? win32.format : posix.format);
1586 > export const parse = (platformIsWin32 ? win32.parse : posix.parse);
1587 > export const toNamespacedPath = (platformIsWin32 ? win32.toNamespacedPath : posix.toNamespacedPath);
1588 > export const sep = (platformIsWin32 ? win32.sep : posix.sep);
1589 > export const delimiter = (platformIsWin32 ? win32.delimiter : posix.delimiter);
src/vs/platform/agentHost/common/state/protocol/channels-terminal/state.ts 173 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI } from '../common/state.js';
10 >
11 > // ─── Terminal Types ──────────────────────────────────────────────────────────
12 >
13 > /**
14 > * Lightweight terminal metadata exposed on the root state.
15 > *
16 > * @category Terminal Types
17 > */
18 > export interface TerminalInfo {
19 > /** Terminal URI (subscribable for full terminal state) */
20 > resource: URI;
21 > /** Human-readable terminal title */
22 > title: string;
23 > /** Who currently holds this terminal */
24 > claim: TerminalClaim;
25 > /** Process exit code, if the terminal process has exited */
26 > exitCode?: number;
27 > }
28 >
29 > /**
30 > * Discriminant for terminal claim kinds.
31 > *
32 > * @category Terminal Types
33 > */
34 > export const enum TerminalClaimKind {
35 > Client = 'client',
36 > Session = 'session',
37 > }
38 >
39 > /**
40 > * A terminal claimed by a connected client.
41 > *
42 > * @category Terminal Types
43 > */
44 > export interface TerminalClientClaim {
45 > /** Discriminant */
46 > kind: TerminalClaimKind.Client;
47 > /** The `clientId` of the claiming client */
48 > clientId: string;
49 > }
50 >
51 > /**
52 > * A terminal claimed by a session, optionally scoped to a specific turn or tool call.
53 > *
54 > * @category Terminal Types
55 > */
56 > export interface TerminalSessionClaim {
57 > /** Discriminant */
58 > kind: TerminalClaimKind.Session;
59 > /** Session URI that claimed the terminal */
60 > session: URI;
61 > /** Optional turn identifier within the session */
62 > turnId?: string;
63 > /** Optional tool call identifier within the turn */
64 > toolCallId?: string;
65 > }
66 >
67 > /**
68 > * Describes who currently holds a terminal. A terminal may be claimed by
69 > * either a connected client or a session (e.g. during a tool call).
70 > *
71 > * @category Terminal Types
72 > */
73 > export type TerminalClaim = TerminalClientClaim | TerminalSessionClaim;
74 >
75 > /**
76 > * Full state for a single terminal, loaded when a client subscribes to the terminal's URI.
77 > *
78 > * @category Terminal Types
79 > */
80 > export interface TerminalState {
81 > /** Human-readable terminal title */
82 > title: string;
83 > /** Current working directory of the terminal process */
84 > cwd?: URI;
85 > /** Terminal width in columns */
86 > cols?: number;
87 > /** Terminal height in rows */
88 > rows?: number;
89 > /**
90 > * Typed content parts, replacing the flat `content: string`.
91 > *
92 > * Naive consumers that only need the raw VT stream can reconstruct it with:
93 > * `content.map(p => p.type === 'command' ? p.output : p.value).join('')`
94 > *
95 > * Consumers that need command boundaries can filter by part type.
96 > */
97 > content: TerminalContentPart[];
98 > /** Process exit code, set when the terminal process exits */
99 > exitCode?: number;
100 > /** Who currently holds this terminal */
101 > claim: TerminalClaim;
102 > /**
103 > * Whether this terminal emits `terminal/commandExecuted` and
104 > * `terminal/commandFinished` actions and populates `command`-typed parts.
105 > *
106 > * Clients MUST check this flag before relying on command detection.
107 > * Do NOT use the presence of a `command` part as a feature flag — parts
108 > * are absent in the normal idle state.
109 > */
110 > supportsCommandDetection?: boolean;
111 > /**
112 > * Whether this terminal-style resource is backed by a pseudoterminal.
113 > * When `false`, output is plain text and clients do not need to parse
114 > * VT sequences.
115 > */
116 > isPty?: boolean;
117 > }
118 >
119 > // ─── Terminal Content Parts ──────────────────────────────────────────────────
120 >
121 > /**
122 > * A content part within terminal output.
123 > *
124 > * @category Terminal Types
125 > */
126 > export type TerminalContentPart =
127 > | TerminalUnclassifiedPart
128 > | TerminalCommandPart;
129 >
130 > /**
131 > * Unstructured terminal output — content before, between, or after commands,
132 > * or from terminals that do not support command detection.
133 > *
134 > * @category Terminal Types
135 > */
136 > export interface TerminalUnclassifiedPart {
137 > type: 'unclassified';
138 > /** Accumulated VT output. Appended to by `terminal/data` when no command is executing. */
139 > value: string;
140 > }
141 >
142 > /**
143 > * A single command: its command line and the output it produced.
144 > *
145 > * While `isComplete` is false the command is still executing; `output` grows
146 > * as `terminal/data` actions arrive. At `terminal/commandFinished` the part
147 > * is mutated in-place with `isComplete: true` and the completion metadata.
148 > *
149 > * @category Terminal Types
150 > */
151 > export interface TerminalCommandPart {
152 > type: 'command';
153 > /**
154 > * Stable id matching the `commandId` on the corresponding
155 > * `terminal/commandExecuted` and `terminal/commandFinished` actions.
156 > */
157 > commandId: string;
158 > /** The command line submitted to the shell. */
159 > commandLine: string;
160 > /**
161 > * Accumulated VT output. Appended to by `terminal/data` while `isComplete`
162 > * is false. Shell integration escape sequences are stripped by the server.
163 > */
164 > output: string;
165 > /** Unix timestamp (ms) when execution started, as reported by the server. */
166 > timestamp: number;
167 > /** Whether the command has finished. */
168 > isComplete: boolean;
169 > /** Shell exit code. Set at completion. `undefined` if unknown. */
170 > exitCode?: number;
171 > /** Wall-clock duration in milliseconds. Set at completion. */
172 > durationMs?: number;
173 > }
src/vs/base/common/buffer.ts 158 covered LOC · 42 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- buffer.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Lazy } from './lazy.js';
7 > import * as streams from './stream.js';
8 >
9 > interface NodeBuffer {
10 > allocUnsafe(size: number): Uint8Array;
11 > isBuffer(obj: unknown): obj is NodeBuffer;
12 > from(arrayBuffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array;
13 > from(data: string): Uint8Array;
14 > }
15 >
16 > declare const Buffer: NodeBuffer;
17 >
18 > const hasBuffer = (typeof Buffer !== 'undefined');
19 > const indexOfTable = new Lazy(() => new Uint8Array(256));
20 >
21 > let textEncoder: { encode: (input: string) => Uint8Array } | null;
22 > let textDecoder: { decode: (input: Uint8Array) => string } | null;
23 >
24 > export class VSBuffer {
25 >
26 > /**
27 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
28 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
29 > */
30 > static alloc(byteLength: number): VSBuffer {
31 if (hasBuffer) {
32 return new VSBuffer(Buffer.allocUnsafe(byteLength));
35 }
36 }
37 > buffer.ts
38 > /**
39 > * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
40 > * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
41 > * which is not transferrable.
42 > */
43 > static wrap(actual: Uint8Array): VSBuffer {
44 if (hasBuffer && !(Buffer.isBuffer(actual))) {
45 // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
49 return new VSBuffer(actual);
50 }
51 > buffer.ts
52 > /**
53 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
54 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
55 > */
56 > static fromString(source: string, options?: { dontUseNodeBuffer?: boolean }): VSBuffer {
57 const dontUseNodeBuffer = options?.dontUseNodeBuffer || false;
58 if (!dontUseNodeBuffer && hasBuffer) {
65 }
66 }
67 > buffer.ts
68 > /**
69 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
70 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
71 > */
72 > static fromByteArray(source: number[]): VSBuffer {
73 const result = VSBuffer.alloc(source.length);
74 for (let i = 0, len = source.length; i < len; i++) {
77 return result;
78 }
79 > buffer.ts
80 > /**
81 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
82 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
83 > */
84 > static concat(buffers: VSBuffer[], totalLength?: number): VSBuffer {
85 if (typeof totalLength === 'undefined') {
86 totalLength = 0;
100 return ret;
101 }
102 > buffer.ts
103 > static isNativeBuffer(buffer: unknown): boolean {
104 return hasBuffer && Buffer.isBuffer(buffer);
105 }
106 > buffer.ts
107 > readonly buffer: Uint8Array;
108 > readonly byteLength: number;
109 >
110 > private constructor(buffer: Uint8Array) {
111 this.buffer = buffer;
112 this.byteLength = this.buffer.byteLength;
113 }
114 > buffer.ts
115 > /**
116 > * When running in a nodejs context, the backing store for the returned `VSBuffer` instance
117 > * might use a nodejs Buffer allocated from node's Buffer pool, which is not transferrable.
118 > */
119 > clone(): VSBuffer {
120 const result = VSBuffer.alloc(this.byteLength);
121 result.set(this);
122 return result;
123 }
124 > buffer.ts
125 > toString(): string {
126 if (hasBuffer) {
127 return this.buffer.toString();
133 }
134 }
135 > buffer.ts
136 > slice(start?: number, end?: number): VSBuffer {
137 // IMPORTANT: use subarray instead of slice because TypedArray#slice
138 // creates shallow copy and NodeBuffer#slice doesn't. The use of subarray
140 return new VSBuffer(this.buffer.subarray(start, end));
141 }
142 > buffer.ts
143 > set(array: VSBuffer, offset?: number): void;
144 > set(array: Uint8Array, offset?: number): void;
145 > set(array: ArrayBuffer, offset?: number): void;
146 > set(array: ArrayBufferView, offset?: number): void;
147 > set(array: VSBuffer | Uint8Array | ArrayBuffer | ArrayBufferView, offset?: number): void;
148 > set(array: VSBuffer | Uint8Array | ArrayBuffer | ArrayBufferView, offset?: number): void {
149 if (array instanceof VSBuffer) {
150 this.buffer.set(array.buffer, offset);
159 }
160 }
161 > buffer.ts
162 > readUInt32BE(offset: number): number {
163 return readUInt32BE(this.buffer, offset);
164 }
165 > buffer.ts
166 > writeUInt32BE(value: number, offset: number): void {
167 writeUInt32BE(this.buffer, value, offset);
168 }
169 > buffer.ts
170 > readUInt32LE(offset: number): number {
171 return readUInt32LE(this.buffer, offset);
172 }
173 > buffer.ts
174 > writeUInt32LE(value: number, offset: number): void {
175 writeUInt32LE(this.buffer, value, offset);
176 }
177 > buffer.ts
178 > readUInt8(offset: number): number {
179 return readUInt8(this.buffer, offset);
180 }
181 > buffer.ts
182 > writeUInt8(value: number, offset: number): void {
183 writeUInt8(this.buffer, value, offset);
184 }
185 > buffer.ts
186 > indexOf(subarray: VSBuffer | Uint8Array, offset = 0) {
187 return binaryIndexOf(this.buffer, subarray instanceof VSBuffer ? subarray.buffer : subarray, offset);
188 }
189 > buffer.ts
190 > equals(other: VSBuffer): boolean {
191 if (this === other) {
192 return true;
199 return this.buffer.every((value, index) => value === other.buffer[index]);
200 }
201 > } buffer.ts
202 >
203 > /**
204 > * Like String.indexOf, but works on Uint8Arrays.
205 > * Uses the boyer-moore-horspool algorithm to be reasonably speedy.
206 > */
207 > export function binaryIndexOf(haystack: Uint8Array, needle: Uint8Array, offset = 0): number {
208 const needleLen = needle.byteLength;
209 const haystackLen = haystack.byteLength;
248 return result;
249 }
250 > buffer.ts
251 > export function readUInt16LE(source: Uint8Array, offset: number): number {
252 return (
253 ((source[offset + 0] << 0) >>> 0) |
255 );
256 }
257 > buffer.ts
258 > export function writeUInt16LE(destination: Uint8Array, value: number, offset: number): void {
259 destination[offset + 0] = (value & 0b11111111);
260 value = value >>> 8;
261 destination[offset + 1] = (value & 0b11111111);
262 }
263 > buffer.ts
264 > export function readUInt32BE(source: Uint8Array, offset: number): number {
265 return (
266 source[offset] * 2 ** 24
270 );
271 }
272 > buffer.ts
273 > export function writeUInt32BE(destination: Uint8Array, value: number, offset: number): void {
274 destination[offset + 3] = value;
275 value = value >>> 8;
280 destination[offset] = value;
281 }
282 > buffer.ts
283 > export function readUInt32LE(source: Uint8Array, offset: number): number {
284 return (
285 ((source[offset + 0] << 0) >>> 0) |
289 );
290 }
291 > buffer.ts
292 > export function writeUInt32LE(destination: Uint8Array, value: number, offset: number): void {
293 destination[offset + 0] = (value & 0b11111111);
294 value = value >>> 8;
299 destination[offset + 3] = (value & 0b11111111);
300 }
301 > buffer.ts
302 > export function readUInt8(source: Uint8Array, offset: number): number {
303 return source[offset];
304 }
305 > buffer.ts
306 > export function writeUInt8(destination: Uint8Array, value: number, offset: number): void {
307 destination[offset] = value;
308 }
309 > buffer.ts
310 > export interface VSBufferReadable extends streams.Readable<VSBuffer> { }
311 >
312 > export interface VSBufferReadableStream extends streams.ReadableStream<VSBuffer> { }
313 >
314 > export interface VSBufferWriteableStream extends streams.WriteableStream<VSBuffer> { }
315 >
316 > export interface VSBufferReadableBufferedStream extends streams.ReadableBufferedStream<VSBuffer> { }
317 >
318 > export function readableToBuffer(readable: VSBufferReadable): VSBuffer {
319 return streams.consumeReadable<VSBuffer>(readable, chunks => VSBuffer.concat(chunks));
320 }
321 > buffer.ts
322 > export function bufferToReadable(buffer: VSBuffer): VSBufferReadable {
323 return streams.toReadable<VSBuffer>(buffer);
324 }
325 > buffer.ts
326 > export function streamToBuffer(stream: streams.ReadableStream<VSBuffer>): Promise<VSBuffer> {
327 return streams.consumeStream<VSBuffer>(stream, chunks => VSBuffer.concat(chunks));
328 }
329 > buffer.ts
330 export async function bufferedStreamToBuffer(bufferedStream: streams.ReadableBufferedStream<VSBuffer>): Promise<VSBuffer> {
331 if (bufferedStream.ended) {
342 ]);
343 }
344 > buffer.ts
345 > export function bufferToStream(buffer: VSBuffer): streams.ReadableStream<VSBuffer> {
346 return streams.toStream<VSBuffer>(buffer, chunks => VSBuffer.concat(chunks));
347 }
348 > buffer.ts
349 > export function streamToBufferReadableStream(stream: streams.ReadableStreamEvents<Uint8Array | string>): streams.ReadableStream<VSBuffer> {
350 return streams.transform<Uint8Array | string, VSBuffer>(stream, { data: data => typeof data === 'string' ? VSBuffer.fromString(data) : VSBuffer.wrap(data) }, chunks => VSBuffer.concat(chunks));
351 }
352 > buffer.ts
353 > export function newWriteableBufferStream(options?: streams.WriteableStreamOptions): streams.WriteableStream<VSBuffer> {
354 return streams.newWriteableStream<VSBuffer>(chunks => VSBuffer.concat(chunks), options);
355 }
356 > buffer.ts
357 > export function prefixedBufferReadable(prefix: VSBuffer, readable: VSBufferReadable): VSBufferReadable {
358 return streams.prefixedReadable(prefix, readable, chunks => VSBuffer.concat(chunks));
359 }
360 > buffer.ts
361 > export function prefixedBufferStream(prefix: VSBuffer, stream: VSBufferReadableStream): VSBufferReadableStream {
362 return streams.prefixedStream(prefix, stream, chunks => VSBuffer.concat(chunks));
363 }
364 > buffer.ts
365 > /** Decodes base64 to a uint8 array. URL-encoded and unpadded base64 is allowed. */
366 > export function decodeBase64(encoded: string) {
367 let building = 0;
368 let remainder = 0;
424 return VSBuffer.wrap(buffer).slice(0, unpadded);
425 }
426 > buffer.ts
427 > const base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
428 > const base64UrlSafeAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
429 >
430 > /** Encodes a buffer to a base64 string. */
431 > export function encodeBase64({ buffer }: VSBuffer, padded = true, urlSafe = false) {
432 const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
433 let output = '';
463 return output;
464 }
465 > buffer.ts
466 > const hexChars = '0123456789abcdef';
467 > export function encodeHex({ buffer }: VSBuffer): string {
468 let result = '';
469 for (let i = 0; i < buffer.length; i++) {
474 return result;
475 }
476 > buffer.ts
477 > export function decodeHex(hex: string): VSBuffer {
478 if (hex.length % 2 !== 0) {
479 throw new SyntaxError('Hex string must have an even length');
485 return VSBuffer.wrap(out);
486 }
487 > buffer.ts
488 function decodeHexChar(str: string, position: number) {
489 const s = str.charCodeAt(position);
src/vs/platform/agentHost/common/state/protocol/channels-chat/commands.ts 147 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commands.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI } from '../common/state.js';
10 > import type { BaseParams } from '../common/commands.js';
11 > import type { Message, SideChatSelection } from './state.js';
12 >
13 > // ─── createChat ──────────────────────────────────────────────────────────────
14 >
15 > /**
16 > * How a new chat uses its source chat and turn.
17 > */
18 > export const enum ChatSourceKind {
19 > /** Copy source history through the referenced turn into the new chat. */
20 > Fork = 'fork',
21 > /** Supply source context without copying it into the new chat's visible history. */
22 > SideChat = 'sideChat',
23 > }
24 >
25 > /**
26 > * Copies source history through a completed turn into the new chat.
27 > */
28 > export interface ForkChatSource {
29 > /** Discriminant */
30 > kind: ChatSourceKind.Fork;
31 > /** URI of the existing source chat. */
32 > chat: URI;
33 > /**
34 > * Completed turn identifier in the source chat.
35 > *
36 > * Content through this turn is copied into the new chat's visible `turns`.
37 > */
38 > turnId: string;
39 > }
40 >
41 > /**
42 > * Supplies source context to a new side chat without copying it into the side
43 > * chat's visible history.
44 > */
45 > export interface SideChatSource {
46 > /** Discriminant */
47 > kind: ChatSourceKind.SideChat;
48 > /** URI of the existing source chat. */
49 > chat: URI;
50 > /**
51 > * Stable source-turn identifier in the source chat.
52 > *
53 > * Hosts resolve this id against the source chat's current `activeTurn` or its
54 > * retained `turns` when accepting `createChat`. If it names the current
55 > * active turn, the host snapshots the source chat's retained history plus
56 > * that turn's current user message and any partial assistant response already
57 > * available. Once that turn later becomes historical, it is still referenced
58 > * by this same identifier.
59 > */
60 > turnId: string;
61 > /**
62 > * Optional immutable selected-text snapshot to carry into the created side
63 > * chat's origin.
64 > *
65 > * When present, the host MUST snapshot and preserve this exact selection when
66 > * it accepts `createChat`; later source-turn deltas do not alter it.
67 > */
68 > selection?: SideChatSelection;
69 > }
70 >
71 > /**
72 > * Identifies a source chat for a new chat.
73 > */
74 > export type ChatSource =
75 > | ForkChatSource
76 > | SideChatSource;
77 >
78 > /**
79 > * Creates a new chat within a session.
80 > *
81 > * @category Commands
82 > * @method createChat
83 > * @direction Client → Server
84 > * @messageType Request
85 > * @version 1
86 > */
87 > export interface CreateChatParams extends BaseParams {
88 > /** Session URI containing the new chat. */
89 > channel: URI;
90 > /** Chat URI (client-chosen, e.g. `ahp-chat:/<uuid>`). */
91 > chat: URI;
92 > /** Optional initial message for the new chat. */
93 > initialMessage?: Message;
94 > /**
95 > * Optional source chat and source turn.
96 > *
97 > * The source chat MUST belong to this session. Clients MUST only request
98 > * `kind: "fork"` when the selected agent advertises
99 > * `capabilities.multipleChats.fork`, and `kind: "sideChat"` when the
100 > * selected agent advertises `capabilities.multipleChats.sideChat`. Both
101 > * source forms carry a stable top-level `turnId`. Forks target completed
102 > * turns. Side chats also carry a stable `turnId`, which the host resolves
103 > * against the source chat's current active turn or retained history. If it
104 > * resolves to the active turn, the host snapshots the currently available
105 > * partial response when accepting `createChat`. When
106 > * `source.kind === "sideChat"` and `source.selection` is present, the host
107 > * also snapshots and preserves that exact selected text in the created chat's
108 > * origin; any `responsePartId` there is provenance only, not a live range.
109 > */
110 > source?: ChatSource;
111 > /**
112 > * Initial working-directory subset for this chat. Every entry MUST be
113 > * present in the owning session's `workingDirectories`; the server MUST
114 > * reject any entry that is not. When absent, the chat inherits the full
115 > * session set. Forked chats (those whose `source.kind` is `"fork"`) inherit
116 > * the source chat's `workingDirectories`; this field is ignored for forks.
117 > *
118 > * A client MUST NOT supply this field unless the agent advertises
119 > * {@link AgentCapabilities.multipleWorkingDirectories}.
120 > */
121 > workingDirectories?: URI[];
122 > /**
123 > * The chat's primary working directory — the distinguished root this chat is
124 > * centered on. When set, it MUST be one of the chat's effective working
125 > * directories ({@link workingDirectories}, or the session's set when that is
126 > * omitted). A client SHOULD supply this when the agent advertises
127 > * {@link MultipleWorkingDirectoriesCapability.requiresPrimary}; a host MAY
128 > * reject creation that omits it, or fall back to the first of the chat's
129 > * directories. Fixed at creation and reported (read-only) on
130 > * {@link ChatState.primaryWorkingDirectory}. Ignored for forks (a chat whose
131 > * `source.kind` is `"fork"` inherits the source chat's primary).
132 > */
133 > primaryWorkingDirectory?: URI;
134 > }
135 >
136 > // ─── disposeChat ─────────────────────────────────────────────────────────────
137 >
138 > /**
139 > * Disposes a chat and cleans up server-side resources.
140 > *
141 > * @category Commands
142 > * @method disposeChat
143 > * @direction Client → Server
144 > * @messageType Request
145 > * @version 1
146 > */
147 > export interface DisposeChatParams extends BaseParams { }
src/vs/platform/agentHost/common/state/protocol/channels-changeset/commands.ts 105 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commands.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI, ContentRef, StringOrMarkdown, TextRange } from '../common/state.js';
10 > import type { BaseParams } from '../common/commands.js';
11 >
12 > // ─── invokeChangesetOperation ────────────────────────────────────────────────
13 >
14 > /**
15 > * Discriminator for {@link ChangesetOperationTarget}. Mirrors the
16 > * non-`Changeset` members of {@link ChangesetOperationScope} — the
17 > * `Changeset` scope has no target.
18 > *
19 > * @category Commands
20 > */
21 > export const enum ChangesetOperationTargetKind {
22 > /** Operation acts on a single file. */
23 > Resource = 'resource',
24 > /** Operation acts on a line range within a single file. */
25 > Range = 'range',
26 > }
27 >
28 > /**
29 > * Identifies the file or range a {@link ChangesetOperation} should act on.
30 > *
31 > * The `kind` MUST match one of the operation's declared
32 > * {@link ChangesetOperation.scopes}.
33 > *
34 > * @category Commands
35 > */
36 > export type ChangesetOperationTarget =
37 > | { kind: ChangesetOperationTargetKind.Resource; resource: URI; side?: 'before' | 'after' }
38 > | { kind: ChangesetOperationTargetKind.Range; resource: URI; side?: 'before' | 'after'; range: TextRange };
39 >
40 > /**
41 > * Optional follow-up surfaced by the server after an operation completes —
42 > * a {@link ContentRef} the client can fetch and display.
43 > *
44 > * Set `external` to `true` to open the content in the user's preferred
45 > * external handler (e.g. browser); otherwise the client is expected to
46 > * surface it inline.
47 > *
48 > * @category Commands
49 > */
50 > export interface ChangesetOperationFollowUp {
51 > content: ContentRef;
52 > /** When `true`, open in an external handler rather than inline. */
53 > external?: boolean;
54 > }
55 >
56 > /**
57 > * Invokes a server-defined {@link ChangesetOperation} against a changeset,
58 > * a single file, or a line range.
59 > *
60 > * The server validates that `operationId` exists in the changeset's
61 > * current `operations` list and that the requested `target.kind` is
62 > * contained in the operation's `scopes`. Invalid combinations result in a
63 > * JSON-RPC error.
64 > *
65 > * State changes resulting from invocation flow back through the normal
66 > * `changeset/*` action stream on the relevant changeset URIs. Clients
67 > * SHOULD NOT synthesise local optimistic changes for invocations unless
68 > * the server explicitly opts in via a future capability.
69 > *
70 > * @category Commands
71 > * @method invokeChangesetOperation
72 > * @direction Client → Server
73 > * @messageType Request
74 > * @version 2
75 > */
76 > export interface InvokeChangesetOperationParams extends BaseParams {
77 > /** The expanded changeset URI. */
78 > channel: URI;
79 > /** Matches {@link ChangesetOperation.id} from the changeset's `operations` list. */
80 > operationId: string;
81 > /**
82 > * Target of the operation. Required iff the chosen scope is
83 > * `'resource'` or `'range'`. Omit for changeset-scoped operations.
84 > */
85 > target?: ChangesetOperationTarget;
86 > }
87 >
88 > /**
89 > * Result of the {@link InvokeChangesetOperationParams | `invokeChangesetOperation`}
90 > * command.
91 > *
92 > * Success is implicit: the server returns this result when it accepted
93 > * the operation. Failure is signalled by rejecting the JSON-RPC request
94 > * with an appropriate error code, not by any field on this result. The
95 > * operation MAY still produce subsequent failure feedback through the
96 > * {@link ChangesetStatusChangedAction | `changeset/statusChanged`} stream.
97 > *
98 > * @category Commands
99 > */
100 > export interface InvokeChangesetOperationResult {
101 > /** Optional human-readable message describing the result. */
102 > message?: StringOrMarkdown;
103 > /** Optional follow-up: a URI to open (e.g. a PR), a content ref, etc. */
104 > followUp?: ChangesetOperationFollowUp;
105 > }
src/vs/base/common/arraysFind.ts 95 covered LOC · 16 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- arraysFind.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Comparator } from './arrays.js';
7 >
8 > export function findLast<T, R extends T>(array: readonly T[], predicate: (item: T, index: number) => item is R, fromIndex?: number): R | undefined;
9 > export function findLast<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex?: number): T | undefined;
10 > export function findLast<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = array.length - 1): T | undefined {
11 const idx = findLastIdx(array, predicate, fromIndex);
12 if (idx === -1) {
15 return array[idx];
16 }
18 > export function findLastIdx<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = array.length - 1): number {
19 for (let i = fromIndex; i >= 0; i--) {
20 const element = array[i];
27 return -1;
28 }
30 > export function findFirst<T, R extends T>(array: readonly T[], predicate: (item: T, index: number) => item is R, fromIndex?: number): R | undefined;
31 > export function findFirst<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex?: number): T | undefined;
32 > export function findFirst<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = 0): T | undefined {
33 const idx = findFirstIdx(array, predicate, fromIndex);
34 if (idx === -1) {
37 return array[idx];
38 }
40 > export function findFirstIdx<T>(array: readonly T[], predicate: (item: T, index: number) => unknown, fromIndex = 0): number {
41 for (let i = fromIndex; i < array.length; i++) {
42 const element = array[i];
49 return -1;
50 }
52 > /**
53 > * Finds the last item where predicate is true using binary search.
54 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
55 > *
56 > * @returns `undefined` if no item matches, otherwise the last item that matches the predicate.
57 > */
58 > export function findLastMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean): T | undefined {
59 const idx = findLastIdxMonotonous(array, predicate);
60 return idx === -1 ? undefined : array[idx];
61 }
63 > /**
64 > * Finds the last item where predicate is true using binary search.
65 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
66 > *
67 > * @returns `startIdx - 1` if predicate is false for all items, otherwise the index of the last item that matches the predicate.
68 > */
69 > export function findLastIdxMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
70 let i = startIdx;
71 let j = endIdxEx;
80 return i - 1;
81 }
83 > /**
84 > * Finds the first item where predicate is true using binary search.
85 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
86 > *
87 > * @returns `undefined` if no item matches, otherwise the first item that matches the predicate.
88 > */
89 > export function findFirstMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean): T | undefined {
90 const idx = findFirstIdxMonotonousOrArrLen(array, predicate);
91 return idx === array.length ? undefined : array[idx];
92 }
94 > /**
95 > * Finds the first item where predicate is true using binary search.
96 > * `predicate` must be monotonous, i.e. `arr.map(predicate)` must be like `[false, ..., false, true, ..., true]`!
97 > *
98 > * @returns `endIdxEx` if predicate is false for all items, otherwise the index of the first item that matches the predicate.
99 > */
100 > export function findFirstIdxMonotonousOrArrLen<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
101 let i = startIdx;
102 let j = endIdxEx;
111 return i;
112 }
114 > export function findFirstIdxMonotonous<T>(array: readonly T[], predicate: (item: T) => boolean, startIdx = 0, endIdxEx = array.length): number {
115 const idx = findFirstIdxMonotonousOrArrLen(array, predicate, startIdx, endIdxEx);
116 return idx === array.length ? -1 : idx;
117 }
119 > /**
120 > * Use this when
121 > * * You have a sorted array
122 > * * You query this array with a monotonous predicate to find the last item that has a certain property.
123 > * * You query this array multiple times with monotonous predicates that get weaker and weaker.
124 > */
125 > export class MonotonousArray<T> {
126 > public static assertInvariants = false;
127 >
128 > private _findLastMonotonousLastIdx = 0;
129 > private _prevFindLastPredicate: ((item: T) => boolean) | undefined;
130 >
131 > constructor(private readonly _array: readonly T[]) {
132 }
134 > /**
135 > * The predicate must be monotonous, i.e. `arr.map(predicate)` must be like `[true, ..., true, false, ..., false]`!
136 > * For subsequent calls, current predicate must be weaker than (or equal to) the previous predicate, i.e. more entries must be `true`.
137 > */
138 > findLastMonotonous(predicate: (item: T) => boolean): T | undefined {
139 if (MonotonousArray.assertInvariants) {
140 if (this._prevFindLastPredicate) {
152 return idx === -1 ? undefined : this._array[idx];
153 }
154 > } arraysFind.ts
155 >
156 > /**
157 > * Returns the first item that is equal to or greater than every other item.
158 > */
159 > export function findFirstMax<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
160 if (array.length === 0) {
161 return undefined;
171 return max;
172 }
174 > /**
175 > * Returns the last item that is equal to or greater than every other item.
176 > */
177 > export function findLastMax<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
178 if (array.length === 0) {
179 return undefined;
189 return max;
190 }
192 > /**
193 > * Returns the first item that is equal to or less than every other item.
194 > */
195 > export function findFirstMin<T>(array: readonly T[], comparator: Comparator<T>): T | undefined {
196 return findFirstMax(array, (a, b) => -comparator(a, b));
197 }
199 > export function findMaxIdx<T>(array: readonly T[], comparator: Comparator<T>): number {
200 if (array.length === 0) {
201 return -1;
211 return maxIdx;
212 }
214 > /**
215 > * Returns the first mapped value of the array which is not undefined.
216 > */
217 > export function mapFindFirst<T, R>(items: Iterable<T>, mapFn: (value: T) => R | undefined): R | undefined {
218 for (const value of items) {
219 const mapped = mapFn(value);
src/vs/platform/agentHost/common/meta/agentToolCallMeta.ts 92 covered LOC · 5 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- agentToolCallMeta.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { Mutable } from '../../../../base/common/types.js';
7 >
8 > /** Anything carrying a tool call's `_meta` bag (persisted state or wire actions). */
9 > interface IHasToolCallMeta {
10 > readonly _meta?: Record<string, unknown>;
11 > }
12 >
13 > /**
14 > * Well-known typed view over a tool call's open `_meta` bag. Producers and
15 > * consumers agree on these keys here so the two sides can't drift; always read
16 > * the bag through {@link readToolCallMeta}, which validates each field and drops
17 > * wrong-typed values.
18 > */
19 > export interface IToolCallMeta {
20 > /**
21 > * VS Code rendering hint. `terminal` routes the call to the command/output
22 > * renderer, `subagent` to the subagent UI, `search` to the search renderer;
23 > * everything else falls through to the generic invocation renderer. Set by
24 > * the agent adapter, never matched on raw tool name by the renderer.
25 > */
26 > readonly toolKind?: ToolKind;
27 > /** Shell language for a `terminal` tool call (drives syntax highlighting). */
28 > readonly language?: string;
29 > /** Short task description for a `subagent` tool call (e.g. "Find related files"). */
30 > readonly subagentDescription?: string;
31 > /** Agent name for a `subagent` tool call (e.g. "explore"). */
32 > readonly subagentAgentName?: string;
33 > /** Chat URI of the subagent this tool call spawns, stamped by the host (see {@link buildSubagentChatUri}); the resource may not be registered yet. */
34 > readonly subagentChatUri?: string;
35 > /** Raw, pre-stringified tool arguments captured for display/debugging. */
36 > readonly toolArguments?: unknown;
37 > /** Originating MCP server name, when the call came from an MCP server. */
38 > readonly mcpServerName?: string;
39 > /** Originating MCP tool name, when the call came from an MCP server. */
40 > readonly mcpToolName?: string;
41 > /** MCP App render data, when the call exposes an interactive App surface. */
42 > readonly ui?: IToolCallUiMeta;
43 > /**
44 > * Set by the host's side-effect layer when the call was auto-approved
45 > * because of an `autoApprove` session-config setting (rather than an
46 > * explicit user action), so the client can render it as setting-driven.
47 > */
48 > readonly autoApproveBySetting?: boolean;
49 > /** Transient runtime corpus for the local client tool-search invocation. */
50 > readonly toolSearchCandidates?: readonly IToolSearchCandidate[];
51 > }
52 >
53 > /** Minimal metadata needed to embed and rank a deferred tool. */
54 > export interface IToolSearchCandidate {
55 > readonly name: string;
56 > readonly description: string;
57 > }
58 >
59 > /**
60 > * The set of VS Code-recognized tool-call rendering kinds. Add a new value here
61 > * (and teach the renderer to handle it) rather than matching on tool name.
62 > */
63 > export type ToolKind = 'terminal' | 'subagent' | 'search';
64 >
65 > /**
66 > * MCP App render data carried under {@link IToolCallMeta.ui}. Clients gate
67 > * mounting the App webview on both a `resourceUri` and a `channel` being
68 > * present.
69 > */
70 > export interface IToolCallUiMeta {
71 > /** The MCP App's UI resource URI (an `ui://` resource the App renders). */
72 > readonly resourceUri: string;
73 > /** AHP `mcp://` channel the App's sub-RPCs route back through, when ready. */
74 > readonly channel?: string;
75 > }
76 >
77 function isToolKind(value: unknown): value is ToolKind {
78 return value === 'terminal' || value === 'subagent' || value === 'search';
79 }
81 function readToolCallUiMeta(value: unknown): IToolCallUiMeta | undefined {
82 if (!value || typeof value !== 'object' || Array.isArray(value)) {
93 return result;
94 }
96 function readToolSearchCandidates(value: unknown): readonly IToolSearchCandidate[] | undefined {
97 if (!Array.isArray(value)) {
114 return result;
115 }
117 > /**
118 > * Reads the well-known {@link IToolCallMeta} keys from a tool call's `_meta`
119 > * bag, dropping unknown keys and wrong-typed values.
120 > */
121 > export function readToolCallMeta(source: IHasToolCallMeta): IToolCallMeta {
122 const meta = source._meta;
123 if (!meta) {
140 return result;
141 }
143 > /**
144 > * Serializes a typed {@link IToolCallMeta} into the `_meta` record, dropping
145 > * `undefined` entries and returning `undefined` when empty. Build a tool call's
146 > * `_meta` through this so producers stay in lock-step with
147 > * {@link readToolCallMeta}.
148 > */
149 > export function toToolCallMeta(meta: IToolCallMeta): Record<string, unknown> | undefined {
150 const result: Record<string, unknown> = {};
151 for (const [key, value] of Object.entries(meta)) {
src/vs/base/common/collections.ts 74 covered LOC · 18 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- collections.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * An interface for a JavaScript object that
8 > * acts a dictionary. The keys are strings.
9 > */
10 > export type IStringDictionary<V> = Record<string, V>;
11 >
12 > /**
13 > * An interface for a JavaScript object that
14 > * acts a dictionary. The keys are numbers.
15 > */
16 > export type INumberDictionary<V> = Record<number, V>;
17 >
18 > /**
19 > * Groups the collection into a dictionary based on the provided
20 > * group function.
21 > */
22 > export function groupBy<K extends string | number | symbol, V>(data: readonly V[], groupFn: (element: V) => K): Partial<Record<K, V[]>> {
23 const result: Partial<Record<K, V[]>> = Object.create(null);
24 for (const element of data) {
32 return result;
33 }
35 > export function groupByMap<K, V>(data: V[], groupFn: (element: V) => K): Map<K, V[]> {
36 const result = new Map<K, V[]>();
37 for (const element of data) {
46 return result;
47 }
49 > export function diffSets<T>(before: ReadonlySet<T>, after: ReadonlySet<T>): { removed: T[]; added: T[] } {
50 const removed: T[] = [];
51 const added: T[] = [];
62 return { removed, added };
63 }
65 > /**
66 > * Checks whether two sets contain exactly the same elements.
67 > *
68 > * @param a - The first set.
69 > * @param b - The second set.
70 > * @returns `true` if both sets have the same size and every element of `a` is also in `b`.
71 > */
72 > export function equalSets<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {
73 if (a === b) {
74 return true;
84 return true;
85 }
87 > export function diffMaps<K, V>(before: Map<K, V>, after: Map<K, V>): { removed: V[]; added: V[] } {
88 const removed: V[] = [];
89 const added: V[] = [];
100 return { removed, added };
101 }
103 > /**
104 > * Computes the intersection of two sets.
105 > *
106 > * @param setA - The first set.
107 > * @param setB - The second iterable.
108 > * @returns A new set containing the elements that are in both `setA` and `setB`.
109 > */
110 > export function intersection<T>(setA: Set<T>, setB: Iterable<T>): Set<T> {
111 const result = new Set<T>();
112 for (const elem of setB) {
117 return result;
118 }
120 > export class SetWithKey<T> implements Set<T> {
121 > private _map = new Map<unknown, T>();
122 >
123 > constructor(values: T[], private toKey: (t: T) => unknown) {
124 for (const value of values) {
125 this.add(value);
126 }
127 }
129 > get size(): number {
130 return this._map.size;
131 }
133 > add(value: T): this {
134 const key = this.toKey(value);
135 this._map.set(key, value);
136 return this;
137 }
139 > delete(value: T): boolean {
140 return this._map.delete(this.toKey(value));
141 }
143 > has(value: T): boolean {
144 return this._map.has(this.toKey(value));
145 }
147 > *entries(): SetIterator<[T, T]> {
148 for (const entry of this._map.values()) {
149 yield [entry, entry];
150 }
151 }
153 > keys(): SetIterator<T> {
154 return this.values();
155 }
157 > *values(): SetIterator<T> {
158 for (const entry of this._map.values()) {
159 yield entry;
160 }
161 }
163 > clear(): void {
164 this._map.clear();
165 }
167 > forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: unknown): void {
168 this._map.forEach(entry => callbackfn.call(thisArg, entry, entry, this));
169 }
171 > [Symbol.iterator](): SetIterator<T> {
172 return this.values();
173 }
175 > [Symbol.toStringTag]: string = 'SetWithKey';
176 > }
src/vs/platform/agentHost/common/state/protocol/channels-resource-watch/state.ts 73 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > import type { URI } from '../common/state.js';
10 >
11 > // ─── Resource Watch Types ────────────────────────────────────────────────────
12 >
13 > /**
14 > * Full state for a single resource watch, returned when a client subscribes
15 > * to an `ahp-resource-watch:` URI.
16 > *
17 > * Watches are otherwise stateless: the watcher exists to deliver
18 > * {@link ResourceWatchChangedAction} events. The state carries only the
19 > * descriptor of what is being watched so a re-subscribing client can
20 > * recover the watch configuration after reconnecting.
21 > *
22 > * @category Resource Watch Types
23 > */
24 > export interface ResourceWatchState {
25 > /**
26 > * The URI being watched. For recursive watches this is the root of the
27 > * subtree; for non-recursive watches this is the single file or
28 > * directory.
29 > */
30 > root: URI;
31 > /**
32 > * `true` if the watcher reports changes for descendants of `root`;
33 > * `false` if it only reports changes to `root` itself (and, when
34 > * `root` is a directory, its direct children).
35 > */
36 > recursive: boolean;
37 > /**
38 > * Optional glob patterns or paths relative to `root` to exclude from
39 > * change reporting.
40 > */
41 > excludes?: { items: string[] };
42 > /**
43 > * Optional glob patterns or paths relative to `root` to restrict
44 > * change reporting to. Omit to report every change under `root`
45 > * subject to `excludes`.
46 > */
47 > includes?: { items: string[] };
48 > }
49 >
50 > // ─── Resource Change ─────────────────────────────────────────────────────────
51 >
52 > /**
53 > * Discriminant for {@link ResourceChange.type}.
54 > *
55 > * @category Resource Watch Types
56 > */
57 > export const enum ResourceChangeType {
58 > Added = 'added',
59 > Updated = 'updated',
60 > Deleted = 'deleted',
61 > }
62 >
63 > /**
64 > * A single change observed by a resource watcher.
65 > *
66 > * @category Resource Watch Types
67 > */
68 > export interface ResourceChange {
69 > /** The URI of the resource that changed. */
70 > uri: URI;
71 > /** The kind of change observed. */
72 > type: ResourceChangeType;
73 > }
src/vs/base/common/iterator.ts 63 covered LOC · 22 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- iterator.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { isIterable } from './types.js';
7 >
8 > export namespace Iterable {
9 >
10 > export function is<T = unknown>(thing: unknown): thing is Iterable<T> {
11 return !!thing && typeof thing === 'object' && typeof (thing as Iterable<T>)[Symbol.iterator] === 'function';
12 }
14 > const _empty: Iterable<never> = Object.freeze([]);
15 > export function empty<T = never>(): readonly never[] {
16 return _empty as readonly never[];
17 }
19 > export function* single<T>(element: T): Iterable<T> {
20 yield element;
21 }
23 > export function wrap<T>(iterableOrElement: Iterable<T> | T): Iterable<T> {
24 if (is(iterableOrElement)) {
25 return iterableOrElement;
28 }
29 }
31 > export function from<T>(iterable: Iterable<T> | undefined | null): Iterable<T> {
32 return iterable ?? (_empty as Iterable<T>);
33 }
35 > export function* reverse<T>(array: ReadonlyArray<T>): Iterable<T> {
36 for (let i = array.length - 1; i >= 0; i--) {
37 yield array[i];
38 }
39 }
41 > export function isEmpty<T>(iterable: Iterable<T> | undefined | null): boolean {
42 return !iterable || iterable[Symbol.iterator]().next().done === true;
43 }
45 > export function first<T>(iterable: Iterable<T>): T | undefined {
46 return iterable[Symbol.iterator]().next().value;
47 }
49 > export function some<T>(iterable: Iterable<T>, predicate: (t: T, i: number) => unknown): boolean {
50 let i = 0;
51 for (const element of iterable) {
56 return false;
57 }
59 > export function every<T>(iterable: Iterable<T>, predicate: (t: T, i: number) => unknown): boolean {
60 let i = 0;
61 for (const element of iterable) {
66 return true;
67 }
69 > export function find<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): R | undefined;
70 > export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined;
71 > export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined {
72 for (const element of iterable) {
73 if (predicate(element)) {
78 return undefined;
79 }
81 > export function filter<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): Iterable<R>;
82 > export function filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T>;
83 > export function* filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T> {
84 for (const element of iterable) {
85 if (predicate(element)) {
88 }
89 }
91 > export function* map<T, R>(iterable: Iterable<T>, fn: (t: T, index: number) => R): Iterable<R> {
92 let index = 0;
93 for (const element of iterable) {
95 }
96 }
98 > export function* flatMap<T, R>(iterable: Iterable<T>, fn: (t: T, index: number) => Iterable<R>): Iterable<R> {
99 let index = 0;
100 for (const element of iterable) {
102 }
103 }
104 > iterator.ts
105 > export function* concat<T>(...iterables: (Iterable<T> | T)[]): Iterable<T> {
106 for (const item of iterables) {
107 if (isIterable(item)) {
112 }
113 }
114 > iterator.ts
115 > export function reduce<T, R>(iterable: Iterable<T>, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R {
116 let value = initialValue;
117 for (const element of iterable) {
120 return value;
121 }
122 > iterator.ts
123 > export function length<T>(iterable: Iterable<T>): number {
124 let count = 0;
125 for (const _ of iterable) {
128 return count;
129 }
130 > iterator.ts
131 > /**
132 > * Returns an iterable slice of the array, with the same semantics as `array.slice()`.
133 > */
134 > export function* slice<T>(arr: ReadonlyArray<T>, from: number, to = arr.length): Iterable<T> {
135 if (from < -arr.length) {
136 from = 0;
150 }
151 }
152 > iterator.ts
153 > /**
154 > * Consumes `atMost` elements from iterable and returns the consumed elements,
155 > * and an iterable for the rest of the elements.
156 > */
157 > export function consume<T>(iterable: Iterable<T>, atMost: number = Number.POSITIVE_INFINITY): [T[], Iterable<T>] {
158 const consumed: T[] = [];
159
176 return [consumed, { [Symbol.iterator]() { return iterator; } }];
177 }
178 > iterator.ts
179 > export async function asyncToArray<T>(iterable: AsyncIterable<T>): Promise<T[]> {
180 const result: T[] = [];
181 for await (const item of iterable) {
184 return result;
185 }
186 > iterator.ts
187 > export async function asyncToArrayFlat<T>(iterable: AsyncIterable<T[]>): Promise<T[]> {
188 let result: T[] = [];
189 for await (const item of iterable) {
src/vs/base/test/common/utils.ts 56 covered LOC · 13 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- utils.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { DisposableStore, DisposableTracker, IDisposable, setDisposableTracker } from '../../common/lifecycle.js';
7 > import { join } from '../../common/path.js';
8 > import { isWindows } from '../../common/platform.js';
9 > import { URI } from '../../common/uri.js';
10 >
11 > export type ValueCallback<T = any> = (value: T | Promise<T>) => void;
12 >
13 > export function toResource(this: any, path: string): URI {
14 if (isWindows) {
15 return URI.file(join('C:\\', btoa(this.test.fullTitle()), path));
18 return URI.file(join('/', btoa(this.test.fullTitle()), path));
19 }
20 > utils.ts
21 > export function suiteRepeat(n: number, description: string, callback: (this: any) => void): void {
22 for (let i = 0; i < n; i++) {
23 suite(`${description} (iteration ${i})`, callback);
24 }
25 }
26 > utils.ts
27 > export function testRepeat(n: number, description: string, callback: (this: any) => any): void {
28 for (let i = 0; i < n; i++) {
29 test(`${description} (iteration ${i})`, callback);
30 }
31 }
32 > utils.ts
33 export async function assertThrowsAsync(block: () => any, message: string | Error = 'Missing expected exception'): Promise<void> {
34 try {
41 throw err;
42 }
43 > utils.ts
44 > /**
45 > * Use this function to ensure that all disposables are cleaned up at the end of each test in the current suite.
46 > *
47 > * Use `markAsSingleton` if disposable singletons are created lazily that are allowed to outlive the test.
48 > * Make sure that the singleton properly registers all child disposables so that they are excluded too.
49 > *
50 > * @returns A {@link DisposableStore} that can optionally be used to track disposables in the test.
51 > * This will be automatically disposed on test teardown.
52 > */
53 > export function ensureNoDisposablesAreLeakedInTestSuite(): Pick<DisposableStore, 'add'> {
54 > let tracker: DisposableTracker | undefined;
55 > let store: DisposableStore;
56 > setup(() => {
57 > store = new DisposableStore(); utils.ts
58 > tracker = new DisposableTracker();
59 > setDisposableTracker(tracker);
60 > }); utils.ts
61 >
62 > teardown(function (this: import('mocha').Context) {
63 > store.dispose(); utils.ts
64 > setDisposableTracker(null);
65 > if (this.currentTest?.state !== 'failed') {
66 > const result = tracker!.computeLeakingDisposables();
67 > if (result) {
68 console.error(result.details);
69 throw new Error(`There are ${result.leaks.length} undisposed disposables!${result.details}`);
70 }
71 > } utils.ts
72 > }); utils.ts
73 >
74 > // Wrap store as the suite function is called before it's initialized
75 > const testContext = {
76 > add<T extends IDisposable>(o: T): T {
77 return store.add(o);
78 }
79 > }; utils.ts
80 > return testContext;
81 > }
82 >
83 > export function throwIfDisposablesAreLeaked(body: () => void, logToConsole = true): void {
84 const tracker = new DisposableTracker();
85 setDisposableTracker(tracker);
88 computeLeakingDisposables(tracker, logToConsole);
89 }
90 > utils.ts
91 export async function throwIfDisposablesAreLeakedAsync(body: () => Promise<void>): Promise<void> {
92 const tracker = new DisposableTracker();
96 computeLeakingDisposables(tracker);
97 }
98 > utils.ts
99 function computeLeakingDisposables(tracker: DisposableTracker, logToConsole = true) {
100 const result = tracker.computeLeakingDisposables();
src/vs/base/common/process.ts 53 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- process.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { INodeProcess, isMacintosh, isWindows } from './platform.js';
7 >
8 > let safeProcess: Omit<INodeProcess, 'arch'> & { arch: string | undefined };
9 > declare const process: INodeProcess;
10 >
11 > // Native sandbox environment
12 > const vscodeGlobal = (globalThis as { vscode?: { process?: INodeProcess } }).vscode;
13 > if (typeof vscodeGlobal !== 'undefined' && typeof vscodeGlobal.process !== 'undefined') {
14 const sandboxProcess: INodeProcess = vscodeGlobal.process;
15 safeProcess = {
20 };
21 }
22 > process.ts
23 > // Native node.js environment
24 > else if (typeof process !== 'undefined' && typeof process?.versions?.node === 'string') {
25 > safeProcess = {
26 > get platform() { return process.platform; },
27 > get arch() { return process.arch; },
28 > get env() { return process.env; },
29 > cwd() { return process.env['VSCODE_CWD'] || process.cwd(); }
30 > };
31 }
32
44 };
45 }
46 > process.ts
47 > /**
48 > * Provides safe access to the `cwd` property in node.js, sandboxed or web
49 > * environments.
50 > *
51 > * Note: in web, this property is hardcoded to be `/`.
52 > *
53 > * @skipMangle
54 > */
55 > export const cwd = safeProcess.cwd;
56 >
57 > /**
58 > * Provides safe access to the `env` property in node.js, sandboxed or web
59 > * environments.
60 > *
61 > * Note: in web, this property is hardcoded to be `{}`.
62 > */
63 > export const env = safeProcess.env;
64 >
65 > /**
66 > * Provides safe access to the `platform` property in node.js, sandboxed or web
67 > * environments.
68 > */
69 > export const platform = safeProcess.platform;
70 >
71 > /**
72 > * Provides safe access to the `arch` method in node.js, sandboxed or web
73 > * environments.
74 > * Note: `arch` is `undefined` in web
75 > */
76 > export const arch = safeProcess.arch;
src/vs/base/common/assert.ts 48 covered LOC · 7 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- assert.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { BugIndicatingError, onUnexpectedError } from './errors.js';
7 >
8 > /**
9 > * Throws an error with the provided message if the provided value does not evaluate to a true Javascript value.
10 > *
11 > * @deprecated Use `assert(...)` instead.
12 > * This method is usually used like this:
13 > * ```ts
14 > * import * as assert from 'vs/base/common/assert';
15 > * assert.ok(...);
16 > * ```
17 > *
18 > * However, `assert` in that example is a user chosen name.
19 > * There is no tooling for generating such an import statement.
20 > * Thus, the `assert(...)` function should be used instead.
21 > */
22 > export function ok(value?: unknown, message?: string) {
23 if (!value) {
24 throw new Error(message ? `Assertion failed (${message})` : 'Assertion Failed');
25 }
26 }
27 > assert.ts
28 > export function assertNever(value: never, message = 'Unreachable'): never {
29 throw new Error(message);
30 }
31 > assert.ts
32 > export function softAssertNever(value: never): void {
33 // no-op
34 }
35 > assert.ts
36 > /**
37 > * Asserts that a condition is `truthy`.
38 > *
39 > * @throws provided {@linkcode messageOrError} if the {@linkcode condition} is `falsy`.
40 > *
41 > * @param condition The condition to assert.
42 > * @param messageOrError An error message or error object to throw if condition is `falsy`.
43 > */
44 > export function assert(
45 condition: boolean,
46 messageOrError: string | Error = 'unexpected state',
55 }
56 }
57 > assert.ts
58 > /**
59 > * Like assert, but doesn't throw.
60 > */
61 > export function softAssert(condition: boolean, message = 'Soft Assertion Failed'): void {
62 if (!condition) {
63 onUnexpectedError(new BugIndicatingError(message));
64 }
65 }
66 > assert.ts
67 > /**
68 > * condition must be side-effect free!
69 > */
70 > export function assertFn(condition: () => boolean): void {
71 if (!condition()) {
72 // eslint-disable-next-line no-debugger
77 }
78 }
79 > assert.ts
80 > export function checkAdjacentItems<T>(items: readonly T[], predicate: (item1: T, item2: T) => boolean): boolean {
81 let i = 0;
82 while (i < items.length - 1) {
src/vs/base/common/lazy.ts 39 covered LOC · 4 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- lazy.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > enum LazyValueState {
7 > Uninitialized,
8 > Running,
9 > Completed,
10 > }
11 >
12 > export class Lazy<T> {
13 >
14 > private _state = LazyValueState.Uninitialized;
15 > private _value?: T;
16 > private _error: Error | undefined;
17 >
18 > constructor(
19 > private readonly executor: () => T, lazy.ts
20 > ) { }
21 > lazy.ts
22 > /**
23 > * True if the lazy value has been resolved.
24 > */
25 > get hasValue(): boolean { return this._state === LazyValueState.Completed; }
26 >
27 > /**
28 > * Get the wrapped value.
29 > *
30 > * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
31 > * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
32 > */
33 > get value(): T {
34 if (this._state === LazyValueState.Uninitialized) {
35 this._state = LazyValueState.Running;
50 return this._value!;
51 }
52 > lazy.ts
53 > /**
54 > * Get the wrapped value without forcing evaluation.
55 > */
56 > get rawValue(): T | undefined { return this._value; }
57 > }
src/vs/platform/agentHost/node/claude/claudeElicitationBridge.ts 36 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- claudeElicitationBridge.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { ElicitationRequest, ElicitationResult } from '@anthropic-ai/claude-agent-sdk';
7 > import { generateUuid } from '../../../../base/common/uuid.js';
8 > import { ChatInputResponseKind } from '../../common/state/sessionState.js';
9 > import { ClaudeAgentSession } from './claudeAgentSession.js';
10 > import { buildElicitationRequest, cancelledElicitationResult, elicitationResultFromAnswers } from './claudeElicitation.js';
11 >
12 > /**
13 > * Dependencies for {@link handleElicitation}. Kept narrow (just a session
14 > * lookup) so the agent's `_sessions` map stays private — mirrors
15 > * {@link import('./claudeCanUseTool.js').IClaudeCanUseToolDeps}. There is no
16 > * `configurationService` because elicitation has no unattended auto-cancel:
17 > * Claude always has a UI, and parked requests unwind on teardown.
18 > */
19 > export interface IClaudeElicitationDeps {
20 > readonly getSession: (sessionId: string) => ClaudeAgentSession | undefined;
21 > }
22 >
23 > /**
24 > * SDK `onElicitation` callback bridge. Fires a `ChatInputRequested` action and
25 > * parks on {@link ClaudeAgentSession.requestUserInput} until the
26 > * workbench dispatches a response, then maps it back to an
27 > * {@link ElicitationResult} for the MCP server.
28 > *
29 > * Routing note: elicitation is structured user input, so it flows through the
30 > * `requestUserInput` channel `AskUserQuestion` uses — NOT the
31 > * `pending_confirmation` permission gate.
32 > *
33 > * Result mapping: only an explicit user Decline returns `decline`; a missing
34 > * session, a pre-aborted request, and an SDK-aborted park all return `cancel`
35 > * (see phase 10.6 Decisions).
36 > */
37 export async function handleElicitation(
38 deps: IClaudeElicitationDeps,
src/vs/base/common/marshallingIds.ts 33 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- marshallingIds.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export const enum MarshalledId {
7 > Uri = 1,
8 > Regexp,
9 > ScmResource,
10 > ScmResourceGroup,
11 > ScmProvider,
12 > CommentController,
13 > CommentThread,
14 > CommentThreadInstance,
15 > CommentThreadReply,
16 > CommentNode,
17 > CommentThreadNode,
18 > TimelineActionContext,
19 > NotebookCellActionContext,
20 > NotebookActionContext,
21 > TerminalContext,
22 > TestItemContext,
23 > Date,
24 > TestMessageMenuArgs,
25 > ChatViewContext,
26 > LanguageModelToolResult,
27 > LanguageModelTextPart,
28 > LanguageModelThinkingPart,
29 > LanguageModelPromptTsxPart,
30 > LanguageModelDataPart,
31 > AgentSessionContext,
32 > ChatResponsePullRequestPart,
33 > }
src/vs/base/common/uuid.ts 25 covered LOC · 3 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- uuid.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 >
7 > const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8 >
9 > export function isUUID(value: string): boolean {
10 return _UUIDPattern.test(value);
11 }
12 > uuid.ts
13 > export const generateUuid = (function (): () => string {
14 >
15 > // use `randomUUID` if possible
16 > if (typeof crypto.randomUUID === 'function') {
17 > // see https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
18 > // > Although crypto is available on all windows, the returned Crypto object only has one
19 > // > usable feature in insecure contexts: the getRandomValues() method.
20 > // > In general, you should use this API only in secure contexts.
21 >
22 > return crypto.randomUUID.bind(crypto);
23 > }
24
25 // prep-work
63 return result;
64 };
65 > })(); uuid.ts
66 >
67 > /** Namespace should be 3 letters, e.g. `abc-<uuid>`. */
68 > export function prefixedUuid(namespace: string): string {
69 return `${namespace}-${generateUuid()}`;
70 }
src/vs/platform/agentHost/common/state/protocol/state.ts 17 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- state.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > export * from './common/state.js';
10 > export * from './channels-root/state.js';
11 > export * from './channels-session/state.js';
12 > export * from './channels-chat/state.js';
13 > export * from './channels-terminal/state.js';
14 > export * from './channels-changeset/state.js';
15 > export * from './channels-annotations/state.js';
16 > export * from './channels-otlp/state.js';
17 > export * from './channels-resource-watch/state.js';
src/vs/platform/agentHost/common/state/protocol/commands.ts 15 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- commands.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > // allow-any-unicode-comment-file
7 > // DO NOT EDIT -- auto-generated by scripts/sync-agent-host-protocol.ts
8 >
9 > export * from './common/commands.js';
10 > export * from './channels-root/commands.js';
11 > export * from './channels-session/commands.js';
12 > export * from './channels-chat/commands.js';
13 > export * from './channels-terminal/commands.js';
14 > export * from './channels-changeset/commands.js';
15 > export * from './channels-resource-watch/commands.js';
src/vs/base/common/functional.ts 9 covered LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- functional.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /**
7 > * Given a function, returns a function that is only calling that function once.
8 > */
9 > export function createSingleCallFunction<T extends Function>(this: unknown, fn: T, fnDidRunCallback?: () => void): T {
10 const _this = this;
11 let didCall = false;