sessionServerTools.ts ×46

Frontier kind: Code frontier

unlabeled · c_89a45474ac87

1290 tests · 14761 LOC · 49 files · introduces 0 tests · 495 LOC · 1 file

Introduces — evidence that enters the hierarchy at this concept

Code
46 ranges495 lines · 1 files
Tests
0 tests

Contains — complete concept membership

All code (extent)
951 ranges14761 lines · 49 files · Browse complete extent
All tests (intent)
1290 testsBrowse complete intent

Neighbourhood graph

The orange circle is the focus. Violet and green circles are every ancestor and descendant, broader and narrower, at any distance; blue squares and pink diamonds are the introduced files and exact introduced tests of every visible concept, not only the focus's. Arrows point from broader to narrower concepts and bridge only concepts omitted from this view. Undirected links show source or test introduction. Concept and file size follows LOC; exact test nodes use test-count units.

Introduced files, introduced tests, and structurally relevant concept specialization

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the native relationship evidence on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the native relationship evidence on this page while the interactive map is unavailable.

Native relationship evidence

Every exact file and test below is linked only from the concept that introduces it.

Introduced tests

Every collected test enters the hierarchy at exactly one concept.

No tests are introduced at this concept. Its intent tests are introduced by other concepts.

Introduced code

Every collected source range enters the hierarchy at exactly one concept.

1 file ranked by introduced lines: 495 introduced LOC across 46 ranges. Expand a file to inspect source; the > gutter marks introduced lines.

