@github/copilot-sdk 1.0.0-beta.5 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -4,7 +4,9 @@
4
4
  * JSON-RPC based SDK for programmatic control of GitHub Copilot CLI
5
5
  */
6
6
  export { CopilotClient } from "./client.js";
7
+ export { RuntimeConnection } from "./types.js";
7
8
  export { CopilotSession, type AssistantMessageEvent } from "./session.js";
8
- export { defineTool, approveAll, convertMcpCallToolResult, createSessionFsAdapter, SYSTEM_PROMPT_SECTIONS, } from "./types.js";
9
+ export { Canvas, CanvasError, createCanvas, type CanvasAction, type CanvasActionContext, type CanvasDeclaration, type CanvasHostContext, type CanvasJsonSchema, type CanvasLifecycleContext, type CanvasOpenContext, type CanvasOpenResponse, type CanvasOptions, } from "./canvas.js";
10
+ export { defineTool, approveAll, convertMcpCallToolResult, createSessionFsAdapter, SYSTEM_MESSAGE_SECTIONS, } from "./types.js";
9
11
  export type * from "./generated/session-events.js";
10
- export type { CommandContext, CommandDefinition, CommandHandler, CloudSessionOptions, CloudSessionRepository, AutoModeSwitchHandler, AutoModeSwitchRequest, AutoModeSwitchResponse, ConnectionState, CopilotClientOptions, CustomAgentConfig, ElicitationFieldValue, ElicitationHandler, ElicitationParams, ElicitationContext, ElicitationResult, ElicitationSchema, ElicitationSchemaField, ExitPlanModeHandler, ExitPlanModeRequest, ExitPlanModeResult, ForegroundSessionInfo, GetAuthStatusResponse, GetStatusResponse, InfiniteSessionConfig, InputOptions, MCPStdioServerConfig, MCPHTTPServerConfig, MCPServerConfig, DefaultAgentConfig, MessageOptions, ModelBilling, ModelCapabilities, ModelCapabilitiesOverride, ModelInfo, ModelPolicy, PermissionHandler, PermissionRequest, PermissionRequestResult, ProviderConfig, RemoteSessionMode, ResumeSessionConfig, SectionOverride, SectionOverrideAction, SectionTransformFn, SessionCapabilities, SessionConfig, SessionEvent, SessionEventHandler, SessionEventPayload, SessionEventType, SessionLifecycleEvent, SessionLifecycleEventType, SessionLifecycleHandler, SessionContext, SessionListFilter, SessionMetadata, SessionUiApi, SessionFsConfig, SessionFsProvider, SessionFsFileInfo, SessionFsSqliteQueryResult, SessionFsSqliteQueryType, SessionFsSqliteProvider, SystemMessageAppendConfig, SystemMessageConfig, SystemMessageCustomizeConfig, SystemMessageReplaceConfig, SystemPromptSection, TelemetryConfig, TraceContext, TraceContextProvider, Tool, ToolHandler, ToolInvocation, ToolResultObject, TypedSessionEventHandler, TypedSessionLifecycleHandler, ZodSchema, } from "./types.js";
12
+ export type { CommandContext, CommandDefinition, CommandHandler, CloudSessionOptions, CloudSessionRepository, AutoModeSwitchHandler, AutoModeSwitchRequest, AutoModeSwitchResponse, CopilotClientOptions, StdioRuntimeConnection, TcpRuntimeConnection, UriRuntimeConnection, CustomAgentConfig, ElicitationFieldValue, ElicitationHandler, ElicitationParams, ElicitationContext, ElicitationResult, ElicitationSchema, ElicitationSchemaField, ExitPlanModeHandler, ExitPlanModeRequest, ExitPlanModeResult, ExtensionInfo, ForegroundSessionInfo, GetAuthStatusResponse, GetStatusResponse, InfiniteSessionConfig, UiInputOptions, MCPStdioServerConfig, MCPHTTPServerConfig, MCPServerConfig, DefaultAgentConfig, MessageOptions, ModelBilling, ModelCapabilities, ModelCapabilitiesOverride, ModelInfo, ModelPolicy, PermissionHandler, PermissionRequest, PermissionRequestResult, ProviderConfig, RemoteSessionMode, ResumeSessionConfig, SectionOverride, SectionOverrideAction, SectionTransformFn, SessionCapabilities, SessionConfig, SessionConfigBase, SessionEvent, SessionEventHandler, SessionEventPayload, SessionEventType, SessionLifecycleEvent, SessionLifecycleEventMetadata, SessionLifecycleEventType, SessionLifecycleHandler, SessionCreatedEvent, SessionDeletedEvent, SessionUpdatedEvent, SessionForegroundEvent, SessionBackgroundEvent, SessionContext, SessionListFilter, SessionMetadata, SessionUiApi, SessionFsConfig, SessionFsProvider, SessionFsFileInfo, SessionFsSqliteQueryResult, SessionFsSqliteQueryType, SessionFsSqliteProvider, SystemMessageAppendConfig, SystemMessageConfig, SystemMessageCustomizeConfig, SystemMessageReplaceConfig, SystemMessageSection, TelemetryConfig, TraceContext, TraceContextProvider, Tool, ToolHandler, ToolInvocation, ToolTelemetry, ToolResultObject, TypedSessionEventHandler, TypedSessionLifecycleHandler, ZodSchema, } from "./types.js";
package/dist/index.js CHANGED
@@ -1,18 +1,28 @@
1
1
  import { CopilotClient } from "./client.js";
