@microsoft/copilot-sdk 0.0.0-stage → 2.0.0-preview.0

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.
Files changed (91) hide show
  1. package/README.md +2531 -2
  2. package/dist/canvas.d.ts +135 -0
  3. package/dist/canvas.js +51 -0
  4. package/dist/cjs/canvas.js +77 -0
  5. package/dist/cjs/cliVersion.js +31 -0
  6. package/dist/cjs/client.js +3941 -0
  7. package/dist/cjs/copilotRequestHandler.js +815 -0
  8. package/dist/cjs/decisions.js +139 -0
  9. package/dist/cjs/entra.js +83 -0
  10. package/dist/cjs/extension.js +79 -0
  11. package/dist/cjs/ffiRuntimeHost.js +400 -0
  12. package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
  13. package/dist/cjs/generated/rpc.js +5883 -0
  14. package/dist/cjs/generated/session-events.js +16 -0
  15. package/dist/cjs/host.js +83 -0
  16. package/dist/cjs/index.js +100 -0
  17. package/dist/cjs/installationConfirmation.js +98 -0
  18. package/dist/cjs/jsonrpcTypes.js +41 -0
  19. package/dist/cjs/localModelJson.js +103 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/providerConfiguration.js +39 -0
  22. package/dist/cjs/rpcCancellation.js +49 -0
  23. package/dist/cjs/runtimeArtifacts.js +255 -0
  24. package/dist/cjs/schema.js +40 -0
  25. package/dist/cjs/sdkProtocolVersion.js +33 -0
  26. package/dist/cjs/session.js +2764 -0
  27. package/dist/cjs/sessionFsProvider.js +283 -0
  28. package/dist/cjs/taskAnalyticsJson.js +47 -0
  29. package/dist/cjs/telemetry.js +35 -0
  30. package/dist/cjs/toolSet.js +107 -0
  31. package/dist/cjs/types.js +204 -0
  32. package/dist/cjs/workflow.js +278 -0
  33. package/dist/cliVersion.d.ts +2 -0
  34. package/dist/cliVersion.js +6 -0
  35. package/dist/client.d.ts +576 -0
  36. package/dist/client.js +3924 -0
  37. package/dist/copilotRequestHandler.d.ts +91 -0
  38. package/dist/copilotRequestHandler.js +787 -0
  39. package/dist/decisions.d.ts +65 -0
  40. package/dist/decisions.js +113 -0
  41. package/dist/entra.d.ts +3 -0
  42. package/dist/entra.js +59 -0
  43. package/dist/extension.d.ts +69 -0
  44. package/dist/extension.js +59 -0
  45. package/dist/ffiRuntimeHost.d.ts +44 -0
  46. package/dist/ffiRuntimeHost.js +366 -0
  47. package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
  48. package/dist/generated/lifecycle-diagnostics.js +0 -0
  49. package/dist/generated/rpc.d.ts +47706 -0
  50. package/dist/generated/rpc.js +5854 -0
  51. package/dist/generated/session-events.d.ts +17349 -0
  52. package/dist/generated/session-events.js +0 -0
  53. package/dist/host.d.ts +143 -0
  54. package/dist/host.js +59 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +74 -0
  57. package/dist/installationConfirmation.d.ts +19 -0
  58. package/dist/installationConfirmation.js +74 -0
  59. package/dist/jsonrpcTypes.d.ts +16 -0
  60. package/dist/jsonrpcTypes.js +17 -0
  61. package/dist/localModelJson.d.ts +1 -0
  62. package/dist/localModelJson.js +69 -0
  63. package/dist/providerConfiguration.d.ts +3 -0
  64. package/dist/providerConfiguration.js +15 -0
  65. package/dist/rpcCancellation.d.ts +3 -0
  66. package/dist/rpcCancellation.js +25 -0
  67. package/dist/runtimeArtifacts.d.ts +18 -0
  68. package/dist/runtimeArtifacts.js +233 -0
  69. package/dist/schema.d.ts +4 -0
  70. package/dist/schema.js +14 -0
  71. package/dist/sdkProtocolVersion.d.ts +10 -0
  72. package/dist/sdkProtocolVersion.js +8 -0
  73. package/dist/session.d.ts +524 -0
  74. package/dist/session.js +2751 -0
  75. package/dist/sessionFsProvider.d.ts +130 -0
  76. package/dist/sessionFsProvider.js +257 -0
  77. package/dist/taskAnalyticsJson.d.ts +8 -0
  78. package/dist/taskAnalyticsJson.js +12 -0
  79. package/dist/telemetry.d.ts +14 -0
  80. package/dist/telemetry.js +11 -0
  81. package/dist/toolSet.d.ts +75 -0
  82. package/dist/toolSet.js +82 -0
  83. package/dist/types.d.ts +3864 -0
  84. package/dist/types.js +169 -0
  85. package/dist/workflow.d.ts +413 -0
  86. package/dist/workflow.js +248 -0
  87. package/docs/agent-author.md +372 -0
  88. package/docs/examples.md +747 -0
  89. package/docs/extensions.md +121 -0
  90. package/docs/workflows.md +303 -0
  91. package/package.json +135 -5