src/vs/platform/agentHost/node/shared/sessionServerTools.ts 495 introduced LOC · 46 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- sessionServerTools.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 '../../../../base/common/uri.js';
7 > import type { Mutable } from '../../../../base/common/types.js';
8 > import { localize } from '../../../../nls.js';
9 > import type { IAgentCreateSessionConfig, IAgentModelInfo, IAgentSessionMetadata } from '../../common/agentService.js';
10 > import { SessionStatus } from '../../common/state/protocol/channels-session/state.js';
11 > import { buildChatUri, buildDefaultChatUri, parseChatUri, readSessionGitState, readSessionGitHubState, ResponsePartKind, ToolCallStatus, TurnState, type Message, type ResponsePart, type ToolCallState, type ToolDefinition, type StringOrMarkdown, type Turn, type URI as ProtocolURI } from '../../common/state/sessionState.js';
12 > import { buildOpenSessionLinkUri, CREATE_CHAT_TOOL_NAME, CREATE_SESSION_TOOL_NAME, parseOpenSessionLinkChatId, parseOpenSessionLinkUri, SEND_MESSAGE_TOOL_NAME } from '../../common/openSessionLink.js';
13 > import { generateUuid } from '../../../../base/common/uuid.js';
14 > import type { AgentHostStateManager } from '../agentHostStateManager.js';
15 > import type { IServerToolDisplay, IServerToolDisplayResult, IServerToolGroup } from './agentServerToolHost.js';
16 >
17 > export const listSessionsToolName = 'list_sessions';
18 > export const getCurrentSessionToolName = 'get_current_session';
19 > export const createSessionToolName = CREATE_SESSION_TOOL_NAME;
20 > export const createChatToolName = CREATE_CHAT_TOOL_NAME;
21 > export const sendMessageToolName = SEND_MESSAGE_TOOL_NAME;
22 > export const getSessionContextToolName = 'get_session_context';
23 > export const deleteSessionToolName = 'delete_session';
24 >
25 > /**
26 > * Maximum `create_session` recursion depth. A user/top-level session is depth 0;
27 > * a session created by `create_session` from within a depth-N session is depth
28 > * N+1. Once a session reaches this depth, its agent may not create further
29 > * sessions — this bounds recursive spawn *chains* (A→B→C→…). Breadth is bounded
30 > * separately by {@link maxCreatedSessions} plus the per-call user confirmation.
31 > */
32 > const maxSessionSpawnDepth = 3;
33 >
34 > /** Process-wide backstop against runaway spawning (breadth), independent of depth. */
35 > const maxCreatedSessions = 25;
36 > const maxCreatedChats = 25;
37 >
38 > /** Process-wide backstop against runaway `send_message` fan-out. */
39 > const maxSentMessages = 50;
40 >
41 > const sessionConfirmationToolNames: ReadonlySet<string> = new Set([createSessionToolName, createChatToolName, sendMessageToolName, deleteSessionToolName]);
42 >
43 > /** Whether the given session server tool requires user confirmation before it runs. */
44 > export function sessionToolRequiresConfirmation(toolName: string): boolean {
45 return sessionConfirmationToolNames.has(toolName);
46 }
48 > const listSessionsStatusValues = ['idle', 'inProgress', 'inputNeeded', 'error', 'archived'] as const;
49 >
50 > const listSessionsInputSchema: ToolDefinition['inputSchema'] = {
51 > type: 'object',
52 > properties: {
53 > session: { type: 'string', description: 'Return only the session with this URI or `agent-host-session://` link (a direct lookup that ignores the other filters). Use this to fetch one known session\'s metadata.' },
54 > status: {
55 > type: 'array',
56 > items: { type: 'string', enum: [...listSessionsStatusValues] },
57 > description: 'Only return sessions whose status matches one of these (e.g. `inputNeeded` for sessions awaiting a reply, `inProgress` for running ones, `archived` for sessions marked Done/completed — implies `includeArchived`). Omit to return every status.',
58 > },
59 > workspace: { type: 'string', description: 'Only return sessions whose working directory is this folder — an absolute path or a workspace URI.' },
60 > withChanges: { type: 'boolean', description: 'When true, only return sessions that have pending worktree changes.' },
61 > unread: { type: 'boolean', description: 'When true, only return sessions with updates the user has not seen yet.' },
62 > withPullRequest: { type: 'boolean', description: 'When true, only return sessions that have a linked GitHub pull request.' },
63 > includeArchived: { type: 'boolean', description: 'Whether to include archived sessions. Defaults to false; set true to also return archived sessions.' },
64 > createdAfter: { type: 'string', description: 'Only return sessions created at or after this time (ISO-8601 timestamp, e.g. `2025-01-31T00:00:00Z`).' },
65 > createdBefore: { type: 'string', description: 'Only return sessions created at or before this time (ISO-8601 timestamp).' },
66 > },
67 > };
68 >
69 > const createSessionInputSchema: ToolDefinition['inputSchema'] = {
70 > type: 'object',
71 > properties: {
72 > workspace: { type: 'string', description: 'Absolute folder path, workspace URI, or a working directory from an existing session.' },
73 > prompt: { type: 'string', description: 'Initial prompt to send to the new session.' },
74 > model: { type: 'string', description: 'Optional model ID or display name.' },
75 > },
76 > required: ['workspace', 'prompt'],
77 > };
78 >
79 > const getCurrentSessionInputSchema: ToolDefinition['inputSchema'] = {
80 > type: 'object',
81 > properties: {},
82 > };
83 >
84 > const createChatInputSchema: ToolDefinition['inputSchema'] = {
85 > type: 'object',
86 > properties: {
87 > session: { type: 'string', description: 'Optional session to add the chat to: a session URI from `list_sessions` or an `agent-host-session://` link. Defaults to the current session when omitted.' },
88 > prompt: { type: 'string', description: 'Initial prompt to send to the new chat.' },
89 > title: { type: 'string', description: 'Optional title for the new chat.' },
90 > model: { type: 'string', description: 'Optional model ID or display name. Defaults to the session\'s model.' },
91 > },
92 > required: ['prompt'],
93 > };
94 >
95 > const deleteSessionInputSchema: ToolDefinition['inputSchema'] = {
96 > type: 'object',
97 > properties: {
98 > session: { type: 'string', description: 'The session to delete: a session URI from `list_sessions` or an `agent-host-session://` link (e.g. from `create_session`).' },
99 > },
100 > required: ['session'],
101 > };
102 >
103 > const sendMessageInputSchema: ToolDefinition['inputSchema'] = {
104 > type: 'object',
105 > properties: {
106 > session: { type: 'string', description: 'The session or chat to message: a session URI from `list_sessions`, or an `agent-host-session://` link (from `create_session`/`create_chat`; a `create_chat` link targets that specific chat).' },
107 > message: { type: 'string', description: 'The message to send.' },
108 > },
109 > required: ['session', 'message'],
110 > };
111 >
112 > const sessionContextDetailValues = ['summary', 'digest', 'full'] as const;
113 >
114 > const getSessionContextInputSchema: ToolDefinition['inputSchema'] = {
115 > type: 'object',
116 > properties: {
117 > session: { type: 'string', description: 'The session or chat to read: a session URI from `list_sessions`, or an `agent-host-session://` link (a `create_chat` link targets that specific chat).' },
118 > detail: {
119 > type: 'string',
120 > enum: [...sessionContextDetailValues],
121 > description: 'How much conversation detail to return. `summary` (default): status and a short per-turn gist (the message plus a compact snippet of the reply). `digest`: adds the full assistant reply text and tool-call names. `full`: adds tool-call inputs. Higher levels return more tokens.',
122 > },
123 > transcriptLimit: { type: 'number', description: 'Maximum number of most-recent turns to include. Defaults to 10; capped at 50.' },
124 > },
125 > required: ['session'],
126 > };
127 >
128 > /** Protocol tool definitions for the session-management server tools. */
129 > export const sessionServerToolDefinitions: ToolDefinition[] = [
130 > {
131 > name: listSessionsToolName,
132 > title: 'List Sessions',
133 > description: 'List sessions and their compact metadata (status, activity, working directory, project, worktree changes, git/GitHub info, timestamps). Pass `session` to fetch a single known session by URI. By default archived sessions are omitted. Optionally filter by `status`, `workspace`, `withChanges`, `unread`, `withPullRequest`, `includeArchived`, `createdAfter`, or `createdBefore`.',
134 > inputSchema: listSessionsInputSchema,
135 > annotations: { readOnlyHint: true },
136 > },
137 > {
138 > name: getCurrentSessionToolName,
139 > title: 'Get Current Session',
140 > description: 'Get metadata and the open link for the session this conversation is running in. Use this to reference the current session (for example before adding a chat to it).',
141 > inputSchema: getCurrentSessionInputSchema,
142 > annotations: { readOnlyHint: true },
143 > },
144 > {
145 > name: createSessionToolName,
146 > title: 'Create Session',
147 > description: 'Create a session in a workspace and start it with an initial prompt. The UI shows a "Session Created" confirmation with a button to open it, so reply with a single short sentence confirming the session was created and do NOT print the session URL or tell the user to click a button.',
148 > inputSchema: createSessionInputSchema,
149 > annotations: { readOnlyHint: false },
150 > },
151 > {
152 > name: createChatToolName,
153 > title: 'Create Chat',
154 > description: 'Add a new chat to an existing session and start it with an initial prompt. Omit `session` to add the chat to the current session; otherwise pass a session URI from `list_sessions`. Optionally pass a `model` to use for the chat (defaults to the session\'s model). The UI shows a "Chat Created" confirmation with a button to open the session, so reply with a single short sentence and do NOT print the session URL or tell the user to click a button.',
155 > inputSchema: createChatInputSchema,
156 > annotations: { readOnlyHint: false },
157 > },
158 > {
159 > name: sendMessageToolName,
160 > title: 'Send Message',
161 > description: 'Send a message to an existing session or chat, starting a new turn there. Provide a session URI from `list_sessions` or an `agent-host-session://` link (a `create_chat` link targets that specific chat). The message is delivered asynchronously — this tool does not wait for or return the reply. The UI shows a confirmation with a button to open the target, so reply with a single short sentence and do NOT print the URL or tell the user to click a button.',
162 > inputSchema: sendMessageInputSchema,
163 > annotations: { readOnlyHint: false },
164 > },
165 > {
166 > name: getSessionContextToolName,
167 > title: 'Get Session Context',
168 > description: 'Read the recent conversation of an existing session or chat: a compacted transcript of its turns (messages, replies, and tool calls). Use this to see what a session you created is doing, or to gather context before sending it a message. Returns a compacted summary by default (`detail: "summary"`); request `digest` or `full` for more detail. For session metadata (status, working directory, changes, …) use `list_sessions` with the `session` argument.',
169 > inputSchema: getSessionContextInputSchema,
170 > annotations: { readOnlyHint: true },
171 > },
172 > {
173 > name: deleteSessionToolName,
174 > title: 'Delete Session',
175 > description: 'Permanently delete a session (identified by a session URI from `list_sessions`), including its stored data. This cannot be undone. Refuses to delete the current session.',
176 > inputSchema: deleteSessionInputSchema,
177 > annotations: { readOnlyHint: false, destructiveHint: true },
178 > },
179 > ];
180 >
181 > /** Resolves the owning backend session URI for the channel a tool call runs on. */
182 > export function currentSessionUri(toolCallChannel: ProtocolURI): URI {
183 const owning = parseChatUri(toolCallChannel) ?? undefined;
184 return URI.parse(owning?.session ?? toolCallChannel);
185 }
187 > interface ICreateSessionArgs {
188 > readonly workspace?: unknown;
189 > readonly prompt?: unknown;
190 > readonly model?: unknown;
191 > }
192 >
193 > export interface IResolvedCreateSessionArgs {
194 > readonly workspace: URI;
195 > readonly prompt: string;
196 > readonly model?: IAgentModelInfo;
197 > }
198 >
199 > /** Minimal dependency surface needed by the session server-tool group. */
200 > export interface ISessionServerToolAccessor {
201 > readonly listSessions: () => Promise<readonly IAgentSessionMetadata[]>;
202 > readonly createSession: (config: IAgentCreateSessionConfig) => Promise<URI>;
203 > readonly getModels: () => readonly IAgentModelInfo[];
204 > readonly startPrompt: (session: URI, chat: URI, prompt: string) => Promise<void>;
205 > readonly createChat: (session: URI, chat: URI, options?: { title?: string; model?: IAgentModelInfo }) => Promise<void>;
206 > readonly deleteSession: (session: URI) => Promise<void>;
207 > /** Reads a point-in-time snapshot of a session's chat conversation (default chat, or a specific chat by id). */
208 > readonly getChatContext: (session: URI, chatId?: string) => IChatContextSnapshot | undefined;
209 > /** The spawn depth of a session (0 for a user/top-level session, N for one created N levels deep by `create_session`). */
210 > readonly getSessionSpawnDepth: (session: URI) => number;
211 > /** Records the spawn depth of a freshly-created session so its own `create_session` calls can enforce the recursion limit. */
212 > readonly setSessionSpawnDepth: (session: URI, depth: number) => void;
213 > }
214 >
215 > /** Point-in-time snapshot of a chat's conversation, read from the host state. */
216 > export interface IChatContextSnapshot {
217 > /** Completed turns, oldest first. */
218 > readonly turns: readonly Turn[];
219 > /** The in-progress turn, if the chat is mid-response. */
220 > readonly activeTurn?: Pick<Turn, 'message' | 'responseParts'>;
221 > /** `true` when older completed turns exist beyond the in-memory window. */
222 > readonly hasMoreHistory: boolean;
223 > }
224 >
225 > interface ISerializedGitState {
226 > readonly branch?: string;
227 > readonly baseBranch?: string;
228 > readonly upstreamBranch?: string;
229 > readonly ahead?: number;
230 > readonly behind?: number;
231 > readonly uncommittedChanges?: number;
232 > }
233 >
234 > interface ISerializedGitHubState {
235 > readonly owner?: string;
236 > readonly repo?: string;
237 > readonly pullRequestUrl?: string;
238 > }
239 >
240 > interface ISerializedSession {
241 > readonly session: string;
242 > readonly title?: string;
243 > readonly status?: string;
244 > /** Human-readable description of what the session is currently doing. */
245 > readonly activity?: string;
246 > readonly workingDirectory?: string;
247 > /** Display name of the session's project/workspace. */
248 > readonly project?: string;
249 > /** `true` when the session has updates the user has not yet seen. */
250 > readonly unread?: boolean;
251 > /** ISO-8601 timestamp of when the session was created. */
252 > readonly createdAt?: string;
253 > /** ISO-8601 timestamp of the session's last activity. */
254 > readonly modifiedAt?: string;
255 > readonly changes?: IAgentSessionMetadata['changes'];
256 > readonly changesets?: readonly {
257 > readonly label: string;
258 > readonly changeKind: string;
259 > readonly uriTemplate: string;
260 > readonly description?: string;
261 > }[];
262 > readonly git?: ISerializedGitState;
263 > readonly github?: ISerializedGitHubState;
264 > }
265 >
266 function getRequiredString(value: unknown, field: string, toolName: string): string {
267 if (typeof value !== 'string' || value.length === 0) {
270 return value;
271 }
273 function getOptionalString(value: unknown, field: string, toolName: string): string | undefined {
274 if (value === undefined) {
280 return value;
281 }
283 function parseWorkspaceUri(workspace: string): URI | undefined {
284 // Absolute filesystem path (POSIX `/…` or Windows `C:\…` / `\\share`).
293 }
294 }
296 function resolveWorkspace(workspace: string, sessions: readonly IAgentSessionMetadata[]): URI {
297 const matchingSession = sessions.find(session =>
306 return parsed;
307 }
309 function resolveModel(modelName: string | undefined, models: readonly IAgentModelInfo[]): IAgentModelInfo | undefined {
310 if (modelName === undefined) {
317 return model;
318 }
320 > /** Validates and resolves create-session arguments against current sessions and models. */
321 > export function getCreateSessionArgs(rawArgs: unknown, sessions: readonly IAgentSessionMetadata[], models: readonly IAgentModelInfo[]): IResolvedCreateSessionArgs {
322 const args = (rawArgs ?? {}) as ICreateSessionArgs;
323 const workspace = getRequiredString(args.workspace, 'workspace', createSessionToolName);
330 };
331 }
333 > /** Decodes the {@link SessionStatus} bit-flags into readable names for the agent. */
334 function describeSessionStatusBits(status: SessionStatus): string[] {
335 const names: string[] = [];
351 return names;
352 }
354 > /**
355 > * Decodes a session's status into readable names, used by both filtering and
356 > * serialization so they agree on which sessions are considered `archived`.
357 > * This combines the {@link SessionStatus} bit-flags with the `isArchived`
358 > * metadata flag (see {@link sessionIsArchived}), since a session can be
359 > * archived through either mechanism.
360 > */
361 function describeSessionStatusNames(session: IAgentSessionMetadata): string[] {
362 const names = session.status !== undefined ? describeSessionStatusBits(session.status) : [];
366 return names;
367 }
369 > /** Renders a session's status names as the compact string used in tool results. */
370 function describeSessionStatus(session: IAgentSessionMetadata): string | undefined {
371 const names = describeSessionStatusNames(session);
375 return session.status !== undefined ? 'unknown' : undefined;
376 }
378 >
379 > /** Filters accepted by `list_sessions` to narrow the returned set. */
380 > export interface IListSessionsArgs {
381 > /** Direct lookup: return only the session with this URI / open link, ignoring all other filters. */
382 > readonly session?: string;
383 > readonly status?: ReadonlySet<string>;
384 > readonly workspace?: string;
385 > readonly withChanges?: boolean;
386 > readonly unread?: boolean;
387 > readonly withPullRequest?: boolean;
388 > readonly includeArchived?: boolean;
389 > /** Lower bound on session creation time, in epoch milliseconds. */
390 > readonly createdAfter?: number;
391 > /** Upper bound on session creation time, in epoch milliseconds. */
392 > readonly createdBefore?: number;
393 > }
394 >
395 function getOptionalBoolean(value: unknown, field: string, toolName: string): boolean | undefined {
396 if (value === undefined) {
402 return value;
403 }
405 function getOptionalTimestamp(value: unknown, field: string, toolName: string): number | undefined {
406 if (value === undefined) {
416 return parsed;
417 }
419 > /** Validates and normalizes the optional `list_sessions` filter arguments. */
420 > export function getListSessionsArgs(rawArgs: unknown): IListSessionsArgs {
421 const args = (rawArgs ?? {}) as { session?: unknown; status?: unknown; workspace?: unknown; withChanges?: unknown; unread?: unknown; withPullRequest?: unknown; includeArchived?: unknown; createdAfter?: unknown; createdBefore?: unknown };
422
445 };
446 }
448 > /** Whether a session has any pending worktree changes (insertions, deletions, or changed files). */
449 function sessionHasChanges(session: IAgentSessionMetadata): boolean {
450 const changes = session.changes;
451 return !!changes && ((changes.files ?? 0) > 0 || (changes.additions ?? 0) > 0 || (changes.deletions ?? 0) > 0);
452 }
454 > /** Whether a session is archived (either the metadata flag or the status bit). */
455 function sessionIsArchived(session: IAgentSessionMetadata): boolean {
456 return session.isArchived === true || (session.status !== undefined && (session.status & SessionStatus.IsArchived) !== 0);
457 }
459 > /** Whether a session's working directory matches the given folder (absolute path or URI). */
460 function sessionMatchesWorkspace(session: IAgentSessionMetadata, workspace: string): boolean {
461 const dir = session.workingDirectory;
469 return !!parsed && parsed.toString() === dir.toString();
470 }
472 > /** Applies the {@link IListSessionsArgs} filters to a set of sessions. */
473 > export function filterSessions(sessions: readonly IAgentSessionMetadata[], args: IListSessionsArgs): readonly IAgentSessionMetadata[] {
474 // A direct `session` lookup returns just that session, bypassing the other
475 // filters (including the default archived exclusion).
511 });
512 }
514 function serializeGitState(session: IAgentSessionMetadata): ISerializedGitState | undefined {
515 const git = readSessionGitState(session._meta);
526 return Object.keys(result).length > 0 ? result : undefined;
527 }
529 function serializeGitHubState(session: IAgentSessionMetadata): ISerializedGitHubState | undefined {
530 const github = readSessionGitHubState(session._meta);
538 return Object.keys(result).length > 0 ? result : undefined;
539 }
541 function serializeSession(session: IAgentSessionMetadata): ISerializedSession {
542 const git = serializeGitState(session);
566 };
567 }
569 > /** Serializes session metadata into the compact tool-result JSON payload. */
570 > export function serializeSessions(sessions: readonly IAgentSessionMetadata[]): string {
571 return JSON.stringify({ sessions: sessions.map(serializeSession) });
572 }
574 > export interface ICreateSessionResult {
575 > readonly session: string;
576 > readonly chat: string;
577 > /** Clickable {@link AGENT_HOST_SESSION_LINK_SCHEME} URI that opens the session in the Agents window. */
578 > readonly openLink: string;
579 > }
580 >
581 > /**
582 > * Creates a session, sends its initial prompt, and returns the created channels.
583 > * Enforces the {@link maxSessionSpawnDepth recursion limit} against
584 > * {@link currentSession} (the session the tool runs in) and stamps the new
585 > * session one level deeper so its own `create_session` calls are bounded too.
586 > */
587 export async function applyCreateSessionTool(accessor: ISessionServerToolAccessor, rawArgs: unknown, currentSession?: URI): Promise<ICreateSessionResult> {
588 const parentDepth = currentSession ? accessor.getSessionSpawnDepth(currentSession) : 0;
602 return { session: session.toString(), chat: chat.toString(), openLink: buildOpenSessionLinkUri(session) };
603 }
605 > /**
606 > * Builds the model-facing `create_session` result. Keeps the machine-readable
607 > * `agent-host-session://` link (parsed client-side to render the deterministic
608 > * "Session Created" confirmation + button) but omits the raw backend session
609 > * URI so the model has nothing ugly to echo, and tells it to reply briefly.
610 > */
611 > export function formatCreateSessionResult(result: ICreateSessionResult): string {
612 return `Session created (${result.openLink}). Reply with one short sentence confirming the session was created; do not print the URL or mention a button.`;
613 }
615 > interface ICreateChatArgs {
616 > readonly session?: unknown;
617 > readonly prompt?: unknown;
618 > readonly title?: unknown;
619 > readonly model?: unknown;
620 > }
621 >
622 > export interface ICreateChatResult {
623 > readonly session: string;
624 > readonly chat: string;
625 > /** Clickable {@link AGENT_HOST_SESSION_LINK_SCHEME} URI that opens the created chat. */
626 > readonly openLink: string;
627 > }
628 >
629 > /**
630 > * Resolves a session identifier — accepting either a backend session URI
631 > * (`copilotcli:/…` from `list_sessions`) or an `agent-host-session://…` open
632 > * link (as returned by `create_session`/`get_current_session`) — against the
633 > * set of known sessions. Returns `undefined` when it matches no known session.
634 > */
635 function resolveKnownSession(sessionInput: string, sessions: readonly IAgentSessionMetadata[]): URI | undefined {
636 // Normalize an open-session link back to its backend session URI.
640 return match?.session;
641 }
643 > /** Resolves the target session URI for `create_chat` against the known sessions. */
644 function resolveChatSession(sessionInput: string, sessions: readonly IAgentSessionMetadata[]): URI {
645 const session = resolveKnownSession(sessionInput, sessions);
649 return session;
650 }
652 > /** Validates and resolves create-chat arguments; defaults the session to {@link currentSession} when omitted. */
653 > export function getCreateChatArgs(rawArgs: unknown, sessions: readonly IAgentSessionMetadata[], models: readonly IAgentModelInfo[], currentSession?: URI): { session: URI; prompt: string; title?: string; model?: IAgentModelInfo } {
654 const args = (rawArgs ?? {}) as ICreateChatArgs;
655 const prompt = getRequiredString(args.prompt, 'prompt', createChatToolName);
668 return { session, prompt, ...(title !== undefined ? { title } : {}), ...(model !== undefined ? { model } : {}) };
669 }
671 > /** Adds a chat to a session, sends its initial prompt, and returns the created channels. */
672 export async function applyCreateChatTool(accessor: ISessionServerToolAccessor, rawArgs: unknown, currentSession?: URI): Promise<ICreateChatResult> {
673 const sessions = await accessor.listSessions();
679 return { session: args.session.toString(), chat: chat.toString(), openLink: buildOpenSessionLinkUri(args.session, chatId) };
680 }
682 > /** Builds the model-facing `create_chat` result. */
683 > export function formatCreateChatResult(result: ICreateChatResult): string {
684 return `Chat created (${result.openLink}). Reply with one short sentence confirming the chat was created; do not print the URL or mention a button.`;
685 }
687 > interface ISendMessageArgs {
688 > readonly session?: unknown;
689 > readonly message?: unknown;
690 > }
691 >
692 > export interface IResolvedSendMessageArgs {
693 > /** The owning backend session URI of the target chat. */
694 > readonly session: URI;
695 > /** The chat channel to deliver the message on (default chat, or a specific chat when the link carried one). */
696 > readonly chat: URI;
697 > /** The chat id when a specific chat was targeted (from a `create_chat` link). */
698 > readonly chatId?: string;
699 > readonly message: string;
700 > }
701 >
702 > /**
703 > * Validates and resolves send-message arguments. When the `session` input is a
704 > * `create_chat` open link (carrying a chat id), the message is targeted at that
705 > * specific chat rather than the session's default chat.
706 > */
707 > export function getSendMessageArgs(rawArgs: unknown, sessions: readonly IAgentSessionMetadata[]): IResolvedSendMessageArgs {
708 const args = (rawArgs ?? {}) as ISendMessageArgs;
709 const message = getRequiredString(args.message, 'message', sendMessageToolName);
717 return { session, chat, message, ...(chatId !== undefined ? { chatId } : {}) };
718 }
720 > /**
721 > * Sends a message to an existing session/chat, starting a new turn there.
722 > * Refuses to target {@link currentChannel} (the chat channel the tool runs on)
723 > * to avoid a session trivially messaging itself in a loop.
724 > */
725 export async function applySendMessageTool(accessor: ISessionServerToolAccessor, rawArgs: unknown, currentChannel?: ProtocolURI): Promise<string> {
726 const sessions = await accessor.listSessions();
732 return formatSendMessageResult(buildOpenSessionLinkUri(session, chatId));
733 }
735 > /** Builds the model-facing `send_message` result. */
736 > export function formatSendMessageResult(openLink: string): string {
737 return `Message sent (${openLink}). Reply with one short sentence confirming the message was sent; do not print the URL or mention a button.`;
738 }
740 > // --- get_session_context -----------------------------------------------------
741 >
742 > type SessionContextDetail = (typeof sessionContextDetailValues)[number];
743 >
744 > const defaultTranscriptLimit = 10;
745 > const maxTranscriptLimit = 50;
746 >
747 > /** Per-detail truncation caps (characters); a value of 0 omits the field. */
748 > const contextCaps: Record<SessionContextDetail, { user: number; assistant: number; toolInput: number }> = {
749 > // `summary` still carries a short assistant gist per turn so the reader sees
750 > // what each turn actually did, not just what was asked.
751 > summary: { user: 160, assistant: 140, toolInput: 0 },
752 > digest: { user: 300, assistant: 800, toolInput: 0 },
753 > full: { user: 1000, assistant: 2000, toolInput: 200 },
754 > };
755 >
756 > interface ISessionContextArgs {
757 > readonly session?: unknown;
758 > readonly detail?: unknown;
759 > readonly transcriptLimit?: unknown;
760 > }
761 >
762 > export interface IResolvedSessionContextArgs {
763 > readonly session: URI;
764 > readonly chatId?: string;
765 > readonly detail: SessionContextDetail;
766 > readonly transcriptLimit: number;
767 > }
768 >
769 > /** Validates and resolves get-session-context arguments against the known sessions. */
770 > export function getSessionContextArgs(rawArgs: unknown, sessions: readonly IAgentSessionMetadata[]): IResolvedSessionContextArgs {
771 const args = (rawArgs ?? {}) as ISessionContextArgs;
772 const sessionInput = getRequiredString(args.session, 'session', getSessionContextToolName);
792 return { session, detail, transcriptLimit, ...(chatId !== undefined ? { chatId } : {}) };
793 }
795 > /** Truncates {@link text} to {@link max} characters, appending an ellipsis when cut. */
796 function truncateText(text: string, max: number): { text: string; truncated: boolean } {
797 const trimmed = text.trim();
801 return { text: `${trimmed.slice(0, Math.max(0, max - 1))}…`, truncated: true };
802 }
804 > /** Reads the tool-call parts of a turn, newest-emitted last. */
805 function toolCallsOf(parts: readonly ResponsePart[]): ToolCallState[] {
806 return parts.filter((p): p is Extract<ResponsePart, { kind: ResponsePartKind.ToolCall }> => p.kind === ResponsePartKind.ToolCall).map(p => p.toolCall);
807 }
809 > /** Concatenated markdown text of a turn's response, in stream order. */
810 function assistantTextOf(parts: readonly ResponsePart[]): string {
811 return parts.filter((p): p is Extract<ResponsePart, { kind: ResponsePartKind.Markdown }> => p.kind === ResponsePartKind.Markdown).map(p => p.content).join('').trim();
812 }
814 > /** Reads a tool call's JSON input string, which is absent while still streaming. */
815 function readToolInput(tc: ToolCallState): string | undefined {
816 return tc.status === ToolCallStatus.Streaming ? undefined : tc.toolInput;
817 }
819 > interface ISerializedContextTurn {
820 > readonly turn: number;
821 > readonly state: string;
822 > readonly user?: string;
823 > readonly assistant?: string;
824 > readonly toolCalls?: readonly (string | { readonly name: string; readonly input?: string })[];
825 > }
826 >
827 > /** Maps a {@link TurnState} (or the in-progress active turn) to a display string. */
828 function describeTurnState(state: TurnState | 'inProgress'): string {
829 switch (state) {
834 }
835 }
837 > interface ISerializedSessionContext {
838 > readonly session: string;
839 > readonly openLink: string;
840 > readonly detail: SessionContextDetail;
841 > readonly transcript: readonly ISerializedContextTurn[];
842 > readonly hasMoreHistory: boolean;
843 > /** `true` when turns were dropped from the window or any field was shortened. */
844 > readonly truncated: boolean;
845 > }
846 >
847 > /** Builds the compacted, model-facing session-context payload from a snapshot. */
848 > export function serializeSessionContext(session: URI, chatId: string | undefined, snapshot: IChatContextSnapshot, detail: SessionContextDetail, transcriptLimit: number): string {
849 const caps = contextCaps[detail];
850 let truncated = false;
902 return JSON.stringify(payload);
903 }
905 > /** Reads and serializes the context of an existing session/chat. */
906 export async function applyGetSessionContextTool(accessor: ISessionServerToolAccessor, rawArgs: unknown): Promise<string> {
907 const sessions = await accessor.listSessions();
922 return serializeSessionContext(session, chatId, snapshot, detail, transcriptLimit);
923 }
925 >
926 > /** Serializes the current session's metadata + open link as the `get_current_session` result. */
927 > export function serializeCurrentSession(currentSession: URI, sessions: readonly IAgentSessionMetadata[]): string {
928 const meta = sessions.find(s => s.session.toString() === currentSession.toString());
929 return JSON.stringify({
933 });
934 }
936 function parseListedSessionCount(resultText: string | undefined): number | undefined {
937 if (!resultText) {
945 }
946 }
948 > interface IDeleteSessionArgs {
949 > readonly session?: unknown;
950 > }
951 >
952 > /**
953 > * Validates delete-session arguments against current sessions and refuses to
954 > * delete {@link currentSession} (deleting the session the tool runs in would
955 > * tear down its own conversation).
956 > */
957 > export function getDeleteSessionArgs(rawArgs: unknown, sessions: readonly IAgentSessionMetadata[], currentSession?: URI): URI {
958 const args = (rawArgs ?? {}) as IDeleteSessionArgs;
959 const sessionInput = getRequiredString(args.session, 'session', deleteSessionToolName);
967 return session;
968 }
970 > /** Deletes a session and returns the model-facing confirmation. */
971 export async function applyDeleteSessionTool(accessor: ISessionServerToolAccessor, rawArgs: unknown, currentSession?: URI): Promise<string> {
972 const sessions = await accessor.listSessions();
975 return `Deleted session ${session.toString()}. Reply with one short sentence confirming the session was deleted.`;
976 }
978 function getSessionToolDisplay(toolName: string, _args: unknown, result?: IServerToolDisplayResult): IServerToolDisplay | undefined {
979 switch (toolName) {
1034 }
1035 }
1037 > /**
1038 > * Creates the session server-tool group with process-local recursion protection.
1039 > *
1040 > * The {@link accessor} is optional so the group can also back the pure display
1041 > * path (`getServerToolDisplay`), which only needs {@link IServerToolGroup.definitions},
1042 > * {@link IServerToolGroup.getDisplay} and {@link IServerToolGroup.requiresConfirmation}
1043 > * and never invokes {@link IServerToolGroup.execute}. `execute` throws when no
1044 > * accessor was provided.
1045 > */
1046 > export function createSessionServerToolGroup(accessor?: ISessionServerToolAccessor): IServerToolGroup {
1047 let createdSessionCount = 0;
1048 let createdChatCount = 0;