src/vs/platform/agentHost/node/shared/sessionServerTools.ts

1101 LOC · 1037 covered · 64 uncovered · 205 ranges · 2795 concepts · 62 introducers · 1290 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

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 related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- sessionServerTools.ts ×46
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); sessionServerTools.ts ×1
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; sessionServerTools.ts ×1
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 { sessionServerTools.ts ×2
267 > if (typeof value !== 'string' || value.length === 0) {
268 > throw new Error(`Invalid ${toolName} input: ${field} must be a non-empty string.`); sessionServerTools.ts ×1
269 > }
270 > return value; sessionServerTools.ts ×2
271 > }
273 > function getOptionalString(value: unknown, field: string, toolName: string): string | undefined { sessionServerTools.ts ×2
274 > if (value === undefined) {
275 > return undefined; sessionServerTools.ts ×1
276 > }
277 > if (typeof value !== 'string' || value.length === 0) { sessionServerTools.ts ×2
278 throw new Error(`Invalid ${toolName} input: ${field} must be a non-empty string.`);
279 }
280 > return value; sessionServerTools.ts ×1
281 > }
283 > function parseWorkspaceUri(workspace: string): URI | undefined { sessionServerTools.ts ×3
284 > // Absolute filesystem path (POSIX `/…` or Windows `C:\…` / `\\share`).
285 > if (/^(\/|[a-zA-Z]:[\\/]|\\\\)/.test(workspace)) {
286 > return URI.file(workspace); sessionServerTools.ts ×1
287 > }
289 > const parsed = URI.parse(workspace, true);
290 > return parsed.scheme ? parsed : undefined; sessionServerTools.ts ×3
291 > } catch {
292 > return undefined; sessionServerTools.ts ×2
293 > }
296 > function resolveWorkspace(workspace: string, sessions: readonly IAgentSessionMetadata[]): URI { sessionServerTools.ts ×2
297 > const matchingSession = sessions.find(session =>
298 > session.workingDirectory?.toString() === workspace || session.workingDirectory?.fsPath === workspace);
299 > if (matchingSession?.workingDirectory) {
300 > return matchingSession.workingDirectory; sessionServerTools.ts ×1
301 > }
302 > const parsed = parseWorkspaceUri(workspace); sessionServerTools.ts ×2
303 > if (!parsed) {
304 > throw new Error(`Invalid ${createSessionToolName} input: workspace must match a known session workingDirectory, an absolute path, or a valid URI string.`); sessionServerTools.ts ×2
305 > }
306 > return parsed; sessionServerTools.ts ×2
307 > }
309 > function resolveModel(modelName: string | undefined, models: readonly IAgentModelInfo[]): IAgentModelInfo | undefined { sessionServerTools.ts ×1
310 > if (modelName === undefined) {
311 > return undefined; sessionServerTools.ts ×1
312 > }
313 > const model = models.find(candidate => candidate.id === modelName || candidate.name === modelName); sessionServerTools.ts ×1
314 > if (!model) {
315 > throw new Error(`Invalid ${createSessionToolName} input: model must match an available model id or name.`); sessionServerTools.ts ×1
316 > }
317 > return model; sessionServerTools.ts ×1
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; sessionServerTools.ts ×2
323 > const workspace = getRequiredString(args.workspace, 'workspace', createSessionToolName);
324 > const prompt = getRequiredString(args.prompt, 'prompt', createSessionToolName);
325 > const modelName = getOptionalString(args.model, 'model', createSessionToolName);
326 > return {
327 > workspace: resolveWorkspace(workspace, sessions),
328 > prompt,
329 > model: resolveModel(modelName, models),
330 > };
331 > }
333 > /** Decodes the {@link SessionStatus} bit-flags into readable names for the agent. */
334 > function describeSessionStatusBits(status: SessionStatus): string[] { sessionServerTools.ts ×14
335 > const names: string[] = [];
336 > // `InputNeeded` is a superset of the `InProgress` bit, so it must be matched
337 > // with an exact-bits check before falling back to plain `InProgress`.
338 > if ((status & SessionStatus.InputNeeded) === SessionStatus.InputNeeded) {
339 > names.push('inputNeeded'); sessionServerTools.ts ×1
340 > } else if (status & SessionStatus.InProgress) { sessionServerTools.ts ×14
341 > names.push('inProgress'); sessionServerTools.ts ×1
342 > } else if (status & SessionStatus.Idle) { sessionServerTools.ts ×1
343 > names.push('idle'); sessionServerTools.ts ×1
344 > }
345 > if (status & SessionStatus.Error) { sessionServerTools.ts ×14
346 names.push('error');
347 }
348 > if (status & SessionStatus.IsArchived) { sessionServerTools.ts ×14
349 > names.push('archived'); sessionServerTools.ts ×1
350 > }
351 > return names; sessionServerTools.ts ×14
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[] { sessionServerTools.ts ×14
362 > const names = session.status !== undefined ? describeSessionStatusBits(session.status) : [];
363 > if (sessionIsArchived(session) && !names.includes('archived')) {
364 > names.push('archived'); sessionServerTools.ts ×1
365 > }
366 > return names; sessionServerTools.ts ×14
367 > }
369 > /** Renders a session's status names as the compact string used in tool results. */
370 > function describeSessionStatus(session: IAgentSessionMetadata): string | undefined { sessionServerTools.ts ×14
371 > const names = describeSessionStatusNames(session);
372 > if (names.length > 0) {
373 > return names.join(',');
374 > }
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 { sessionServerTools.ts ×5
396 > if (value === undefined) {
397 > return undefined;
398 > }
399 > if (typeof value !== 'boolean') { sessionServerTools.ts ×5
400 > throw new Error(`Invalid ${toolName} input: ${field} must be a boolean.`); sessionServerTools.ts ×3
401 > }
402 > return value; sessionServerTools.ts ×14
403 > }
405 > function getOptionalTimestamp(value: unknown, field: string, toolName: string): number | undefined { sessionServerTools.ts ×5
406 > if (value === undefined) {
407 > return undefined;
408 > }
409 > if (typeof value !== 'string') { sessionServerTools.ts ×5
410 throw new Error(`Invalid ${toolName} input: ${field} must be an ISO-8601 timestamp string.`);
411 }
412 > const parsed = Date.parse(value); sessionServerTools.ts ×5
413 > if (Number.isNaN(parsed)) {
414 > throw new Error(`Invalid ${toolName} input: ${field} must be a valid ISO-8601 timestamp (e.g. 2025-01-31T00:00:00Z).`); sessionServerTools.ts ×3
415 > }
416 > return parsed; sessionServerTools.ts ×14
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 }; sessionServerTools.ts ×5
422 >
423 > let status: Set<string> | undefined;
424 > if (args.status !== undefined) {
425 > if (!Array.isArray(args.status) || args.status.some(value => typeof value !== 'string')) { sessionServerTools.ts ×5
426 throw new Error(`Invalid ${listSessionsToolName} input: status must be an array of status names.`);
427 }
428 > const invalid = (args.status as string[]).filter(value => !(listSessionsStatusValues as readonly string[]).includes(value)); sessionServerTools.ts ×5
429 > if (invalid.length > 0) {
430 > throw new Error(`Invalid ${listSessionsToolName} input: unknown status value(s) ${invalid.join(', ')}. Valid values: ${listSessionsStatusValues.join(', ')}.`); sessionServerTools.ts ×3
431 > }
432 > status = new Set(args.status as string[]); sessionServerTools.ts ×14
433 > }
435 > return {
436 > session: getOptionalString(args.session, 'session', listSessionsToolName),
437 > status,
438 > workspace: getOptionalString(args.workspace, 'workspace', listSessionsToolName),
439 > withChanges: getOptionalBoolean(args.withChanges, 'withChanges', listSessionsToolName),
440 > unread: getOptionalBoolean(args.unread, 'unread', listSessionsToolName),
441 > withPullRequest: getOptionalBoolean(args.withPullRequest, 'withPullRequest', listSessionsToolName),
442 > includeArchived: getOptionalBoolean(args.includeArchived, 'includeArchived', listSessionsToolName),
443 > createdAfter: getOptionalTimestamp(args.createdAfter, 'createdAfter', listSessionsToolName),
444 > createdBefore: getOptionalTimestamp(args.createdBefore, 'createdBefore', listSessionsToolName),
445 > };
446 > }
448 > /** Whether a session has any pending worktree changes (insertions, deletions, or changed files). */
449 > function sessionHasChanges(session: IAgentSessionMetadata): boolean { sessionServerTools.ts ×14
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 { sessionServerTools.ts ×1
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 { sessionServerTools.ts ×14
461 > const dir = session.workingDirectory;
462 > if (!dir) {
463 return false;
464 }
465 > if (dir.toString() === workspace || dir.fsPath === workspace) { sessionServerTools.ts ×14
466 > return true;
467 > }
468 > const parsed = parseWorkspaceUri(workspace);
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 sessionServerTools.ts ×5
475 > // filters (including the default archived exclusion).
476 > if (args.session !== undefined) {
477 > const target = parseOpenSessionLinkUri(args.session)?.toString() ?? args.session; sessionServerTools.ts ×1
478 > return sessions.filter(session => session.session.toString() === target);
479 > }
480 > return sessions.filter(session => { sessionServerTools.ts ×9
481 > if (args.status) {
482 > const names = describeSessionStatusNames(session); sessionServerTools.ts ×14
483 > if (!names.some(name => args.status!.has(name))) {
484 > return false;
485 > }
486 > }
487 > if (args.workspace !== undefined && !sessionMatchesWorkspace(session, args.workspace)) { sessionServerTools.ts ×9
488 > return false; sessionServerTools.ts ×14
489 > }
490 > if (args.withChanges && !sessionHasChanges(session)) { sessionServerTools.ts ×9
491 > return false; sessionServerTools.ts ×14
492 > }
493 > if (args.unread && session.isRead !== false) { sessionServerTools.ts ×9
494 > return false; sessionServerTools.ts ×14
495 > }
496 > if (args.withPullRequest && !readSessionGitHubState(session._meta)?.pullRequestUrl) { sessionServerTools.ts ×9
497 > return false; sessionServerTools.ts ×14
498 > }
499 > // Archived sessions are hidden unless explicitly requested, either via sessionServerTools.ts ×9
500 > // `includeArchived` or by asking for the `archived` status directly.
501 > if (args.includeArchived !== true && !args.status?.has('archived') && sessionIsArchived(session)) {
502 > return false; sessionServerTools.ts ×14
503 > }
504 > if (args.createdAfter !== undefined && session.startTime < args.createdAfter) { sessionServerTools.ts ×9
505 > return false; sessionServerTools.ts ×14
506 > }
507 > if (args.createdBefore !== undefined && session.startTime > args.createdBefore) { sessionServerTools.ts ×9
508 > return false; sessionServerTools.ts ×14
509 > }
510 > return true; sessionServerTools.ts ×9
511 > });
512 > }
514 > function serializeGitState(session: IAgentSessionMetadata): ISerializedGitState | undefined { sessionServerTools.ts ×14
515 > const git = readSessionGitState(session._meta);
516 > if (!git) {
517 > return undefined; sessionServerTools.ts ×2
518 > }
519 > const result: Mutable<ISerializedGitState> = {}; sessionServerTools.ts ×1
520 > if (git.branchName !== undefined) { result.branch = git.branchName; }
521 > if (git.baseBranchName !== undefined) { result.baseBranch = git.baseBranchName; }
522 > if (git.upstreamBranchName !== undefined) { result.upstreamBranch = git.upstreamBranchName; }
523 > if (git.outgoingChanges !== undefined) { result.ahead = git.outgoingChanges; }
524 > if (git.incomingChanges !== undefined) { result.behind = git.incomingChanges; }
525 > if (git.uncommittedChanges !== undefined) { result.uncommittedChanges = git.uncommittedChanges; }
526 > return Object.keys(result).length > 0 ? result : undefined; sessionServerTools.ts ×14
527 > }
529 > function serializeGitHubState(session: IAgentSessionMetadata): ISerializedGitHubState | undefined { sessionServerTools.ts ×14
530 > const github = readSessionGitHubState(session._meta);
531 > if (!github) {
532 > return undefined; sessionServerTools.ts ×2
533 > }
534 > const result: Mutable<ISerializedGitHubState> = {}; sessionServerTools.ts ×1
535 > if (github.owner !== undefined) { result.owner = github.owner; }
536 > if (github.repo !== undefined) { result.repo = github.repo; }
537 > if (github.pullRequestUrl !== undefined) { result.pullRequestUrl = github.pullRequestUrl; }
538 > return Object.keys(result).length > 0 ? result : undefined; sessionServerTools.ts ×14
539 > }
541 > function serializeSession(session: IAgentSessionMetadata): ISerializedSession { sessionServerTools.ts ×14
542 > const git = serializeGitState(session);
543 > const github = serializeGitHubState(session);
544 > const status = describeSessionStatus(session);
545 > return {
546 > session: session.session.toString(),
547 > ...(session.summary !== undefined ? { title: session.summary } : {}),
548 > ...(status !== undefined ? { status } : {}),
549 > ...(session.activity !== undefined ? { activity: session.activity } : {}),
550 > ...(session.workingDirectory !== undefined ? { workingDirectory: session.workingDirectory.toString() } : {}),
551 > ...(session.project !== undefined ? { project: session.project.displayName } : {}),
552 > ...(session.isRead === false ? { unread: true } : {}),
553 > ...(session.startTime > 0 ? { createdAt: new Date(session.startTime).toISOString() } : {}),
554 > ...(session.modifiedTime > 0 ? { modifiedAt: new Date(session.modifiedTime).toISOString() } : {}),
555 > ...(session.changes !== undefined ? { changes: session.changes } : {}),
556 > ...(session.changesets !== undefined ? {
557 changesets: session.changesets.map(changeset => ({
558 label: changeset.label,
559 changeKind: changeset.changeKind,
560 uriTemplate: changeset.uriTemplate,
561 ...(changeset.description !== undefined ? { description: changeset.description } : {}),
562 })),
564 > ...(git !== undefined ? { git } : {}),
565 > ...(github !== undefined ? { github } : {}),
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) }); sessionServerTools.ts ×1
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> { sessionServerTools.ts ×5
588 > const parentDepth = currentSession ? accessor.getSessionSpawnDepth(currentSession) : 0;
589 > if (parentDepth >= maxSessionSpawnDepth) {
590 > throw new Error(`Refusing to create a session: recursion limit reached (max spawn depth ${maxSessionSpawnDepth}). This session was itself created ${parentDepth} level(s) deep.`); sessionServerTools.ts ×1
591 > }
592 > const sessions = await accessor.listSessions(); sessionServerTools.ts ×5
593 > const args = getCreateSessionArgs(rawArgs, sessions, accessor.getModels());
594 > const config: IAgentCreateSessionConfig = {
595 > workingDirectory: args.workspace,
596 > ...(args.model !== undefined ? { provider: args.model.provider, model: { id: args.model.id } } : {}),
597 > };
598 > const session = await accessor.createSession(config);
599 > accessor.setSessionSpawnDepth(session, parentDepth + 1);
600 > const chat = URI.parse(buildDefaultChatUri(session));
601 > await accessor.startPrompt(session, chat, args.prompt);
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.`; sessionServerTools.ts ×5
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 { sessionServerTools.ts ×1
636 > // Normalize an open-session link back to its backend session URI.
637 > const fromLink = parseOpenSessionLinkUri(sessionInput);
638 > const candidate = fromLink?.toString() ?? sessionInput;
639 > const match = sessions.find(s => s.session.toString() === candidate);
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 { sessionServerTools.ts ×4
645 > const session = resolveKnownSession(sessionInput, sessions);
646 > if (!session) {
647 > throw new Error(`Invalid ${createChatToolName} input: session must match the URI of a known session (see list_sessions).`); sessionServerTools.ts ×2
648 > }
649 > return session; sessionServerTools.ts ×4
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; sessionServerTools.ts ×4
655 > const prompt = getRequiredString(args.prompt, 'prompt', createChatToolName);
656 > const title = getOptionalString(args.title, 'title', createChatToolName);
657 > const modelName = getOptionalString(args.model, 'model', createChatToolName);
658 > const model = resolveModel(modelName, models);
659 > const sessionInput = getOptionalString(args.session, 'session', createChatToolName);
660 > let session: URI;
661 > if (sessionInput !== undefined) {
662 > session = resolveChatSession(sessionInput, sessions);
663 > } else if (currentSession) {
664 > session = currentSession; sessionServerTools.ts ×2
665 > } else {
666 > throw new Error(`Invalid ${createChatToolName} input: no session provided and the current session could not be determined.`);
667 > }
668 > return { session, prompt, ...(title !== undefined ? { title } : {}), ...(model !== undefined ? { model } : {}) }; sessionServerTools.ts ×4
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> { sessionServerTools.ts ×1
673 > const sessions = await accessor.listSessions();
674 > const args = getCreateChatArgs(rawArgs, sessions, accessor.getModels(), currentSession);
675 > const chatId = generateUuid();
676 > const chat = URI.parse(buildChatUri(args.session.toString(), chatId));
677 > await accessor.createChat(args.session, chat, { title: args.title, model: args.model });
678 > await accessor.startPrompt(args.session, chat, args.prompt);
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; sessionServerTools.ts ×3
709 > const message = getRequiredString(args.message, 'message', sendMessageToolName);
710 > const sessionInput = getRequiredString(args.session, 'session', sendMessageToolName);
711 > const session = resolveKnownSession(sessionInput, sessions);
712 > if (!session) {
713 > throw new Error(`Invalid ${sendMessageToolName} input: session must match the URI of a known session (see list_sessions).`);
714 > }
715 > const chatId = parseOpenSessionLinkChatId(sessionInput);
716 > const chat = URI.parse(chatId ? buildChatUri(session.toString(), chatId) : buildDefaultChatUri(session.toString()));
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> { sessionServerTools.ts ×3
726 > const sessions = await accessor.listSessions();
727 > const { session, chat, chatId, message } = getSendMessageArgs(rawArgs, sessions);
728 > if (currentChannel && chat.toString() === URI.parse(currentChannel).toString()) {
729 > throw new Error(`Invalid ${sendMessageToolName} input: refusing to send a message to the current chat.`);
730 > }
731 > await accessor.startPrompt(session, chat, message);
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.`; sessionServerTools.ts ×3
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; sessionServerTools.ts ×4
772 > const sessionInput = getRequiredString(args.session, 'session', getSessionContextToolName);
773 > const session = resolveKnownSession(sessionInput, sessions);
774 > if (!session) {
775 > throw new Error(`Invalid ${getSessionContextToolName} input: session must match the URI of a known session (see list_sessions).`); sessionServerTools.ts ×4
776 > }
777 > let detail: SessionContextDetail = 'summary'; sessionServerTools.ts ×4
778 > if (args.detail !== undefined) {
779 > if (typeof args.detail !== 'string' || !(sessionContextDetailValues as readonly string[]).includes(args.detail)) { sessionServerTools.ts ×4
780 > throw new Error(`Invalid ${getSessionContextToolName} input: detail must be one of ${sessionContextDetailValues.join(', ')}.`);
781 > }
782 detail = args.detail as SessionContextDetail;
783 }
784 > let transcriptLimit = defaultTranscriptLimit; sessionServerTools.ts ×4
785 > if (args.transcriptLimit !== undefined) {
786 > if (typeof args.transcriptLimit !== 'number' || !Number.isFinite(args.transcriptLimit) || args.transcriptLimit < 1) { sessionServerTools.ts ×4
787 throw new Error(`Invalid ${getSessionContextToolName} input: transcriptLimit must be a positive number.`);
788 }
789 > transcriptLimit = Math.min(Math.floor(args.transcriptLimit), maxTranscriptLimit); sessionServerTools.ts ×4
790 > }
791 > const chatId = parseOpenSessionLinkChatId(sessionInput); sessionServerTools.ts ×4
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 } { sessionServerTools.ts ×9
797 > const trimmed = text.trim();
798 > if (trimmed.length <= max) {
799 > return { text: trimmed, truncated: false };
800 > }
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[] { sessionServerTools.ts ×9
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 { sessionServerTools.ts ×9
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 { sessionServerTools.ts ×2
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 { sessionServerTools.ts ×9
829 > switch (state) {
830 > case TurnState.Complete: return 'complete';
831 > case TurnState.Cancelled: return 'cancelled';
832 > case TurnState.Error: return 'error';
833 > default: return 'inProgress';
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]; sessionServerTools.ts ×9
850 > let truncated = false;
851 > const trunc = (text: string, max: number): string | undefined => {
852 > if (max <= 0 || !text) {
853 return undefined;
854 }
855 > const result = truncateText(text, max); sessionServerTools.ts ×9
856 > truncated = truncated || result.truncated;
857 > return result.text || undefined;
858 > };
859 >
860 > const entries: { message: Message; parts: readonly ResponsePart[]; state: TurnState | 'inProgress' }[] =
861 > snapshot.turns.map(t => ({ message: t.message, parts: t.responseParts, state: t.state }));
862 > if (snapshot.activeTurn) {
863 entries.push({ message: snapshot.activeTurn.message, parts: snapshot.activeTurn.responseParts, state: 'inProgress' });
864 }
865 > if (entries.length > transcriptLimit) { sessionServerTools.ts ×9
866 > truncated = true; sessionServerTools.ts ×1
867 > }
868 > const windowStart = Math.max(0, entries.length - transcriptLimit); sessionServerTools.ts ×9
869 > const windowed = entries.slice(windowStart);
870 >
871 > const transcript: ISerializedContextTurn[] = windowed.map((entry, index): ISerializedContextTurn => {
872 > const user = trunc(entry.message.text, caps.user);
873 > const assistant = trunc(assistantTextOf(entry.parts), caps.assistant);
874 > const toolCalls = toolCallsOf(entry.parts);
875 > let serializedToolCalls: (string | { name: string; input?: string })[] | undefined;
876 > if (detail !== 'summary' && toolCalls.length > 0) {
877 > serializedToolCalls = toolCalls.map(tc => { sessionServerTools.ts ×2
878 > if (caps.toolInput > 0) {
879 > const input = trunc(readToolInput(tc) ?? '', caps.toolInput); sessionServerTools.ts ×2
880 > return input !== undefined ? { name: tc.toolName, input } : { name: tc.toolName };
881 > }
882 > return tc.toolName; sessionServerTools.ts ×1
884 > }
885 > return { sessionServerTools.ts ×9
886 > turn: windowStart + index + 1,
887 > state: describeTurnState(entry.state),
888 > ...(user !== undefined ? { user } : {}),
889 > ...(assistant !== undefined ? { assistant } : {}),
890 > ...(serializedToolCalls ? { toolCalls: serializedToolCalls } : {}),
891 > };
892 > });
893 >
894 > const payload: ISerializedSessionContext = {
895 > session: session.toString(),
896 > openLink: buildOpenSessionLinkUri(session, chatId),
897 > detail,
898 > transcript,
899 > hasMoreHistory: snapshot.hasMoreHistory,
900 > truncated,
901 > };
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> { sessionServerTools.ts ×2
907 > const sessions = await accessor.listSessions();
908 > const { session, chatId, detail, transcriptLimit } = getSessionContextArgs(rawArgs, sessions);
909 > const snapshot = accessor.getChatContext(session, chatId);
910 > if (!snapshot) {
911 > // No live conversation state (e.g. a cold/unsubscribed session): return the
912 > // identity + an empty transcript. Metadata is available via list_sessions.
913 > return JSON.stringify({
914 > session: session.toString(),
915 > openLink: buildOpenSessionLinkUri(session, chatId),
916 > detail,
917 > transcript: [],
918 > hasMoreHistory: false,
919 > truncated: false,
920 > } satisfies ISerializedSessionContext);
921 > }
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()); sessionServerTools.ts ×2
929 > return JSON.stringify({
930 > session: currentSession.toString(),
931 > openLink: buildOpenSessionLinkUri(currentSession),
932 > ...(meta ? serializeSession(meta) : {}),
933 > });
934 > }
936 function parseListedSessionCount(resultText: string | undefined): number | undefined {
937 if (!resultText) {
938 return undefined;
939 }
940 try {
941 const parsed = JSON.parse(resultText) as { sessions?: unknown };
942 return Array.isArray(parsed.sessions) ? parsed.sessions.length : undefined;
943 } catch {
944 return undefined;
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; sessionServerTools.ts ×3
959 > const sessionInput = getRequiredString(args.session, 'session', deleteSessionToolName);
960 > const session = resolveKnownSession(sessionInput, sessions);
961 > if (!session) {
962 > throw new Error(`Invalid ${deleteSessionToolName} input: session must match the URI of a known session (see list_sessions).`); sessionServerTools.ts ×2
963 > }
964 > if (currentSession && session.toString() === currentSession.toString()) { sessionServerTools.ts ×3
965 > throw new Error(`Invalid ${deleteSessionToolName} input: refusing to delete the current session.`); sessionServerTools.ts ×2
966 > }
967 > return session; sessionServerTools.ts ×3
968 > }
970 > /** Deletes a session and returns the model-facing confirmation. */
971 > export async function applyDeleteSessionTool(accessor: ISessionServerToolAccessor, rawArgs: unknown, currentSession?: URI): Promise<string> { sessionServerTools.ts ×1
972 > const sessions = await accessor.listSessions();
973 > const session = getDeleteSessionArgs(rawArgs, sessions, currentSession);
974 > await accessor.deleteSession(session);
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 { sessionServerTools.ts ×4
979 > switch (toolName) {
980 > case listSessionsToolName: {
981 > let pastTenseMessage: StringOrMarkdown;
982 > const count = result ? parseListedSessionCount(result.text) : undefined;
983 > if (count === undefined) {
984 > pastTenseMessage = localize('toolComplete.listSessions', "Checked sessions");
985 > } else if (count === 1) {
986 pastTenseMessage = localize('toolComplete.listSessions.one', "Checked 1 session");
987 } else {
988 pastTenseMessage = localize('toolComplete.listSessions.many', "Checked {0} sessions", count);
989 }
990 > return { sessionServerTools.ts ×4
991 > displayName: localize('toolName.listSessions', "List Sessions"),
992 > invocationMessage: localize('toolInvoke.listSessions', "Checking sessions"),
993 > pastTenseMessage,
994 > };
995 > }
996 > case createSessionToolName:
997 > return {
998 > displayName: localize('toolName.createSession', "Create Session"),
999 > invocationMessage: localize('toolInvoke.createSession', "Creating session"),
1000 > pastTenseMessage: localize('toolComplete.createSession', "Created session"),
1001 > };
1002 > case createChatToolName:
1003 > return {
1004 > displayName: localize('toolName.createChat', "Create Chat"),
1005 > invocationMessage: localize('toolInvoke.createChat', "Creating chat"),
1006 > pastTenseMessage: localize('toolComplete.createChat', "Created chat"),
1007 > };
1008 > case sendMessageToolName:
1009 > return {
1010 > displayName: localize('toolName.sendMessage', "Send Message"),
1011 > invocationMessage: localize('toolInvoke.sendMessage', "Sending message"),
1012 > pastTenseMessage: localize('toolComplete.sendMessage', "Sent message"),
1013 > };
1014 > case getSessionContextToolName:
1015 > return {
1016 > displayName: localize('toolName.getSessionContext', "Get Session Context"),
1017 > invocationMessage: localize('toolInvoke.getSessionContext', "Reading session context"),
1018 > pastTenseMessage: localize('toolComplete.getSessionContext', "Read session context"),
1019 > };
1020 > case getCurrentSessionToolName:
1021 > return {
1022 > displayName: localize('toolName.getCurrentSession', "Get Current Session"),
1023 > invocationMessage: localize('toolInvoke.getCurrentSession', "Checking current session"),
1024 > pastTenseMessage: localize('toolComplete.getCurrentSession', "Checked current session"),
1025 > };
1026 > case deleteSessionToolName:
1027 > return {
1028 > displayName: localize('toolName.deleteSession', "Delete Session"),
1029 > invocationMessage: localize('toolInvoke.deleteSession', "Deleting session"),
1030 > pastTenseMessage: localize('toolComplete.deleteSession', "Deleted session"),
1031 > };
1032 > default:
1033 return undefined;
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; sessionServerTools.ts ×4
1048 > let createdChatCount = 0;
1049 > let sentMessageCount = 0;
1050 > const group: IServerToolGroup = {
1051 > definitions: sessionServerToolDefinitions,
1052 > requiresConfirmation(toolName: string): boolean {
1053 return sessionToolRequiresConfirmation(toolName);
1054 },
1055 > getDisplay(toolName: string, args: unknown, result?: IServerToolDisplayResult): IServerToolDisplay | undefined { sessionServerTools.ts ×4
1056 > return getSessionToolDisplay(toolName, args, result); sessionServerTools.ts ×4
1057 > },
1058 > async execute(_stateManager: AgentHostStateManager, sessionUri: ProtocolURI, toolName: string, rawArgs: unknown): Promise<string> { sessionServerTools.ts ×4
1059 > if (!accessor) { sessionServerTools.ts ×10
1060 throw new Error(`Session server tool "${toolName}" cannot run: the group was built without a session accessor.`);
1061 }
1062 > switch (toolName) { sessionServerTools.ts ×10
1063 > case listSessionsToolName:
1064 > return serializeSessions(filterSessions(await accessor.listSessions(), getListSessionsArgs(rawArgs))); sessionServerTools.ts ×1
1065 > case getCurrentSessionToolName: sessionServerTools.ts ×10
1066 > return serializeCurrentSession(currentSessionUri(sessionUri), await accessor.listSessions()); sessionServerTools.ts ×2
1067 > case createSessionToolName: { sessionServerTools.ts ×10
1068 > if (createdSessionCount >= maxCreatedSessions) { sessionServerTools.ts ×5
1069 > throw new Error(`Refusing to create more than ${maxCreatedSessions} sessions from server tools in this process.`); sessionServerTools.ts ×1
1070 > }
1071 > const result = await applyCreateSessionTool(accessor, rawArgs, currentSessionUri(sessionUri)); sessionServerTools.ts ×5
1072 > createdSessionCount++;
1073 > return formatCreateSessionResult(result);
1074 > }
1075 > case createChatToolName: { sessionServerTools.ts ×10
1076 if (createdChatCount >= maxCreatedChats) {
1077 throw new Error(`Refusing to create more than ${maxCreatedChats} chats from server tools in this process.`);
1078 }
1079 const result = await applyCreateChatTool(accessor, rawArgs, currentSessionUri(sessionUri));
1080 createdChatCount++;
1081 return formatCreateChatResult(result);
1082 }
1083 > case sendMessageToolName: { sessionServerTools.ts ×10
1084 if (sentMessageCount >= maxSentMessages) {
1085 throw new Error(`Refusing to send more than ${maxSentMessages} messages from server tools in this process.`);
1086 }
1087 const result = await applySendMessageTool(accessor, rawArgs, sessionUri);
1088 sentMessageCount++;
1089 return result;
1090 }
1091 > case getSessionContextToolName: sessionServerTools.ts ×10
1092 > return applyGetSessionContextTool(accessor, rawArgs); sessionServerTools.ts ×2
1093 > case deleteSessionToolName: sessionServerTools.ts ×10
1094 return applyDeleteSessionTool(accessor, rawArgs, currentSessionUri(sessionUri));
1095 > default: sessionServerTools.ts ×10
1096 throw new Error(`Unknown session server tool: ${toolName}`);
1098 > },
1100 > return group;
1101 > }