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

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.
@@ -145,7 +145,7 @@ function createServerRpc(connection) {
145
145
  /**
146
146
  * Lists persisted sessions, optionally filtered by working-directory context.
147
147
  *
148
- * @param params Optional metadata-load limit and context filter applied to the returned sessions.
148
+ * @param params Optional metadata-load limit and filters applied to the returned sessions.
149
149
  *
150
150
  * @returns Persisted sessions matching the filter, ordered most-recently-modified first.
151
151
  */
@@ -249,7 +249,7 @@ function createServerRpc(connection) {
249
249
  *
250
250
  * @param params Session metadata records to enrich with summary and context information.
251
251
  *
252
- * @returns The same metadata records, with summary and context fields backfilled where available.
252
+ * @returns The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted.
253
253
  */
254
254
  enrichMetadata: async (params) => connection.sendRequest("sessions.enrichMetadata", params),
255
255
  /**
@@ -276,6 +276,17 @@ function createServerRpc(connection) {
276
276
  * @returns Replace the manager-wide additional plugins. New session creations and subsequent hook reloads see the new set; already-running sessions keep their existing hook installation until the next reload.
277
277
  */
278
278
  setAdditionalPlugins: async (params) => connection.sendRequest("sessions.setAdditionalPlugins", params)
279
+ },
280
+ /** @experimental */
281
+ agentRegistry: {
282
+ /**
283
+ * Spawns a managed-server child with the supplied configuration and returns a discriminated-union result. The caller (typically the CLI controller) is responsible for attaching to the spawned child and sending any follow-up prompt. When the controller-local spawn gate is closed the server returns JSON-RPC MethodNotFound.
284
+ *
285
+ * @param params Inputs to spawn a managed-server child via the controller's spawn delegate.
286
+ *
287
+ * @returns Outcome of an agentRegistry.spawn call.
288
+ */
289
+ spawn: async (params) => connection.sendRequest("agentRegistry.spawn", params)
279
290
  }
280
291
  };
281
292
  }
@@ -512,7 +523,15 @@ function createSessionRpc(connection, sessionId) {
512
523
  *
513
524
  * @returns Descriptor for the saved paste file, or null when the workspace is unavailable.
514
525
  */
515
- saveLargePaste: async (params) => connection.sendRequest("session.workspaces.saveLargePaste", { sessionId, ...params })
526
+ saveLargePaste: async (params) => connection.sendRequest("session.workspaces.saveLargePaste", { sessionId, ...params }),
527
+ /**
528
+ * Computes a diff for the session workspace.
529
+ *
530
+ * @param params Parameters for computing a workspace diff.
531
+ *
532
+ * @returns Workspace diff result for the requested mode.
533
+ */
534
+ diff: async (params) => connection.sendRequest("session.workspaces.diff", { sessionId, ...params })
516
535
  },
517
536
  /** @experimental */