2
+ import { RuntimeConnection } from "./types.js";
2
3
  import { CopilotSession } from "./session.js";
4
+ import {
5
+ Canvas,
6
+ CanvasError,
7
+ createCanvas
8
+ } from "./canvas.js";
3
9
  import {
4
10
  defineTool,
5
11
  approveAll,
6
12
  convertMcpCallToolResult,
7
13
  createSessionFsAdapter,
8
- SYSTEM_PROMPT_SECTIONS
14
+ SYSTEM_MESSAGE_SECTIONS
9
15
  } from "./types.js";
10
16
  export {
17
+ Canvas,
18
+ CanvasError,
11
19
  CopilotClient,
12
20
  CopilotSession,
13
- SYSTEM_PROMPT_SECTIONS,
21
+ RuntimeConnection,
22
+ SYSTEM_MESSAGE_SECTIONS,
14
23
  approveAll,
15
24
  convertMcpCallToolResult,
25
+ createCanvas,
16
26
  createSessionFsAdapter,
17
27
  defineTool
18
28
  };
package/dist/session.d.ts CHANGED
@@ -1,12 +1,6 @@
1
- /**
2
- * Copilot Session - represents a single conversation session with the Copilot CLI.
3
- * @module session
4
- */
5
- import type { MessageConnection } from "vscode-jsonrpc/node.js";
6
1
  import { createSessionRpc } from "./generated/rpc.js";
7
- import type { ClientSessionApiHandlers } from "./generated/rpc.js";
8
- import type { CommandHandler, AutoModeSwitchHandler, AutoModeSwitchRequest, AutoModeSwitchResponse, ElicitationHandler, ElicitationContext, ExitPlanModeHandler, ExitPlanModeRequest, ExitPlanModeResult, MessageOptions, PermissionHandler, PermissionRequestResult, ReasoningEffort, ModelCapabilitiesOverride, SectionTransformFn, SessionCapabilities, SessionEvent, SessionEventHandler, SessionEventType, SessionHooks, SessionUiApi, Tool, ToolHandler, TraceContextProvider, TypedSessionEventHandler, UserInputHandler, UserInputResponse } from "./types.js";
9
- export declare const NO_RESULT_PERMISSION_V2_ERROR = "Permission handlers cannot return 'no-result' when connected to a protocol v2 server.";
2
+ import type { OpenCanvasInstance } from "./generated/rpc.js";
3
+ import type { MessageOptions, ReasoningEffort, ModelCapabilitiesOverride, SessionCapabilities, SessionEvent, SessionEventHandler, SessionEventType, SessionUiApi, TypedSessionEventHandler } from "./types.js";
10
4
  /** Assistant message event - the final response from the assistant. */