@@ -0,0 +1,2751 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import {
3
+ CancellationTokenSource,
4
+ ConnectionError,
5
+ ErrorCodes,
6
+ ResponseError
7
+ } from "vscode-jsonrpc/node";
8
+ import { createInternalSessionRpc, createSessionRpc } from "./generated/rpc.js";
9
+ import { CanvasError } from "./canvas.js";
10
+ import { getTraceContext } from "./telemetry.js";
11
+ import { rawHistoryResponse } from "./taskAnalyticsJson.js";
12
+ import { isResponseSchema, toJsonSchema } from "./schema.js";
13
+ import { isAttributedPermissionResult } from "./types.js";
14
+ import {
15
+ WORKFLOW_AGENT_OPTION_KEYS,
16
+ getWorkflowDefinition,
17
+ getWorkflowAgentReference,
18
+ WorkflowResumeError,
19
+ isWorkflowRunTerminal
20
+ } from "./workflow.js";
21
+ function isWorkflowResumeErrorCode(value) {
22
+ return value === "not_found" || value === "non_resumable" || value === "workflow_run_not_resumable" || value === "already_active" || value === "workflow_already_running" || value === "workflow_limits_invalid" || value === "workflow_session_disposed" || value === "workflow_storage_unavailable" || value === "workflow_storage_corrupt" || value === "workflow_role_definition_mismatch";
23
+ }
24
+ function copyDefinedWorkflowAgentOption(source, target, key) {
25
+ const value = source[key];
26
+ if (value !== void 0) {
27
+ target[key] = value;
28
+ }
29
+ }
30
+ function toToolDefinition(tool) {
31
+ return {
32
+ name: tool.name,
33
+ title: tool.title,
34
+ description: tool.description ?? "",
35
+ parameters: toJsonSchema(tool.parameters),
36
+ overridesBuiltInTool: tool.overridesBuiltInTool,
37
+ skipPermission: tool.skipPermission,
38
+ hasHandler: !!tool.handler,
39
+ defer: tool.defer,
40
+ metadata: tool.metadata,
41
+ isTerminal: tool.isTerminal,
42
+ idempotent: tool.idempotent,
43
+ namespace: tool.namespace
44
+ };
45
+ }
46
+ const workflowExecutionStore = new AsyncLocalStorage();
47
+ function throwIfWorkflowExecutionIsActive() {
48
+ if (workflowExecutionStore.getStore()?.active) {
49
+ throw new Error(
50
+ "workflow.start, workflow.run, workflow.resume, and workflow.pause are not allowed while a workflow body is running on this call path."
51
+ );
52
+ }
53
+ }
54
+ function runInWorkflowHelperScope(helperScope, callback) {
55
+ const current = workflowExecutionStore.getStore();
56
+ return workflowExecutionStore.run({ active: current?.active ?? false, helperScope }, callback);
57
+ }
58
+ function deserializeHookInput(raw) {
59
+ if (!raw || typeof raw !== "object" || typeof raw.timestamp !== "number") {
60
+ return raw;
61
+ }
62
+ const obj = raw;
63
+ const { cwd, stop_hook_active, ...rest } = obj;
64
+ return {
65
+ ...rest,
66
+ timestamp: new Date(obj.timestamp),
67
+ workingDirectory: cwd,
68
+ ...stop_hook_active === void 0 ? {} : { stopHookActive: stop_hook_active }
69
+ };
70
+ }
71
+ function normalizeHookError(hookType, input) {
72
+ if (hookType !== "errorOccurred" && hookType !== "sessionEnd") {
73
+ return input;
74
+ }
75
+ if (!input || typeof input !== "object" || !("error" in input)) {
76
+ return input;
77
+ }
78
+ const { error } = input;
79
+ if (!error || typeof error !== "object" || Array.isArray(error)) {
80
+ return input;
81
+ }
82
+ const { message } = error;
83
+ return { ...input, error: typeof message === "string" ? message : JSON.stringify(error) };
84
+ }
85
+ function isOpenCanvasInstance(value) {
86
+ if (!value || typeof value !== "object") {
87
+ return false;
88
+ }
89
+ const instance = value;
90
+ return typeof instance.instanceId === "string" && instance.instanceId.length > 0 && typeof instance.extensionId === "string" && instance.extensionId.length > 0 && typeof instance.canvasId === "string" && instance.canvasId.length > 0;
91
+ }
92
+ const WORKFLOW_LOG_FLUSH_DELAY_MS = 10;
93
+ const MAX_WORKFLOW_FANOUT_ITEMS = 4096;
94
+ function assertWorkflowFanoutSize(kind, size) {
95
+ if (size > MAX_WORKFLOW_FANOUT_ITEMS) {
96
+ throw new Error(
97
+ `${kind}() accepts at most ${MAX_WORKFLOW_FANOUT_ITEMS} items; got ${size}.`
98
+ );
99
+ }
100
+ }
101
+ async function runWorkflowParallel(thunks) {
102
+ if (!Array.isArray(thunks)) {
103
+ throw new Error(
104
+ "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)"
105
+ );
106
+ }
107
+ assertWorkflowFanoutSize("parallel", thunks.length);
108
+ if (thunks.some((thunk) => typeof thunk !== "function")) {
109
+ throw new Error(
110
+ "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)"
111
+ );
112
+ }
113
+ return Promise.all(
114
+ thunks.map(
115
+ (thunk) => Promise.resolve().then(() => runInWorkflowHelperScope("parallel", thunk)).catch((error) => {
116
+ if (isWorkflowFatalError(error)) {
117
+ throw error;
118
+ }
119
+ return null;
120
+ })
121
+ )
122
+ );
123
+ }
124
+ async function runWorkflowPipeline(items, ...stages) {
125
+ if (!Array.isArray(items)) {
126
+ throw new Error("pipeline(items, ...stages): items must be an array");
127
+ }
128
+ assertWorkflowFanoutSize("pipeline", items.length);
129
+ return Promise.all(
130
+ items.map(async (item, index) => {
131
+ let previous = item;
132
+ for (const stage of stages) {
133
+ try {
134
+ previous = await runInWorkflowHelperScope(
135
+ "pipeline",
136
+ () => stage(previous, item, index)
137
+ );
138
+ } catch (error) {
139
+ if (isWorkflowFatalError(error)) {
140
+ throw error;
141
+ }
142
+ return null;
143
+ }
144
+ }
145
+ return previous;
146
+ })
147
+ );
148
+ }
149
+ class WorkflowProgressBuffer {
150
+ constructor(send) {
151
+ this.send = send;
152
+ }
153
+ send;
154
+ nextSeq = 0;
155
+ pending = [];
156
+ flushTimer;
157
+ flushTail = Promise.resolve();
158
+ flushError;
159
+ flushFailed = false;
160
+ closed = false;
161
+ enqueue(kind, text) {
162
+ if (this.closed) {
163
+ throw new Error("Cannot log after the workflow run has settled");
164
+ }
165
+ if (typeof text !== "string") {
166
+ throw new TypeError(
167
+ `${kind}() expects a string; got ${text === null ? "null" : typeof text}.`
168
+ );
169
+ }
170
+ this.pending.push({ seq: this.nextSeq++, kind, text });
171
+ this.scheduleFlush();
172
+ }
173
+ async flush() {
174
+ this.clearFlushTimer();
175
+ const lines = this.pending.splice(0);
176
+ if (lines.length > 0) {
177
+ this.flushTail = this.flushTail.then(async () => {
178
+ try {
179
+ await this.send(lines);
180
+ } catch (error) {
181
+ if (!this.flushFailed) {
182
+ this.flushFailed = true;
183
+ this.flushError = error;
184
+ }
185
+ }
186
+ });
187
+ }
188
+ await this.flushTail;
189
+ if (this.flushFailed) {
190
+ throw this.flushError;
191
+ }
192
+ }
193
+ async close() {
194
+ this.closed = true;
195
+ this.clearFlushTimer();
196
+ const lines = this.pending.splice(0);
197
+ await this.flushTail;
198
+ if (this.flushFailed) {
199
+ console.warn(
200
+ "Ignoring a background workflow progress flush failure after the workflow body settled",
201
+ this.flushError
202
+ );
203
+ }
204
+ if (lines.length > 0) {
205
+ try {
206
+ await this.send(lines);
207
+ } catch (error) {
208
+ console.warn(
209
+ "Failed to flush final workflow progress after the workflow body settled",
210
+ error
211
+ );
212
+ }
213
+ }
214
+ }
215
+ scheduleFlush() {
216
+ if (this.flushTimer !== void 0) {
217
+ return;
218
+ }
219
+ this.flushTimer = setTimeout(() => {
220
+ this.flushTimer = void 0;
221
+ void this.flush().catch(() => {
222
+ });
223
+ }, WORKFLOW_LOG_FLUSH_DELAY_MS);
224
+ this.flushTimer.unref?.();
225
+ }
226
+ clearFlushTimer() {
227
+ if (this.flushTimer !== void 0) {
228
+ clearTimeout(this.flushTimer);
229
+ this.flushTimer = void 0;
230
+ }
231
+ }
232
+ }
233
+ async function awaitWorkflowOperation(operation, signal) {
234
+ let rejectAbort;
235
+ const abortPromise = new Promise((_resolve, reject) => {
236
+ rejectAbort = reject;
237
+ });
238
+ const onAbort = () => rejectAbort?.(signal.reason ?? new DOMException("Workflow run was aborted", "AbortError"));
239
+ signal.addEventListener("abort", onAbort, { once: true });
240
+ try {
241
+ throwIfWorkflowAborted(signal);
242
+ return await Promise.race([operation(), abortPromise]);
243
+ } finally {
244
+ signal.removeEventListener("abort", onAbort);
245
+ }
246
+ }
247
+ function throwIfWorkflowAborted(signal) {
248
+ if (signal.aborted) {
249
+ throw signal.reason ?? new DOMException("Workflow run was aborted", "AbortError");
250
+ }
251
+ }
252
+ function isWorkflowAbortError(error) {
253
+ return typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
254
+ }
255
+ function isWorkflowFatalError(error) {
256
+ return isWorkflowAbortError(error) || error instanceof ResponseError || error instanceof ConnectionError;
257
+ }
258
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
259
+ function setLongTimeout(callback, delayMs) {
260
+ let timer;
261
+ const arm = (remainingMs) => {
262
+ timer = remainingMs > MAX_TIMER_DELAY_MS ? setTimeout(() => arm(remainingMs - MAX_TIMER_DELAY_MS), MAX_TIMER_DELAY_MS) : setTimeout(callback, remainingMs);
263
+ };
264
+ arm(delayMs);
265
+ return () => clearTimeout(timer);
266
+ }
267
+ const TOOL_SEARCH_TOOL_NAME = "tool_search_tool";
268
+ class CopilotSession {
269
+ /**
270
+ * Creates a new CopilotSession instance.
271
+ *
272
+ * @param sessionId - The unique identifier for this session
273
+ * @param connection - The JSON-RPC message connection to the Copilot CLI
274
+ * @param workspacePath - Path to the session workspace directory (when infinite sessions enabled)
275
+ * @param traceContextProvider - Optional callback to get W3C Trace Context for outbound RPCs
276
+ * @internal This constructor is internal. Use {@link CopilotClient.createSession} to create sessions.
277
+ */
278
+ constructor(_sessionId, connection, _workspacePath, traceContextProvider, options) {
279
+ this._sessionId = _sessionId;
280
+ this.connection = connection;
281
+ this._workspacePath = _workspacePath;
282
+ this.traceContextProvider = traceContextProvider;
283
+ this.mcpAuthHandler = options?.mcpAuthHandler;
284
+ this.managedSettingsEnabled = options?.managedSettingsEnabled === true;
285
+ this.onDisconnected = options?.onDisconnected;
286
+ }
287
+ _sessionId;
288
+ connection;
289
+ _workspacePath;
290
+ _transcriptRecovery;
291
+ _permissionModeResult;
292
+ eventHandlers = /* @__PURE__ */ new Set();
293
+ typedEventHandlers = /* @__PURE__ */ new Map();
294
+ toolHandlers = /* @__PURE__ */ new Map();
295
+ /** Settles once every earlier `setTools` call has finished. */
296
+ setToolsQueue = Promise.resolve();
297
+ pendingExternalTools = /* @__PURE__ */ new Map();
298
+ pendingSessionCreations = /* @__PURE__ */ new Set();
299
+ canvases = /* @__PURE__ */ new Map();
300
+ bearerTokenProviders = /* @__PURE__ */ new Map();
301
+ commandHandlers = /* @__PURE__ */ new Map();
302
+ workflows = /* @__PURE__ */ new Map();
303
+ workflowAbortControllers = /* @__PURE__ */ new Map();
304
+ permissionHandler;
305
+ mcpAuthHandler;
306
+ userInputHandler;
307
+ shellAuthenticationHandler;
308
+ pendingShellAuthenticationRequests = /* @__PURE__ */ new Map();
309
+ elicitationHandler;
310
+ exitPlanModeHandler;
311
+ autoModeSwitchHandler;
312
+ skillProvider;
313
+ sessionCreationHandler;
314
+ memoryStoreHandler;
315
+ hooks;
316
+ transformCallbacks;
317
+ _rpc = null;
318
+ _internalRpc = null;
319
+ traceContextProvider;
320
+ managedSettingsEnabled;
321
+ _capabilities = {};
322
+ openCanvasInstances = [];
323
+ disconnected = false;
324
+ pendingResponseWaits = /* @__PURE__ */ new Set();
325
+ pendingStructuredWaits = /* @__PURE__ */ new Set();
326
+ completionRpcUnsupported = false;
327
+ disconnecting = false;
328
+ onDisconnected;
329
+ releaseFromClient;
330
+ /** @internal Client session API handlers, populated by CopilotClient during create/resume. */
331
+ clientSessionApis = {};
332
+ /**
333
+ * Friendly workflow API for running registered workflows by name or handle.
334
+ *
335
+ * @experimental Part of the experimental Dynamic Workflows surface and may
336
+ * change or be removed in future SDK or CLI releases.
337
+ */
338
+ workflow = {
339
+ start: (async (nameOrHandle, options) => {
340
+ throwIfWorkflowExecutionIsActive();
341
+ const name = typeof nameOrHandle === "string" ? nameOrHandle : getWorkflowDefinition(nameOrHandle).meta.name;
342
+ return this.rpc.workflow.run({
343
+ name,
344
+ args: options?.args === void 0 ? {} : options.args,
345
+ options: {
346
+ limits: options?.limits,
347
+ notifyOnComplete: options?.notifyOnComplete,
348
+ logPhaseNames: options?.logPhaseNames
349
+ }
350
+ });
351
+ }),
352
+ run: (async (nameOrHandle, options) => {
353
+ throwIfWorkflowExecutionIsActive();
354
+ const name = typeof nameOrHandle === "string" ? nameOrHandle : getWorkflowDefinition(nameOrHandle).meta.name;
355
+ const envelope = await this.workflow.start(name, options);
356
+ return this.settleWorkflowRun(envelope);
357
+ }),
358
+ resume: (async (runId, options) => {
359
+ throwIfWorkflowExecutionIsActive();
360
+ let response;
361
+ try {
362
+ response = await this.rpc.workflow.resume({
363
+ runId,
364
+ limits: options?.limits,
365
+ notifyOnComplete: options?.notifyOnComplete,
366
+ logPhaseNames: options?.logPhaseNames
367
+ });
368
+ } catch (error) {
369
+ if (error instanceof ResponseError && typeof error.data === "object" && error.data !== null) {
370
+ const code = error.data.code;
371
+ if (isWorkflowResumeErrorCode(code)) {
372
+ throw new WorkflowResumeError(code, error.message);
373
+ }
374
+ }
375
+ throw error;
376
+ }
377
+ return this.settleWorkflowRun(response.run);
378
+ }),
379
+ getRun: async (runId) => this.rpc.workflow.getRun({ runId }),
380
+ waitForRun: (runId, options) => this.waitForWorkflowRun(runId, options?.signal),
381
+ listRuns: (async (options) => {
382
+ const page = await this.rpc.workflow.listRuns(options ?? {});
383
+ return options === void 0 ? page.runs : page;
384
+ }),
385
+ getRunDetail: (runId) => this.rpc.workflow.getRunDetail({ runId }),
386
+ getRunProgress: (runId, options = {}) => this.rpc.workflow.getRunProgress({ runId, ...options }),
387
+ pause: async (runId) => {
388
+ throwIfWorkflowExecutionIsActive();
389
+ return this.rpc.workflow.pause({ runId });
390
+ },
391
+ cancel: async (runId) => this.rpc.workflow.cancel({ runId })
392
+ };
393
+ settleWorkflowRun(envelope) {
394
+ if (isWorkflowRunTerminal(envelope.status)) {
395
+ return Promise.resolve(envelope);
396
+ }
397
+ return this.waitForWorkflowRun(envelope.runId);
398
+ }
399
+ /**
400
+ * Resolve when a workflow run reaches a terminal status.
401
+ *
402
+ * The subscription is installed *before* the first read so a transition
403
+ * landing between the two cannot be missed, and re-reads are serialized so
404
+ * overlapping invalidation events cannot interleave — the run's revision
405
+ * advances once per operation, so a burst of events is common and must
406
+ * collapse into a single in-flight read. A bounded periodic re-read keeps a
407
+ * dropped invalidation from leaving the wait pending forever.
408
+ */
409
+ waitForWorkflowRun(runId, signal) {
410
+ const abortError = () => signal?.reason ?? new DOMException("Workflow run wait was aborted", "AbortError");
411
+ if (signal?.aborted === true) {
412
+ return Promise.reject(abortError());
413
+ }
414
+ return new Promise((resolve, reject) => {
415
+ let settled = false;
416
+ let reading = false;
417
+ let rereadRequested = false;
418
+ let pollHandle;
419
+ let unsubscribe;
420
+ let onAbort;
421
+ const finish = (complete) => {
422
+ if (settled) {
423
+ return;
424
+ }
425
+ settled = true;
426
+ if (pollHandle !== void 0) {
427
+ clearInterval(pollHandle);
428
+ }
429
+ unsubscribe?.();
430
+ if (onAbort !== void 0) {
431
+ signal?.removeEventListener("abort", onAbort);
432
+ }
433
+ complete();
434
+ };
435
+ const read = async () => {
436
+ if (settled) {
437
+ return;
438
+ }
439
+ if (reading) {
440
+ rereadRequested = true;
441
+ return;
442
+ }
443
+ reading = true;
444
+ try {
445
+ do {
446
+ rereadRequested = false;
447
+ const envelope = await this.rpc.workflow.getRun({ runId });
448
+ if (isWorkflowRunTerminal(envelope.status)) {
449
+ finish(() => resolve(envelope));
450
+ return;
451
+ }
452
+ } while (rereadRequested && !settled);
453
+ } catch (error) {
454
+ finish(() => reject(error));
455
+ } finally {
456
+ reading = false;
457
+ }
458
+ };
459
+ if (signal !== void 0) {
460
+ onAbort = () => finish(() => reject(abortError()));
461
+ signal.addEventListener("abort", onAbort, { once: true });
462
+ }
463
+ unsubscribe = this.on("workflow.run_updated", (event) => {
464
+ if (event.data.runId === runId) {
465
+ void read();
466
+ }
467
+ });
468
+ pollHandle = setInterval(() => void read(), 5e3);
469
+ pollHandle.unref?.();
470
+ void read();
471
+ });
472
+ }
473
+ get sessionId() {
474
+ return this._sessionId;
475
+ }
476
+ /** @internal */
477
+ _setSessionId(sessionId) {
478
+ this._sessionId = sessionId;
479
+ this._rpc = null;
480
+ this._internalRpc = null;
481
+ }
482
+ /**
483
+ * Typed session-scoped RPC methods.
484
+ */
485
+ get rpc() {
486
+ if (!this._rpc) {
487
+ this._rpc = createSessionRpc(this.connection, this.sessionId);
488
+ }
489
+ return this._rpc;
490
+ }
491
+ /** @internal */
492
+ get internalRpc() {
493
+ if (!this._internalRpc) {
494
+ this._internalRpc = createInternalSessionRpc(this.connection, this.sessionId);
495
+ }
496
+ return this._internalRpc;
497
+ }
498
+ /**
499
+ * Path to the session workspace directory when infinite sessions are enabled.
500
+ * Contains checkpoints/, plan.md, and files/ subdirectories.
501
+ * Undefined if infinite sessions are disabled.
502
+ */
503
+ get workspacePath() {
504
+ return this._workspacePath;
505
+ }
506
+ /** Recovery observed while loading this session; undefined on a clean resume. */
507
+ get transcriptRecovery() {
508
+ return this._transcriptRecovery;
509
+ }
510
+ /** @internal */
511
+ setTranscriptRecovery(recovery) {
512
+ this._transcriptRecovery = recovery;
513
+ }
514
+ /**
515
+ * Outcome of the `permissionMode` requested when this session was created
516
+ * or resumed: whether it was applied, and the authoritative mode the
517
+ * session started in. Undefined when no mode was requested.
518
+ */
519
+ get permissionModeResult() {
520
+ return this._permissionModeResult;
521
+ }
522
+ /** @internal */
523
+ setPermissionModeResult(result) {
524
+ this._permissionModeResult = result;
525
+ }
526
+ /**
527
+ * Host capabilities reported when the session was created or resumed.
528
+ * Use this to check feature support before calling capability-gated APIs.
529
+ */
530
+ get capabilities() {
531
+ return this._capabilities;
532
+ }
533
+ /**
534
+ * Interactive UI methods for showing dialogs to the user.
535
+ * Only available when the CLI host supports elicitation
536
+ * (`session.capabilities.ui?.elicitation === true`).
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * if (session.capabilities.ui?.elicitation) {
541
+ * const ok = await session.ui.confirm("Deploy to production?");
542
+ * }
543
+ * ```
544
+ */
545
+ get ui() {
546
+ return {
547
+ elicitation: (params) => this._elicitation(params),
548
+ confirm: (message) => this._confirm(message),
549
+ select: (message, options) => this._select(message, options),
550
+ input: (message, options) => this._input(message, options)
551
+ };
552
+ }
553
+ async send(optionsOrPrompt) {
554
+ const options = typeof optionsOrPrompt === "string" ? { prompt: optionsOrPrompt } : optionsOrPrompt;
555
+ return this.sendMessage(options);
556
+ }
557
+ async sendMessage(options, cancelled) {
558
+ const message = await this.createSendParams(options);
559
+ if (cancelled?.()) {
560
+ throw new Error("Completion wait cancelled");
561
+ }
562
+ const response = await this.connection.sendRequest("session.send", {
563
+ sessionId: this.sessionId,
564
+ ...message
565
+ });
566
+ return response.messageId;
567
+ }
568
+ async createSendParams(options) {
569
+ return {
570
+ ...await getTraceContext(this.traceContextProvider),
571
+ prompt: options.prompt,
572
+ source: options.source,
573
+ displayPrompt: options.displayPrompt,
574
+ clientTurnId: options.clientTurnId,
575
+ attachments: options.attachments,
576
+ mode: options.mode,
577
+ agentMode: options.agentMode,
578
+ requestHeaders: options.requestHeaders,
579
+ ...options.responseSchema ? {
580
+ responseFormat: {
581
+ type: "json_schema",
582
+ jsonSchema: {
583
+ name: "response",
584
+ strict: true,
585
+ schema: toJsonSchema(options.responseSchema)
586
+ }
587
+ }
588
+ } : {}
589
+ };
590
+ }
591
+ async sendAndWait(optionsOrPrompt, schemaOrTimeout, timeout) {
592
+ const options = typeof optionsOrPrompt === "string" ? { prompt: optionsOrPrompt } : optionsOrPrompt;
593
+ const typedSchema = isResponseSchema(schemaOrTimeout) ? schemaOrTimeout : void 0;
594
+ if (schemaOrTimeout !== void 0 && typeof schemaOrTimeout !== "number" && !typedSchema) {
595
+ throw new TypeError(
596
+ "The second argument must be a timeout or a schema with toJSONSchema() and parse(). Pass raw JSON Schema in options.responseSchema instead."
597
+ );
598
+ }
599
+ const effectiveTimeout = (typeof schemaOrTimeout === "number" ? schemaOrTimeout : timeout) ?? 6e4;
600
+ if (typedSchema && options.responseSchema) {
601
+ throw new Error(
602
+ "Do not specify responseSchema in options when requesting a typed response."
603
+ );
604
+ }
605
+ if (typedSchema && options.mode === "immediate") {
606
+ throw new Error(
607
+ "Structured output cannot be requested on an immediate steering message."
608
+ );
609
+ }
610
+ const startedAt = Date.now();
611
+ const completion = await this.sendWithCompletion(
612
+ typedSchema ? { ...options, responseSchema: typedSchema } : options,
613
+ effectiveTimeout
614
+ );
615
+ if (completion !== void 0) {
616
+ const message = completion.response;
617
+ if (message !== void 0 && (message.type !== "assistant.message" || message.agentId)) {
618
+ throw new Error("The runtime returned a non-assistant response.");
619
+ }
620
+ if (typedSchema || options.responseSchema) {
621
+ if (completion.aborted) {
622
+ throw new Error(
623
+ "The requested run was aborted before a structured result was completed."
624
+ );
625
+ }
626
+ if (!message || message.data.toolRequests?.length || !message.data.content.trim()) {
627
+ throw new Error(
628
+ "The requested run completed without a structured assistant response."
629
+ );
630
+ }
631
+ return typedSchema ? typedSchema.parse(JSON.parse(message.data.content)) : message;
632
+ }
633
+ if (completion.aborted) {
634
+ throw new Error("The requested run was aborted before completion.");
635
+ }
636
+ return message;
637
+ }
638
+ const remainingTimeout = Math.max(0, effectiveTimeout - (Date.now() - startedAt));
639
+ if (typedSchema || options.responseSchema) {
640
+ const message = await this.sendAndWaitForStructuredMessage(
641
+ typedSchema ? { ...options, responseSchema: typedSchema } : options,
642
+ remainingTimeout
643
+ );
644
+ if (typedSchema) {
645
+ if (!message) {
646
+ throw new Error(
647
+ "The requested run completed without a structured assistant response."
648
+ );
649
+ }
650
+ return typedSchema.parse(JSON.parse(message.data.content));
651
+ }
652
+ return message;
653
+ }
654
+ let resolveOutcome;
655
+ const outcomePromise = new Promise((resolve) => {
656
+ resolveOutcome = resolve;
657
+ });
658
+ let lastAssistantMessage;
659
+ let messageId;
660
+ let requestStarted = false;
661
+ let admitted = false;
662
+ const buffered = [];
663
+ const observe = (event) => {
664
+ if (event.agentId) return;
665
+ if (event.type === "user.message" && event.data.messageId === messageId) {
666
+ requestStarted = true;
667
+ } else if (event.type === "session.warning" && event.data.warningType === "policy_blocked" && event.data.originatingMessageId === messageId) {
668
+ requestStarted = true;
669
+ } else if (event.type === "assistant.message" && (event.data.originatingMessageId === messageId || !event.data.originatingMessageId && requestStarted)) {
670
+ lastAssistantMessage = event;
671
+ if (event.data.originatingMessageId === messageId) requestStarted = true;
672
+ } else if (event.type === "session.idle" && requestStarted && event.data.mode !== "autopilot") {
673
+ resolveOutcome(
674
+ event.data.aborted ? {
675
+ kind: "error",
676
+ error: new Error("The requested run was aborted before completion.")
677
+ } : { kind: "idle", message: lastAssistantMessage }
678
+ );
679
+ } else if (event.type === "session.autopilot_stopped" && messageId && event.data.requestId === messageId) {
680
+ if (event.data.reason === "error") {
681
+ resolveOutcome({
682
+ kind: "error",
683
+ error: new Error("Autopilot request failed")
684
+ });
685
+ } else if (event.data.reason === "aborted") {
686
+ resolveOutcome({
687
+ kind: "error",
688
+ error: new Error("The requested run was aborted before completion.")
689
+ });
690
+ } else {
691
+ resolveOutcome({ kind: "idle", message: lastAssistantMessage });
692
+ }
693
+ } else if (event.type === "session.error" && (!event.data.originatingMessageId || event.data.originatingMessageId === messageId)) {
694
+ const error = Object.assign(new Error(event.data.message), {
695
+ data: {
696
+ ...event.data,
697
+ stack: event.data.stack ?? null,
698
+ completionEventId: event.id
699
+ }
700
+ });
701
+ error.stack = event.data.stack;
702
+ resolveOutcome({ kind: "error", error });
703
+ }
704
+ };
705
+ const unsubscribe = this.on((event) => {
706
+ if (event.agentId || event.type !== "assistant.message" && event.type !== "user.message" && event.type !== "session.warning" && event.type !== "session.idle" && event.type !== "session.autopilot_stopped" && event.type !== "session.error") {
707
+ return;
708
+ }
709
+ if (!admitted) buffered.push(event);
710
+ else observe(event);
711
+ });
712
+ const fail = (error) => {
713
+ if (!admitted) buffered.push(error);
714
+ else resolveOutcome({ kind: "error", error });
715
+ };
716
+ this.pendingResponseWaits.add(fail);
717
+ let cancelTimeout;
718
+ let waiting = true;
719
+ try {
720
+ const timeoutPromise = new Promise((_, reject) => {
721
+ cancelTimeout = setLongTimeout(
722
+ () => reject(
723
+ new Error(
724
+ `Timeout after ${effectiveTimeout}ms waiting for response completion`
725
+ )
726
+ ),
727
+ remainingTimeout
728
+ );
729
+ });
730
+ const outcome = await Promise.race([
731
+ this.sendMessage(options, () => !waiting).then((id) => {
732
+ messageId = id;
733
+ admitted = true;
734
+ for (const event of buffered) {
735
+ if (event instanceof Error) fail(event);
736
+ else observe(event);
737
+ }
738
+ buffered.length = 0;
739
+ return outcomePromise;
740
+ }),
741
+ timeoutPromise
742
+ ]);
743
+ if (outcome.kind === "error") {
744
+ throw outcome.error;
745
+ }
746
+ return outcome.message;
747
+ } finally {
748
+ waiting = false;
749
+ cancelTimeout?.();
750
+ unsubscribe();
751
+ buffered.length = 0;
752
+ this.pendingResponseWaits.delete(fail);
753
+ }
754
+ }
755
+ async sendWithCompletion(options, timeout) {
756
+ if (this.completionRpcUnsupported) return void 0;
757
+ if (this.disconnected) throw new Error("Session is disconnected");
758
+ const cancellation = new CancellationTokenSource();
759
+ const dispatched = /* @__PURE__ */ new Set();
760
+ let completionEventId;
761
+ let resolveDispatched;
762
+ const dispatchCompleted = new Promise((resolve) => {
763
+ resolveDispatched = resolve;
764
+ });
765
+ const unsubscribe = this.on((event) => {
766
+ if (event.agentId || event.type !== "session.idle" && event.type !== "session.autopilot_stopped" && event.type !== "session.error") {
767
+ return;
768
+ }
769
+ dispatched.add(event.id);
770
+ if (event.id === completionEventId) resolveDispatched();
771
+ });
772
+ const drain = async (id) => {
773
+ if (id && !dispatched.has(id)) {
774
+ completionEventId = id;
775
+ await dispatchCompleted;
776
+ }
777
+ };
778
+ let fail;
779
+ const stopped = new Promise((_, reject) => {
780
+ fail = reject;
781
+ });
782
+ this.pendingResponseWaits.add(fail);
783
+ const cancelTimeout = setLongTimeout(
784
+ () => fail(new Error(`Timeout after ${timeout}ms waiting for session.idle`)),
785
+ timeout
786
+ );
787
+ const operation = async () => {
788
+ try {
789
+ const message = await this.createSendParams(options);
790
+ if (cancellation.token.isCancellationRequested) {
791
+ throw new Error("Completion wait cancelled");
792
+ }
793
+ const result = await this.connection.sendRequest(
794
+ "session.sendAndWait",
795
+ {
796
+ sessionId: this.sessionId,
797
+ ...message
798
+ },
799
+ cancellation.token
800
+ );
801
+ await drain(result.completionEventId);
802
+ return result;
803
+ } catch (error) {
804
+ if (error instanceof ResponseError && error.code === ErrorCodes.MethodNotFound) {
805
+ this.completionRpcUnsupported = true;
806
+ return void 0;
807
+ }
808
+ if (error instanceof ResponseError && typeof error.data === "object" && error.data !== null) {
809
+ if ("stack" in error.data && typeof error.data.stack === "string") {
810
+ error.stack = error.data.stack;
811
+ }
812
+ if ("completionEventId" in error.data && typeof error.data.completionEventId === "string") {
813
+ await drain(error.data.completionEventId);
814
+ }
815
+ }
816
+ throw error;
817
+ }
818
+ };
819
+ try {
820
+ return await Promise.race([operation(), stopped]);
821
+ } finally {
822
+ cancelTimeout();
823
+ unsubscribe();
824
+ this.pendingResponseWaits.delete(fail);
825
+ resolveDispatched();
826
+ cancellation.cancel();
827
+ cancellation.dispose();
828
+ }
829
+ }
830
+ async sendAndWaitForStructuredMessage(options, timeout) {
831
+ if (this.disconnected) {
832
+ throw new Error("Session is disconnected");
833
+ }
834
+ let resolveOutcome;
835
+ const outcomePromise = new Promise((resolve) => {
836
+ resolveOutcome = resolve;
837
+ });
838
+ const fail = (error) => resolveOutcome({ kind: "error", error });
839
+ let messageId;
840
+ let consumed = false;
841
+ let lastMessage;
842
+ const buffered = [];
843
+ const observe = (event) => {
844
+ if (event.agentId) return;
845
+ if (event.type === "user.message" && event.data.messageId === messageId) {
846
+ consumed = true;
847
+ } else if (event.type === "assistant.message" && event.data.originatingMessageId === messageId) {
848
+ consumed = true;
849
+ lastMessage = event.data.toolRequests?.length ? void 0 : event;
850
+ } else if (consumed && event.type === "session.idle" && event.data.mode !== "autopilot" || event.type === "session.autopilot_stopped" && event.data.requestId === messageId) {
851
+ if (event.type === "session.autopilot_stopped" && event.data.reason === "error") {
852
+ fail(new Error("Autopilot request failed"));
853
+ } else if (event.type === "session.idle" && event.data.aborted || event.type === "session.autopilot_stopped" && event.data.reason === "aborted") {
854
+ fail(
855
+ new Error(
856
+ "The requested run was aborted before a structured result was completed."
857
+ )
858
+ );
859
+ } else {
860
+ resolveOutcome({ kind: "idle", message: lastMessage });
861
+ }
862
+ } else if (event.type === "session.error" && (event.data.originatingMessageId ? event.data.originatingMessageId === messageId : consumed)) {
863
+ const error = Object.assign(new Error(event.data.message), {
864
+ data: {
865
+ ...event.data,
866
+ stack: event.data.stack ?? null,
867
+ completionEventId: event.id
868
+ }
869
+ });
870
+ error.stack = event.data.stack;
871
+ fail(error);
872
+ }
873
+ };
874
+ const unsubscribe = this.on((event) => {
875
+ if (event.type !== "user.message" && event.type !== "assistant.message" && event.type !== "session.idle" && event.type !== "session.autopilot_stopped" && event.type !== "session.error") {
876
+ return;
877
+ }
878
+ if (messageId === void 0) {
879
+ buffered.push(event);
880
+ } else {
881
+ observe(event);
882
+ }
883
+ });
884
+ this.pendingStructuredWaits.add(fail);
885
+ let waiting = true;
886
+ const cancelTimeout = setLongTimeout(
887
+ () => fail(new Error(`Timeout after ${timeout}ms waiting for the structured response`)),
888
+ timeout
889
+ );
890
+ try {
891
+ const sendOutcome = this.sendMessage(options, () => !waiting).then(
892
+ (id) => {
893
+ if (!id) {
894
+ throw new Error(
895
+ "The runtime did not return a message ID for the structured send."
896
+ );
897
+ }
898
+ messageId = id;
899
+ for (const event of buffered) observe(event);
900
+ buffered.length = 0;
901
+ return outcomePromise;
902
+ },
903
+ (error) => ({
904
+ kind: "error",
905
+ error: error instanceof Error ? error : new Error(String(error))
906
+ })
907
+ );
908
+ const outcome = await Promise.race([sendOutcome, outcomePromise]);
909
+ if (outcome.kind === "error") throw outcome.error;
910
+ return outcome.message;
911
+ } finally {
912
+ waiting = false;
913
+ cancelTimeout();
914
+ buffered.length = 0;
915
+ unsubscribe();
916
+ this.pendingStructuredWaits.delete(fail);
917
+ }
918
+ }
919
+ assertConnected() {
920
+ if (this.disconnected) {
921
+ throw new Error("Session is disconnected");
922
+ }
923
+ }
924
+ /** @internal */
925
+ _markDisconnected() {
926
+ if (this.disconnected) {
927
+ return;
928
+ }
929
+ this.disconnected = true;
930
+ this.releaseFromClient = void 0;
931
+ for (const fail of this.pendingResponseWaits) {
932
+ fail(new Error("Session disconnected while waiting for a response"));
933
+ }
934
+ this.pendingResponseWaits.clear();
935
+ for (const fail of this.pendingStructuredWaits) {
936
+ fail(new Error("Session disconnected while waiting for a structured response"));
937
+ }
938
+ this.pendingStructuredWaits.clear();
939
+ for (const controller of this.pendingExternalTools.values()) {
940
+ controller.abort();
941
+ }
942
+ this.pendingExternalTools.clear();
943
+ for (const controller of this.pendingSessionCreations) {
944
+ controller.abort();
945
+ }
946
+ this.pendingSessionCreations.clear();
947
+ this._clearMemoryStore();
948
+ this.eventHandlers.clear();
949
+ this.typedEventHandlers.clear();
950
+ this.toolHandlers.clear();
951
+ this.permissionHandler = void 0;
952
+ this.mcpAuthHandler = void 0;
953
+ this.userInputHandler = void 0;
954
+ this.shellAuthenticationHandler = void 0;
955
+ for (const controller of this.pendingShellAuthenticationRequests.values()) {
956
+ controller.abort();
957
+ }
958
+ this.pendingShellAuthenticationRequests.clear();
959
+ this.elicitationHandler = void 0;
960
+ this.exitPlanModeHandler = void 0;
961
+ this.autoModeSwitchHandler = void 0;
962
+ this.skillProvider = void 0;
963
+ this.sessionCreationHandler = void 0;
964
+ this.memoryStoreHandler = void 0;
965
+ this.hooks = void 0;
966
+ this.traceContextProvider = void 0;
967
+ this.bearerTokenProviders.clear();
968
+ this.commandHandlers.clear();
969
+ this.canvases.clear();
970
+ this.workflows.clear();
971
+ for (const controllersForRun of this.workflowAbortControllers.values()) {
972
+ for (const controller of controllersForRun.values()) {
973
+ controller.abort();
974
+ }
975
+ }
976
+ this.workflowAbortControllers.clear();
977
+ this.transformCallbacks = void 0;
978
+ delete this.clientSessionApis.providerToken;
979
+ delete this.clientSessionApis.canvas;
980
+ delete this.clientSessionApis.workflow;
981
+ delete this.clientSessionApis.sessionFs;
982
+ this._runOnDisconnected();
983
+ }
984
+ /** @internal */
985
+ _runOnDisconnected() {
986
+ const callback = this.onDisconnected;
987
+ this.onDisconnected = void 0;
988
+ callback?.();
989
+ }
990
+ /** @internal */
991
+ _setOnDisconnected(callback) {
992
+ this.assertConnected();
993
+ this.onDisconnected = callback;
994
+ }
995
+ /**
996
+ * @internal Lets the owning client stop tracking this session once `disconnect()`
997
+ * succeeds. Failed create/resume paths unregister the session themselves.
998
+ */
999
+ _setReleaseFromClient(callback) {
1000
+ this.releaseFromClient = callback;
1001
+ }
1002
+ /** @internal */
1003
+ _isDisconnected() {
1004
+ return this.disconnected;
1005
+ }
1006
+ on(eventTypeOrHandler, handler) {
1007
+ if (this.disconnected) {
1008
+ throw new Error("Session is disconnected");
1009
+ }
1010
+ if (typeof eventTypeOrHandler === "string" && handler) {
1011
+ const eventType = eventTypeOrHandler;
1012
+ if (!this.typedEventHandlers.has(eventType)) {
1013
+ this.typedEventHandlers.set(eventType, /* @__PURE__ */ new Set());
1014
+ }
1015
+ const storedHandler = handler;
1016
+ this.typedEventHandlers.get(eventType).add(storedHandler);
1017
+ return () => {
1018
+ const handlers = this.typedEventHandlers.get(eventType);
1019
+ if (handlers) {
1020
+ handlers.delete(storedHandler);
1021
+ }
1022
+ };
1023
+ }
1024
+ const wildcardHandler = eventTypeOrHandler;
1025
+ this.eventHandlers.add(wildcardHandler);
1026
+ return () => {
1027
+ this.eventHandlers.delete(wildcardHandler);
1028
+ };
1029
+ }
1030
+ /**
1031
+ * Dispatches an event to all registered handlers.
1032
+ * Also handles broadcast request events internally (external tool calls, permissions).
1033
+ *
1034
+ * @param event - The session event to dispatch
1035
+ * @internal This method is for internal use by the SDK.
1036
+ */
1037
+ _dispatchEvent(event) {
1038
+ this._handleBroadcastEvent(event);
1039
+ const typedHandlers = this.typedEventHandlers.get(event.type);
1040
+ if (typedHandlers) {
1041
+ for (const handler of typedHandlers) {
1042
+ try {
1043
+ handler(event);
1044
+ } catch (_error) {
1045
+ }
1046
+ }
1047
+ }
1048
+ for (const handler of this.eventHandlers) {
1049
+ try {
1050
+ handler(event);
1051
+ } catch (_error) {
1052
+ }
1053
+ }
1054
+ }
1055
+ /**
1056
+ * Handles broadcast request events by executing local handlers and responding via RPC.
1057
+ * Handlers are dispatched as fire-and-forget — rejections propagate as unhandled promise
1058
+ * rejections, consistent with standard EventEmitter / event handler semantics.
1059
+ * @internal
1060
+ */
1061
+ _handleBroadcastEvent(event) {
1062
+ if (this.disconnected) {
1063
+ return;
1064
+ }
1065
+ if (event.type === "external_tool.requested") {
1066
+ if (event.data.hasHandler === false) {
1067
+ return;
1068
+ }
1069
+ const { requestId, toolName } = event.data;
1070
+ const args = event.data.arguments;
1071
+ const toolCallId = event.data.toolCallId;
1072
+ const traceparent = event.data.traceparent;
1073
+ const tracestate = event.data.tracestate;
1074
+ const handler = this.toolHandlers.get(toolName);
1075
+ if (handler) {
1076
+ void this._executeToolAndRespond(
1077
+ requestId,
1078
+ toolName,
1079
+ toolCallId,
1080
+ args,
1081
+ handler,
1082
+ traceparent,
1083
+ tracestate,
1084
+ event.agentId || void 0
1085
+ );
1086
+ }
1087
+ } else if (event.type === "external_tool.completed") {
1088
+ const { requestId } = event.data;
1089
+ if (requestId) {
1090
+ const controller = this.pendingExternalTools.get(requestId);
1091
+ if (controller) {
1092
+ this.pendingExternalTools.delete(requestId);
1093
+ controller.abort();
1094
+ }
1095
+ }
1096
+ } else if (event.type === "permission.requested") {
1097
+ const {
1098
+ requestId,
1099
+ permissionRequest,
1100
+ promptRequest,
1101
+ assistedApprovalAssessment,
1102
+ resolvedByHook,
1103
+ programToolCallId
1104
+ } = event.data;
1105
+ if (resolvedByHook) {
1106
+ return;
1107
+ }
1108
+ if (this.permissionHandler) {
1109
+ void this._executePermissionAndRespond(
1110
+ requestId,
1111
+ permissionRequest,
1112
+ promptRequest,
1113
+ assistedApprovalAssessment,
1114
+ programToolCallId
1115
+ );
1116
+ }
1117
+ } else if (event.type === "mcp.oauth_required") {
1118
+ const data = event.data;
1119
+ if (!data?.requestId) {
1120
+ return;
1121
+ }
1122
+ if (!this.mcpAuthHandler) {
1123
+ console.warn(
1124
+ `Received MCP OAuth request without a registered MCP auth handler. SessionId=${this.sessionId}, RequestId=${data.requestId}`
1125
+ );
1126
+ return;
1127
+ }
1128
+ void this._executeMcpAuthAndRespond(data);
1129
+ } else if (event.type === "command.execute") {
1130
+ const { requestId, commandName, command, args } = event.data;
1131
+ void this._executeCommandAndRespond(requestId, commandName, command, args);
1132
+ } else if (event.type === "elicitation.requested") {
1133
+ if (this.elicitationHandler) {
1134
+ const { message, requestedSchema, mode, elicitationSource, url, requestId } = event.data;
1135
+ void this._handleElicitationRequest(
1136
+ {
1137
+ sessionId: this.sessionId,
1138
+ message,
1139
+ requestedSchema,
1140
+ mode,
1141
+ elicitationSource,
1142
+ url
1143
+ },
1144
+ requestId
1145
+ );
1146
+ }
1147
+ } else if (event.type === "capabilities.changed") {
1148
+ const { ui, ...changed } = event.data;
1149
+ this._capabilities = { ...this._capabilities, ...changed };
1150
+ if (ui) {
1151
+ this._capabilities.ui = { ...this._capabilities.ui, ...ui };
1152
+ }
1153
+ } else if (event.type === "session.canvas.opened") {
1154
+ this.upsertOpenCanvasFromEvent(event.data);
1155
+ } else if (event.type === "session.canvas.closed") {
1156
+ this.removeOpenCanvasFromEvent(event.data);
1157
+ }
1158
+ }
1159
+ upsertOpenCanvasFromEvent(data) {
1160
+ if (!isOpenCanvasInstance(data)) {
1161
+ console.warn("failed to deserialize session.canvas.opened payload");
1162
+ return;
1163
+ }
1164
+ this.upsertOpenCanvas(data);
1165
+ }
1166
+ removeOpenCanvasFromEvent(data) {
1167
+ if (!data || typeof data !== "object" || typeof data.instanceId !== "string" || data.instanceId.length === 0) {
1168
+ console.warn("failed to deserialize session.canvas.closed payload");
1169
+ return;
1170
+ }
1171
+ this.removeOpenCanvas(data.instanceId);
1172
+ }
1173
+ removeOpenCanvas(instanceId) {
1174
+ this.openCanvasInstances = this.openCanvasInstances.filter(
1175
+ (open) => open.instanceId !== instanceId
1176
+ );
1177
+ }
1178
+ upsertOpenCanvas(instance) {
1179
+ const index = this.openCanvasInstances.findIndex(
1180
+ (open) => open.instanceId === instance.instanceId
1181
+ );
1182
+ if (index >= 0) {
1183
+ this.openCanvasInstances[index] = instance;
1184
+ } else {
1185
+ this.openCanvasInstances.push(instance);
1186
+ }
1187
+ }
1188
+ /**
1189
+ * Executes a tool handler and sends the result back via RPC.
1190
+ * @internal
1191
+ */
1192
+ async _executeToolAndRespond(requestId, toolName, toolCallId, args, handler, traceparent, tracestate, agentId) {
1193
+ const controller = new AbortController();
1194
+ if (this.disconnected || this.pendingExternalTools.has(requestId)) {
1195
+ return;
1196
+ }
1197
+ this.pendingExternalTools.set(requestId, controller);
1198
+ let claimed = false;
1199
+ try {
1200
+ let availableTools;
1201
+ if (toolName === TOOL_SEARCH_TOOL_NAME) {
1202
+ if (controller.signal.aborted) {
1203
+ return;
1204
+ }
1205
+ const aborted = new Promise((resolve) => {
1206
+ controller.signal.addEventListener("abort", () => resolve(void 0), {
1207
+ once: true
1208
+ });
1209
+ });
1210
+ try {
1211
+ const metadata = await Promise.race([
1212
+ this.rpc.tools.getCurrentMetadata(),
1213
+ aborted
1214
+ ]);
1215
+ availableTools = metadata?.tools ?? void 0;
1216
+ } catch {
1217
+ availableTools = void 0;
1218
+ }
1219
+ }
1220
+ if (controller.signal.aborted) {
1221
+ return;
1222
+ }
1223
+ const rawResult = await handler(args, {
1224
+ sessionId: this.sessionId,
1225
+ toolCallId,
1226
+ toolName,
1227
+ arguments: args,
1228
+ availableTools,
1229
+ traceparent,
1230
+ tracestate,
1231
+ signal: controller.signal,
1232
+ agentId,
1233
+ requestId
1234
+ });
1235
+ let result;
1236
+ if (rawResult == null) {
1237
+ result = "";
1238
+ } else if (typeof rawResult === "string") {
1239
+ result = rawResult;
1240
+ } else if (isToolResultObject(rawResult)) {
1241
+ try {
1242
+ JSON.stringify(rawResult.toolTelemetry);
1243
+ } catch (error) {
1244
+ const message = error instanceof Error ? error.message : String(error);
1245
+ throw new Error(`failed to serialize tool telemetry: ${message}`);
1246
+ }
1247
+ JSON.stringify(rawResult);
1248
+ result = rawResult;
1249
+ } else {
1250
+ result = JSON.stringify(rawResult);
1251
+ }
1252
+ if (!this._claimExternalTool(requestId, controller)) {
1253
+ return;
1254
+ }
1255
+ claimed = true;
1256
+ await this.rpc.tools.handlePendingToolCall({ requestId, result });
1257
+ } catch (error) {
1258
+ if (claimed) {
1259
+ if (this.disconnected) {
1260
+ return;
1261
+ }
1262
+ console.error("External tool result delivery failed", {
1263
+ sessionId: this.sessionId,
1264
+ requestId,
1265
+ toolName,
1266
+ error
1267
+ });
1268
+ } else if (!this._claimExternalTool(requestId, controller)) {
1269
+ return;
1270
+ }
1271
+ let message = error instanceof Error ? error.message : String(error);
1272
+ if (!message) {
1273
+ message = error instanceof Error && error.name || "Error";
1274
+ }
1275
+ for (let attempt = 0; attempt < (claimed ? 1 : 2); attempt++) {
1276
+ try {
1277
+ await this.rpc.tools.handlePendingToolCall({ requestId, error: message });
1278
+ return;
1279
+ } catch (rpcError) {
1280
+ const retryable = !claimed && attempt === 0 && !this.disconnected;
1281
+ if (!retryable) {
1282
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1283
+ throw rpcError;
1284
+ }
1285
+ return;
1286
+ }
1287
+ console.error("External tool error delivery failed", {
1288
+ sessionId: this.sessionId,
1289
+ requestId,
1290
+ toolName,
1291
+ error: rpcError
1292
+ });
1293
+ message = (rpcError instanceof Error ? rpcError.message || rpcError.name : "") || String(rpcError) || "Error";
1294
+ }
1295
+ }
1296
+ } finally {
1297
+ if (this.pendingExternalTools.get(requestId) === controller) {
1298
+ this.pendingExternalTools.delete(requestId);
1299
+ }
1300
+ controller.abort();
1301
+ }
1302
+ }
1303
+ _claimExternalTool(requestId, controller) {
1304
+ if (this.disconnected || this.pendingExternalTools.get(requestId) !== controller) {
1305
+ return false;
1306
+ }
1307
+ this.pendingExternalTools.delete(requestId);
1308
+ return true;
1309
+ }
1310
+ /**
1311
+ * Executes a permission handler and sends the result back via RPC.
1312
+ * @internal
1313
+ */
1314
+ async _executePermissionAndRespond(requestId, permissionRequest, promptRequest, assistedApprovalAssessment, programToolCallId) {
1315
+ try {
1316
+ const invocation = {
1317
+ sessionId: this.sessionId,
1318
+ managedSettingsEnabled: this.managedSettingsEnabled,
1319
+ ...promptRequest === void 0 ? {} : { promptRequest },
1320
+ ...assistedApprovalAssessment === void 0 ? {} : { assistedApprovalAssessment },
1321
+ ...programToolCallId === void 0 ? {} : { programToolCallId }
1322
+ };
1323
+ const handlerResult = await this.permissionHandler(permissionRequest, invocation);
1324
+ const isAttributed = isAttributedPermissionResult(handlerResult);
1325
+ const result = isAttributed ? handlerResult.result : handlerResult;
1326
+ const decisionContext = isAttributed ? handlerResult.decisionContext : void 0;
1327
+ if (result.kind === "no-result") {
1328
+ return;
1329
+ }
1330
+ if (this.disconnected) {
1331
+ return;
1332
+ }
1333
+ await this.rpc.permissions.handlePendingPermissionRequest(
1334
+ decisionContext === void 0 ? { requestId, result } : { requestId, result, decisionContext }
1335
+ );
1336
+ } catch (error) {
1337
+ if (this.disconnected) {
1338
+ return;
1339
+ }
1340
+ console.error("Permission handler or response delivery failed", {
1341
+ sessionId: this.sessionId,
1342
+ requestId,
1343
+ error
1344
+ });
1345
+ try {
1346
+ await this.rpc.permissions.handlePendingPermissionRequest({
1347
+ requestId,
1348
+ result: {
1349
+ kind: "user-not-available"
1350
+ }
1351
+ });
1352
+ } catch (rpcError) {
1353
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1354
+ throw rpcError;
1355
+ }
1356
+ }
1357
+ }
1358
+ }
1359
+ /**
1360
+ * Executes an MCP auth handler and sends the result back via RPC.
1361
+ * @internal
1362
+ */
1363
+ async _executeMcpAuthAndRespond(request) {
1364
+ try {
1365
+ const result = await this.mcpAuthHandler(request, { sessionId: this.sessionId });
1366
+ const response = result && "kind" in result && result.kind === "cancelled" ? { kind: "cancelled" } : result && "accessToken" in result && typeof result.accessToken === "string" && result.accessToken.length > 0 ? { ...result, kind: "token" } : result && "kind" in result && result.kind === "runtimeRefresh" && request.runtimeRefreshSupported === true ? { kind: "runtimeRefresh" } : { kind: "cancelled" };
1367
+ await this.rpc.mcp.oauth.handlePendingRequest({
1368
+ requestId: request.requestId,
1369
+ result: response
1370
+ });
1371
+ } catch (_error) {
1372
+ try {
1373
+ await this.rpc.mcp.oauth.handlePendingRequest({
1374
+ requestId: request.requestId,
1375
+ result: { kind: "cancelled" }
1376
+ });
1377
+ } catch (rpcError) {
1378
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1379
+ throw rpcError;
1380
+ }
1381
+ }
1382
+ }
1383
+ }
1384
+ /**
1385
+ * Executes a command handler and sends the result back via RPC.
1386
+ * @internal
1387
+ */
1388
+ async _executeCommandAndRespond(requestId, commandName, command, args) {
1389
+ const handler = this.commandHandlers.get(commandName);
1390
+ if (!handler) {
1391
+ try {
1392
+ await this.rpc.commands.handlePendingCommand({
1393
+ requestId,
1394
+ error: `Unknown command: ${commandName}`
1395
+ });
1396
+ } catch (rpcError) {
1397
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1398
+ throw rpcError;
1399
+ }
1400
+ }
1401
+ return;
1402
+ }
1403
+ try {
1404
+ await handler({ sessionId: this.sessionId, command, commandName, args });
1405
+ if (this.disconnected) {
1406
+ return;
1407
+ }
1408
+ await this.rpc.commands.handlePendingCommand({ requestId });
1409
+ } catch (error) {
1410
+ if (this.disconnected) {
1411
+ return;
1412
+ }
1413
+ const message = error instanceof Error ? error.message : String(error);
1414
+ try {
1415
+ await this.rpc.commands.handlePendingCommand({ requestId, error: message });
1416
+ } catch (rpcError) {
1417
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1418
+ throw rpcError;
1419
+ }
1420
+ }
1421
+ }
1422
+ }
1423
+ /**
1424
+ * Registers custom tool handlers for this session.
1425
+ *
1426
+ * Tools with handlers allow the assistant to execute custom functions automatically.
1427
+ * Declaration-only tools are surfaced as events and left pending for the consumer.
1428
+ *
1429
+ * @param tools - An array of tool definitions with their handlers, or undefined to clear all tools
1430
+ * @internal This method is typically called internally when creating a session with tools.
1431
+ */
1432
+ registerTools(tools) {
1433
+ this.assertConnected();
1434
+ this.toolHandlers.clear();
1435
+ if (!tools) {
1436
+ return;
1437
+ }
1438
+ for (const tool of tools) {
1439
+ if (tool.handler) {
1440
+ const handler = tool.handler;
1441
+ if (tool.name === "apply_patch" && tool.overridesBuiltInTool && toJsonSchema(tool.parameters)?.type === "string") {
1442
+ this.toolHandlers.set(tool.name, (args, invocation) => {
1443
+ if (typeof args === "string") {
1444
+ return handler(args, invocation);
1445
+ }
1446
+ if (typeof args === "object" && args !== null && "input" in args && typeof args.input === "string") {
1447
+ return handler(args.input, invocation);
1448
+ }
1449
+ throw new TypeError("apply_patch string override requires a string input");
1450
+ });
1451
+ } else {
1452
+ this.toolHandlers.set(tool.name, handler);
1453
+ }
1454
+ }
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Retrieves a registered tool handler by name.
1459
+ *
1460
+ * @param name - The name of the tool to retrieve
1461
+ * @returns The tool handler if found, or undefined
1462
+ * @internal This method is for internal use by the SDK.
1463
+ */
1464
+ getToolHandler(name) {
1465
+ return this.toolHandlers.get(name);
1466
+ }
1467
+ /**
1468
+ * Registers canvas declarations and handlers for this session.
1469
+ *
1470
+ * @param canvases - Canvases created via `createCanvas`, or undefined to clear all canvases
1471
+ * @internal Called by the SDK when creating/resuming a session with `canvases`.
1472
+ */
1473
+ registerCanvases(canvases) {
1474
+ this.assertConnected();
1475
+ this.canvases.clear();
1476
+ if (!canvases || canvases.length === 0) {
1477
+ delete this.clientSessionApis.canvas;
1478
+ return;
1479
+ }
1480
+ for (const canvas of canvases) {
1481
+ this.canvases.set(canvas.declaration.id, canvas);
1482
+ }
1483
+ const self = this;
1484
+ this.clientSessionApis.canvas = {
1485
+ async open(params) {
1486
+ const canvas = self.canvases.get(params.canvasId);
1487
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
1488
+ try {
1489
+ return await canvas.open(params) ?? {};
1490
+ } catch (error) {
1491
+ throw toCanvasRpcError(error);
1492
+ }
1493
+ },
1494
+ async close(params) {
1495
+ const canvas = self.canvases.get(params.canvasId);
1496
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
1497
+ try {
1498
+ if (canvas.onClose) {
1499
+ await canvas.onClose(params);
1500
+ }
1501
+ } catch (error) {
1502
+ throw toCanvasRpcError(error);
1503
+ }
1504
+ },
1505
+ async invoke(params) {
1506
+ const canvas = self.canvases.get(params.canvasId);
1507
+ if (!canvas) throw new Error(`No canvas registered with id "${params.canvasId}"`);
1508
+ const handler = canvas.actionHandlers.get(params.actionName);
1509
+ if (!handler) {
1510
+ throw new CanvasError(
1511
+ "canvas_action_no_handler",
1512
+ "No handler implemented for this canvas action"
1513
+ );
1514
+ }
1515
+ try {
1516
+ return await handler(params);
1517
+ } catch (error) {
1518
+ throw toCanvasRpcError(error);
1519
+ }
1520
+ }
1521
+ };
1522
+ }
1523
+ /**
1524
+ * Registers workflow closures and reverse-RPC handlers for this session.
1525
+ *
1526
+ * @param workflows - Workflow handles declared by the joining extension.
1527
+ * @internal Called by the SDK when an extension joins a session.
1528
+ */
1529
+ registerWorkflows(workflows) {
1530
+ this.assertConnected();
1531
+ this.workflows.clear();
1532
+ if (!workflows || workflows.length === 0) {
1533
+ delete this.clientSessionApis.workflow;
1534
+ return;
1535
+ }
1536
+ for (const handle of workflows) {
1537
+ const definition = getWorkflowDefinition(handle);
1538
+ if (this.workflows.has(definition.meta.name)) {
1539
+ throw new Error(
1540
+ `Duplicate workflow name "${definition.meta.name}". Workflow names must be unique within a joinSession call.`
1541
+ );
1542
+ }
1543
+ this.workflows.set(definition.meta.name, definition);
1544
+ }
1545
+ const self = this;
1546
+ this.clientSessionApis.workflow = {
1547
+ async execute(params) {
1548
+ const definition = self.workflows.get(params.name);
1549
+ if (!definition) {
1550
+ const message = `No workflow registered with name "${params.name}"`;
1551
+ throw new ResponseError(ErrorCodes.InvalidParams, message, {
1552
+ code: "workflow_not_found",
1553
+ name: params.name
1554
+ });
1555
+ }
1556
+ const controller = new AbortController();
1557
+ let controllersForRun = self.workflowAbortControllers.get(params.runId);
1558
+ if (controllersForRun === void 0) {
1559
+ controllersForRun = /* @__PURE__ */ new Map();
1560
+ self.workflowAbortControllers.set(params.runId, controllersForRun);
1561
+ }
1562
+ controllersForRun.set(params.executionToken, controller);
1563
+ const progress = new WorkflowProgressBuffer(async (lines) => {
1564
+ await self.rpc.workflow.log({
1565
+ runId: params.runId,
1566
+ executionToken: params.executionToken,
1567
+ lines
1568
+ });
1569
+ });
1570
+ try {
1571
+ const context = {
1572
+ runId: params.runId,
1573
+ agents: definition.agents,
1574
+ args: params.args,
1575
+ session: self,
1576
+ signal: controller.signal,
1577
+ phase: (title) => {
1578
+ throwIfWorkflowAborted(controller.signal);
1579
+ progress.enqueue("phase", title);
1580
+ },
1581
+ log: (message) => {
1582
+ throwIfWorkflowAborted(controller.signal);
1583
+ progress.enqueue("log", message);
1584
+ },
1585
+ agent: async (prompt, options = {}) => {
1586
+ await progress.flush();
1587
+ const opts = {};
1588
+ for (const key of WORKFLOW_AGENT_OPTION_KEYS) {
1589
+ if (key === "agent") {
1590
+ if (typeof options.agent === "string") {
1591
+ opts.agent = options.agent;
1592
+ } else if (options.agent !== void 0) {
1593
+ opts.role = getWorkflowAgentReference(
1594
+ definition,
1595
+ options.agent
1596
+ );
1597
+ }
1598
+ } else {
1599
+ copyDefinedWorkflowAgentOption(options, opts, key);
1600
+ }
1601
+ }
1602
+ const response = await awaitWorkflowOperation(
1603
+ () => self.rpc.workflow.agent({
1604
+ workflowRunId: params.runId,
1605
+ executionToken: params.executionToken,
1606
+ prompt,
1607
+ opts
1608
+ }),
1609
+ controller.signal
1610
+ );
1611
+ return response.result ?? null;
1612
+ },
1613
+ step: async (key, producer, options = {}) => {
1614
+ await progress.flush();
1615
+ if (options.volatile) {
1616
+ throwIfWorkflowAborted(controller.signal);
1617
+ return producer();
1618
+ }
1619
+ const cached = await awaitWorkflowOperation(
1620
+ () => self.rpc.workflow.journal.get({
1621
+ runId: params.runId,
1622
+ executionToken: params.executionToken,
1623
+ key
1624
+ }),
1625
+ controller.signal
1626
+ );
1627
+ if (cached.hit) {
1628
+ if (cached.resultJson === void 0) {
1629
+ throw new Error(
1630
+ `step("${key}") journal returned a hit without a result`
1631
+ );
1632
+ }
1633
+ assertWorkflowStepResult(cached.resultJson, key);
1634
+ return cached.resultJson;
1635
+ }
1636
+ const result2 = await producer();
1637
+ assertWorkflowStepResult(result2, key);
1638
+ await awaitWorkflowOperation(
1639
+ () => self.rpc.workflow.journal.put({
1640
+ runId: params.runId,
1641
+ executionToken: params.executionToken,
1642
+ key,
1643
+ resultJson: result2
1644
+ }),
1645
+ controller.signal
1646
+ );
1647
+ return result2;
1648
+ },
1649
+ pause: async (key) => {
1650
+ if (typeof key !== "string" || key.length === 0) {
1651
+ throw new Error("Workflow pause checkpoint key must not be empty");
1652
+ }
1653
+ const helperScope = workflowExecutionStore.getStore()?.helperScope;
1654
+ if (helperScope !== void 0) {
1655
+ throw new Error(
1656
+ `Workflow pause checkpoints are not allowed inside ${helperScope}() branches`
1657
+ );
1658
+ }
1659
+ await progress.flush();
1660
+ const response = await awaitWorkflowOperation(
1661
+ () => self.internalRpc.workflow.pauseAtCheckpoint({
1662
+ runId: params.runId,
1663
+ executionToken: params.executionToken,
1664
+ key
1665
+ }),
1666
+ controller.signal
1667
+ );
1668
+ switch (response.action) {
1669
+ case "continue":
1670
+ return;
1671
+ case "pause":
1672
+ await awaitWorkflowOperation(
1673
+ () => new Promise(() => {
1674
+ }),
1675
+ controller.signal
1676
+ );
1677
+ }
1678
+ },
1679
+ parallel: runWorkflowParallel,
1680
+ pipeline: runWorkflowPipeline,
1681
+ workflow: async () => {
1682
+ throw new Error("nested workflows are not supported");
1683
+ }
1684
+ };
1685
+ const execution = { active: true };
1686
+ const result = await workflowExecutionStore.run(execution, async () => {
1687
+ try {
1688
+ return await definition.run(context);
1689
+ } finally {
1690
+ execution.active = false;
1691
+ }
1692
+ });
1693
+ if (result === void 0) {
1694
+ return {};
1695
+ }
1696
+ assertWorkflowResult(result);
1697
+ return { result };
1698
+ } finally {
1699
+ controller.abort(new DOMException("Workflow run has settled", "AbortError"));
1700
+ try {
1701
+ await progress.close();
1702
+ } finally {
1703
+ const controllersForRun2 = self.workflowAbortControllers.get(params.runId);
1704
+ if (controllersForRun2?.get(params.executionToken) === controller) {
1705
+ controllersForRun2.delete(params.executionToken);
1706
+ if (controllersForRun2.size === 0) {
1707
+ self.workflowAbortControllers.delete(params.runId);
1708
+ }
1709
+ }
1710
+ }
1711
+ }
1712
+ },
1713
+ async abort(params) {
1714
+ const controllersForRun = self.workflowAbortControllers.get(params.runId);
1715
+ const controller = controllersForRun?.get(params.executionToken);
1716
+ if (controller !== void 0) {
1717
+ controller.abort(new DOMException("Workflow run was aborted", "AbortError"));
1718
+ }
1719
+ return {};
1720
+ }
1721
+ };
1722
+ }
1723
+ /**
1724
+ * Registers per-provider {@link BearerTokenProvider} callbacks for BYOK providers
1725
+ * configured with managed-identity / on-demand bearer-token auth.
1726
+ *
1727
+ * The runtime never receives the callback itself; the SDK strips it from the
1728
+ * provider config and instead sends `hasBearerTokenProvider: true`. When the
1729
+ * runtime needs a token it issues a session-scoped `providerToken.getToken`
1730
+ * request, which this handler routes to the matching per-provider callback.
1731
+ *
1732
+ * @param providers - Map of provider name → callback, or undefined/empty to clear.
1733
+ * @internal This method is called internally when creating/resuming a session.
1734
+ */
1735
+ registerBearerTokenProviders(providers) {
1736
+ this.assertConnected();
1737
+ this.bearerTokenProviders.clear();
1738
+ if (!providers || providers.size === 0) {
1739
+ delete this.clientSessionApis.providerToken;
1740
+ return;
1741
+ }
1742
+ for (const [name, callback] of providers) {
1743
+ this.bearerTokenProviders.set(name, callback);
1744
+ }
1745
+ const self = this;
1746
+ this.clientSessionApis.providerToken = {
1747
+ async getToken(params) {
1748
+ self.assertConnected();
1749
+ const callback = self.bearerTokenProviders.get(params.providerName);
1750
+ if (!callback) {
1751
+ throw new Error(
1752
+ `No bearer-token provider registered for provider "${params.providerName}"`
1753
+ );
1754
+ }
1755
+ const token = await callback({
1756
+ providerName: params.providerName,
1757
+ sessionId: params.sessionId
1758
+ });
1759
+ return { token };
1760
+ }
1761
+ };
1762
+ }
1763
+ /**
1764
+ * Registers command handlers for this session.
1765
+ *
1766
+ * @param commands - An array of command definitions with handlers, or undefined to clear
1767
+ * @internal This method is typically called internally when creating/resuming a session.
1768
+ */
1769
+ registerCommands(commands) {
1770
+ this.assertConnected();
1771
+ this.commandHandlers.clear();
1772
+ if (!commands) {
1773
+ return;
1774
+ }
1775
+ for (const cmd of commands) {
1776
+ this.commandHandlers.set(cmd.name, cmd.handler);
1777
+ }
1778
+ }
1779
+ /**
1780
+ * Registers the elicitation handler for this session.
1781
+ *
1782
+ * @param handler - The handler to invoke when the server dispatches an elicitation request
1783
+ * @internal This method is typically called internally when creating/resuming a session.
1784
+ */
1785
+ registerElicitationHandler(handler) {
1786
+ this.assertConnected();
1787
+ this.elicitationHandler = handler;
1788
+ }
1789
+ /**
1790
+ * Registers the exit-plan-mode handler for this session.
1791
+ *
1792
+ * @param handler - The handler to invoke when the server dispatches an exit-plan-mode request
1793
+ * @internal This method is typically called internally when creating/resuming a session.
1794
+ */
1795
+ registerExitPlanModeHandler(handler) {
1796
+ this.assertConnected();
1797
+ this.exitPlanModeHandler = handler;
1798
+ }
1799
+ /**
1800
+ * Registers the auto-mode-switch handler for this session.
1801
+ *
1802
+ * @param handler - The handler to invoke when the server dispatches an auto-mode-switch request
1803
+ * @internal This method is typically called internally when creating/resuming a session.
1804
+ */
1805
+ registerAutoModeSwitchHandler(handler) {
1806
+ this.assertConnected();
1807
+ this.autoModeSwitchHandler = handler;
1808
+ }
1809
+ /**
1810
+ * Handles an elicitation.requested broadcast event.
1811
+ * Invokes the registered handler and responds via handlePendingElicitation RPC.
1812
+ * @internal
1813
+ */
1814
+ async _handleElicitationRequest(context, requestId) {
1815
+ if (!this.elicitationHandler) {
1816
+ return;
1817
+ }
1818
+ try {
1819
+ const result = await this.elicitationHandler(context);
1820
+ await this.rpc.ui.handlePendingElicitation({
1821
+ requestId,
1822
+ result: {
1823
+ action: result.action,
1824
+ ...result.content ? { content: result.content } : {}
1825
+ },
1826
+ ...result.decisionContext !== void 0 ? { decisionContext: result.decisionContext } : {}
1827
+ });
1828
+ } catch {
1829
+ try {
1830
+ await this.rpc.ui.handlePendingElicitation({
1831
+ requestId,
1832
+ result: { action: "cancel" }
1833
+ });
1834
+ } catch (rpcError) {
1835
+ if (!(rpcError instanceof ConnectionError || rpcError instanceof ResponseError)) {
1836
+ throw rpcError;
1837
+ }
1838
+ }
1839
+ }
1840
+ }
1841
+ /**
1842
+ * Handles an exitPlanMode.request callback from the runtime.
1843
+ * @internal
1844
+ */
1845
+ async _handleExitPlanModeRequest(request) {
1846
+ this.assertConnected();
1847
+ if (!this.exitPlanModeHandler) {
1848
+ return { approved: true };
1849
+ }
1850
+ return await this.exitPlanModeHandler(request, { sessionId: this.sessionId });
1851
+ }
1852
+ /**
1853
+ * Handles an autoModeSwitch.request callback from the runtime.
1854
+ * @internal
1855
+ */
1856
+ async _handleAutoModeSwitchRequest(request) {
1857
+ this.assertConnected();
1858
+ if (!this.autoModeSwitchHandler) {
1859
+ return "no";
1860
+ }
1861
+ return await this.autoModeSwitchHandler(request, { sessionId: this.sessionId });
1862
+ }
1863
+ /**
1864
+ * Sets the host capabilities for this session.
1865
+ *
1866
+ * @param capabilities - The capabilities object from the create/resume response
1867
+ * @internal This method is typically called internally when creating/resuming a session.
1868
+ */
1869
+ setCapabilities(capabilities) {
1870
+ this._capabilities = capabilities ?? {};
1871
+ }
1872
+ /**
1873
+ * Snapshot of canvas instances currently known to be open for this session.
1874
+ * Populated from the `session.resume` response and live `session.canvas.opened`
1875
+ * and `session.canvas.closed` events. Returns a defensive copy — mutating the
1876
+ * returned array has no effect on the session.
1877
+ */
1878
+ get openCanvases() {
1879
+ return [...this.openCanvasInstances];
1880
+ }
1881
+ /**
1882
+ * Sets the open-canvas snapshot for this session.
1883
+ *
1884
+ * @param instances - The `openCanvases` array from the `session.resume` response.
1885
+ * @internal This method is typically called internally when resuming a session.
1886
+ */
1887
+ setOpenCanvases(instances) {
1888
+ this.openCanvasInstances = [...instances];
1889
+ }
1890
+ assertElicitation() {
1891
+ if (!this._capabilities.ui?.elicitation) {
1892
+ throw new Error(
1893
+ "Elicitation is not supported by the host. Check session.capabilities.ui?.elicitation before calling UI methods."
1894
+ );
1895
+ }
1896
+ }
1897
+ async _elicitation(params) {
1898
+ this.assertElicitation();
1899
+ return this.rpc.ui.elicitation({
1900
+ message: params.message,
1901
+ requestedSchema: params.requestedSchema
1902
+ });
1903
+ }
1904
+ async _confirm(message) {
1905
+ this.assertElicitation();
1906
+ const result = await this.rpc.ui.elicitation({
1907
+ message,
1908
+ requestedSchema: {
1909
+ type: "object",
1910
+ properties: {
1911
+ confirmed: { type: "boolean", default: true }
1912
+ },
1913
+ required: ["confirmed"]
1914
+ }
1915
+ });
1916
+ return result.action === "accept" && result.content?.confirmed === true;
1917
+ }
1918
+ async _select(message, options) {
1919
+ this.assertElicitation();
1920
+ const result = await this.rpc.ui.elicitation({
1921
+ message,
1922
+ requestedSchema: {
1923
+ type: "object",
1924
+ properties: {
1925
+ selection: { type: "string", enum: options }
1926
+ },
1927
+ required: ["selection"]
1928
+ }
1929
+ });
1930
+ if (result.action === "accept" && result.content?.selection != null) {
1931
+ return result.content.selection;
1932
+ }
1933
+ return null;
1934
+ }
1935
+ async _input(message, options) {
1936
+ this.assertElicitation();
1937
+ const field = { type: "string" };
1938
+ if (options?.title) field.title = options.title;
1939
+ if (options?.description) field.description = options.description;
1940
+ if (options?.minLength != null) field.minLength = options.minLength;
1941
+ if (options?.maxLength != null) field.maxLength = options.maxLength;
1942
+ if (options?.format) field.format = options.format;
1943
+ if (options?.default != null) field.default = options.default;
1944
+ const result = await this.rpc.ui.elicitation({
1945
+ message,
1946
+ requestedSchema: {
1947
+ type: "object",
1948
+ properties: {
1949
+ value: field
1950
+ },
1951
+ required: ["value"]
1952
+ }
1953
+ });
1954
+ if (result.action === "accept" && result.content?.value != null) {
1955
+ return result.content.value;
1956
+ }
1957
+ return null;
1958
+ }
1959
+ /**
1960
+ * Registers a handler for permission requests.
1961
+ *
1962
+ * When the assistant needs permission to perform certain actions (e.g., file operations),
1963
+ * this handler is called to approve or deny the request.
1964
+ *
1965
+ * @param handler - The permission handler function, or undefined to remove the handler
1966
+ * @internal This method is typically called internally when creating a session.
1967
+ */
1968
+ registerPermissionHandler(handler) {
1969
+ this.assertConnected();
1970
+ this.permissionHandler = handler;
1971
+ }
1972
+ /**
1973
+ * Registers a user input handler for ask_user requests.
1974
+ *
1975
+ * When the agent needs input from the user (via ask_user tool),
1976
+ * this handler is called to provide the response.
1977
+ *
1978
+ * @param handler - The user input handler function, or undefined to remove the handler
1979
+ * @internal This method is typically called internally when creating a session.
1980
+ */
1981
+ registerUserInputHandler(handler) {
1982
+ this.assertConnected();
1983
+ this.userInputHandler = handler;
1984
+ }
1985
+ /**
1986
+ * Registers the handler for passwords and other answers that shell
1987
+ * commands run by the agent ask for.
1988
+ *
1989
+ * @param handler - The shell authentication handler, or undefined to remove it
1990
+ * @internal This method is typically called internally when creating a session.
1991
+ */
1992
+ registerShellAuthenticationHandler(handler) {
1993
+ this.assertConnected();
1994
+ this.shellAuthenticationHandler = handler;
1995
+ }
1996
+ /**
1997
+ * Registers the session's skill provider.
1998
+ *
1999
+ * @param provider - The skill provider, or undefined to remove it
2000
+ * @internal This method is typically called internally when creating a session.
2001
+ */
2002
+ registerSkillProvider(provider) {
2003
+ this.assertConnected();
2004
+ this.skillProvider = provider;
2005
+ }
2006
+ /**
2007
+ * Registers the host's creation callback without enabling the tool group.
2008
+ * Enable it separately with `session.rpc.management.configure({ enabled: true })`.
2009
+ */
2010
+ async setSessionCreationHandler(handler) {
2011
+ this.assertConnected();
2012
+ const previous = this.sessionCreationHandler;
2013
+ this.sessionCreationHandler = handler;
2014
+ try {
2015
+ return await this.rpc.management.configure({ hasCreateHandler: handler !== void 0 });
2016
+ } catch (error) {
2017
+ if (this.sessionCreationHandler === handler) this.sessionCreationHandler = previous;
2018
+ throw error;
2019
+ }
2020
+ }
2021
+ /**
2022
+ * Registers the callback the runtime calls through `memoryStore.store`.
2023
+ * Registered before create or resume declares `hasMemoryStore`.
2024
+ * @internal
2025
+ */
2026
+ _registerMemoryStore(handler) {
2027
+ this.assertConnected();
2028
+ this.memoryStoreHandler = handler;
2029
+ }
2030
+ /** @internal */
2031
+ _clearMemoryStore() {
2032
+ this.memoryStoreHandler = void 0;
2033
+ }
2034
+ /** @internal */
2035
+ async _handleMemoryStore(memory, signal) {
2036
+ this.assertConnected();
2037
+ const handler = this.memoryStoreHandler;
2038
+ if (!handler) throw new Error("No memory store is registered");
2039
+ try {
2040
+ await handler(
2041
+ {
2042
+ sessionId: memory.sessionId,
2043
+ subject: memory.subject,
2044
+ fact: memory.fact,
2045
+ citations: memory.citations,
2046
+ reason: memory.reason
2047
+ },
2048
+ { signal }
2049
+ );
2050
+ } catch (error) {
2051
+ if (signal.aborted) {
2052
+ throw new ResponseError(-32800, "Memory store call cancelled");
2053
+ }
2054
+ console.warn("Memory store callback failed", error);
2055
+ throw new Error("Memory store callback failed");
2056
+ }
2057
+ }
2058
+ /** @internal */
2059
+ async _handleSessionManagementCreate(request, token) {
2060
+ this.assertConnected();
2061
+ const handler = this.sessionCreationHandler;
2062
+ if (!handler || request.parentSessionId !== this.sessionId || request.sessionId !== this.sessionId) {
2063
+ throw new Error("Session creation handler is unavailable");
2064
+ }
2065
+ const controller = new AbortController();
2066
+ this.pendingSessionCreations.add(controller);
2067
+ const subscription = token.onCancellationRequested(() => controller.abort());
2068
+ if (token.isCancellationRequested) controller.abort();
2069
+ try {
2070
+ return await handler(request, { signal: controller.signal });
2071
+ } catch {
2072
+ throw new Error("Session creation callback failed");
2073
+ } finally {
2074
+ subscription.dispose();
2075
+ this.pendingSessionCreations.delete(controller);
2076
+ }
2077
+ }
2078
+ /**
2079
+ * Handles a `skillProvider.list` request from the runtime.
2080
+ *
2081
+ * @internal This method is for internal use by the SDK.
2082
+ */
2083
+ async _handleSkillProviderList(token) {
2084
+ const provider = this.requireSkillProvider();
2085
+ return await this.callSkillProvider("listSkills", token, async (options) => ({
2086
+ skills: await provider.listSkills(options) ?? []
2087
+ }));
2088
+ }
2089
+ /**
2090
+ * Handles a `skillProvider.read` request from the runtime.
2091
+ *
2092
+ * @internal This method is for internal use by the SDK.
2093
+ */
2094
+ async _handleSkillProviderRead(name, token) {
2095
+ const provider = this.requireSkillProvider();
2096
+ return await this.callSkillProvider("readSkill", token, async (options) => ({
2097
+ markdown: await provider.readSkill(name, options) ?? null
2098
+ }));
2099
+ }
2100
+ requireSkillProvider() {
2101
+ this.assertConnected();
2102
+ if (!this.skillProvider) {
2103
+ throw new Error(`No skill provider for session: ${this.sessionId}`);
2104
+ }
2105
+ return this.skillProvider;
2106
+ }
2107
+ /**
2108
+ * Runs a provider call with an abort signal tied to the runtime's request
2109
+ * cancellation. Failures are logged locally and reported generically.
2110
+ */
2111
+ async callSkillProvider(operation, token, call) {
2112
+ const controller = new AbortController();
2113
+ const subscription = token?.onCancellationRequested(() => controller.abort());
2114
+ if (token?.isCancellationRequested) {
2115
+ controller.abort();
2116
+ }
2117
+ try {
2118
+ return await call({ signal: controller.signal });
2119
+ } catch (error) {
2120
+ if (controller.signal.aborted) {
2121
+ throw new ResponseError(-32800, `Skill provider ${operation} cancelled`);
2122
+ }
2123
+ console.error(`Skill provider ${operation} failed`, {
2124
+ sessionId: this.sessionId,
2125
+ error
2126
+ });
2127
+ throw skillProviderFailure(operation);
2128
+ } finally {
2129
+ subscription?.dispose();
2130
+ }
2131
+ }
2132
+ /**
2133
+ * Registers hook handlers for session lifecycle events.
2134
+ *
2135
+ * Hooks allow custom logic to be executed at various points during
2136
+ * the session lifecycle (before/after tool use, session start/end, etc.).
2137
+ *
2138
+ * @param hooks - The hook handlers object, or undefined to remove all hooks
2139
+ * @internal This method is typically called internally when creating a session.
2140
+ */
2141
+ registerHooks(hooks) {
2142
+ this.assertConnected();
2143
+ this.hooks = hooks;
2144
+ }
2145
+ /**
2146
+ * Registers transform callbacks for system message sections.
2147
+ *
2148
+ * @param callbacks - Map of section ID to transform callback, or undefined to clear
2149
+ * @internal This method is typically called internally when creating a session.
2150
+ */
2151
+ registerTransformCallbacks(callbacks) {
2152
+ this.assertConnected();
2153
+ this.transformCallbacks = callbacks;
2154
+ }
2155
+ /**
2156
+ * Handles a systemMessage.transform request from the runtime.
2157
+ * Dispatches each section to its registered transform callback.
2158
+ *
2159
+ * @param sections - Map of section IDs to their current rendered content
2160
+ * @returns A promise that resolves with the transformed sections
2161
+ * @internal This method is for internal use by the SDK.
2162
+ */
2163
+ async _handleSystemMessageTransform(sections) {
2164
+ this.assertConnected();
2165
+ const result = {};
2166
+ for (const [sectionId, { content }] of Object.entries(sections)) {
2167
+ const callback = this.transformCallbacks?.get(sectionId);
2168
+ if (callback) {
2169
+ try {
2170
+ const transformed = await callback(content);
2171
+ result[sectionId] = { content: transformed };
2172
+ } catch (_error) {
2173
+ result[sectionId] = { content };
2174
+ }
2175
+ } else {
2176
+ result[sectionId] = { content };
2177
+ }
2178
+ }
2179
+ return { sections: result };
2180
+ }
2181
+ /**
2182
+ * Handles a user input request from the Copilot CLI.
2183
+ *
2184
+ * @param request - The user input request data from the CLI
2185
+ * @returns A promise that resolves with the user's response
2186
+ * @internal This method is for internal use by the SDK.
2187
+ */
2188
+ async _handleUserInputRequest(request) {
2189
+ this.assertConnected();
2190
+ if (!this.userInputHandler) {
2191
+ throw new Error("User input requested but no handler registered");
2192
+ }
2193
+ try {
2194
+ const result = await this.userInputHandler(request, {
2195
+ sessionId: this.sessionId
2196
+ });
2197
+ return result;
2198
+ } catch (error) {
2199
+ throw error;
2200
+ }
2201
+ }
2202
+ /**
2203
+ * Asks the registered handler for a secret. Any failure, a malformed answer,
2204
+ * or an abort cancels the prompt, so the program that asked fails instead
2205
+ * of receiving a wrong value. Never logs the answer.
2206
+ *
2207
+ * @param cancelled - Aborted when the runtime no longer needs the answer.
2208
+ * @internal This method is for internal use by the SDK.
2209
+ */
2210
+ async _handleShellAuthenticationRequest(request, cancelled) {
2211
+ const handler = this.shellAuthenticationHandler;
2212
+ if (!handler || cancelled.aborted || this.pendingShellAuthenticationRequests.has(request.requestId)) {
2213
+ return { action: "cancel" };
2214
+ }
2215
+ const controller = new AbortController();
2216
+ const abort = () => controller.abort();
2217
+ cancelled.addEventListener("abort", abort, { once: true });
2218
+ this.pendingShellAuthenticationRequests.set(request.requestId, controller);
2219
+ try {
2220
+ const cancellation = new Promise((resolve) => {
2221
+ controller.signal.addEventListener("abort", () => resolve(void 0), {
2222
+ once: true
2223
+ });
2224
+ });
2225
+ const result = await Promise.race([
2226
+ Promise.resolve(
2227
+ handler(request, {
2228
+ sessionId: this.sessionId,
2229
+ signal: controller.signal
2230
+ })
2231
+ ),
2232
+ cancellation
2233
+ ]);
2234
+ if (controller.signal.aborted || result?.action !== "accept" || typeof result.value !== "string") {
2235
+ return { action: "cancel" };
2236
+ }
2237
+ return { action: "accept", value: result.value };
2238
+ } catch (error) {
2239
+ console.error("Shell authentication handler failed", {
2240
+ sessionId: this.sessionId,
2241
+ requestId: request.requestId,
2242
+ errorType: errorTypeName(error)
2243
+ });
2244
+ return { action: "cancel" };
2245
+ } finally {
2246
+ cancelled.removeEventListener("abort", abort);
2247
+ this.pendingShellAuthenticationRequests.delete(request.requestId);
2248
+ }
2249
+ }
2250
+ /**
2251
+ * Handles a hooks invocation from the Copilot CLI.
2252
+ *
2253
+ * @param hookType - The type of hook being invoked
2254
+ * @param input - The input data for the hook
2255
+ * @returns A promise that resolves with the hook output, or undefined
2256
+ * @internal This method is for internal use by the SDK.
2257
+ */
2258
+ async _handleHooksInvoke(hookType, input) {
2259
+ this.assertConnected();
2260
+ if (!this.hooks) {
2261
+ return void 0;
2262
+ }
2263
+ const normalized = normalizeHookError(hookType, deserializeHookInput(input));
2264
+ const handlerMap = {
2265
+ preToolUse: this.hooks.onPreToolUse,
2266
+ preMcpToolCall: this.hooks.onPreMcpToolCall,
2267
+ postToolUse: this.hooks.onPostToolUse,
2268
+ postToolUseFailure: this.hooks.onPostToolUseFailure,
2269
+ userPromptSubmitted: this.hooks.onUserPromptSubmitted,
2270
+ userPromptTransformed: this.hooks.onUserPromptTransformed,
2271
+ sessionStart: this.hooks.onSessionStart,
2272
+ sessionEnd: this.hooks.onSessionEnd,
2273
+ errorOccurred: this.hooks.onErrorOccurred,
2274
+ agentStop: this.hooks.onAgentStop,
2275
+ subagentStart: this.hooks.onSubagentStart,
2276
+ subagentStop: this.hooks.onSubagentStop
2277
+ };
2278
+ const handler = handlerMap[hookType];
2279
+ if (!handler) {
2280
+ return void 0;
2281
+ }
2282
+ try {
2283
+ const result = await handler(normalized, { sessionId: this.sessionId });
2284
+ return result;
2285
+ } catch (_error) {
2286
+ return void 0;
2287
+ }
2288
+ }
2289
+ /**
2290
+ * Retrieves all events and messages from this session's history.
2291
+ *
2292
+ * This returns the complete conversation history including user messages,
2293
+ * assistant responses, tool executions, and other session events.
2294
+ * Use getRawEvents for archives containing integers outside JavaScript's safe range.
2295
+ *
2296
+ * @returns A promise that resolves with an array of all session events
2297
+ * @throws Error if the session has been disconnected or the connection fails
2298
+ *
2299
+ * @example
2300
+ * ```typescript
2301
+ * const events = await session.getEvents();
2302
+ * for (const event of events) {
2303
+ * if (event.type === "assistant.message") {
2304
+ * console.log("Assistant:", event.data.content);
2305
+ * }
2306
+ * }
2307
+ * ```
2308
+ */
2309
+ async getEvents() {
2310
+ const response = await this.connection.sendRequest("session.getMessages", {
2311
+ sessionId: this.sessionId
2312
+ });
2313
+ return response.events;
2314
+ }
2315
+ /**
2316
+ * Retrieves history with unsafe integers preserved as bigint values.
2317
+ * Timestamp strings, explicit nulls, and unknown fields are retained.
2318
+ * Pass the result directly to taskAnalytics.classifyTrajectory; JSON.stringify
2319
+ * does not support bigint, but that RPC's encoder does.
2320
+ */
2321
+ async getRawEvents() {
2322
+ const response = await this.connection.sendRequest(
2323
+ "session.getMessages",
2324
+ { sessionId: this.sessionId, [rawHistoryResponse]: true }
2325
+ );
2326
+ return response.events;
2327
+ }
2328
+ /**
2329
+ * Disconnects this session and releases all in-memory resources (event handlers,
2330
+ * tool handlers, permission handlers).
2331
+ *
2332
+ * Session state on disk (conversation history, planning state, artifacts) is
2333
+ * preserved, so the conversation can be resumed later by calling
2334
+ * {@link CopilotClient.resumeSession} with the session ID. To permanently
2335
+ * remove all session data including files on disk, use
2336
+ * {@link CopilotClient.deleteSession} instead.
2337
+ *
2338
+ * After calling this method, the session object can no longer be used.
2339
+ *
2340
+ * @returns A promise that resolves when the session is disconnected
2341
+ * @throws Error if the connection fails
2342
+ *
2343
+ * @example
2344
+ * ```typescript
2345
+ * // Clean up when done — session can still be resumed later
2346
+ * await session.disconnect();
2347
+ * ```
2348
+ */
2349
+ async disconnect() {
2350
+ if (this.disconnected || this.disconnecting) {
2351
+ return;
2352
+ }
2353
+ this.disconnecting = true;
2354
+ try {
2355
+ let response = { success: false };
2356
+ for (let attempt = 0; attempt < 2 && !response.success; attempt++) {
2357
+ response = await this.connection.sendRequest("session.detach", {
2358
+ sessionId: this.sessionId
2359
+ });
2360
+ }
2361
+ if (!response.success) {
2362
+ throw new Error(
2363
+ `Failed to disconnect session ${this.sessionId}: ${response.error || "Unknown error"}`
2364
+ );
2365
+ }
2366
+ const release = this.releaseFromClient;
2367
+ this._markDisconnected();
2368
+ release?.();
2369
+ } catch (error) {
2370
+ this.disconnecting = false;
2371
+ throw error;
2372
+ }
2373
+ }
2374
+ /** Enables `await using session = ...` syntax for automatic cleanup. */
2375
+ async [Symbol.asyncDispose]() {
2376
+ return this.disconnect();
2377
+ }
2378
+ /**
2379
+ * Aborts the currently processing message in this session.
2380
+ *
2381
+ * Use this to cancel a long-running request. The session remains valid
2382
+ * and can continue to be used for new messages.
2383
+ *
2384
+ * @returns A promise that resolves when the abort request is acknowledged
2385
+ * @throws Error if the session has been disconnected or the connection fails
2386
+ *
2387
+ * @example
2388
+ * ```typescript
2389
+ * // Start a long-running request
2390
+ * const messagePromise = session.send({ prompt: "Write a very long story..." });
2391
+ *
2392
+ * // Abort after 5 seconds
2393
+ * setTimeout(async () => {
2394
+ * await session.abort();
2395
+ * }, 5000);
2396
+ * ```
2397
+ */
2398
+ async abort() {
2399
+ await this.connection.sendRequest("session.abort", {
2400
+ sessionId: this.sessionId
2401
+ });
2402
+ }
2403
+ /**
2404
+ * Change the model for this session.
2405
+ * The new model takes effect for the next message. Conversation history is preserved.
2406
+ *
2407
+ * @param model - Model ID to switch to
2408
+ * @param options - Optional settings for the new model
2409
+ *
2410
+ * @example
2411
+ * ```typescript
2412
+ * await session.setModel("gpt-5.4");
2413
+ * await session.setModel("claude-sonnet-4.6", { reasoningEffort: "high" });
2414
+ *
2415
+ * // Select Copilot Fusion and its tier in one call, like
2416
+ * // `copilot --model fusion --fusion-tier high`.
2417
+ * await session.setModel("fusion", { fusionTier: "high" });
2418
+ * ```
2419
+ */
2420
+ async setModel(model, options) {
2421
+ await this.rpc.model.switchTo({ modelId: model, ...options });
2422
+ }
2423
+ /**
2424
+ * Change the Auto routing preference without changing the selected model.
2425
+ *
2426
+ * The runtime does not apply the preference immediately. It records the
2427
+ * request and commits it only when a later user turn using the `auto` model
2428
+ * successfully obtains a usable model from the provider. A `pending` status
2429
+ * therefore confirms that the request was accepted, not that it took effect.
2430
+ *
2431
+ * Watch for the outcome through the `session.model_change` event on success,
2432
+ * or the ephemeral `session.auto_tier_switch_failed` event on failure. You
2433
+ * can also read the current committed and in-flight state at any time with
2434
+ * `session.rpc.model.getCurrent()`.
2435
+ *
2436
+ * Only the most recent request survives: issuing a new request replaces any
2437
+ * earlier one that has not yet been claimed by a turn.
2438
+ *
2439
+ * For Copilot Fusion, prefer {@link setFusionTier}. The `balance`,
2440
+ * `hydrafusion` and `hydrafusion-max` identifiers it replaces remain
2441
+ * accepted but are deprecated.
2442
+ *
2443
+ * @param autoTier - Routing preference to activate, or `null` to return to
2444
+ * the provider's default Auto routing
2445
+ * @returns The runtime's immediate acknowledgement and Auto preference snapshot
2446
+ *
2447
+ * @experimental Part of an experimental Auto routing surface and may change
2448
+ * or be removed in a future release.
2449
+ *
2450
+ * @example
2451
+ * ```typescript
2452
+ * const result = await session.setAutoTier("intelligence");
2453
+ * if (result.status === "pending") {
2454
+ * // Takes effect on a later turn that uses the `auto` model.
2455
+ * }
2456
+ * ```
2457
+ */
2458
+ async setAutoTier(autoTier) {
2459
+ return await this.rpc.model.switchAutoTier({ autoTier });
2460
+ }
2461
+ /**
2462
+ * Change the Copilot Fusion tier without changing the selected model,
2463
+ * naming the tier as the CLI's `--fusion-tier` does.
2464
+ *
2465
+ * The runtime resolves the tier to the Auto routing preference it stands
2466
+ * for and then handles the request exactly like {@link setAutoTier}: it
2467
+ * takes effect on a later user turn that uses the `fusion` or `auto`
2468
+ * model. To return to the provider's default routing, call
2469
+ * `setAutoTier(null)`.
2470
+ *
2471
+ * @param fusionTier - Copilot Fusion tier to activate
2472
+ * @returns The runtime's immediate acknowledgement and Auto preference snapshot
2473
+ *
2474
+ * @experimental Part of an experimental Auto routing surface and may change
2475
+ * or be removed in a future release.
2476
+ *
2477
+ * @example
2478
+ * ```typescript
2479
+ * const result = await session.setFusionTier("max");
2480
+ * if (result.status === "pending") {
2481
+ * // Takes effect on a later turn that uses Copilot Fusion.
2482
+ * }
2483
+ * ```
2484
+ */
2485
+ async setFusionTier(fusionTier) {
2486
+ return await this.rpc.model.switchFusionTier({ fusionTier });
2487
+ }
2488
+ /**
2489
+ * Replace the tools this client supplies to the session.
2490
+ *
2491
+ * `tools` becomes the complete set of tools this client implements,
2492
+ * replacing the ones it supplied when the session was created or resumed,
2493
+ * or in an earlier call. Built-in, MCP, and plugin tools, and tools other
2494
+ * connected clients supply, are unaffected. Pass an empty array to remove
2495
+ * all of this client's tools.
2496
+ *
2497
+ * Tools are defined the same way as for `createSession`: calls to tools
2498
+ * with a `handler` are dispatched to it, and tools without one are
2499
+ * declaration-only. Once the runtime accepts the replacement, every tool
2500
+ * call this session dispatches uses the new handlers; calls already
2501
+ * running finish on their original handlers. If the runtime rejects the
2502
+ * replacement, this rejects and the previous tools and handlers stay in
2503
+ * place. Concurrent calls on the same session are applied one at a time,
2504
+ * in the order they are made.
2505
+ *
2506
+ * The agent sees the new tools from its next model request, which can fall
2507
+ * within a turn in progress. A model request already in flight was made
2508
+ * with the previous tools, so the agent can still call a tool you removed.
2509
+ * If no connected client supplies a tool with that name any more, the call
2510
+ * fails with an error that tells the agent the tool is no longer available,
2511
+ * and the turn continues. If you don't want the agent to see that failure,
2512
+ * replace tools while the session is idle.
2513
+ *
2514
+ * @param tools - The complete set of tools this client supplies
2515
+ * @throws Error if the session disconnects before the replacement is applied
2516
+ *
2517
+ * @experimental Wraps the experimental `session.tools.set` RPC and may change
2518
+ * or be removed in a future release.
2519
+ *
2520
+ * @example
2521
+ * ```typescript
2522
+ * await session.setTools([
2523
+ * defineTool("search_issues", {
2524
+ * description: "Search the issues shown on the current page",
2525
+ * parameters: z.object({ query: z.string() }),
2526
+ * handler: async ({ query }) => searchIssues(query),
2527
+ * }),
2528
+ * ]);
2529
+ * ```
2530
+ */
2531
+ async setTools(tools) {
2532
+ this.assertConnected();
2533
+ const definitions = tools.map(toToolDefinition);
2534
+ const replacement = this.setToolsQueue.then(async () => {
2535
+ this.assertConnected();
2536
+ await this.rpc.tools.set({ tools: definitions });
2537
+ this.registerTools(tools);
2538
+ });
2539
+ this.setToolsQueue = replacement.then(
2540
+ () => void 0,
2541
+ () => void 0
2542
+ );
2543
+ await replacement;
2544
+ }
2545
+ /**
2546
+ * Log a message to the session timeline.
2547
+ * The message appears in the session event stream and is visible to SDK consumers
2548
+ * and (for non-ephemeral messages) persisted to the session event log on disk.
2549
+ *
2550
+ * @param message - Human-readable message text
2551
+ * @param options - Optional log level and ephemeral flag
2552
+ *
2553
+ * @example
2554
+ * ```typescript
2555
+ * await session.log("Processing started");
2556
+ * await session.log("Disk usage high", { level: "warning" });
2557
+ * await session.log("Connection failed", { level: "error" });
2558
+ * await session.log("Debug info", { ephemeral: true });
2559
+ * ```
2560
+ */
2561
+ async log(message, options) {
2562
+ await this.rpc.log({ message, ...options });
2563
+ }
2564
+ }
2565
+ function isToolResultObject(value) {
2566
+ if (typeof value !== "object" || value === null) {
2567
+ return false;
2568
+ }
2569
+ if (!("textResultForLlm" in value) || typeof value.textResultForLlm !== "string") {
2570
+ return false;
2571
+ }
2572
+ if (!("resultType" in value) || typeof value.resultType !== "string") {
2573
+ return false;
2574
+ }
2575
+ const allowedResultTypes = [
2576
+ "success",
2577
+ "failure",
2578
+ "rejected",
2579
+ "denied",
2580
+ "timeout"
2581
+ ];
2582
+ return allowedResultTypes.includes(value.resultType);
2583
+ }
2584
+ function toCanvasRpcError(error) {
2585
+ if (error instanceof ResponseError) return error;
2586
+ const code = error instanceof CanvasError ? error.code : "canvas_handler_error";
2587
+ const message = error instanceof Error ? error.message : String(error);
2588
+ return new ResponseError(ErrorCodes.InternalError, message, { code, message });
2589
+ }
2590
+ function skillProviderFailure(operation) {
2591
+ return new ResponseError(ErrorCodes.InternalError, `Skill provider ${operation} failed`);
2592
+ }
2593
+ function errorTypeName(error) {
2594
+ if (typeof error !== "object" && typeof error !== "function" || error === null) {
2595
+ return typeof error;
2596
+ }
2597
+ try {
2598
+ const name = Object.getPrototypeOf(error)?.constructor?.name;
2599
+ return typeof name === "string" && name !== "" ? name : typeof error;
2600
+ } catch {
2601
+ return typeof error;
2602
+ }
2603
+ }
2604
+ function strictJsonValidationError(context, category, message, path) {
2605
+ return new ResponseError(ErrorCodes.InternalError, message, {
2606
+ code: context.code,
2607
+ category,
2608
+ path
2609
+ });
2610
+ }
2611
+ function assertStrictJson(value, context) {
2612
+ const ancestors = /* @__PURE__ */ new Set();
2613
+ const visit = (current, path, allowUndefined) => {
2614
+ if (current === void 0) {
2615
+ if (allowUndefined) {
2616
+ return;
2617
+ }
2618
+ throw strictJsonValidationError(
2619
+ context,
2620
+ "nested_undefined",
2621
+ `${context.label} contains nested undefined at ${path}`,
2622
+ path
2623
+ );
2624
+ }
2625
+ if (current === null || typeof current === "boolean" || typeof current === "string") {
2626
+ return;
2627
+ }
2628
+ if (typeof current === "number") {
2629
+ if (!Number.isFinite(current)) {
2630
+ throw strictJsonValidationError(
2631
+ context,
2632
+ "non_finite_number",
2633
+ `${context.label} contains a non-finite number at ${path}`,
2634
+ path
2635
+ );
2636
+ }
2637
+ if (Object.is(current, -0)) {
2638
+ throw strictJsonValidationError(
2639
+ context,
2640
+ "negative_zero",
2641
+ `${context.label} contains negative zero at ${path}; normalize it to 0`,
2642
+ path
2643
+ );
2644
+ }
2645
+ return;
2646
+ }
2647
+ if (typeof current === "function" || typeof current === "symbol" || typeof current === "bigint") {
2648
+ throw strictJsonValidationError(
2649
+ context,
2650
+ "unsupported_type",
2651
+ `${context.label} contains a function, symbol, or BigInt at ${path}`,
2652
+ path
2653
+ );
2654
+ }
2655
+ if (typeof current !== "object") {
2656
+ throw strictJsonValidationError(
2657
+ context,
2658
+ "unsupported_type",
2659
+ `${context.label} contains a function, symbol, or BigInt at ${path}`,
2660
+ path
2661
+ );
2662
+ }
2663
+ if (ancestors.has(current)) {
2664
+ throw strictJsonValidationError(
2665
+ context,
2666
+ "cyclic_value",
2667
+ `${context.label} contains a cyclic reference at ${path}`,
2668
+ path
2669
+ );
2670
+ }
2671
+ ancestors.add(current);
2672
+ try {
2673
+ if (Array.isArray(current)) {
2674
+ const keys = Reflect.ownKeys(current);
2675
+ if (keys.length !== current.length + 1 || keys.some(
2676
+ (key) => key !== "length" && (typeof key !== "string" || !/^(0|[1-9]\d*)$/.test(key) || Number(key) >= current.length)
2677
+ )) {
2678
+ throw strictJsonValidationError(
2679
+ context,
2680
+ "unsupported_object",
2681
+ `${context.label} contains a non-JSON array property at ${path}`,
2682
+ path
2683
+ );
2684
+ }
2685
+ for (let index = 0; index < current.length; index++) {
2686
+ const descriptor = Object.getOwnPropertyDescriptor(current, String(index));
2687
+ if (descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor)) {
2688
+ throw strictJsonValidationError(
2689
+ context,
2690
+ "unsupported_object",
2691
+ `${context.label} contains a non-JSON array property at ${path}[${index}]`,
2692
+ `${path}[${index}]`
2693
+ );
2694
+ }
2695
+ visit(descriptor.value, `${path}[${index}]`, false);
2696
+ }
2697
+ return;
2698
+ }
2699
+ const prototype = Object.getPrototypeOf(current);
2700
+ if (prototype !== Object.prototype && prototype !== null) {
2701
+ throw strictJsonValidationError(
2702
+ context,
2703
+ "unsupported_object",
2704
+ `${context.label} contains a non-JSON object at ${path}`,
2705
+ path
2706
+ );
2707
+ }
2708
+ for (const key of Reflect.ownKeys(current)) {
2709
+ if (typeof key === "symbol") {
2710
+ throw strictJsonValidationError(
2711
+ context,
2712
+ "unsupported_type",
2713
+ `${context.label} contains a function, symbol, or BigInt at ${path}`,
2714
+ path
2715
+ );
2716
+ }
2717
+ const propertyPath = /^[A-Za-z_$][\w$]*$/.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;
2718
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
2719
+ if (descriptor === void 0 || !descriptor.enumerable || !("value" in descriptor)) {
2720
+ throw strictJsonValidationError(
2721
+ context,
2722
+ "unsupported_object",
2723
+ `${context.label} contains a non-JSON property at ${propertyPath}`,
2724
+ propertyPath
2725
+ );
2726
+ }
2727
+ visit(descriptor.value, propertyPath, false);
2728
+ }
2729
+ } finally {
2730
+ ancestors.delete(current);
2731
+ }
2732
+ };
2733
+ visit(value, "$", context.allowTopLevelUndefined);
2734
+ }
2735
+ function assertWorkflowResult(value) {
2736
+ assertStrictJson(value, {
2737
+ code: "workflow_result_not_json",
2738
+ label: "Workflow result",
2739
+ allowTopLevelUndefined: true
2740
+ });
2741
+ }
2742
+ function assertWorkflowStepResult(value, key) {
2743
+ assertStrictJson(value, {
2744
+ code: "workflow_step_not_json",
2745
+ label: `Workflow step "${key}" result`,
2746
+ allowTopLevelUndefined: false
2747
+ });
2748
+ }
2749
+ export {
2750
+ CopilotSession
2751
+ };