@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,576 @@
1
+ import { createServerRpc } from "./generated/rpc.js";
2
+ import { CopilotDecisions } from "./decisions.js";
3
+ import { CopilotSession } from "./session.js";
4
+ import { AhpHost, type AhpHostOptions } from "./host.js";
5
+ import type { CopilotClientOptions, GetAuthStatusResponse, GetStatusResponse, ModelInfo, ResumeSessionConfig, SessionConfig, SessionLifecycleEventType, SessionLifecycleHandler, SessionListFilter, SessionMetadata, TypedSessionLifecycleHandler } from "./types.js";
6
+ export declare class CopilotClient {
7
+ private cliStartTimeout;
8
+ private cliProcess;
9
+ private ffiHost;
10
+ private connection;
11
+ private requestAdapter;
12
+ private pendingMemoryStores;
13
+ private messageWriter;
14
+ private connectionClosed;
15
+ private retireClosedConnection;
16
+ private connectionEpoch;
17
+ private socket;
18
+ private runtimePort;
19
+ private actualHost;
20
+ private state;
21
+ /** Shared in-flight start; concurrent callers await the same runtime startup. */
22
+ private startPromise;
23
+ private shutdownCanceledStartup;
24
+ private stopPromise;
25
+ private forceStopPromise;
26
+ private sessions;
27
+ /**
28
+ * Open secret prompts by session ID, then request ID. Tracked here rather
29
+ * than on a session object, which a resume can replace while a prompt is open.
30
+ */
31
+ private pendingShellAuthenticationRequests;
32
+ private pendingSessionResumes;
33
+ private sessionInitializations;
34
+ private failedAutoModeRecoveryCleanups;
35
+ private sessionInitializationContext;
36
+ private sessionInitializationLifetime;
37
+ private sessionInitializationGeneration;
38
+ private hostExitCallbacks;
39
+ private hostSessionFactories;
40
+ private hostAuthenticators;
41
+ private hostAuthentications;
42
+ private hostHandoffs;
43
+ private stderrBuffer;
44
+ /** Resolved connection mode chosen in the constructor. */
45
+ private connectionConfig;
46
+ /** Resolved path to the runtime executable (only used for child-process kinds). */
47
+ private resolvedCliPath;
48
+ /** Resolved environment passed to the spawned runtime. */
49
+ private resolvedEnv;
50
+ private options;
51
+ private isExternalServer;
52
+ private forceStopping;
53
+ /** Token sent in `connect`; auto-generated when the SDK spawns its own CLI in TCP mode. */
54
+ private effectiveConnectionToken?;
55
+ private onListModels?;
56
+ private onGetTraceContext?;
57
+ private modelsCache;
58
+ private sessionLifecycleHandlers;
59
+ private typedLifecycleHandlers;
60
+ private _rpc;
61
+ private _internalRpc;
62
+ private _decisions;
63
+ private processExitPromise;
64
+ private processTransportError;
65
+ private negotiatedProtocolVersion;
66
+ /** Connection-level session filesystem config, set via constructor option. */
67
+ private sessionFsConfig;
68
+ private requestHandler;
69
+ private extensionLaunchProvider?;
70
+ private readonly network?;
71
+ private installationConfirmationHandler?;
72
+ private builtinPluginDirectories;
73
+ private onGitHubTelemetry?;
74
+ private clientGlobalHandlers;
75
+ private githubTokenProviders;
76
+ /**
77
+ * Typed server-scoped RPC methods.
78
+ * @throws Error if the client is not connected
79
+ */
80
+ get rpc(): ReturnType<typeof createServerRpc>;
81
+ /**
82
+ * One-off yes/no, pick-one and rating questions answered by Copilot decision
83
+ * models. Requires the runtime's `DECISIONS_API` feature flag.
84
+ *
85
+ * @experimental
86
+ */
87
+ get decisions(): CopilotDecisions;
88
+ private logDebugTiming;
89
+ private logDebug;
90
+ /**
91
+ * Environment variable that overrides the transport when the caller does not set
92
+ * {@link CopilotClientOptions.connection}. Accepts `"inprocess"` or `"stdio"`
93
+ * (case-insensitive); unset selects the in-process transport. Any other value
94
+ * is an error.
95
+ */
96
+ private static readonly DEFAULT_CONNECTION_ENV_VAR;
97
+ /**
98
+ * Resolves the default {@link RuntimeConnection} for the no-connection case,
99
+ * honoring {@link CopilotClient.DEFAULT_CONNECTION_ENV_VAR}.
100
+ */
101
+ private static resolveDefaultConnection;
102
+ /**
103
+ * Creates a new CopilotClient instance.
104
+ *
105
+ * @param options - Configuration options for the client
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * // Default: loads the native runtime in this process
110
+ * const client = new CopilotClient({ mode: "coding-agent" });
111
+ *
112
+ * // Connect to an existing runtime
113
+ * const client = new CopilotClient({
114
+ * mode: "coding-agent",
115
+ * connection: RuntimeConnection.forUri("localhost:3000"),
116
+ * });
117
+ *
118
+ * // Spawn the runtime over TCP on a chosen port
119
+ * const client = new CopilotClient({
120
+ * mode: "coding-agent",
121
+ * connection: RuntimeConnection.forTcp({ port: 9001 }),
122
+ * });
123
+ *
124
+ * // Use a custom runtime binary
125
+ * const client = new CopilotClient({
126
+ * mode: "coding-agent",
127
+ * connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
128
+ * logLevel: "debug",
129
+ * });
130
+ * ```
131
+ */
132
+ constructor(options: CopilotClientOptions);
133
+ private connectionExtraArgs;
134
+ /**
135
+ * Parse CLI URL into host and port
136
+ * Supports raw TCP addresses: "host:port", "[ipv6]:port", "http://host:port", or just "port"
137
+ */
138
+ private parseCliUrl;
139
+ private validateSessionFsConfig;
140
+ private setupSessionFs;
141
+ private setupClientGlobalHandlers;
142
+ private acquireGitHubToken;
143
+ private registerGitHubTokenProvider;
144
+ private assignGitHubTokenProvider;
145
+ private commitGitHubTokenProvider;
146
+ /**
147
+ * Starts the runtime host and establishes a connection.
148
+ *
149
+ * An explicit {@link RuntimeConnection.forUri} only establishes the connection.
150
+ * Otherwise, starts an in-process host or the explicitly selected subprocess.
151
+ * If its subprocess survives a lost connection, it is terminated before restarting.
152
+ *
153
+ * This method is called automatically the first time you create or resume a session.
154
+ *
155
+ * @returns A promise that resolves when the connection is established
156
+ * @throws Error if the server fails to start or the connection fails
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * const client = new CopilotClient({ mode: "coding-agent" });
161
+ * await client.start();
162
+ * // Now ready to create sessions
163
+ * ```
164
+ */
165
+ start(): Promise<void>;
166
+ private doStart;
167
+ /**
168
+ * Stops the CLI server and closes all active sessions.
169
+ *
170
+ * This method performs graceful cleanup:
171
+ * 1. Closes all active sessions, suspending unfinished work for resume;
172
+ * detach requests share one shutdown timeout
173
+ * 2. Requests runtime shutdown for SDK-owned CLI processes
174
+ * 3. Closes the JSON-RPC connection
175
+ * 4. Signals EOF to an owned stdio process and waits for host cleanup, then
176
+ * terminates the process if it does not exit within the shutdown timeout
177
+ *
178
+ * Note: session data on disk is preserved, so sessions can be resumed later.
179
+ * To permanently remove session data before stopping, call
180
+ * {@link deleteSession} for each session first.
181
+ *
182
+ * @returns A promise that resolves with an array of errors encountered during cleanup.
183
+ * An empty array indicates all cleanup succeeded.
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * const errors = await client.stop();
188
+ * if (errors.length > 0) {
189
+ * console.error("Cleanup errors:", errors);
190
+ * }
191
+ * ```
192
+ */
193
+ stop(): Promise<Error[]>;
194
+ private doStop;
195
+ /**
196
+ * Alias for {@link stop} that lets `CopilotClient` participate in `await using`
197
+ * blocks for automatic cleanup.
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * await using client = new CopilotClient({ mode: "coding-agent" });
202
+ * const session = await client.createSession({ onPermissionRequest: approveAll });
203
+ * await session.sendAndWait("Hello");
204
+ * // client.stop() is called automatically when the block exits.
205
+ * ```
206
+ */
207
+ [Symbol.asyncDispose](): Promise<void>;
208
+ /**
209
+ * Forcefully stops the CLI server without graceful cleanup.
210
+ *
211
+ * Use this when {@link stop} fails or takes too long. This method:
212
+ * - Clears all sessions immediately without destroying them
213
+ * - Force closes the connection
214
+ * - Sends SIGKILL to the CLI process (if spawned by this client)
215
+ * - Waits for the spawned CLI process to exit
216
+ *
217
+ * @returns Resolves after disconnection and spawned-process exit; later starts
218
+ * wait for pending startup cleanup.
219
+ * @throws If the spawned CLI process cannot be terminated
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * // If normal stop hangs, force stop
224
+ * const stopPromise = client.stop();
225
+ * const timeout = new Promise((_, reject) =>
226
+ * setTimeout(() => reject(new Error("Timeout")), 5000)
227
+ * );
228
+ *
229
+ * try {
230
+ * await Promise.race([stopPromise, timeout]);
231
+ * } catch {
232
+ * await client.forceStop();
233
+ * }
234
+ * ```
235
+ */
236
+ forceStop(): Promise<void>;
237
+ private doForceStop;
238
+ /** Sends SIGKILL to the spawned CLI process, if it is still running, and waits for it to exit. */
239
+ private killCliProcess;
240
+ /** Mode-specific defaults spread under the caller's config (app values win). */
241
+ private configDefaultsForMode;
242
+ /** Mode-specific default for enableExperimentalMode. */
243
+ private experimentalModeForMode;
244
+ /**
245
+ * Returns the systemMessage config to use, adjusted for the current mode.
246
+ * In empty mode we ensure the environment_context section is removed
247
+ * unless the app has already taken control of it. `append` (and
248
+ * unspecified) mode is promoted to `customize` so we can also strip
249
+ * environment_context; the caller's `content` is preserved verbatim
250
+ * because the runtime appends it as additional instructions in both
251
+ * customize and append modes.
252
+ */
253
+ private getSystemMessageConfigForMode;
254
+ /**
255
+ * Mode-specific options applied via session.options.update after create/resume.
256
+ *
257
+ * In empty mode, defaults the four overridable feature flags to safe values
258
+ * (caller values from `config` win). `installedPlugins=[]` is unconditional
259
+ * in empty mode. `includedBuiltinSkills` defaults to `[]`, but callers can
260
+ * explicitly allow selected runtime-bundled skills.
261
+ */
262
+ private updateSessionOptionsForMode;
263
+ createSession(config: SessionConfig): Promise<CopilotSession>;
264
+ private invalidateSessionInitializations;
265
+ private getSessionInitializationSignal;
266
+ private runInitializationCallback;
267
+ private acquireSessionInitialization;
268
+ private createSessionInternal;
269
+ /**
270
+ * Resumes an existing conversation session by its ID.
271
+ *
272
+ * This allows you to continue a previous conversation, maintaining all
273
+ * conversation history. The session must have been previously created
274
+ * and not deleted.
275
+ *
276
+ * @param sessionId - The ID of the session to resume
277
+ * @param config - Optional configuration for the resumed session
278
+ * @returns A promise that resolves with the resumed session
279
+ * @throws Error if the session does not exist or the client is not connected
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * // Resume a previous session
284
+ * const session = await client.resumeSession("session-123", { onPermissionRequest: approveAll });
285
+ *
286
+ * // Resume with new tools
287
+ * const session = await client.resumeSession("session-123", {
288
+ * onPermissionRequest: approveAll,
289
+ * tools: [myNewTool]
290
+ * });
291
+ * ```
292
+ */
293
+ resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>;
294
+ private resumeSessionInternal;
295
+ private resumeSessionWithInitialization;
296
+ private requireAutoModeRecovery;
297
+ private recordFailedAutoModeRecoveryCleanup;
298
+ /**
299
+ * Start a complete AHP listener hosted in-process by this runtime.
300
+ *
301
+ * This connection owns the host. Disposing it or disconnecting the client
302
+ * stops the listener without deleting sessions. The host uses a separate
303
+ * SDK connection to the same runtime, not another runtime process.
304
+ * Only one AHP host may own a compute-scoped catalog in an effective Copilot home
305
+ * at a time. Other SDK clients and sessions remain usable in that home.
306
+ * Select localServer, githubEnvironment, or both. An empty localServer
307
+ * selects 127.0.0.1 on an available port. `onExit` runs at most once; owner disconnection cannot
308
+ * acknowledge listener cleanup over the disconnected transport.
309
+ *
310
+ * @experimental
311
+ */
312
+ startAhpHost(options: AhpHostOptions): Promise<AhpHost>;
313
+ private handleHostExit;
314
+ private abortPendingMemoryStores;
315
+ private disconnectHosts;
316
+ private releaseHostSessions;
317
+ private releaseHostSession;
318
+ private notifyHostSessionReleased;
319
+ private createHostSession;
320
+ /**
321
+ * Sends a ping request to the server to verify connectivity.
322
+ *
323
+ * @param message - Optional message to include in the ping
324
+ * @returns A promise that resolves with the ping response containing the message and timestamp
325
+ * @throws Error if the client is not connected, or if a {@link start} in progress when
326
+ * this was called fails
327
+ *
328
+ * @example
329
+ * ```typescript
330
+ * const response = await client.ping("health check");
331
+ * console.log(`Server responded at ${new Date(response.timestamp)}`);
332
+ * ```
333
+ */
334
+ ping(message?: string): Promise<{
335
+ message: string;
336
+ timestamp: string;
337
+ protocolVersion?: number;
338
+ }>;
339
+ /**
340
+ * Get CLI status including version and protocol information
341
+ */
342
+ getStatus(): Promise<GetStatusResponse>;
343
+ /**
344
+ * Get current authentication status
345
+ */
346
+ getAuthStatus(): Promise<GetAuthStatusResponse>;
347
+ /**
348
+ * Returns the connection for a request that must not start the client. A
349
+ * {@link start} already in progress is awaited, so the request never precedes the
350
+ * `connect` handshake or the provider registrations that follow it. A caller that
351
+ * queues before it calls this passes the startup it observed first, because
352
+ * `startPromise` is cleared once that startup settles.
353
+ */
354
+ private getStartedConnection;
355
+ /**
356
+ * List available models with their metadata.
357
+ *
358
+ * If an `onListModels` handler was provided in the client options,
359
+ * it is called instead of querying the CLI server.
360
+ *
361
+ * Results are cached after the first successful call to avoid rate limiting.
362
+ * The cache is cleared when the client disconnects.
363
+ *
364
+ * @throws Error if not connected, or if a {@link start} in progress when this was
365
+ * called fails (when no custom handler is set)
366
+ */
367
+ listModels(): Promise<ModelInfo[]>;
368
+ /**
369
+ * Send the `connect` handshake (carrying the optional token) and verify the
370
+ * server's protocol version. Falls back to `ping` against legacy servers
371
+ * that don't implement `connect`.
372
+ */
373
+ private verifyProtocolVersion;
374
+ /**
375
+ * Gets the ID of the most recently updated session.
376
+ *
377
+ * This is useful for resuming the last conversation when the session ID
378
+ * was not stored.
379
+ *
380
+ * @returns A promise that resolves with the session ID, or undefined if no sessions exist
381
+ * @throws Error if the client is not connected
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * const lastId = await client.getLastSessionId();
386
+ * if (lastId) {
387
+ * const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
388
+ * }
389
+ * ```
390
+ */
391
+ getLastSessionId(): Promise<string | undefined>;
392
+ /**
393
+ * Permanently deletes a session and all its data from disk, including
394
+ * conversation history, planning state, and artifacts.
395
+ *
396
+ * Unlike {@link CopilotSession.disconnect}, which only releases in-memory
397
+ * resources and preserves session data for later resumption, this method
398
+ * is irreversible. The session cannot be resumed after deletion.
399
+ *
400
+ * @param sessionId - The ID of the session to delete
401
+ * @returns A promise that resolves when the session is deleted
402
+ * @throws Error if the session does not exist or deletion fails
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * await client.deleteSession("session-123");
407
+ * ```
408
+ */
409
+ deleteSession(sessionId: string): Promise<void>;
410
+ private requestSessionDeletion;
411
+ /** Stops tracking a disconnected session unless a later create or resume replaced it. */
412
+ private forgetSession;
413
+ /**
414
+ * List all available sessions.
415
+ *
416
+ * @param filter - Optional filter to limit returned sessions by context fields
417
+ *
418
+ * @example
419
+ * // List all sessions
420
+ * const sessions = await client.listSessions();
421
+ *
422
+ * @example
423
+ * // List sessions for a specific repository
424
+ * const sessions = await client.listSessions({ repository: "owner/repo" });
425
+ */
426
+ listSessions(filter?: SessionListFilter): Promise<SessionMetadata[]>;
427
+ /**
428
+ * Gets metadata for a specific session by ID.
429
+ *
430
+ * This provides an efficient O(1) lookup of a single session's metadata
431
+ * instead of listing all sessions. Returns undefined if the session is not found.
432
+ *
433
+ * @param sessionId - The ID of the session to look up
434
+ * @returns A promise that resolves with the session metadata, or undefined if not found
435
+ * @throws Error if the client is not connected
436
+ *
437
+ * @example
438
+ * ```typescript
439
+ * const metadata = await client.getSessionMetadata("session-123");
440
+ * if (metadata) {
441
+ * console.log(`Session started at: ${metadata.startTime}`);
442
+ * }
443
+ * ```
444
+ */
445
+ getSessionMetadata(sessionId: string): Promise<SessionMetadata | undefined>;
446
+ private static toSessionMetadata;
447
+ /**
448
+ * Gets the foreground session ID in TUI+server mode.
449
+ *
450
+ * This returns the ID of the session currently displayed in the TUI.
451
+ * Only available when connecting to a server running in TUI+server mode (--ui-server).
452
+ *
453
+ * @returns A promise that resolves with the foreground session ID, or undefined if none
454
+ * @throws Error if the client is not connected
455
+ *
456
+ * @example
457
+ * ```typescript
458
+ * const sessionId = await client.getForegroundSessionId();
459
+ * if (sessionId) {
460
+ * console.log(`TUI is displaying session: ${sessionId}`);
461
+ * }
462
+ * ```
463
+ */
464
+ getForegroundSessionId(): Promise<string | undefined>;
465
+ /**
466
+ * Sets the foreground session in TUI+server mode.
467
+ *
468
+ * This requests the TUI to switch to displaying the specified session.
469
+ * Only available when connecting to a server running in TUI+server mode (--ui-server).
470
+ *
471
+ * @param sessionId - The ID of the session to display in the TUI
472
+ * @returns A promise that resolves when the session is switched
473
+ * @throws Error if the client is not connected or if the operation fails
474
+ *
475
+ * @example
476
+ * ```typescript
477
+ * // Switch the TUI to display a specific session
478
+ * await client.setForegroundSessionId("session-123");
479
+ * ```
480
+ */
481
+ setForegroundSessionId(sessionId: string): Promise<void>;
482
+ /**
483
+ * Subscribes to a specific session lifecycle event type.
484
+ *
485
+ * Lifecycle events are emitted when sessions are created, deleted, updated,
486
+ * or change foreground/background state (in TUI+server mode).
487
+ *
488
+ * @param eventType - The specific event type to listen for
489
+ * @param handler - A callback function that receives events of the specified type
490
+ * @returns A function that, when called, unsubscribes the handler
491
+ *
492
+ * @example
493
+ * ```typescript
494
+ * // Listen for when a session becomes foreground in TUI
495
+ * const unsubscribe = client.onLifecycle("session.foreground", (event) => {
496
+ * console.log(`Session ${event.sessionId} is now displayed in TUI`);
497
+ * });
498
+ *
499
+ * // Later, to stop receiving events:
500
+ * unsubscribe();
501
+ * ```
502
+ */
503
+ onLifecycle<K extends SessionLifecycleEventType>(eventType: K, handler: TypedSessionLifecycleHandler<K>): () => void;
504
+ /**
505
+ * Subscribes to all session lifecycle events.
506
+ *
507
+ * @param handler - A callback function that receives all lifecycle events
508
+ * @returns A function that, when called, unsubscribes the handler
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * const unsubscribe = client.onLifecycle((event) => {
513
+ * switch (event.type) {
514
+ * case "session.foreground":
515
+ * console.log(`Session ${event.sessionId} is now in foreground`);
516
+ * break;
517
+ * case "session.created":
518
+ * console.log(`New session created: ${event.sessionId}`);
519
+ * break;
520
+ * }
521
+ * });
522
+ *
523
+ * // Later, to stop receiving events:
524
+ * unsubscribe();
525
+ * ```
526
+ */
527
+ onLifecycle(handler: SessionLifecycleHandler): () => void;
528
+ /**
529
+ * Builds runtime configuration for child processes and the per-host FFI snapshot.
530
+ * Typed auth, home, keychain, and telemetry options override the effective env.
531
+ */
532
+ private buildRuntimeEnv;
533
+ /**
534
+ * Start the CLI server process
535
+ */
536
+ private startCLIServer;
537
+ /**
538
+ * Connect to the CLI server (via socket or stdio)
539
+ */
540
+ private connectToServer;
541
+ /** Starts the in-process FFI runtime with SDK-managed typed options. */
542
+ private startInProcessFfi;
543
+ /**
544
+ * Connect to the in-process FFI runtime host over its receive/send streams,
545
+ * reusing the same `vscode-jsonrpc` framing as the stdio transport.
546
+ */
547
+ private connectViaFfi;
548
+ private static getNapiPrebuildsFolder;
549
+ private static isMusl;
550
+ /**
551
+ * Connect to child via stdio pipes
552
+ */
553
+ private connectToChildProcessViaStdio;
554
+ /**
555
+ * Connect to parent via stdio pipes
556
+ */
557
+ private connectToParentProcessViaStdio;
558
+ /**
559
+ * Connect to the CLI server via TCP socket
560
+ */
561
+ private connectViaTcp;
562
+ private attachConnectionHandlers;
563
+ private resolveSessionCallback;
564
+ private handleSessionEventNotification;
565
+ private handleSessionLifecycleNotification;
566
+ private handleUserInputRequest;
567
+ private handleShellAuthenticationRequest;
568
+ private cancelShellAuthenticationRequest;
569
+ /** Cancels every open secret prompt once the runtime can no longer use an answer. */
570
+ private abortPendingShellAuthenticationRequests;
571
+ private handleExitPlanModeRequest;
572
+ private handleAutoModeSwitchRequest;
573
+ private resolveSkillProviderSession;
574
+ private handleHooksInvoke;
575
+ private handleSystemMessageTransform;
576
+ }