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