518
537
  instructions: {
@@ -1026,6 +1045,20 @@ function createSessionRpc(connection, sessionId) {
1026
1045
  * @returns Indicates whether the operation succeeded.
1027
1046
  */
1028
1047
  setApproveAll: async (params) => connection.sendRequest("session.permissions.setApproveAll", { sessionId, ...params }),
1048
+ /**
1049
+ * Enables or disables full allow-all permissions (tools, paths, and URLs) for the session. Used by attach-mode clients (e.g. LocalRpcSession's `/allow-all` forwarder) to flip the target session's permission state. Unlike `setApproveAll`, this swaps in the unrestricted path and URL managers and emits `session.permissions_changed` on transition. The result returns the authoritative post-mutation state so callers can update their local mirrors without racing the `session.permissions_changed` notification on the same wire.
1050
+ *
1051
+ * @param params Whether to enable full allow-all permissions for the session.
1052
+ *
1053
+ * @returns Indicates whether the operation succeeded and reports the post-mutation state.
1054
+ */
1055
+ setAllowAll: async (params) => connection.sendRequest("session.permissions.setAllowAll", { sessionId, ...params }),
1056
+ /**
1057
+ * Returns whether full allow-all permissions are currently active for the session.
1058
+ *
1059
+ * @returns Current full allow-all permission state.
1060
+ */
1061
+ getAllowAll: async () => connection.sendRequest("session.permissions.getAllowAll", { sessionId }),
1029
1062
  /**
1030
1063
  * Adds or removes session-scoped or location-scoped permission rules.
1031
1064
  *
@@ -1432,6 +1465,21 @@ function registerClientSessionApiHandlers(connection, getHandlers) {
1432
1465
  if (!handler) throw new Error(`No sessionFs handler registered for session: ${params.sessionId}`);
1433
1466
  return handler.sqliteExists(params);
1434
1467
  });
1468
+ connection.onRequest("canvas.open", async (params) => {
1469
+ const handler = getHandlers(params.sessionId).canvas;
1470
+ if (!handler) throw new Error(`No canvas handler registered for session: ${params.sessionId}`);
1471
+ return handler.open(params);
1472
+ });
1473
+ connection.onRequest("canvas.close", async (params) => {
1474
+ const handler = getHandlers(params.sessionId).canvas;
1475
+ if (!handler) throw new Error(`No canvas handler registered for session: ${params.sessionId}`);
1476
+ return handler.close(params);
1477
+ });
1478
+ connection.onRequest("canvas.invokeAction", async (params) => {
1479
+ const handler = getHandlers(params.sessionId).canvas;
1480
+ if (!handler) throw new Error(`No canvas handler registered for session: ${params.sessionId}`);
1481
+ return handler.invokeAction(params);
1482
+ });
1435
1483
  }
1436
1484
  export {
1437
1485
  createInternalServerRpc,
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * Union of all session event variants emitted by the Copilot CLI runtime.
7
7
  */
8
- export type SessionEvent = StartEvent | ResumeEvent | RemoteSteerableChangedEvent | ErrorEvent | IdleEvent | TitleChangedEvent | ScheduleCreatedEvent | ScheduleCancelledEvent | InfoEvent | WarningEvent | ModelChangeEvent | ModeChangedEvent | PlanChangedEvent | WorkspaceFileChangedEvent | HandoffEvent | TruncationEvent | SnapshotRewindEvent | ShutdownEvent | ContextChangedEvent | UsageInfoEvent | CompactionStartEvent | CompactionCompleteEvent | TaskCompleteEvent | UserMessageEvent | PendingMessagesModifiedEvent | AssistantTurnStartEvent | AssistantIntentEvent | AssistantReasoningEvent | AssistantReasoningDeltaEvent | AssistantStreamingDeltaEvent | AssistantMessageEvent | AssistantMessageStartEvent | AssistantMessageDeltaEvent | AssistantTurnEndEvent | AssistantUsageEvent | ModelCallFailureEvent | AbortEvent | ToolUserRequestedEvent | ToolExecutionStartEvent | ToolExecutionPartialResultEvent | ToolExecutionProgressEvent | ToolExecutionCompleteEvent | SkillInvokedEvent | SubagentStartedEvent | SubagentCompletedEvent | SubagentFailedEvent | SubagentSelectedEvent | SubagentDeselectedEvent | HookStartEvent | HookEndEvent | SystemMessageEvent | SystemNotificationEvent | PermissionRequestedEvent | PermissionCompletedEvent | UserInputRequestedEvent | UserInputCompletedEvent | ElicitationRequestedEvent | ElicitationCompletedEvent | SamplingRequestedEvent | SamplingCompletedEvent | McpOauthRequiredEvent | McpOauthCompletedEvent | CustomNotificationEvent | ExternalToolRequestedEvent | ExternalToolCompletedEvent | CommandQueuedEvent | CommandExecuteEvent | CommandCompletedEvent | AutoModeSwitchRequestedEvent | AutoModeSwitchCompletedEvent | CommandsChangedEvent | CapabilitiesChangedEvent | ExitPlanModeRequestedEvent | ExitPlanModeCompletedEvent | ToolsUpdatedEvent | BackgroundTasksChangedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent | ExtensionsLoadedEvent | CanvasOpenedEvent | CanvasRegistryChangedEvent | McpAppToolCallCompleteEvent;
8
+ export type SessionEvent = StartEvent | ResumeEvent | RemoteSteerableChangedEvent | ErrorEvent | IdleEvent | TitleChangedEvent | ScheduleCreatedEvent | ScheduleCancelledEvent | AutopilotObjectiveChangedEvent | InfoEvent | WarningEvent | ModelChangeEvent | ModeChangedEvent | PermissionsChangedEvent | PlanChangedEvent | WorkspaceFileChangedEvent | HandoffEvent | TruncationEvent | SnapshotRewindEvent | ShutdownEvent | ContextChangedEvent | UsageInfoEvent | CompactionStartEvent | CompactionCompleteEvent | TaskCompleteEvent | UserMessageEvent | PendingMessagesModifiedEvent | AssistantTurnStartEvent | AssistantIntentEvent | AssistantReasoningEvent | AssistantReasoningDeltaEvent | AssistantStreamingDeltaEvent | AssistantMessageEvent | AssistantMessageStartEvent | AssistantMessageDeltaEvent | AssistantTurnEndEvent | AssistantUsageEvent | ModelCallFailureEvent | AbortEvent | ToolUserRequestedEvent | ToolExecutionStartEvent | ToolExecutionPartialResultEvent | ToolExecutionProgressEvent | ToolExecutionCompleteEvent | SkillInvokedEvent | SubagentStartedEvent | SubagentCompletedEvent | SubagentFailedEvent | SubagentSelectedEvent | SubagentDeselectedEvent | HookStartEvent | HookEndEvent | HookProgressEvent | SystemMessageEvent | SystemNotificationEvent | PermissionRequestedEvent | PermissionCompletedEvent | UserInputRequestedEvent | UserInputCompletedEvent | ElicitationRequestedEvent | ElicitationCompletedEvent | SamplingRequestedEvent | SamplingCompletedEvent | McpOauthRequiredEvent | McpOauthCompletedEvent | CustomNotificationEvent | ExternalToolRequestedEvent | ExternalToolCompletedEvent | CommandQueuedEvent | CommandExecuteEvent | CommandCompletedEvent | AutoModeSwitchRequestedEvent | AutoModeSwitchCompletedEvent | CommandsChangedEvent | CapabilitiesChangedEvent | ExitPlanModeRequestedEvent | ExitPlanModeCompletedEvent | ToolsUpdatedEvent | BackgroundTasksChangedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent | McpServerStatusChangedEvent | ExtensionsLoadedEvent | CanvasOpenedEvent | CanvasRegistryChangedEvent | McpAppToolCallCompleteEvent;
9
9
  /**
10
10
  * Hosting platform type of the repository (github or ado)
11
11
  */
@@ -24,6 +24,28 @@ export type ReasoningSummary =
24
24
  | "concise"
25
25
  /** Request a detailed summary of the model's reasoning. */
26
26
  | "detailed";
27
+ /**
28
+ * The type of operation performed on the autopilot objective state file
29
+ */
30
+ export type AutopilotObjectiveChangedOperation =
31
+ /** Autopilot objective state file was created for a new objective. */
32
+ "create"
33
+ /** Autopilot objective state file was updated for an existing objective. */
34
+ | "update"
35
+ /** Autopilot objective state file was deleted or cleared. */
36
+ | "delete";
37
+ /**
38
+ * Current autopilot objective status, if one exists
39
+ */
40
+ export type AutopilotObjectiveChangedStatus =
41
+ /** Objective is active and can drive autopilot continuations. */
42
+ "active"
43
+ /** Objective is paused and will not drive autopilot continuations. */
44
+ | "paused"
45
+ /** Legacy objective state indicating the previous continuation cap was reached. */
46
+ | "cap_reached"
47
+ /** Objective was completed by the agent. */
48
+ | "completed";
27
49
  /**
28
50
  * The session mode the agent is operating in
29
51
  */
@@ -828,6 +850,47 @@ export interface ScheduleCancelledData {
828
850
  */
829
851
  id: number;
830
852
  }
853
+ /**
854
+ * Session event "session.autopilot_objective_changed". Autopilot objective state file operation details indicating what changed
855
+ */
856
+ export interface AutopilotObjectiveChangedEvent {
857
+ /**
858
+ * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events.
859
+ */
860
+ agentId?: string;
861
+ data: AutopilotObjectiveChangedData;
862
+ /**
863
+ * When true, the event is transient and not persisted to the session event log on disk
864
+ */
865
+ ephemeral?: boolean;
866
+ /**
867
+ * Unique event identifier (UUID v4), generated when the event is emitted
868
+ */
869
+ id: string;
870
+ /**
871
+ * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event.
872
+ */
873
+ parentId: string | null;
874
+ /**
875
+ * ISO 8601 timestamp when the event was created
876
+ */
877
+ timestamp: string;
878
+ /**
879
+ * Type discriminator. Always "session.autopilot_objective_changed".
880
+ */
881
+ type: "session.autopilot_objective_changed";
882
+ }
883
+ /**
884
+ * Autopilot objective state file operation details indicating what changed
885
+ */
886
+ export interface AutopilotObjectiveChangedData {
887
+ /**
888
+ * Current autopilot objective id, if one exists
889
+ */
890
+ id?: number;
891
+ operation: AutopilotObjectiveChangedOperation;
892
+ status?: AutopilotObjectiveChangedStatus;
893
+ }
831
894
  /**
832
895
  * Session event "session.info". Informational message for timeline display with categorization
833
896
  */
@@ -1026,6 +1089,49 @@ export interface ModeChangedData {
1026
1089
  newMode: SessionMode;
1027
1090
  previousMode: SessionMode;
1028
1091
  }
1092
+ /**
1093
+ * Session event "session.permissions_changed". Permissions change details carrying the aggregate allow-all boolean transition.
1094
+ */
1095
+ export interface PermissionsChangedEvent {
1096
+ /**
1097
+ * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events.
1098
+ */
1099
+ agentId?: string;
1100
+ data: PermissionsChangedData;
1101
+ /**
1102
+ * When true, the event is transient and not persisted to the session event log on disk
1103
+ */
1104
+ ephemeral?: boolean;
1105
+ /**
1106
+ * Unique event identifier (UUID v4), generated when the event is emitted
1107
+ */
1108
+ id: string;
1109
+ /**
1110
+ * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event.
1111
+ */
1112
+ parentId: string | null;
1113
+ /**
1114
+ * ISO 8601 timestamp when the event was created
1115
+ */
1116
+ timestamp: string;
1117
+ /**
1118
+ * Type discriminator. Always "session.permissions_changed".
1119
+ */
1120
+ type: "session.permissions_changed";
1121
+ }
1122
+ /**
1123
+ * Permissions change details carrying the aggregate allow-all boolean transition.
1124
+ */
1125
+ export interface PermissionsChangedData {
1126
+ /**
1127
+ * Aggregate allow-all flag after the change
1128
+ */
1129
+ allowAllPermissions: boolean;
1130
+ /**
1131
+ * Aggregate allow-all flag before the change
1132
+ */
1133
+ previousAllowAllPermissions: boolean;
1134
+ }
1029
1135
  /**
1030
1136
  * Session event "session.plan_changed". Plan file operation details indicating what changed
1031
1137
  */
@@ -2853,6 +2959,10 @@ export interface ToolExecutionStartData {
2853
2959
  arguments?: {
2854
2960
  [k: string]: unknown | undefined;
2855
2961
  };
2962
+ /**
2963
+ * When true, the tool output should be displayed expanded (verbatim) in the CLI timeline
2964
+ */
2965
+ displayVerbatim?: boolean;
2856
2966
  /**
2857
2967
  * Name of the MCP server hosting this tool, when the tool is an MCP tool
2858
2968
  */
@@ -3803,6 +3913,45 @@ export interface HookEndError {
3803
3913
  */
3804
3914
  stack?: string;
3805
3915
  }
3916
+ /**
3917
+ * Session event "hook.progress". Ephemeral progress update from a running hook process
3918
+ */
3919
+ export interface HookProgressEvent {
3920
+ /**
3921
+ * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events.
3922
+ */
3923
+ agentId?: string;
3924
+ data: HookProgressData;
3925
+ /**
3926
+ * Always true for events that are transient and not persisted to the session event log on disk.
3927
+ */
3928
+ ephemeral: true;
3929
+ /**
3930
+ * Unique event identifier (UUID v4), generated when the event is emitted
3931
+ */
3932
+ id: string;
3933
+ /**
3934
+ * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event.
3935
+ */
3936
+ parentId: string | null;
3937
+ /**
3938
+ * ISO 8601 timestamp when the event was created
3939
+ */
3940
+ timestamp: string;
3941
+ /**
3942
+ * Type discriminator. Always "hook.progress".
3943
+ */
3944
+ type: "hook.progress";
3945
+ }
3946
+ /**
3947
+ * Ephemeral progress update from a running hook process
3948
+ */
3949
+ export interface HookProgressData {
3950
+ /**
3951
+ * Human-readable progress message from the hook process
3952
+ */
3953
+ message: string;
3954
+ }
3806
3955
  /**
3807
3956
  * Session event "system.message". System/developer instruction content with role and optional template metadata
3808
3957
  */
@@ -5473,6 +5622,10 @@ export interface ExternalToolRequestedData {
5473
5622
  * W3C Trace Context tracestate header for the execute_tool span
5474
5623
  */
5475
5624
  tracestate?: string;
5625
+ /**
5626
+ * Active session working directory, when known.
5627
+ */
5628
+ workingDirectory?: string;
5476
5629
  }
5477
5630
  /**
5478
5631
  * Session event "external_tool.completed". External tool completion notification signaling UI dismissal
package/dist/index.d.ts CHANGED
@@ -5,8 +5,9 @@
5
5
  */
6
6
  export { CopilotClient } from "./client.js";
7
7
  export { RuntimeConnection } from "./types.js";
8
+ export { BuiltInTools, ToolSet } from "./toolSet.js";
8
9
  export { CopilotSession, type AssistantMessageEvent } from "./session.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 { Canvas, CanvasError, createCanvas, type CanvasAction, type CanvasDeclaration, type CanvasHostContext, type CanvasJsonSchema, type CanvasOptions, } from "./canvas.js";
10
11
  export { defineTool, approveAll, convertMcpCallToolResult, createSessionFsAdapter, SYSTEM_MESSAGE_SECTIONS, } from "./types.js";
11
12
  export type * from "./generated/session-events.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";
13
+ export type { CommandContext, CommandDefinition, CommandHandler, CloudSessionOptions, CloudSessionRepository, AutoModeSwitchHandler, AutoModeSwitchRequest, AutoModeSwitchResponse, CopilotClientMode, 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,5 +1,6 @@
1
1
  import { CopilotClient } from "./client.js";
2
2
  import { RuntimeConnection } from "./types.js";
3
+ import { BuiltInTools, ToolSet } from "./toolSet.js";
3
4
  import { CopilotSession } from "./session.js";
4
5
  import {
5
6
  Canvas,
@@ -14,12 +15,14 @@ import {
14
15
  SYSTEM_MESSAGE_SECTIONS
15
16
  } from "./types.js";
16
17
  export {
18
+ BuiltInTools,
17
19
  Canvas,
18
20
  CanvasError,
19
21
  CopilotClient,
20
22
  CopilotSession,
21
23
  RuntimeConnection,
22
24
  SYSTEM_MESSAGE_SECTIONS,
25
+ ToolSet,
23
26
  approveAll,
24
27
  convertMcpCallToolResult,
25
28
  createCanvas,
package/dist/session.js CHANGED
@@ -1,5 +1,6 @@
1
- import { ConnectionError, ResponseError } from "vscode-jsonrpc/node.js";
1
+ import { ConnectionError, ErrorCodes, ResponseError } from "vscode-jsonrpc/node.js";
2
2
  import { createSessionRpc } from "./generated/rpc.js";
3
+ import { CanvasError } from "./canvas.js";
3
4
  import { getTraceContext } from "./telemetry.js";
4
5
  function deserializeHookInput(raw) {
5
6
  if (!raw || typeof raw !== "object" || typeof raw.timestamp !== "number") {
@@ -95,6 +96,7 @@ class CopilotSession {
95
96
  prompt: options.prompt,
96
97
  attachments: options.attachments,
97
98
  mode: options.mode,
99
+ agentMode: options.agentMode,
98
100
  requestHeaders: options.requestHeaders
99
101
  });
100
102
  return response.messageId;
@@ -378,22 +380,52 @@ class CopilotSession {
378
380
  */
379
381
  registerCanvases(canvases) {
380
382
  this.canvases.clear();
381
- if (!canvases) {
383
+ if (!canvases || canvases.length === 0) {
384
+ delete this.clientSessionApis.canvas;
382
385
  return;
383
386
  }
384
387
  for (const canvas of canvases) {
385
388
  this.canvases.set(canvas.declaration.id, canvas);
386
389
  }
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);
390
+ const self = this;
391
+ this.clientSessionApis.canvas = {
392
+ async open(params) {
393
+ const canvas = self.canvases.get(params.canvasId);
394
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
395
+ try {
396
+ return await canvas.open(params) ?? {};
397
+ } catch (error) {
398
+ throw toCanvasRpcError(error);
399
+ }
400
+ },
401
+ async close(params) {
402
+ const canvas = self.canvases.get(params.canvasId);
403
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
404
+ try {
405
+ if (canvas.onClose) {
406
+ await canvas.onClose(params);
407
+ }
408
+ } catch (error) {
409
+ throw toCanvasRpcError(error);
410
+ }
411
+ },
412
+ async invokeAction(params) {
413
+ const canvas = self.canvases.get(params.canvasId);
414
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
415
+ const handler = canvas.actionHandlers.get(params.actionName);
416
+ if (!handler) {
417
+ throw new CanvasError(
418
+ "canvas_action_no_handler",
419
+ "No handler implemented for this canvas action"
420
+ );
421
+ }
422
+ try {
423
+ return await handler(params);
424
+ } catch (error) {
425
+ throw toCanvasRpcError(error);
426
+ }
427
+ }
428
+ };
397
429
  }
398
430
  /**
399
431
  * Registers command handlers for this session.
@@ -685,6 +717,7 @@ class CopilotSession {
685
717
  preToolUse: this.hooks.onPreToolUse,
686
718
  preMcpToolCall: this.hooks.onPreMcpToolCall,
687
719
  postToolUse: this.hooks.onPostToolUse,
720
+ postToolUseFailure: this.hooks.onPostToolUseFailure,
688
721
  userPromptSubmitted: this.hooks.onUserPromptSubmitted,
689
722
  sessionStart: this.hooks.onSessionStart,
690
723
  sessionEnd: this.hooks.onSessionEnd,
@@ -844,6 +877,12 @@ function isToolResultObject(value) {
844
877
  ];
845
878
  return allowedResultTypes.includes(value.resultType);
846
879
  }
880
+ function toCanvasRpcError(error) {
881
+ if (error instanceof ResponseError) return error;
882
+ const code = error instanceof CanvasError ? error.code : "canvas_handler_error";
883
+ const message = error instanceof Error ? error.message : String(error);
884
+ return new ResponseError(ErrorCodes.InternalError, message, { code, message });
885
+ }
847
886
  export {
848
887
  CopilotSession
849
888
  };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Builder that produces a list of source-qualified tool filter strings for
3
+ * {@link SessionConfigBase.availableTools}.
4
+ *
5
+ * Tools are classified by the runtime at registration time (not from name
6
+ * parsing), so `addBuiltIn("foo")` matches only tools the runtime registered
7
+ * as built-in, even if an MCP server or custom-agent extension happens to
8
+ * register a tool with the same wire name.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const tools = new ToolSet()
13
+ * .addBuiltIn(BuiltInTools.Isolated)
14
+ * .addMcp("*")
15
+ * .addCustom("*");
16
+ *
17
+ * const session = await client.createSession({
18
+ * availableTools: tools,
19
+ * // ...
20
+ * });
21
+ * ```
22
+ */
23
+ export declare class ToolSet {
24
+ private readonly items;
25
+ /**
26
+ * Adds one or more built-in tool patterns.
27
+ *
28
+ * @param name A specific built-in tool name (e.g. `"bash"`) or `"*"` to match all
29
+ * built-in tools.
30
+ */
31
+ addBuiltIn(name: string): ToolSet;
32
+ /**
33
+ * Adds a list of built-in tool patterns (e.g. {@link BuiltInTools.Isolated}).
34
+ */
35
+ addBuiltIn(names: readonly string[]): ToolSet;
36
+ /**
37
+ * Adds a custom tool pattern. Matches tools registered via the SDK's
38
+ * `tools` option or via custom agents.
39
+ *
40
+ * @param name A specific custom tool name or `"*"` to match all custom tools.
41
+ */
42
+ addCustom(name: string): ToolSet;
43
+ /**
44
+ * Adds an MCP tool pattern. Matches tools advertised by any configured
45
+ * MCP server.
46
+ *
47
+ * @param toolName The runtime's canonical wire name for the MCP tool
48
+ * (e.g. `"github-list_issues"`), or `"*"` to match all MCP tools from
49
+ * any server.
50
+ */
51
+ addMcp(toolName: string): ToolSet;
52
+ /**
53
+ * Returns a defensive copy of the accumulated filter strings, suitable for
54
+ * passing as {@link SessionConfigBase.availableTools}.
55
+ */
56
+ toArray(): string[];
57
+ }
58
+ /**
59
+ * Curated sets of built-in tool names for common scenarios. Each constant is
60
+ * meant to be passed to {@link ToolSet.addBuiltIn}.
61
+ */
62
+ export declare const BuiltInTools: {
63
+ /**
64
+ * Built-in tools that operate only within the bounds of a single session —
65
+ * no host filesystem access outside the session, no cross-session state,
66
+ * no host environment access, no network. Safe to enable in `Mode = "empty"`
67
+ * scenarios (e.g. multi-tenant servers) without leaking host capabilities.
68
+ *
69
+ * **Contract:** tools in this set MUST NOT be extended (even behind options
70
+ * or args) to read or write state outside the session boundary. Adding
71
+ * cross-session or host-state behavior to one of these tools is a
72
+ * breaking change that requires removing it from this set.
73
+ */
74
+ readonly Isolated: readonly string[];
75
+ };
@@ -0,0 +1,82 @@
1
+ const VALID_TOOL_NAME = /^[a-zA-Z0-9_-]+$/;
2
+ function validateName(kind, name) {
3
+ if (name === "*") {
4
+ return;
5
+ }
6
+ if (!VALID_TOOL_NAME.test(name)) {
7
+ throw new Error(
8
+ `Invalid ${kind} tool name '${name}': tool names must match /^[a-zA-Z0-9_-]+$/ or be the wildcard '*'.`
9
+ );
10
+ }
11
+ }
12
+ class ToolSet {
13
+ items = [];
14
+ addBuiltIn(nameOrNames) {
15
+ const names = typeof nameOrNames === "string" ? [nameOrNames] : nameOrNames;
16
+ for (const name of names) {
17
+ validateName("builtin", name);
18
+ this.items.push(`builtin:${name}`);
19
+ }
20
+ return this;
21
+ }
22
+ /**
23
+ * Adds a custom tool pattern. Matches tools registered via the SDK's
24
+ * `tools` option or via custom agents.
25
+ *
26
+ * @param name A specific custom tool name or `"*"` to match all custom tools.
27
+ */
28
+ addCustom(name) {
29
+ validateName("custom", name);
30
+ this.items.push(`custom:${name}`);
31
+ return this;
32
+ }
33
+ /**
34
+ * Adds an MCP tool pattern. Matches tools advertised by any configured
35
+ * MCP server.
36
+ *
37
+ * @param toolName The runtime's canonical wire name for the MCP tool
38
+ * (e.g. `"github-list_issues"`), or `"*"` to match all MCP tools from
39
+ * any server.
40
+ */
41
+ addMcp(toolName) {
42
+ validateName("mcp", toolName);
43
+ this.items.push(`mcp:${toolName}`);
44
+ return this;
45
+ }
46
+ /**
47
+ * Returns a defensive copy of the accumulated filter strings, suitable for
48
+ * passing as {@link SessionConfigBase.availableTools}.
49
+ */
50
+ toArray() {
51
+ return [...this.items];
52
+ }
53
+ }
54
+ const BuiltInTools = {
55
+ /**
56
+ * Built-in tools that operate only within the bounds of a single session —
57
+ * no host filesystem access outside the session, no cross-session state,
58
+ * no host environment access, no network. Safe to enable in `Mode = "empty"`
59
+ * scenarios (e.g. multi-tenant servers) without leaking host capabilities.
60
+ *
61
+ * **Contract:** tools in this set MUST NOT be extended (even behind options
62
+ * or args) to read or write state outside the session boundary. Adding
63
+ * cross-session or host-state behavior to one of these tools is a
64
+ * breaking change that requires removing it from this set.
65
+ */
66
+ Isolated: [
67
+ "ask_user",
68
+ "task_complete",
69
+ "exit_plan_mode",
70
+ "task",
71
+ "read_agent",
72
+ "write_agent",
73
+ "list_agents",
74
+ "send_inbox",
75
+ "context_board",
76
+ "skill"
77
+ ]
78
+ };
79
+ export {
80
+ BuiltInTools,
81
+ ToolSet
82
+ };