11
5
  export type AssistantMessageEvent = Extract<SessionEvent, {
12
6
  type: "assistant.message";
@@ -43,6 +37,7 @@ export declare class CopilotSession {
43
37
  private eventHandlers;
44
38
  private typedEventHandlers;
45
39
  private toolHandlers;
40
+ private canvases;
46
41
  private commandHandlers;
47
42
  private permissionHandler?;
48
43
  private userInputHandler?;
@@ -54,18 +49,7 @@ export declare class CopilotSession {
54
49
  private _rpc;
55
50
  private traceContextProvider?;
56
51
  private _capabilities;
57
- /** @internal Client session API handlers, populated by CopilotClient during create/resume. */
58
- clientSessionApis: ClientSessionApiHandlers;
59
- /**
60
- * Creates a new CopilotSession instance.
61
- *
62
- * @param sessionId - The unique identifier for this session
63
- * @param connection - The JSON-RPC message connection to the Copilot CLI
64
- * @param workspacePath - Path to the session workspace directory (when infinite sessions enabled)
65
- * @param traceContextProvider - Optional callback to get W3C Trace Context for outbound RPCs
66
- * @internal This constructor is internal. Use {@link CopilotClient.createSession} to create sessions.
67
- */
68
- constructor(sessionId: string, connection: MessageConnection, _workspacePath?: string | undefined, traceContextProvider?: TraceContextProvider);
52
+ private openCanvasInstances;
69
53
  /**
70
54
  * Typed session-scoped RPC methods.
71
55
  */
@@ -112,6 +96,7 @@ export declare class CopilotSession {
112
96
  * });
113
97
  * ```
114
98
  */
99
+ send(prompt: string): Promise<string>;
115
100
  send(options: MessageOptions): Promise<string>;
116
101
  /**
117
102
  * Sends a message to this session and waits until the session becomes idle.
@@ -136,6 +121,7 @@ export declare class CopilotSession {
136
121
  * console.log(response?.data.content); // "4"
137
122
  * ```
138
123
  */
124
+ sendAndWait(prompt: string, timeout?: number): Promise<AssistantMessageEvent | undefined>;
139
125
  sendAndWait(options: MessageOptions, timeout?: number): Promise<AssistantMessageEvent | undefined>;
140
126
  /**
141
127
  * Subscribes to events from this session.
@@ -184,190 +170,17 @@ export declare class CopilotSession {
184
170
  */
185
171
  on(handler: SessionEventHandler): () => void;
186
172
  /**
187
- * Dispatches an event to all registered handlers.
188
- * Also handles broadcast request events internally (external tool calls, permissions).
189
- *
190
- * @param event - The session event to dispatch
191
- * @internal This method is for internal use by the SDK.
192
- */
193
- _dispatchEvent(event: SessionEvent): void;
194
- /**
195
- * Handles broadcast request events by executing local handlers and responding via RPC.
196
- * Handlers are dispatched as fire-and-forget — rejections propagate as unhandled promise
197
- * rejections, consistent with standard EventEmitter / event handler semantics.
198
- * @internal
199
- */
200
- private _handleBroadcastEvent;
201
- /**
202
- * Executes a tool handler and sends the result back via RPC.
203
- * @internal
204
- */
205
- private _executeToolAndRespond;
206
- /**
207
- * Executes a permission handler and sends the result back via RPC.
208
- * @internal
209
- */
210
- private _executePermissionAndRespond;
211
- /**
212
- * Executes a command handler and sends the result back via RPC.
213
- * @internal
214
- */
215
- private _executeCommandAndRespond;
216
- /**
217
- * Registers custom tool handlers for this session.
218
- *
219
- * Tools with handlers allow the assistant to execute custom functions automatically.
220
- * Declaration-only tools are surfaced as events and left pending for the consumer.
221
- *
222
- * @param tools - An array of tool definitions with their handlers, or undefined to clear all tools
223
- * @internal This method is typically called internally when creating a session with tools.
224
- */
225
- registerTools(tools?: Tool[]): void;
226
- /**
227
- * Retrieves a registered tool handler by name.
228
- *
229
- * @param name - The name of the tool to retrieve
230
- * @returns The tool handler if found, or undefined
231
- * @internal This method is for internal use by the SDK.
232
- */
233
- getToolHandler(name: string): ToolHandler | undefined;
234
- /**
235
- * Registers command handlers for this session.
236
- *
237
- * @param commands - An array of command definitions with handlers, or undefined to clear
238
- * @internal This method is typically called internally when creating/resuming a session.
239
- */
240
- registerCommands(commands?: {
241
- name: string;
242
- handler: CommandHandler;
243
- }[]): void;
244
- /**
245
- * Registers the elicitation handler for this session.
246
- *
247
- * @param handler - The handler to invoke when the server dispatches an elicitation request
248
- * @internal This method is typically called internally when creating/resuming a session.
173
+ * Snapshot of canvas instances that were already open when the session was
174
+ * resumed. Populated from the `session.resume` response; empty for freshly
175
+ * created sessions. Returns a defensive copy — mutating the returned array
176
+ * has no effect on the session.
249
177
  */
250
- registerElicitationHandler(handler?: ElicitationHandler): void;
251
- /**
252
- * Registers the exit-plan-mode handler for this session.
253
- *
254
- * @param handler - The handler to invoke when the server dispatches an exit-plan-mode request
255
- * @internal This method is typically called internally when creating/resuming a session.
256
- */
257
- registerExitPlanModeHandler(handler?: ExitPlanModeHandler): void;
258
- /**
259
- * Registers the auto-mode-switch handler for this session.
260
- *
261
- * @param handler - The handler to invoke when the server dispatches an auto-mode-switch request
262
- * @internal This method is typically called internally when creating/resuming a session.
263
- */
264
- registerAutoModeSwitchHandler(handler?: AutoModeSwitchHandler): void;
265
- /**
266
- * Handles an elicitation.requested broadcast event.
267
- * Invokes the registered handler and responds via handlePendingElicitation RPC.
268
- * @internal
269
- */
270
- _handleElicitationRequest(context: ElicitationContext, requestId: string): Promise<void>;
271
- /**
272
- * Handles an exitPlanMode.request callback from the runtime.
273
- * @internal
274
- */
275
- _handleExitPlanModeRequest(request: ExitPlanModeRequest): Promise<ExitPlanModeResult>;
276
- /**
277
- * Handles an autoModeSwitch.request callback from the runtime.
278
- * @internal
279
- */
280
- _handleAutoModeSwitchRequest(request: AutoModeSwitchRequest): Promise<AutoModeSwitchResponse>;
281
- /**
282
- * Sets the host capabilities for this session.
283
- *
284
- * @param capabilities - The capabilities object from the create/resume response
285
- * @internal This method is typically called internally when creating/resuming a session.
286
- */
287
- setCapabilities(capabilities?: SessionCapabilities): void;
178
+ get openCanvases(): OpenCanvasInstance[];
288
179
  private assertElicitation;
289
180
  private _elicitation;
290
181
  private _confirm;
291
182
  private _select;
292
183
  private _input;
293
- /**
294
- * Registers a handler for permission requests.
295
- *
296
- * When the assistant needs permission to perform certain actions (e.g., file operations),
297
- * this handler is called to approve or deny the request.
298
- *
299
- * @param handler - The permission handler function, or undefined to remove the handler
300
- * @internal This method is typically called internally when creating a session.
301
- */
302
- registerPermissionHandler(handler?: PermissionHandler): void;
303
- /**
304
- * Registers a user input handler for ask_user requests.
305
- *
306
- * When the agent needs input from the user (via ask_user tool),
307
- * this handler is called to provide the response.
308
- *
309
- * @param handler - The user input handler function, or undefined to remove the handler
310
- * @internal This method is typically called internally when creating a session.
311
- */
312
- registerUserInputHandler(handler?: UserInputHandler): void;
313
- /**
314
- * Registers hook handlers for session lifecycle events.
315
- *
316
- * Hooks allow custom logic to be executed at various points during
317
- * the session lifecycle (before/after tool use, session start/end, etc.).
318
- *
319
- * @param hooks - The hook handlers object, or undefined to remove all hooks
320
- * @internal This method is typically called internally when creating a session.
321
- */
322
- registerHooks(hooks?: SessionHooks): void;
323
- /**
324
- * Registers transform callbacks for system message sections.
325
- *
326
- * @param callbacks - Map of section ID to transform callback, or undefined to clear
327
- * @internal This method is typically called internally when creating a session.
328
- */
329
- registerTransformCallbacks(callbacks?: Map<string, SectionTransformFn>): void;
330
- /**
331
- * Handles a systemMessage.transform request from the runtime.
332
- * Dispatches each section to its registered transform callback.
333
- *
334
- * @param sections - Map of section IDs to their current rendered content
335
- * @returns A promise that resolves with the transformed sections
336
- * @internal This method is for internal use by the SDK.
337
- */
338
- _handleSystemMessageTransform(sections: Record<string, {
339
- content: string;
340
- }>): Promise<{
341
- sections: Record<string, {
342
- content: string;
343
- }>;
344
- }>;
345
- /**
346
- * Handles a permission request in the v2 protocol format (synchronous RPC).
347
- * Used as a back-compat adapter when connected to a v2 server.
348
- *
349
- * @param request - The permission request data from the CLI
350
- * @returns A promise that resolves with the permission decision
351
- * @internal This method is for internal use by the SDK.
352
- */
353
- _handlePermissionRequestV2(request: unknown): Promise<PermissionRequestResult>;
354
- /**
355
- * Handles a user input request from the Copilot CLI.
356
- *
357
- * @param request - The user input request data from the CLI
358
- * @returns A promise that resolves with the user's response
359
- * @internal This method is for internal use by the SDK.
360
- */
361
- _handleUserInputRequest(request: unknown): Promise<UserInputResponse>;
362
- /**
363
- * Handles a hooks invocation from the Copilot CLI.
364
- *
365
- * @param hookType - The type of hook being invoked
366
- * @param input - The input data for the hook
367
- * @returns A promise that resolves with the hook output, or undefined
368
- * @internal This method is for internal use by the SDK.
369
- */
370
- _handleHooksInvoke(hookType: string, input: unknown): Promise<unknown>;
371
184
  /**
372
185
  * Retrieves all events and messages from this session's history.
373
186
  *
@@ -379,7 +192,7 @@ export declare class CopilotSession {
379
192
  *
380
193
  * @example
381
194
  * ```typescript
382
- * const events = await session.getMessages();
195
+ * const events = await session.getEvents();
383
196
  * for (const event of events) {
384
197
  * if (event.type === "assistant.message") {
385
198
  * console.log("Assistant:", event.data.content);
@@ -387,7 +200,7 @@ export declare class CopilotSession {
387
200
  * }
388
201
  * ```
389
202
  */
390
- getMessages(): Promise<SessionEvent[]>;
203
+ getEvents(): Promise<SessionEvent[]>;
391
204
  /**
392
205
  * Disconnects this session and releases all in-memory resources (event handlers,
393
206
  * tool handlers, permission handlers).
@@ -410,16 +223,6 @@ export declare class CopilotSession {
410
223
  * ```
411
224
  */
412
225
  disconnect(): Promise<void>;
413
- /**
414
- * @deprecated Use {@link disconnect} instead. This method will be removed in a future release.
415
- *
416
- * Disconnects this session and releases all in-memory resources.
417
- * Session data on disk is preserved for later resumption.
418
- *
419
- * @returns A promise that resolves when the session is disconnected
420
- * @throws Error if the connection fails
421
- */
422
- destroy(): Promise<void>;
423
226
  /** Enables `await using session = ...` syntax for automatic cleanup. */
424
227
  [Symbol.asyncDispose](): Promise<void>;
425
228
  /**
package/dist/session.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import { ConnectionError, ResponseError } from "vscode-jsonrpc/node.js";
2
2
  import { createSessionRpc } from "./generated/rpc.js";
3
3
  import { getTraceContext } from "./telemetry.js";
4
- const NO_RESULT_PERMISSION_V2_ERROR = "Permission handlers cannot return 'no-result' when connected to a protocol v2 server.";
4
+ function deserializeHookInput(raw) {
5
+ if (!raw || typeof raw !== "object" || typeof raw.timestamp !== "number") {
6
+ return raw;
7
+ }
8
+ const obj = raw;
9
+ const { cwd, ...rest } = obj;
10
+ return { ...rest, timestamp: new Date(obj.timestamp), workingDirectory: cwd };
11
+ }
5
12
  class CopilotSession {
6
13
  /**
7
14
  * Creates a new CopilotSession instance.
@@ -21,6 +28,7 @@ class CopilotSession {
21
28
  eventHandlers = /* @__PURE__ */ new Set();
22
29
  typedEventHandlers = /* @__PURE__ */ new Map();
23
30
  toolHandlers = /* @__PURE__ */ new Map();
31
+ canvases = /* @__PURE__ */ new Map();
24
32
  commandHandlers = /* @__PURE__ */ new Map();
25
33
  permissionHandler;
26
34
  userInputHandler;
@@ -32,6 +40,7 @@ class CopilotSession {
32
40
  _rpc = null;
33
41
  traceContextProvider;
34
42
  _capabilities = {};
43
+ openCanvasInstances = [];
35
44
  /** @internal Client session API handlers, populated by CopilotClient during create/resume. */
36
45
  clientSessionApis = {};
37
46
  /**
@@ -78,25 +87,8 @@ class CopilotSession {
78
87
  input: (message, options) => this._input(message, options)
79
88
  };
80
89
  }
81
- /**
82
- * Sends a message to this session and waits for the response.
83
- *
84
- * The message is processed asynchronously. Subscribe to events via {@link on}
85
- * to receive streaming responses and other session events.
86
- *
87
- * @param options - The message options including the prompt and optional attachments
88
- * @returns A promise that resolves with the message ID of the response
89
- * @throws Error if the session has been disconnected or the connection fails
90
- *
91
- * @example
92
- * ```typescript
93
- * const messageId = await session.send({
94
- * prompt: "Explain this code",
95
- * attachments: [{ type: "file", path: "./src/index.ts" }]
96
- * });
97
- * ```
98
- */
99
- async send(options) {
90
+ async send(optionsOrPrompt) {
91
+ const options = typeof optionsOrPrompt === "string" ? { prompt: optionsOrPrompt } : optionsOrPrompt;
100
92
  const response = await this.connection.sendRequest("session.send", {
101
93
  ...await getTraceContext(this.traceContextProvider),
102
94
  sessionId: this.sessionId,
@@ -107,30 +99,8 @@ class CopilotSession {
107
99
  });
108
100
  return response.messageId;
109
101
  }
110
- /**
111
- * Sends a message to this session and waits until the session becomes idle.
112
- *
113
- * This is a convenience method that combines {@link send} with waiting for
114
- * the `session.idle` event. Use this when you want to block until the
115
- * assistant has finished processing the message.
116
- *
117
- * Events are still delivered to handlers registered via {@link on} while waiting.
118
- *
119
- * @param options - The message options including the prompt and optional attachments
120
- * @param timeout - Timeout in milliseconds (default: 60000). Controls how long to wait; does not abort in-flight agent work.
121
- * @returns A promise that resolves with the final assistant message when the session becomes idle,
122
- * or undefined if no assistant message was received
123
- * @throws Error if the timeout is reached before the session becomes idle
124
- * @throws Error if the session has been disconnected or the connection fails
125
- *
126
- * @example
127
- * ```typescript
128
- * // Send and wait for completion with default 60s timeout
129
- * const response = await session.sendAndWait({ prompt: "What is 2+2?" });
130
- * console.log(response?.data.content); // "4"
131
- * ```
132
- */
133
- async sendAndWait(options, timeout) {
102
+ async sendAndWait(optionsOrPrompt, timeout) {
103
+ const options = typeof optionsOrPrompt === "string" ? { prompt: optionsOrPrompt } : optionsOrPrompt;
134
104
  const effectiveTimeout = timeout ?? 6e4;
135
105
  let resolveIdle;
136
106
  let rejectWithError;
@@ -400,6 +370,31 @@ class CopilotSession {
400
370
  getToolHandler(name) {
401
371
  return this.toolHandlers.get(name);
402
372
  }
373
+ /**
374
+ * Registers canvas declarations and handlers for this session.
375
+ *
376
+ * @param canvases - Canvases created via `createCanvas`, or undefined to clear all canvases
377
+ * @internal Called by the SDK when creating/resuming a session with `canvases`.
378
+ */
379
+ registerCanvases(canvases) {
380
+ this.canvases.clear();
381
+ if (!canvases) {
382
+ return;
383
+ }
384
+ for (const canvas of canvases) {
385
+ this.canvases.set(canvas.declaration.id, canvas);
386
+ }
387
+ }
388
+ /**
389
+ * Retrieves a registered canvas by id.
390
+ *
391
+ * @param canvasId - The id of the canvas to retrieve
392
+ * @returns The registered Canvas if found, or undefined
393
+ * @internal Used by the SDK's direct `canvas.*` dispatcher.
394
+ */
395
+ getCanvas(canvasId) {
396
+ return this.canvases.get(canvasId);
397
+ }
403
398
  /**
404
399
  * Registers command handlers for this session.
405
400
  *
@@ -496,6 +491,24 @@ class CopilotSession {
496
491
  setCapabilities(capabilities) {
497
492
  this._capabilities = capabilities ?? {};
498
493
  }
494
+ /**
495
+ * Snapshot of canvas instances that were already open when the session was
496
+ * resumed. Populated from the `session.resume` response; empty for freshly
497
+ * created sessions. Returns a defensive copy — mutating the returned array
498
+ * has no effect on the session.
499
+ */
500
+ get openCanvases() {
501
+ return [...this.openCanvasInstances];
502
+ }
503
+ /**
504
+ * Sets the open-canvas snapshot for this session.
505
+ *
506
+ * @param instances - The `openCanvases` array from the `session.resume` response.
507
+ * @internal This method is typically called internally when resuming a session.
508
+ */
509
+ setOpenCanvases(instances) {
510
+ this.openCanvasInstances = [...instances];
511
+ }
499
512
  assertElicitation() {
500
513
  if (!this._capabilities.ui?.elicitation) {
501
514
  throw new Error(
@@ -635,33 +648,6 @@ class CopilotSession {
635
648
  }
636
649
  return { sections: result };
637
650
  }
638
- /**
639
- * Handles a permission request in the v2 protocol format (synchronous RPC).
640
- * Used as a back-compat adapter when connected to a v2 server.
641
- *
642
- * @param request - The permission request data from the CLI
643
- * @returns A promise that resolves with the permission decision
644
- * @internal This method is for internal use by the SDK.
645
- */
646
- async _handlePermissionRequestV2(request) {
647
- if (!this.permissionHandler) {
648
- return { kind: "user-not-available" };
649
- }
650
- try {
651
- const result = await this.permissionHandler(request, {
652
- sessionId: this.sessionId
653
- });
654
- if (result.kind === "no-result") {
655
- throw new Error(NO_RESULT_PERMISSION_V2_ERROR);
656
- }
657
- return result;
658
- } catch (error) {
659
- if (error instanceof Error && error.message === NO_RESULT_PERMISSION_V2_ERROR) {
660
- throw error;
661
- }
662
- return { kind: "user-not-available" };
663
- }
664
- }
665
651
  /**
666
652
  * Handles a user input request from the Copilot CLI.
667
653
  *
@@ -694,8 +680,10 @@ class CopilotSession {
694
680
  if (!this.hooks) {
695
681
  return void 0;
696
682
  }
683
+ const normalized = deserializeHookInput(input);
697
684
  const handlerMap = {
698
685
  preToolUse: this.hooks.onPreToolUse,
686
+ preMcpToolCall: this.hooks.onPreMcpToolCall,
699
687
  postToolUse: this.hooks.onPostToolUse,
700
688
  userPromptSubmitted: this.hooks.onUserPromptSubmitted,
701
689
  sessionStart: this.hooks.onSessionStart,
@@ -707,7 +695,7 @@ class CopilotSession {
707
695
  return void 0;
708
696
  }
709
697
  try {
710
- const result = await handler(input, { sessionId: this.sessionId });
698
+ const result = await handler(normalized, { sessionId: this.sessionId });
711
699
  return result;
712
700
  } catch (_error) {
713
701
  return void 0;
@@ -724,7 +712,7 @@ class CopilotSession {
724
712
  *
725
713
  * @example
726
714
  * ```typescript
727
- * const events = await session.getMessages();
715
+ * const events = await session.getEvents();
728
716
  * for (const event of events) {
729
717
  * if (event.type === "assistant.message") {
730
718
  * console.log("Assistant:", event.data.content);
@@ -732,7 +720,7 @@ class CopilotSession {
732
720
  * }
733
721
  * ```
734
722
  */
735
- async getMessages() {
723
+ async getEvents() {
736
724
  const response = await this.connection.sendRequest("session.getMessages", {
737
725
  sessionId: this.sessionId
738
726
  });
@@ -772,18 +760,6 @@ class CopilotSession {
772
760
  this.exitPlanModeHandler = void 0;
773
761
  this.autoModeSwitchHandler = void 0;
774
762
  }
775
- /**
776
- * @deprecated Use {@link disconnect} instead. This method will be removed in a future release.
777
- *
778
- * Disconnects this session and releases all in-memory resources.
779
- * Session data on disk is preserved for later resumption.
780
- *
781
- * @returns A promise that resolves when the session is disconnected
782
- * @throws Error if the connection fails
783
- */
784
- async destroy() {
785
- return this.disconnect();
786
- }
787
763
  /** Enables `await using session = ...` syntax for automatic cleanup. */
788
764
  async [Symbol.asyncDispose]() {
789
765
  return this.disconnect();
@@ -869,6 +845,5 @@ function isToolResultObject(value) {
869
845
  return allowedResultTypes.includes(value.resultType);
870
846
  }
871
847
  export {
872
- CopilotSession,
873
- NO_RESULT_PERMISSION_V2_ERROR
848
+ CopilotSession
874
849
  };