@microsoft/copilot-sdk 2.0.0-preview.0 → 2.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,7 +22,7 @@ replaces both with the CLI version published for that snapshot.
22
22
  `COPILOT_CLI_DOWNLOAD_BASE_URL` to use a release mirror while packaging.
23
23
  Standalone source builds acquire stable/prerelease runtime assets from
24
24
  `github/copilot-cli` at `v<runtime-version>`, and canonical unstable assets from
25
- `github/copilot-sdk` at `runtime-<runtime-version>`. Both checksum and package
25
+ `microsoft/copilot-sdk` at `runtime-<runtime-version>`. Both checksum and package
26
26
  downloads use that release location; mirror overrides retain the same tag scheme.
27
27
  Release workflows instead set `COPILOT_SDK_RUNTIME_PACKAGE_DIR` to a directory
28
28
  containing validated runtime npm package roots named for all eight platforms.
@@ -44,8 +44,8 @@ npm install @microsoft/copilot-sdk
44
44
  ## Model provider metadata
45
45
 
46
46
  `client.listModels()` and `client.rpc.models.list()` preserve the runtime's optional
47
- `provider` reference on each model: `{ id, kind, label }`. The existing `Model`,
48
- `ModelInfo`, and `ModelProviderRef` types are available from the package root.
47
+ `provider` reference on each model: `{ id, kind, label }`. The existing `Model`
48
+ and `ModelProviderRef` types are available from the package root.
49
49
  Native kinds remain `copilot` and `loki`; `id` is opaque and `label` is display text.
50
50
  Configured BYOK and older, unattributed rows omit `provider`; do not infer Copilot
51
51
  branding from a model ID or fill it from the active account. This metadata identifies
@@ -64,7 +64,8 @@ Each callback's `signal` aborts when the runtime stops waiting (it cancels the r
64
64
  By default the callbacks serve only requests made for sessions this client creates or resumes. With `scope: "runtime"` they also serve the runtime's shared traffic, such as catalog refreshes, telemetry and remote MCP server connections; only one connection at a time can hold that scope, so startup fails if another client holds it. The registration ends when the connection closes.
65
65
 
66
66
  ```ts
67
- const client = new CopilotClient({ mode: "coding-agent",
67
+ const client = new CopilotClient({
68
+ mode: "coding-agent",
68
69
  network: {
69
70
  scope: "runtime",
70
71
  resolveProxy: async ({ url }) => session.resolveProxy(url),
@@ -81,6 +82,7 @@ const client = new CopilotClient({ mode: "coding-agent",
81
82
  (`requireIdentity` and a validator returning `{identity,expiresAt}` or `null`):
82
83
 
83
84
  <!-- docs-validate: strict -->
85
+
84
86
  ```typescript
85
87
  import { CopilotClient } from "@microsoft/copilot-sdk";
86
88
 
@@ -153,6 +155,7 @@ by the SDK. Published sessions remain discoverable after hosting stops.
153
155
  Supply `createSession` to materialize fresh AHP sessions in your application:
154
156
 
155
157
  <!-- docs-validate: strict -->
158
+
156
159
  ```typescript
157
160
  import { approveAll, CopilotClient, defineTool } from "@microsoft/copilot-sdk";
158
161
 
@@ -164,15 +167,21 @@ await using host = await client.startAhpHost({
164
167
  signal.throwIfAborted();
165
168
  return client.createSession({
166
169
  ...config,
167
- onPermissionRequest: approveAll,
170
+ permissions: {
171
+ ...config.permissions,
172
+ onRequest: approveAll,
173
+ },
168
174
  systemMessage: { mode: "append", content: "Use the app's greeting tool." },
169
- tools: [
170
- defineTool("greeting", {
171
- description: "Get the application's greeting",
172
- parameters: { type: "object", properties: {} },
173
- handler: () => "Hello from the application!",
174
- }),
175
- ],
175
+ tools: {
176
+ ...config.tools?.definitions,
177
+ definitions: [
178
+ defineTool("greeting", {
179
+ description: "Get the application's greeting",
180
+ parameters: { type: "object", properties: {} },
181
+ handler: () => "Hello from the application!",
182
+ }),
183
+ ],
184
+ },
176
185
  });
177
186
  },
178
187
  onSessionReleased: async (originalSession) => {
@@ -250,7 +259,9 @@ await client.start();
250
259
  // approveAll is only valid when managed settings are disabled.
251
260
  const session = await client.createSession({
252
261
  model: "gpt-5",
253
- onPermissionRequest: approveAll,
262
+ permissions: {
263
+ onRequest: approveAll,
264
+ },
254
265
  });
255
266
 
256
267
  // Wait for the response using typed event handlers
@@ -281,14 +292,16 @@ import { approveAll } from "@microsoft/copilot-sdk";
281
292
 
282
293
  await using session = await client.createSession({
283
294
  model: "gpt-5",
284
- onPermissionRequest: approveAll,
295
+ permissions: {
296
+ onRequest: approveAll,
297
+ },
285
298
  });
286
299
  // session is automatically disconnected when leaving scope
287
300
  ```
288
301
 
289
- When targeting MCP tools configured through `mcpServers`, remember the runtime
290
- tool name is `<server-key>-<tool-name>`. For `availableTools` and
291
- `excludedTools`, prefer `new ToolSet().addMcp("<server-key>-<tool-name>")` or
302
+ When targeting MCP tools configured through `mcp.servers`, remember the runtime
303
+ tool name is `<server-key>-<tool-name>`. For `tools.availableTools` and
304
+ `tools.excludedTools`, prefer `new ToolSet().addMcp("<server-key>-<tool-name>")` or
292
305
  the raw `mcp:<server-key>-<tool-name>` form. For `customAgents[].tools` and
293
306
  `defaultAgent.excludedTools`, use `<server-key>-<tool-name>` directly.
294
307
 
@@ -324,36 +337,37 @@ new CopilotClient(options: CopilotClientOptions)
324
337
 
325
338
  **Options:**
326
339
 
327
- - `connection?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`:
328
- - `RuntimeConnection.forStdio({ path?, args?, env? })` — spawn the runtime and communicate over its stdin/stdout.
329
- - `RuntimeConnection.forTcp({ port?, connectionToken?, path?, args?, env? })` — spawn the runtime as a TCP server.
330
- - `RuntimeConnection.forUri(url, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `gitHubToken`/`useLoggedInUser`). There is no top-level `cliUrl` shortcut; use this factory for URL-based connections.
331
- - `RuntimeConnection.forInProcess()` (default) — host the runtime in-process over its native C ABI (FFI). Typed `telemetry` is host-scoped; client-level `env` and `workingDirectory` are rejected. Configure working directories per session.
332
- - The child-process transports (`forStdio`/`forTcp`) also accept a per-connection `env`. Set it there or via the top-level `env` option — not both (setting both throws).
340
+ - `runtime?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`:
341
+ - `RuntimeConnection.forDefault({ baseDirectory?, sessionIdleTimeoutSeconds? })` — synchronously resolve the deployment default at call time, honoring `COPILOT_SDK_DEFAULT_CONNECTION` (`stdio` or `inprocess`, case-insensitive; empty uses in-process).
342
+ - `RuntimeConnection.forSpawnedStdio({ path?, args?, env?, workingDirectory?, baseDirectory?, sessionIdleTimeoutSeconds? })` — spawn the runtime and communicate over its stdin/stdout.
343
+ - `RuntimeConnection.forSpawnedTcp({ port?, connectionToken?, path?, args?, env?, workingDirectory?, baseDirectory?, sessionIdleTimeoutSeconds? })` — spawn the runtime as a TCP server.
344
+ - `RuntimeConnection.forTcp(host, port, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `github.token`/`github.useLoggedInUser`). There is no top-level `cliUrl` shortcut; use this factory for plaintext TCP connections.
345
+ - `RuntimeConnection.forInProcess({ baseDirectory?, sessionIdleTimeoutSeconds?, runOnUiThread? })` — host the runtime in-process over its native C ABI (FFI). Typed `observability.telemetry` is host-scoped; process `env` and `workingDirectory` are unsupported. Configure working directories per session.
346
+ - Only spawned transports accept `env` and `workingDirectory`; `env` replaces inheritance (`{}` clears it). Owned transports accept `baseDirectory` and `sessionIdleTimeoutSeconds`.
333
347
  - Managed child-process connections materialize the bundled `copilot-runtime` and adjacent `runtime.node`, then launch the wrapper by default. An explicit connection `path` or `COPILOT_CLI_PATH` overrides the bundled runtime.
334
348
  - `mode: "empty" | "coding-agent"` - Required defaulting strategy. Use `"empty"` for multi-user server mode or explicitly select `"coding-agent"` for CLI-like behavior.
335
- - `workingDirectory?: string` - Working directory for the runtime process (default: current process cwd).
336
- - `baseDirectory?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When not set, the runtime defaults to `~/.copilot`. Ignored when connecting via `RuntimeConnection.forUri`.
337
- - `extensionLaunchProvider?: ExtensionLaunchProvider` - Experimental connection-level resolver for extension launch profiles. The client installs the reverse-RPC handler and registers the provider during startup before sessions can be created.
338
- - `installationConfirmationHandler?: InstallationConfirmationHandler` - Experimental connection-global human review for `installations.confirm`. Receives the typed request and independent request/connection cancellation signals, and returns an explicit decision. Does not enable installation capabilities.
339
- - `logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all"` - Log level. When omitted, the runtime uses its own default (currently `"info"`).
340
- - `env?: Record<string, string | undefined>` - Environment variables for the runtime process. When omitted, inherits `process.env`.
349
+ - `runtime.workingDirectory?: string` - Working directory for the runtime process (default: current process cwd).
350
+ - `runtime.baseDirectory?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned runtime. When not set, the runtime defaults to `~/.copilot`. Available only on owned runtime connections, not `RuntimeConnection.forTcp`.
351
+ - `extensions.launchProvider?: ExtensionLaunchProvider` - Experimental connection-level resolver for extension launch profiles. The client installs the reverse-RPC handler and registers the provider during startup before sessions can be created.
352
+ - `installations.confirmationHandler?: InstallationConfirmationHandler` - Experimental connection-global human review for `installations.confirm`. Receives the typed request and independent request/connection cancellation signals, and returns an explicit decision. Does not enable installation capabilities.
353
+ - `observability.logLevel?: "none" | "error" | "warning" | "info" | "debug" | "all"` - Log level. When omitted, the runtime uses its own default (currently `"info"`).
354
+ - `runtime.env?: Record<string, string | undefined>` - Environment variables for the runtime process. When omitted, inherits `process.env`.
341
355
 
342
356
  Set `COPILOT_TELEMETRY_DISABLED=true` before startup to disable Copilot-owned
343
357
  GitHub and Entra authentication telemetry process-wide, including sessionless
344
- events. Authentication, SDK `onGitHubTelemetry` forwarding, and user-configured
358
+ events. Authentication, SDK `github.onTelemetry` forwarding, and user-configured
345
359
  OpenTelemetry remain unchanged. The value must be exactly `"true"`; restart
346
360
  the process to change it. With `RuntimeConnection.forInProcess()`, set the host
347
- process environment; per-client `env` is rejected. `enableSessionTelemetry: false`
361
+ process environment. `enableSessionTelemetry: false`
348
362
  affects only the session pipeline. The existing native-runtime-only
349
363
  `COPILOT_GITHUB_TELEMETRY_DISABLED=true` remains GitHub-only; the Node CLI host
350
364
  uses the general variable or `--disable-client-telemetry` instead.
351
365
 
352
- - `gitHubToken?: string` - GitHub token for authentication. When provided, takes priority over other auth methods.
353
- - `useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `gitHubToken` is provided). Cannot be used with `RuntimeConnection.forUri`.
354
- - `onListModels?: () => Promise<ModelInfo[]> | ModelInfo[]` - Optional model-list provider, useful when using a custom provider.
355
- - `telemetry?: TelemetryConfig` - OpenTelemetry configuration for the runtime process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
356
- - `onGetTraceContext?: TraceContextProvider` - Advanced: callback for linking your application's own OpenTelemetry spans into the same distributed trace as the runtime's spans. Not needed for normal telemetry collection. See [Telemetry](#telemetry) below.
366
+ - `github.token?: string` - GitHub token for authentication. When provided, takes priority over other auth methods.
367
+ - `github.useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `github.token` is provided). Cannot be used with `RuntimeConnection.forTcp`.
368
+ - `models.onListModels?: () => Promise<Model[]> | Model[]` - Optional model-list provider, useful when using a custom provider.
369
+ - `observability.telemetry?: TelemetryConfig` - OpenTelemetry configuration for the runtime process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
370
+ - `observability.onGetTraceContext?: TraceContextProvider` - Advanced: callback for linking your application's own OpenTelemetry spans into the same distributed trace as the runtime's spans. Not needed for normal telemetry collection. See [Telemetry](#telemetry) below.
357
371
  - `sessionFs?: SessionFsConfig` - Custom session filesystem provider.
358
372
 
359
373
  For a custom provider to serve images to the `view` tool, declare
@@ -368,7 +382,7 @@ when a session is created.
368
382
  Binary reads and writes are limited to 50,330,880 raw bytes (approximately 48 MiB);
369
383
  larger results return a filesystem error before encoding or decoding.
370
384
 
371
- - `sessionIdleTimeoutSeconds?: number` - Server-wide idle timeout for sessions in seconds. Ignored when connecting via `RuntimeConnection.forUri`.
385
+ - `runtime.sessionIdleTimeoutSeconds?: number` - Server-wide idle timeout for sessions in seconds. Available only on owned runtime connections, not `RuntimeConnection.forTcp`.
372
386
 
373
387
  #### Installation confirmation (experimental)
374
388
 
@@ -435,7 +449,7 @@ Retirement releases session-owned tool, hook, auth/input, provider, workflow, ca
435
449
  and transform registrations without changing caller-owned configuration. Late
436
450
  registration and callback dispatch are rejected; callbacks already admitted may finish.
437
451
 
438
- ##### `createSession(config: SessionConfig): Promise<CopilotSession>`
452
+ ##### `createSession(config: CreateSessionOptions): Promise<CopilotSession>`
439
453
 
440
454
  Create a new conversation session.
441
455
 
@@ -443,55 +457,62 @@ Create a new conversation session.
443
457
 
444
458
  - `sessionId?: string` - Custom session ID.
445
459
  - `model?: string` - Model to use ("gpt-5", "claude-sonnet-4.5", etc.). **Required when using custom provider.**
446
- - `capi?: CapiSessionOptions` - Copilot API options. With `model: "auto"`, set `autoTier` to `"efficiency"`, `"balance"`, `"intelligence"`, or `"fast"` to choose a routing preference. `"fast"` is an integrator-only latency preset, not a first-party GitHub Copilot product preference. Requires a runtime with Auto tier support and V2 Auto routing. Omission preserves default behavior. See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for resume semantics. For Copilot Fusion, use `model: "fusion"` and set `fusionTier` to `"standard"`, `"high"`, or `"max"`, like the CLI's `--model fusion --fusion-tier <tier>`; the `autoTier` values `"balance"`, `"hydrafusion"`, and `"hydrafusion-max"` that these replace are deprecated. See [Copilot Fusion names](../docs/features/session-persistence.md#copilot-fusion-names).
447
- - `reasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max"` - Reasoning effort level for models that support it. Use `listModels()` to check which models support this option.
448
- - `tools?: Tool[]` - Custom tools exposed to the CLI. Tools without `handler` are declaration-only and must be resolved via pending tool-call RPCs.
460
+ - `github.capi?: CapiSessionOptions` - Copilot API options. With `model: "auto"`, set `autoTier` to `"efficiency"`, `"balance"`, `"intelligence"`, or `"fast"` to choose a routing preference. `"fast"` is an integrator-only latency preset, not a first-party GitHub Copilot product preference. Requires a runtime with Auto tier support and V2 Auto routing. Omission preserves default behavior. See [Auto tier persistence](../docs/features/session-persistence.md#auto-tier-persistence) for resume semantics. For Copilot Fusion, use `model: "fusion"` and set `fusionTier` to `"standard"`, `"high"`, or `"max"`, like the CLI's `--model fusion --fusion-tier <tier>`; the `autoTier` values `"balance"`, `"hydrafusion"`, and `"hydrafusion-max"` that these replace are deprecated. See [Copilot Fusion names](../docs/features/session-persistence.md#copilot-fusion-names).
461
+ - `inference.reasoningEffort?: "low" | "medium" | "high" | "xhigh" | "max"` - Reasoning effort level for models that support it. Use `listModels()` to check which models support this option.
462
+ - `tools.definitions?: Tool[]` - Custom tools exposed to the CLI. Tools without `handler` are declaration-only and must be resolved via pending tool-call RPCs.
449
463
  - `systemMessage?: SystemMessageConfig` - System message customization (see below)
450
- - `infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
464
+ - `state.infiniteSessions?: InfiniteSessionConfig` - Configure automatic context compaction (see below)
451
465
  - `workingDirectory?: string` - Working directory for the session (default: runtime process cwd).
452
- - `trustWorkingDirectory?: "session" | "user"` - Grant trust to the canonical working directory during session creation. `"session"` trusts it only for this session; `"user"` persists trust for later sessions. Omit to leave trust unchanged. Not available on resume.
453
- - `refreshCustomInstructions?: boolean` - Invalidates the process-wide custom-instruction discovery cache before creating this session, so instruction-file edits made in the same runtime are read again. Defaults to `false` (cache reuse). Other sessions in this runtime may observe updated instructions on later turns or discovery. This does not watch files or enable disabled instruction loading. Available on `SessionConfig`, not `ResumeSessionConfig`.
454
- - `enableSessionStore?: boolean` - Enables the cross-session store for search and retrieval across sessions. When unset in `"coding-agent"` mode, the runtime default applies (enabled). In `"empty"` mode, defaults to disabled.
455
- - `enableSessionTelemetry?: boolean` - Disables internal session telemetry only when set to `false`. Omission or `true` enables it for eligible GitHub-authenticated sessions, including custom-provider (BYOK) sessions. Host and account policies still control uploads; this is separate from OpenTelemetry configuration.
456
- - `gitHubTokenProvider?: GitHubTokenProvider` - Acquires rotating, session-scoped GitHub tokens. Token results require an `expiresIn` value in seconds remaining when the callback completes, of which more than one hour must still remain after the runtime validates the token; production tokens typically last eight hours. Cannot be combined with `gitHubToken`.
457
- - `provider?: ProviderConfig` - Custom API provider configuration (BYOK - Bring Your Own Key). See [Custom Providers](#custom-providers) section.
458
- - `onPermissionRequest?: PermissionHandler` - Optional handler called before each tool execution to approve or deny it. When omitted, permission requests are emitted as events and left pending for manual resolution. `approveAll` approves requests when managed settings are disabled and throws when `enableManagedSettings` is true. Custom handlers can inspect `managedApprovalRequired` for human-facing confirmation logic. See [Permission Handling](#permission-handling) section.
459
- - `onUserInputRequest?: UserInputHandler` - Handler for legacy question-and-answer requests from the agent. Enables the legacy `ask_user` tool. See [User Input Requests](#user-input-requests) section.
460
- - `onShellAuthenticationRequest?: ShellAuthenticationHandler` - Handler for passwords and other answers that shell commands run by the agent ask for, such as `sudo -A`, `ssh`, and `git` over HTTPS. The answer goes only to the program that asked; the model never sees it. Without a handler, those commands fail as they do without a terminal. See [Shell password prompts](../docs/features/shell-password-prompts.md).
461
- - `askUserVariant?: "legacy" | "elicitation"` - Selects the model-facing `ask_user` tool shape when creating or cold-resuming a session. Defaults to `"legacy"`; use `"elicitation"` with `onElicitationRequest`.
462
- - `interactiveUser?: boolean` - Declares that a person types this session's messages, as in an editor chat panel. Enables the runtime's user-message analysis telemetry for user-authored messages; automated messages stay excluded. Defaults to `false`. Ignored for cloud sessions. Re-supply it when cold-resuming a session; it is ignored when resuming a session that is already active.
463
- - `permissionMode?: PermissionMode` - Applies `"manual"`, `"assisted"`, or `"allow-all"` before the session's first turn: before `createSession` returns, and before a resume continues pending work. Uses the same checks as `session.rpc.permissions.setMode`; `session.permissionModeResult` reports whether it was applied and the authoritative mode. Not supported for cloud sessions.
464
- - `onElicitationRequest?: ElicitationHandler` - Handler for elicitation requests dispatched by the server. Enables this client to present form-based UI dialogs on behalf of the agent or other session participants. See [Elicitation Requests](#elicitation-requests) section.
465
- - `hooks?: SessionHooks` - Hook handlers for session lifecycle events. See [Session Hooks](#session-hooks) section.
466
- - `skillProvider?: SkillProvider` - **Experimental.** Serves skills from host storage instead of skill directories. Not persisted; pass it again on resume. See [Skill providers](#skill-providers-experimental).
466
+ - `filesystem.trustWorkingDirectory?: "session" | "user"` - Grant trust to the canonical working directory during session creation. `"session"` trusts it only for this session; `"user"` persists trust for later sessions. Omit to leave trust unchanged. Not available on resume.
467
+ - `instructions.refreshCustomInstructions?: boolean` - Invalidates the process-wide custom-instruction discovery cache before creating this session, so instruction-file edits made in the same runtime are read again. Defaults to `false` (cache reuse). Other sessions in this runtime may observe updated instructions on later turns or discovery. This does not watch files or enable disabled instruction loading. Available on `CreateSessionOptions`, not `ResumeSessionOptions`.
468
+ - `state.enableCrossSessionStore?: boolean` - Enables the cross-session store for search and retrieval across sessions. When unset in `"coding-agent"` mode, the runtime default applies (enabled). In `"empty"` mode, defaults to disabled.
469
+ - `github.telemetryEnabled?: boolean` - Disables internal session telemetry only when set to `false`. Omission or `true` enables it for eligible GitHub-authenticated sessions, including custom-provider (BYOK) sessions. Host and account policies still control uploads; this is separate from OpenTelemetry configuration.
470
+ - `github.tokenProvider?: GitHubTokenProvider` - Acquires rotating, session-scoped GitHub tokens. Token results require an `expiresIn` value in seconds remaining when the callback completes, of which more than one hour must still remain after the runtime validates the token; production tokens typically last eight hours. Cannot be combined with `github.token`.
471
+ - `inference.providers?: NamedProviderConfig[]` - Custom API provider configuration (BYOK - Bring Your Own Key). See [Custom Providers](#custom-providers) section.
472
+ - `permissions.onRequest?: PermissionHandler` - Optional handler called before each tool execution to approve or deny it. When omitted, permission requests are emitted as events and left pending for manual resolution. `approveAll` approves requests when managed settings are disabled and throws when `github.fetchManagedSettings` is true. Custom handlers can inspect `managedApprovalRequired` for human-facing confirmation logic. See [Permission Handling](#permission-handling) section.
473
+ - `interaction.onUserInputRequest?: UserInputHandler` - Handler for legacy question-and-answer requests from the agent. Enables the legacy `ask_user` tool. See [User Input Requests](#user-input-requests) section.
474
+ - `interaction.onShellAuthenticationRequest?: ShellAuthenticationHandler` - Handler for passwords and other answers that shell commands run by the agent ask for, such as `sudo -A`, `ssh`, and `git` over HTTPS. The answer goes only to the program that asked; the model never sees it. Without a handler, those commands fail as they do without a terminal. See [Shell password prompts](../docs/features/shell-password-prompts.md).
475
+ - `interaction.askUserVariant?: "legacy" | "elicitation"` - Selects the model-facing `ask_user` tool shape when creating or cold-resuming a session. Defaults to `"legacy"`; use `"elicitation"` with `interaction.onElicitationRequest`.
476
+ - `github.interactiveUser?: boolean` - Declares that a person types this session's messages, as in an editor chat panel. Enables the runtime's user-message analysis telemetry for user-authored messages; automated messages stay excluded. Defaults to `false`. Ignored for cloud sessions. Re-supply it when cold-resuming a session; it is ignored when resuming a session that is already active.
477
+ - `permissions.mode?: PermissionMode` - Applies `"manual"`, `"assisted"`, or `"allow-all"` before the session's first turn: before `createSession` returns, and before a resume continues pending work. Uses the same checks as `session.rpc.permissions.setMode`; `session.permissionModeResult` reports whether it was applied and the authoritative mode. Not supported for cloud sessions.
478
+ - `interaction.onElicitationRequest?: ElicitationHandler` - Handler for elicitation requests dispatched by the server. Enables this client to present form-based UI dialogs on behalf of the agent or other session participants. See [Elicitation Requests](#elicitation-requests) section.
479
+ - `hooks.handlers?: SessionHooks` - Hook handlers for session lifecycle events. See [Session Hooks](#session-hooks) section.
480
+ - `skills.provider?: SkillProvider` - **Experimental.** Serves skills from host storage instead of skill directories. Not persisted; pass it again on resume. See [Skill providers](#skill-providers-experimental).
467
481
 
468
482
  <!-- docs-validate: strict -->
469
483
  <!-- docs-validate: hidden -->
484
+
470
485
  ```typescript
471
486
  declare function acquireTokenForHost(host: string): Promise<string>;
472
487
 
473
488
  const session = await client.createSession({
474
- gitHubTokenProvider: async ({ host }) => ({
475
- kind: "token",
476
- accessToken: await acquireTokenForHost(host),
477
- expiresIn: 8 * 60 * 60,
478
- }),
489
+ github: {
490
+ tokenProvider: async ({ host }) => ({
491
+ kind: "token",
492
+ accessToken: await acquireTokenForHost(host),
493
+ expiresIn: 8 * 60 * 60,
494
+ }),
495
+ },
479
496
  });
480
497
  ```
498
+
481
499
  <!-- /docs-validate: hidden -->
500
+
482
501
  ```typescript
483
502
  const session = await client.createSession({
484
- gitHubTokenProvider: async ({ host }) => ({
485
- kind: "token",
486
- accessToken: await acquireTokenForHost(host),
487
- expiresIn: 8 * 60 * 60,
488
- }),
503
+ github: {
504
+ tokenProvider: async ({ host }) => ({
505
+ kind: "token",
506
+ accessToken: await acquireTokenForHost(host),
507
+ expiresIn: 8 * 60 * 60,
508
+ }),
509
+ },
489
510
  });
490
511
  ```
491
512
 
492
513
  Initial acquisition runs during session creation or resume. Cancellation, provider errors, and invalid token responses reject that operation instead of falling back to ambient authentication. Idle sessions refresh only before their next credential-consuming operation; there is no background refresh timer.
493
514
 
494
- ##### `resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>`
515
+ ##### `resumeSession(sessionId: string, config: ResumeSessionOptions): Promise<CopilotSession>`
495
516
 
496
517
  Both create and resume accept experimental `autopilot: AutopilotOptions`, and
497
518
  `session.rpc.options.update({ autopilot: ... })` patches the same policy.
@@ -554,6 +575,7 @@ Request the TUI to switch to displaying the specified session. Only available in
554
575
  Subscribe to a specific session lifecycle event type. Returns an unsubscribe function.
555
576
 
556
577
  <!-- docs-validate: strict -->
578
+
557
579
  ```typescript
558
580
  const unsubscribe = client.onLifecycle("session.foreground", (event) => {
559
581
  console.log(`Session ${event.sessionId} is now in foreground`);
@@ -565,6 +587,7 @@ const unsubscribe = client.onLifecycle("session.foreground", (event) => {
565
587
  Subscribe to all session lifecycle events. Returns an unsubscribe function.
566
588
 
567
589
  <!-- docs-validate: strict -->
590
+
568
591
  ```typescript
569
592
  const unsubscribe = client.onLifecycle((event) => {
570
593
  console.log(`${event.type}: ${event.sessionId}`);
@@ -615,6 +638,7 @@ Use `source: "system"` for automated messages from your application:
615
638
 
616
639
  <!-- docs-validate: strict -->
617
640
  <!-- docs-validate: hidden -->
641
+
618
642
  ```typescript
619
643
  import type { CopilotSession } from "@microsoft/copilot-sdk";
620
644
 
@@ -622,7 +646,9 @@ declare const session: CopilotSession;
622
646
 
623
647
  await session.send({ prompt: "Context updated", source: "system" });
624
648
  ```
649
+
625
650
  <!-- /docs-validate: hidden -->
651
+
626
652
  ```typescript
627
653
  await session.send({ prompt: "Context updated", source: "system" });
628
654
  ```
@@ -631,6 +657,7 @@ For a message from another agent, use its trusted sender ID:
631
657
 
632
658
  <!-- docs-validate: strict -->
633
659
  <!-- docs-validate: hidden -->
660
+
634
661
  ```typescript
635
662
  import type { CopilotSession } from "@microsoft/copilot-sdk";
636
663
 
@@ -638,7 +665,9 @@ declare const session: CopilotSession;
638
665
 
639
666
  await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
640
667
  ```
668
+
641
669
  <!-- /docs-validate: hidden -->
670
+
642
671
  ```typescript
643
672
  await session.send({ prompt: "Review complete", source: "agent-reviewer-id" });
644
673
  ```
@@ -674,6 +703,7 @@ JSON Schema before sending them:
674
703
 
675
704
  <!-- docs-validate: strict -->
676
705
  <!-- docs-validate: hidden -->
706
+
677
707
  ```typescript
678
708
  import type { CopilotSession } from "@microsoft/copilot-sdk";
679
709
 
@@ -688,7 +718,9 @@ const message = await session.sendAndWait({
688
718
  });
689
719
  console.log(message?.data.content); // JSON text
690
720
  ```
721
+
691
722
  <!-- /docs-validate: hidden -->
723
+
692
724
  ```typescript
693
725
  import { z } from "zod";
694
726
 
@@ -704,6 +736,7 @@ For a typed result, pass the Zod schema as the **second argument** instead:
704
736
 
705
737
  <!-- docs-validate: strict -->
706
738
  <!-- docs-validate: hidden -->
739
+
707
740
  ```typescript
708
741
  import type { CopilotSession } from "@microsoft/copilot-sdk";
709
742
 
@@ -715,7 +748,9 @@ const answerSchema = z.object({ answer: z.number().int() });
715
748
  const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
716
749
  console.log(answer.answer); // number; TResult is inferred from answerSchema
717
750
  ```
751
+
718
752
  <!-- /docs-validate: hidden -->
753
+
719
754
  ```typescript
720
755
  const answer = await session.sendAndWait("What is 19 + 23?", answerSchema);
721
756
  console.log(answer.answer); // number; TResult is inferred from answerSchema
@@ -790,6 +825,7 @@ Subscribe to a specific event type. The handler receives properly typed events.
790
825
 
791
826
  <!-- docs-validate: strict -->
792
827
  <!-- docs-validate: hidden -->
828
+
793
829
  ```typescript
794
830
  import type { CopilotSession } from "@microsoft/copilot-sdk";
795
831
 
@@ -809,7 +845,9 @@ session.on("assistant.message_delta", (event) => {
809
845
  process.stdout.write(event.data.deltaContent);
810
846
  });
811
847
  ```
848
+
812
849
  <!-- /docs-validate: hidden -->
850
+
813
851
  ```typescript
814
852
  // Listen for specific event types with full type inference
815
853
  session.on("assistant.message", (event) => {
@@ -832,6 +870,7 @@ Subscribe to all session events. Returns an unsubscribe function.
832
870
 
833
871
  <!-- docs-validate: strict -->
834
872
  <!-- docs-validate: hidden -->
873
+
835
874
  ```typescript
836
875
  import type { CopilotSession } from "@microsoft/copilot-sdk";
837
876
 
@@ -845,7 +884,9 @@ const unsubscribe = session.on((event) => {
845
884
  // Later...
846
885
  unsubscribe();
847
886
  ```
887
+
848
888
  <!-- /docs-validate: hidden -->
889
+
849
890
  ```typescript
850
891
  const unsubscribe = session.on((event) => {
851
892
  // Handle any event type
@@ -862,7 +903,7 @@ Change the model for this session. The new model takes effect for the next messa
862
903
 
863
904
  **Options:**
864
905
 
865
- - `reasoningEffort?: string` - Reasoning effort level
906
+ - `inference.reasoningEffort?: string` - Reasoning effort level
866
907
  - `autoTier?: AutoTier | null` - Auto routing preference to stage together with selecting `auto`. Pass `null` to return to the provider's default Auto routing; omit it to leave the current preference unchanged.
867
908
  - `fusionTier?: FusionTier` - Copilot Fusion tier (`"standard"`, `"high"`, or `"max"`) to stage together with selecting `fusion` or `auto`, for example `setModel("fusion", { fusionTier: "high" })`. Cannot be combined with `autoTier`.
868
909
 
@@ -876,6 +917,7 @@ Watch for the outcome through the `session.model_change` event on success or the
876
917
 
877
918
  <!-- docs-validate: strict -->
878
919
  <!-- docs-validate: hidden -->
920
+
879
921
  ```typescript
880
922
  import type { CopilotSession } from "@microsoft/copilot-sdk";
881
923
 
@@ -886,7 +928,9 @@ if (result.status === "pending") {
886
928
  // Accepted, but not yet in effect.
887
929
  }
888
930
  ```
931
+
889
932
  <!-- /docs-validate: hidden -->
933
+
890
934
  ```typescript
891
935
  const result = await session.setAutoTier("intelligence");
892
936
  if (result.status === "pending") {
@@ -910,6 +954,7 @@ Read the current model's reasoning-summary presentation policy without changing
910
954
 
911
955
  <!-- docs-validate: strict -->
912
956
  <!-- docs-validate: hidden -->
957
+
913
958
  ```typescript
914
959
  import type { CopilotSession } from "@microsoft/copilot-sdk";
915
960
 
@@ -924,7 +969,9 @@ const presentation: ModelGetReasoningSummariesRequest = { summariesVisible: fals
924
969
  const policy: ModelGetReasoningSummariesResult =
925
970
  await session.rpc.model.getReasoningSummaries(presentation);
926
971
  ```
972
+
927
973
  <!-- /docs-validate: hidden -->
974
+
928
975
  ```typescript
929
976
  import type {
930
977
  ModelGetReasoningSummariesRequest,
@@ -946,6 +993,7 @@ Once the runtime accepts the replacement, every tool call this session dispatche
946
993
 
947
994
  <!-- docs-validate: strict -->
948
995
  <!-- docs-validate: hidden -->
996
+
949
997
  ```typescript
950
998
  import type { CopilotSession } from "@microsoft/copilot-sdk";
951
999
 
@@ -963,7 +1011,9 @@ await session.setTools([
963
1011
  }),
964
1012
  ]);
965
1013
  ```
1014
+
966
1015
  <!-- /docs-validate: hidden -->
1016
+
967
1017
  ```typescript
968
1018
  await session.setTools([
969
1019
  defineTool("search_issues", {
@@ -994,6 +1044,7 @@ Host capabilities reported when the session was created or resumed. Use this to
994
1044
 
995
1045
  <!-- docs-validate: strict -->
996
1046
  <!-- docs-validate: hidden -->
1047
+
997
1048
  ```typescript
998
1049
  import type { CopilotSession } from "@microsoft/copilot-sdk";
999
1050
 
@@ -1003,7 +1054,9 @@ if (session.capabilities.ui?.elicitation) {
1003
1054
  const ok = await session.ui.confirm("Deploy?");
1004
1055
  }
1005
1056
  ```
1057
+
1006
1058
  <!-- /docs-validate: hidden -->
1059
+
1007
1060
  ```typescript
1008
1061
  if (session.capabilities.ui?.elicitation) {
1009
1062
  const ok = await session.ui.confirm("Deploy?");
@@ -1125,7 +1178,9 @@ Enable streaming to receive assistant response chunks as they're generated:
1125
1178
  ```typescript
1126
1179
  const session = await client.createSession({
1127
1180
  model: "gpt-5",
1128
- streaming: true,
1181
+ events: {
1182
+ streaming: true,
1183
+ },
1129
1184
  });
1130
1185
 
1131
1186
  // Wait for completion using typed event handlers
@@ -1180,7 +1235,7 @@ Note: `assistant.message` and `assistant.reasoning` (final events) are always se
1180
1235
  ```typescript
1181
1236
  import { CopilotClient } from "@microsoft/copilot-sdk";
1182
1237
 
1183
- const client = new CopilotClient({ mode: "coding-agent"});
1238
+ const client = new CopilotClient({ mode: "coding-agent" });
1184
1239
 
1185
1240
  // Start manually
1186
1241
  await client.start();
@@ -1206,18 +1261,20 @@ declare function fetchIssue(id: string): Promise<string>;
1206
1261
 
1207
1262
  const session = await client.createSession({
1208
1263
  model: "gpt-5",
1209
- tools: [
1210
- defineTool("lookup_issue", {
1211
- description: "Fetch issue details from our tracker",
1212
- parameters: z.object({
1213
- id: z.string().describe("Issue identifier"),
1264
+ tools: {
1265
+ definitions: [
1266
+ defineTool("lookup_issue", {
1267
+ description: "Fetch issue details from our tracker",
1268
+ parameters: z.object({
1269
+ id: z.string().describe("Issue identifier"),
1270
+ }),
1271
+ handler: async ({ id }) => {
1272
+ const issue = await fetchIssue(id);
1273
+ return issue;
1274
+ },
1214
1275
  }),
1215
- handler: async ({ id }) => {
1216
- const issue = await fetchIssue(id);
1217
- return issue;
1218
- },
1219
- }),
1220
- ],
1276
+ ],
1277
+ },
1221
1278
  });
1222
1279
  ```
1223
1280
 
@@ -1229,18 +1286,20 @@ import { defineTool } from "@microsoft/copilot-sdk";
1229
1286
 
1230
1287
  const session = await client.createSession({
1231
1288
  model: "gpt-5",
1232
- tools: [
1233
- defineTool("lookup_issue", {
1234
- description: "Fetch issue details from our tracker",
1235
- parameters: z.object({
1236
- id: z.string().describe("Issue identifier"),
1289
+ tools: {
1290
+ definitions: [
1291
+ defineTool("lookup_issue", {
1292
+ description: "Fetch issue details from our tracker",
1293
+ parameters: z.object({
1294
+ id: z.string().describe("Issue identifier"),
1295
+ }),
1296
+ handler: async ({ id }) => {
1297
+ const issue = await fetchIssue(id);
1298
+ return issue;
1299
+ },
1237
1300
  }),
1238
- handler: async ({ id }) => {
1239
- const issue = await fetchIssue(id);
1240
- return issue;
1241
- },
1242
- }),
1243
- ],
1301
+ ],
1302
+ },
1244
1303
  });
1245
1304
  ```
1246
1305
 
@@ -1391,17 +1450,21 @@ Register slash commands so that users of the CLI's TUI can invoke custom actions
1391
1450
  import { approveAll } from "@microsoft/copilot-sdk";
1392
1451
 
1393
1452
  const session = await client.createSession({
1394
- onPermissionRequest: approveAll,
1395
- commands: [
1396
- {
1397
- name: "deploy",
1398
- description: "Deploy the app to production",
1399
- handler: async ({ commandName, args }) => {
1400
- console.log(`Deploying with args: ${args}`);
1401
- // Do work here — any thrown error is reported back to the CLI
1453
+ permissions: {
1454
+ onRequest: approveAll,
1455
+ },
1456
+ interaction: {
1457
+ commands: [
1458
+ {
1459
+ name: "deploy",
1460
+ description: "Deploy the app to production",
1461
+ handler: async ({ commandName, args }) => {
1462
+ console.log(`Deploying with args: ${args}`);
1463
+ // Do work here — any thrown error is reported back to the CLI
1464
+ },
1402
1465
  },
1403
- },
1404
- ],
1466
+ ],
1467
+ },
1405
1468
  });
1406
1469
  ```
1407
1470
 
@@ -1409,17 +1472,21 @@ const session = await client.createSession({
1409
1472
 
1410
1473
  ```ts
1411
1474
  const session = await client.createSession({
1412
- onPermissionRequest: approveAll,
1413
- commands: [
1414
- {
1415
- name: "deploy",
1416
- description: "Deploy the app to production",
1417
- handler: async ({ commandName, args }) => {
1418
- console.log(`Deploying with args: ${args}`);
1419
- // Do work here — any thrown error is reported back to the CLI
1475
+ permissions: {
1476
+ onRequest: approveAll,
1477
+ },
1478
+ interaction: {
1479
+ commands: [
1480
+ {
1481
+ name: "deploy",
1482
+ description: "Deploy the app to production",
1483
+ handler: async ({ commandName, args }) => {
1484
+ console.log(`Deploying with args: ${args}`);
1485
+ // Do work here — any thrown error is reported back to the CLI
1486
+ },
1420
1487
  },
1421
- },
1422
- ],
1488
+ ],
1489
+ },
1423
1490
  });
1424
1491
  ```
1425
1492
 
@@ -1429,7 +1496,7 @@ Commands are sent to the CLI on both `createSession` and `resumeSession`, so you
1429
1496
 
1430
1497
  ### UI Elicitation
1431
1498
 
1432
- When the session has elicitation support — either from the CLI's TUI or from another client that registered an `onElicitationRequest` handler (see [Elicitation Requests](#elicitation-requests)) — the SDK can request interactive form dialogs from the user. The `session.ui` object provides convenience methods built on a single generic `elicitation` RPC.
1499
+ When the session has elicitation support — either from the CLI's TUI or from another client that registered an `interaction.onElicitationRequest` handler (see [Elicitation Requests](#elicitation-requests)) — the SDK can request interactive form dialogs from the user. The `session.ui` object provides convenience methods built on a single generic `elicitation` RPC.
1433
1500
 
1434
1501
  > **Capability check:** Elicitation is only available when at least one connected participant advertises support. Always check `session.capabilities.ui?.elicitation` before calling UI methods — this property updates automatically as participants join and leave.
1435
1502
 
@@ -1439,7 +1506,11 @@ When the session has elicitation support — either from the CLI's TUI or from a
1439
1506
  ```ts
1440
1507
  import { approveAll } from "@microsoft/copilot-sdk";
1441
1508
 
1442
- const session = await client.createSession({ onPermissionRequest: approveAll });
1509
+ const session = await client.createSession({
1510
+ permissions: {
1511
+ onRequest: approveAll,
1512
+ },
1513
+ });
1443
1514
 
1444
1515
  if (session.capabilities.ui?.elicitation) {
1445
1516
  // Confirm dialog — returns boolean
@@ -1475,7 +1546,11 @@ if (session.capabilities.ui?.elicitation) {
1475
1546
  <!-- /docs-validate: hidden -->
1476
1547
 
1477
1548
  ```ts
1478
- const session = await client.createSession({ onPermissionRequest: approveAll });
1549
+ const session = await client.createSession({
1550
+ permissions: {
1551
+ onRequest: approveAll,
1552
+ },
1553
+ });
1479
1554
 
1480
1555
  if (session.capabilities.ui?.elicitation) {
1481
1556
  // Confirm dialog — returns boolean
@@ -1615,17 +1690,21 @@ console.log(session.workspacePath);
1615
1690
  // Custom thresholds
1616
1691
  const tuned = await client.createSession({
1617
1692
  model: "gpt-5",
1618
- infiniteSessions: {
1619
- enabled: true,
1620
- backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1621
- bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1693
+ state: {
1694
+ infiniteSessions: {
1695
+ enabled: true,
1696
+ backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1697
+ bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1698
+ },
1622
1699
  },
1623
1700
  });
1624
1701
 
1625
1702
  // Disable infinite sessions
1626
1703
  const disabled = await client.createSession({
1627
1704
  model: "gpt-5",
1628
- infiniteSessions: { enabled: false },
1705
+ state: {
1706
+ infiniteSessions: { enabled: false },
1707
+ },
1629
1708
  });
1630
1709
  ```
1631
1710
 
@@ -1642,17 +1721,21 @@ console.log(session.workspacePath);
1642
1721
  // Custom thresholds
1643
1722
  const tuned = await client.createSession({
1644
1723
  model: "gpt-5",
1645
- infiniteSessions: {
1646
- enabled: true,
1647
- backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1648
- bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1724
+ state: {
1725
+ infiniteSessions: {
1726
+ enabled: true,
1727
+ backgroundCompactionThreshold: 0.8, // Start compacting at 80% context usage
1728
+ bufferExhaustionThreshold: 0.95, // Block at 95% until compaction completes
1729
+ },
1649
1730
  },
1650
1731
  });
1651
1732
 
1652
1733
  // Disable infinite sessions
1653
1734
  const disabled = await client.createSession({
1654
1735
  model: "gpt-5",
1655
- infiniteSessions: { enabled: false },
1736
+ state: {
1737
+ infiniteSessions: { enabled: false },
1738
+ },
1656
1739
  });
1657
1740
  ```
1658
1741
 
@@ -1677,13 +1760,17 @@ For more background, see [About GitHub Copilot Memory](https://docs.github.com/e
1677
1760
  // Enable memory for a session
1678
1761
  const enabled = await client.createSession({
1679
1762
  model: "gpt-5",
1680
- memory: { enabled: true },
1763
+ state: {
1764
+ memory: { enabled: true },
1765
+ },
1681
1766
  });
1682
1767
 
1683
1768
  // Disable memory for a session
1684
1769
  const disabled = await client.createSession({
1685
1770
  model: "gpt-5",
1686
- memory: { enabled: false },
1771
+ state: {
1772
+ memory: { enabled: false },
1773
+ },
1687
1774
  });
1688
1775
  ```
1689
1776
 
@@ -1693,13 +1780,17 @@ const disabled = await client.createSession({
1693
1780
  // Enable memory for a session
1694
1781
  const enabled = await client.createSession({
1695
1782
  model: "gpt-5",
1696
- memory: { enabled: true },
1783
+ state: {
1784
+ memory: { enabled: true },
1785
+ },
1697
1786
  });
1698
1787
 
1699
1788
  // Disable memory for a session
1700
1789
  const disabled = await client.createSession({
1701
1790
  model: "gpt-5",
1702
- memory: { enabled: false },
1791
+ state: {
1792
+ memory: { enabled: false },
1793
+ },
1703
1794
  });
1704
1795
  ```
1705
1796
 
@@ -1731,8 +1822,12 @@ const skillProvider: SkillProvider = {
1731
1822
  };
1732
1823
 
1733
1824
  const session = await client.createSession({
1734
- onPermissionRequest: approveAll,
1735
- skillProvider,
1825
+ permissions: {
1826
+ onRequest: approveAll,
1827
+ },
1828
+ skills: {
1829
+ provider: skillProvider,
1830
+ },
1736
1831
  });
1737
1832
  ```
1738
1833
 
@@ -1749,8 +1844,12 @@ const skillProvider: SkillProvider = {
1749
1844
  };
1750
1845
 
1751
1846
  const session = await client.createSession({
1752
- onPermissionRequest: approveAll,
1753
- skillProvider,
1847
+ permissions: {
1848
+ onRequest: approveAll,
1849
+ },
1850
+ skills: {
1851
+ provider: skillProvider,
1852
+ },
1754
1853
  });
1755
1854
  ```
1756
1855
 
@@ -1821,7 +1920,11 @@ const session = await client.createSession({
1821
1920
  ```typescript
1822
1921
  import { approveAll } from "@microsoft/copilot-sdk";
1823
1922
 
1824
- const session = await client.createSession({ onPermissionRequest: approveAll });
1923
+ const session = await client.createSession({
1924
+ permissions: {
1925
+ onRequest: approveAll,
1926
+ },
1927
+ });
1825
1928
 
1826
1929
  await session.send({
1827
1930
  prompt: "Analyze this file",
@@ -1854,7 +1957,7 @@ await session.send({
1854
1957
 
1855
1958
  The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own Key), including local providers like Ollama. When using a custom provider, you must specify the `model` explicitly.
1856
1959
 
1857
- **ProviderConfig:**
1960
+ **NamedProviderConfig:**
1858
1961
 
1859
1962
  - `type?: "openai" | "azure" | "anthropic" | "google"` - Provider type (default: "openai"). `"google"` (experimental) uses Google's native Gemini Interactions API.
1860
1963
  - `baseUrl: string` - API endpoint URL (required)
@@ -1869,11 +1972,19 @@ The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own K
1869
1972
 
1870
1973
  ```typescript
1871
1974
  const session = await client.createSession({
1872
- model: "deepseek-coder-v2:16b", // Required when using custom provider
1873
- provider: {
1874
- type: "openai",
1875
- baseUrl: "http://localhost:11434/v1", // Ollama endpoint
1876
- // apiKey not required for Ollama
1975
+ model: "deepseek-coder-v2:16b",
1976
+ github: { capi: { enabled: false } },
1977
+ inference: {
1978
+ // Required when using custom provider
1979
+ defaultProvider: "byok",
1980
+ providers: [
1981
+ {
1982
+ name: "byok",
1983
+ type: "openai",
1984
+ baseUrl: "http://localhost:11434/v1", // Ollama endpoint
1985
+ // apiKey not required for Ollama
1986
+ },
1987
+ ],
1877
1988
  },
1878
1989
  });
1879
1990
 
@@ -1887,10 +1998,17 @@ await session.sendAndWait({ prompt: "Hello!" });
1887
1998
  ```typescript
1888
1999
  const session = await client.createSession({
1889
2000
  model: "gpt-4",
1890
- provider: {
1891
- type: "openai",
1892
- baseUrl: "https://my-api.example.com/v1",
1893
- apiKey: process.env.MY_API_KEY,
2001
+ github: { capi: { enabled: false } },
2002
+ inference: {
2003
+ defaultProvider: "byok",
2004
+ providers: [
2005
+ {
2006
+ name: "byok",
2007
+ type: "openai",
2008
+ baseUrl: "https://my-api.example.com/v1",
2009
+ apiKey: process.env.MY_API_KEY,
2010
+ },
2011
+ ],
1894
2012
  },
1895
2013
  });
1896
2014
  ```
@@ -1902,13 +2020,20 @@ const session = await client.createSession({
1902
2020
  ```typescript
1903
2021
  const session = await client.createSession({
1904
2022
  model: "gpt-4",
1905
- provider: {
1906
- type: "azure", // Must be "azure" for Azure endpoints, NOT "openai"
1907
- baseUrl: "https://my-resource.openai.azure.com", // Just the host, no path
1908
- apiKey: process.env.AZURE_OPENAI_KEY,
1909
- azure: {
1910
- apiVersion: "2024-10-21",
1911
- },
2023
+ github: { capi: { enabled: false } },
2024
+ inference: {
2025
+ defaultProvider: "byok",
2026
+ providers: [
2027
+ {
2028
+ name: "byok",
2029
+ type: "azure", // Must be "azure" for Azure endpoints, NOT "openai"
2030
+ baseUrl: "https://my-resource.openai.azure.com", // Just the host, no path
2031
+ apiKey: process.env.AZURE_OPENAI_KEY,
2032
+ azure: {
2033
+ apiVersion: "2024-10-21",
2034
+ },
2035
+ },
2036
+ ],
1912
2037
  },
1913
2038
  });
1914
2039
  ```
@@ -1930,8 +2055,10 @@ import { CopilotClient } from "@microsoft/copilot-sdk";
1930
2055
 
1931
2056
  const client = new CopilotClient({
1932
2057
  mode: "coding-agent",
1933
- telemetry: {
1934
- otlpEndpoint: "http://localhost:4318",
2058
+ observability: {
2059
+ telemetry: {
2060
+ otlpEndpoint: "http://localhost:4318",
2061
+ },
1935
2062
  },
1936
2063
  });
1937
2064
  ```
@@ -1961,11 +2088,13 @@ import { propagation, context } from "@opentelemetry/api";
1961
2088
 
1962
2089
  const client = new CopilotClient({
1963
2090
  mode: "coding-agent",
1964
- telemetry: { otlpEndpoint: "http://localhost:4318" },
1965
- onGetTraceContext: () => {
1966
- const carrier: Record<string, string> = {};
1967
- propagation.inject(context.active(), carrier);
1968
- return carrier;
2091
+ observability: {
2092
+ telemetry: { otlpEndpoint: "http://localhost:4318" },
2093
+ onGetTraceContext: () => {
2094
+ const carrier: Record<string, string> = {};
2095
+ propagation.inject(context.active(), carrier);
2096
+ return carrier;
2097
+ },
1969
2098
  },
1970
2099
  });
1971
2100
  ```
@@ -1974,7 +2103,7 @@ Inbound trace context from the CLI is available on the `ToolInvocation` object p
1974
2103
 
1975
2104
  ## Permission Handling
1976
2105
 
1977
- An `onPermissionRequest` handler is optional when you create or resume a session. When provided, it is called before the agent executes each tool (file writes, shell commands, custom tools, etc.) and returns a decision. When omitted, permission requests are emitted as events and left pending for the consumer to resolve with the pending permission RPC.
2106
+ An `permissions.onRequest` handler is optional when you create or resume a session. When provided, it is called before the agent executes each tool (file writes, shell commands, custom tools, etc.) and returns a decision. When omitted, permission requests are emitted as events and left pending for the consumer to resolve with the pending permission RPC.
1978
2107
 
1979
2108
  Callbacks receive optional derived prompt context as `invocation.promptRequest`. The raw request's `managedApprovalRequired` remains managed-policy provenance and enforces one-shot restrictions. Only derived `commands`, `read`, `write`, `url`, and `workflow` prompts can clear the human requirement after Assisted approval; for missing or other prompt kinds, keep the raw marker authoritative.
1980
2109
 
@@ -1990,7 +2119,9 @@ import { approveAll } from "@microsoft/copilot-sdk";
1990
2119
 
1991
2120
  const session = await client.createSession({
1992
2121
  model: "gpt-5",
1993
- onPermissionRequest: approveAll,
2122
+ permissions: {
2123
+ onRequest: approveAll,
2124
+ },
1994
2125
  });
1995
2126
  ```
1996
2127
 
@@ -2001,11 +2132,13 @@ import { CopilotClient, approveAll } from "@microsoft/copilot-sdk";
2001
2132
 
2002
2133
  const session = await client.createSession({
2003
2134
  model: "gpt-5",
2004
- onPermissionRequest: approveAll,
2135
+ permissions: {
2136
+ onRequest: approveAll,
2137
+ },
2005
2138
  });
2006
2139
  ```
2007
2140
 
2008
- When `enableManagedSettings` is true for the session, `approveAll` throws. Use a custom handler for managed sessions; request-level `managedApprovalRequired` remains available for human-facing confirmation logic.
2141
+ When `github.fetchManagedSettings` is true for the session, `approveAll` throws. Use a custom handler for managed sessions; request-level `managedApprovalRequired` remains available for human-facing confirmation logic.
2009
2142
 
2010
2143
  ### Custom Permission Handler
2011
2144
 
@@ -2018,33 +2151,35 @@ import type { PermissionRequest, PermissionRequestResult } from "@microsoft/copi
2018
2151
 
2019
2152
  const session = await client.createSession({
2020
2153
  model: "gpt-5",
2021
- onPermissionRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
2022
- if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
2023
- // Leave the request pending for the host's human-facing confirmation flow.
2024
- return { kind: "no-result" };
2025
- }
2026
-
2027
- // request.kind — what type of operation is being requested:
2028
- // "shell" — executing a shell command
2029
- // "write" — writing or editing a file
2030
- // "read" — reading a file
2031
- // "mcp" — calling an MCP tool
2032
- // "custom-tool" — calling one of your registered tools
2033
- // "url" — fetching a URL
2034
- // "memory" — storing or retrieving persistent session memory
2035
- // "hook" — invoking a server-side hook or integration
2036
- // (additional kinds may be added; include a default case in handlers)
2037
- // request.toolCallId — the tool call that triggered this request
2038
- // request.toolName — name of the tool (for custom-tool / mcp)
2039
- // request.fileName — file being written (for write)
2040
- // request.fullCommandText — full shell command (for shell)
2041
-
2042
- if (request.kind === "shell") {
2043
- // Deny shell commands, optionally telling the model why
2044
- return { kind: "reject", feedback: "Shell commands are not allowed." };
2045
- }
2046
-
2047
- return { kind: "approve-once" };
2154
+ permissions: {
2155
+ onRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
2156
+ if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
2157
+ // Leave the request pending for the host's human-facing confirmation flow.
2158
+ return { kind: "no-result" };
2159
+ }
2160
+
2161
+ // request.kind — what type of operation is being requested:
2162
+ // "shell" — executing a shell command
2163
+ // "write" — writing or editing a file
2164
+ // "read" — reading a file
2165
+ // "mcp" — calling an MCP tool
2166
+ // "custom-tool" — calling one of your registered tools
2167
+ // "url" — fetching a URL
2168
+ // "memory" — storing or retrieving persistent session memory
2169
+ // "hook" — invoking a server-side hook or integration
2170
+ // (additional kinds may be added; include a default case in handlers)
2171
+ // request.toolCallId — the tool call that triggered this request
2172
+ // request.toolName — name of the tool (for custom-tool / mcp)
2173
+ // request.fileName — file being written (for write)
2174
+ // request.fullCommandText — full shell command (for shell)
2175
+
2176
+ if (request.kind === "shell") {
2177
+ // Deny shell commands, optionally telling the model why
2178
+ return { kind: "reject", feedback: "Shell commands are not allowed." };
2179
+ }
2180
+
2181
+ return { kind: "approve-once" };
2182
+ },
2048
2183
  },
2049
2184
  });
2050
2185
  ```
@@ -2145,7 +2280,7 @@ The handler must return one of the `PermissionDecision` shapes (or `{ kind: "no-
2145
2280
 
2146
2281
  ### Resuming Sessions
2147
2282
 
2148
- You may pass `onPermissionRequest` when resuming a session too:
2283
+ You may pass `permissions.onRequest` when resuming a session too:
2149
2284
 
2150
2285
  <!-- docs-validate: strict -->
2151
2286
  <!-- docs-validate: hidden -->
@@ -2154,7 +2289,9 @@ You may pass `onPermissionRequest` when resuming a session too:
2154
2289
  import { approveAll } from "@microsoft/copilot-sdk";
2155
2290
 
2156
2291
  const session = await client.resumeSession("session-id", {
2157
- onPermissionRequest: approveAll,
2292
+ permissions: {
2293
+ onRequest: approveAll,
2294
+ },
2158
2295
  });
2159
2296
  ```
2160
2297
 
@@ -2162,7 +2299,9 @@ const session = await client.resumeSession("session-id", {
2162
2299
 
2163
2300
  ```typescript
2164
2301
  const session = await client.resumeSession("session-id", {
2165
- onPermissionRequest: approveAll,
2302
+ permissions: {
2303
+ onRequest: approveAll,
2304
+ },
2166
2305
  });
2167
2306
  ```
2168
2307
 
@@ -2172,29 +2311,31 @@ To let a specific custom tool bypass the permission prompt entirely, set `skipPe
2172
2311
 
2173
2312
  ## User Input Requests
2174
2313
 
2175
- Enable the legacy question-and-answer `ask_user` tool by providing an `onUserInputRequest` handler:
2314
+ Enable the legacy question-and-answer `ask_user` tool by providing an `interaction.onUserInputRequest` handler:
2176
2315
 
2177
2316
  <!-- docs-validate: strict -->
2178
2317
 
2179
2318
  ```typescript
2180
2319
  const session = await client.createSession({
2181
2320
  model: "gpt-5",
2182
- onUserInputRequest: async (request, invocation) => {
2183
- // request.question - The question to ask
2184
- // request.choices - Optional array of choices for multiple choice
2185
- // request.allowFreeform - Whether freeform input is allowed (default: true)
2186
- // request.requestId - Runtime ID of the pending request (absent on older runtimes)
2187
-
2188
- console.log(`Agent asks: ${request.question}`);
2189
- if (request.choices) {
2190
- console.log(`Choices: ${request.choices.join(", ")}`);
2191
- }
2192
-
2193
- // Return the user's response
2194
- return {
2195
- answer: "User's answer here",
2196
- wasFreeform: true, // Whether the answer was freeform (not from choices)
2197
- };
2321
+ interaction: {
2322
+ onUserInputRequest: async (request, invocation) => {
2323
+ // request.question - The question to ask
2324
+ // request.choices - Optional array of choices for multiple choice
2325
+ // request.allowFreeform - Whether freeform input is allowed (default: true)
2326
+ // request.requestId - Runtime ID of the pending request (absent on older runtimes)
2327
+
2328
+ console.log(`Agent asks: ${request.question}`);
2329
+ if (request.choices) {
2330
+ console.log(`Choices: ${request.choices.join(", ")}`);
2331
+ }
2332
+
2333
+ // Return the user's response
2334
+ return {
2335
+ answer: "User's answer here",
2336
+ wasFreeform: true, // Whether the answer was freeform (not from choices)
2337
+ };
2338
+ },
2198
2339
  },
2199
2340
  });
2200
2341
  ```
@@ -2217,10 +2358,12 @@ const personAnswered: PermissionDecisionContext = {
2217
2358
 
2218
2359
  const session = await client.createSession({
2219
2360
  model: "gpt-5",
2220
- onUserInputRequest: async (request) =>
2221
- createAttributedResult({ answer: "Only src/app.ts", wasFreeform: true }, personAnswered),
2222
- onExitPlanModeRequest: async () =>
2223
- createAttributedResult({ approved: true, selectedAction: "interactive" }, personAnswered),
2361
+ interaction: {
2362
+ onUserInputRequest: async (request) =>
2363
+ createAttributedResult({ answer: "Only src/app.ts", wasFreeform: true }, personAnswered),
2364
+ onExitPlanModeRequest: async () =>
2365
+ createAttributedResult({ approved: true, selectedAction: "interactive" }, personAnswered),
2366
+ },
2224
2367
  });
2225
2368
  ```
2226
2369
 
@@ -2228,7 +2371,7 @@ Label a person's declines and dismissals too; the runtime decides which answers
2228
2371
 
2229
2372
  ## Elicitation Requests
2230
2373
 
2231
- Register an `onElicitationRequest` handler to let your client act as an elicitation provider — presenting form-based UI dialogs on behalf of the agent. When provided, the server notifies your client whenever a tool or MCP server needs structured user input.
2374
+ Register an `interaction.onElicitationRequest` handler to let your client act as an elicitation provider — presenting form-based UI dialogs on behalf of the agent. When provided, the server notifies your client whenever a tool or MCP server needs structured user input.
2232
2375
 
2233
2376
  <!-- docs-validate: strict -->
2234
2377
 
@@ -2237,22 +2380,26 @@ import { approveAll } from "@microsoft/copilot-sdk";
2237
2380
 
2238
2381
  const session = await client.createSession({
2239
2382
  model: "gpt-5",
2240
- onPermissionRequest: approveAll,
2241
- askUserVariant: "elicitation",
2242
- onElicitationRequest: async (context) => {
2243
- // context.sessionId - Session that triggered the request
2244
- // context.message - Description of what information is needed
2245
- // context.requestedSchema - JSON Schema describing the form fields
2246
- // context.mode - "form" (structured input) or "url" (browser redirect)
2247
- // context.elicitationSource - Origin of the request (e.g. MCP server name)
2248
-
2249
- console.log(`Elicitation from ${context.elicitationSource}: ${context.message}`);
2250
-
2251
- // Present UI to the user and collect their response...
2252
- return {
2253
- action: "accept", // "accept", "decline", or "cancel"
2254
- content: { region: "us-east", dryRun: true },
2255
- };
2383
+ permissions: {
2384
+ onRequest: approveAll,
2385
+ },
2386
+ interaction: {
2387
+ askUserVariant: "elicitation",
2388
+ onElicitationRequest: async (context) => {
2389
+ // context.sessionId - Session that triggered the request
2390
+ // context.message - Description of what information is needed
2391
+ // context.requestedSchema - JSON Schema describing the form fields
2392
+ // context.mode - "form" (structured input) or "url" (browser redirect)
2393
+ // context.elicitationSource - Origin of the request (e.g. MCP server name)
2394
+
2395
+ console.log(`Elicitation from ${context.elicitationSource}: ${context.message}`);
2396
+
2397
+ // Present UI to the user and collect their response...
2398
+ return {
2399
+ action: "accept", // "accept", "decline", or "cancel"
2400
+ content: { region: "us-east", dryRun: true },
2401
+ };
2402
+ },
2256
2403
  },
2257
2404
  });
2258
2405
 
@@ -2263,7 +2410,7 @@ console.log(session.capabilities.ui?.elicitation); // true
2263
2410
  Set `askUserVariant: "elicitation"` to expose the structured form as the model's
2264
2411
  `ask_user` tool. Omit it to retain the legacy SDK behavior.
2265
2412
 
2266
- When `onElicitationRequest` is provided, the SDK sends `requestElicitation: true` during session create/resume, which enables `session.capabilities.ui.elicitation` on the session.
2413
+ When `interaction.onElicitationRequest` is provided, the SDK sends `requestElicitation: true` during session create/resume, which enables `session.capabilities.ui.elicitation` on the session.
2267
2414
 
2268
2415
  In multi-client scenarios:
2269
2416
 
@@ -2284,87 +2431,89 @@ declare function needsMoreWork(): boolean;
2284
2431
  const session = await client.createSession({
2285
2432
  model: "gpt-5",
2286
2433
  hooks: {
2287
- // Called before each tool execution
2288
- onPreToolUse: async (input, invocation) => {
2289
- console.log(`About to run tool: ${input.toolName}`);
2290
- // Return permission decision and optionally modify args
2291
- return {
2292
- permissionDecision: "allow", // "allow", "deny", or "ask"
2293
- modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2294
- additionalContext: "Extra context for the model",
2295
- };
2296
- },
2297
-
2298
- // Called after each successful tool execution
2299
- onPostToolUse: async (input, invocation) => {
2300
- console.log(`Tool ${input.toolName} completed`);
2301
- // Optionally modify the result or add context
2302
- return {
2303
- additionalContext: "Post-execution notes",
2304
- };
2305
- },
2434
+ handlers: {
2435
+ // Called before each tool execution
2436
+ onPreToolUse: async (input, invocation) => {
2437
+ console.log(`About to run tool: ${input.toolName}`);
2438
+ // Return permission decision and optionally modify args
2439
+ return {
2440
+ permissionDecision: "allow", // "allow", "deny", or "ask"
2441
+ modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2442
+ additionalContext: "Extra context for the model",
2443
+ };
2444
+ },
2306
2445
 
2307
- // Called after a tool execution whose result was "failure".
2308
- // onPostToolUse does NOT fire for failed tool calls — register this
2309
- // hook to observe them. Input includes `error` (the failure message
2310
- // extracted from the tool's result), not the full result object.
2311
- onPostToolUseFailure: async (input, invocation) => {
2312
- console.log(`Tool ${input.toolName} failed: ${input.error}`);
2313
- // Optionally append hidden guidance to the model.
2314
- return { additionalContext: "Suggest checking inputs and retrying." };
2315
- },
2446
+ // Called after each successful tool execution
2447
+ onPostToolUse: async (input, invocation) => {
2448
+ console.log(`Tool ${input.toolName} completed`);
2449
+ // Optionally modify the result or add context
2450
+ return {
2451
+ additionalContext: "Post-execution notes",
2452
+ };
2453
+ },
2316
2454
 
2317
- // Called when user submits a prompt
2318
- onUserPromptSubmitted: async (input, invocation) => {
2319
- console.log(`User prompt: ${input.prompt}`);
2320
- return {
2321
- modifiedPrompt: input.prompt, // Optionally modify the prompt
2322
- };
2323
- },
2455
+ // Called after a tool execution whose result was "failure".
2456
+ // onPostToolUse does NOT fire for failed tool calls — register this
2457
+ // hook to observe them. Input includes `error` (the failure message
2458
+ // extracted from the tool's result), not the full result object.
2459
+ onPostToolUseFailure: async (input, invocation) => {
2460
+ console.log(`Tool ${input.toolName} failed: ${input.error}`);
2461
+ // Optionally append hidden guidance to the model.
2462
+ return { additionalContext: "Suggest checking inputs and retrying." };
2463
+ },
2324
2464
 
2325
- // Called when session starts
2326
- onSessionStart: async (input, invocation) => {
2327
- console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2328
- return {
2329
- additionalContext: "Session initialization context",
2330
- };
2331
- },
2465
+ // Called when user submits a prompt
2466
+ onUserPromptSubmitted: async (input, invocation) => {
2467
+ console.log(`User prompt: ${input.prompt}`);
2468
+ return {
2469
+ modifiedPrompt: input.prompt, // Optionally modify the prompt
2470
+ };
2471
+ },
2332
2472
 
2333
- // Called when session ends
2334
- onSessionEnd: async (input, invocation) => {
2335
- console.log(`Session ended: ${input.reason}`);
2336
- },
2473
+ // Called when session starts
2474
+ onSessionStart: async (input, invocation) => {
2475
+ console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2476
+ return {
2477
+ additionalContext: "Session initialization context",
2478
+ };
2479
+ },
2337
2480
 
2338
- // Called when an error occurs
2339
- onErrorOccurred: async (input, invocation) => {
2340
- console.error(`Error in ${input.errorContext}: ${input.error}`);
2341
- return {
2342
- errorHandling: "retry", // "retry", "skip", or "abort"
2343
- };
2344
- },
2481
+ // Called when session ends
2482
+ onSessionEnd: async (input, invocation) => {
2483
+ console.log(`Session ended: ${input.reason}`);
2484
+ },
2345
2485
 
2346
- // Called when the top-level agent naturally stops
2347
- onAgentStop: async (input, invocation) => {
2348
- if (!input.stopHookActive && needsMoreWork()) {
2486
+ // Called when an error occurs
2487
+ onErrorOccurred: async (input, invocation) => {
2488
+ console.error(`Error in ${input.errorContext}: ${input.error}`);
2349
2489
  return {
2350
- decision: "block",
2351
- reason: "Run the final validation and fix any failures.",
2490
+ errorHandling: "retry", // "retry", "skip", or "abort"
2352
2491
  };
2353
- }
2354
- },
2492
+ },
2355
2493
 
2356
- // Called before a sub-agent's first turn (the input identifies the parent session)
2357
- onSubagentStart: (input, invocation) => {
2358
- console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2359
- return { additionalContext: "Check the requested file before reporting back." };
2360
- },
2494
+ // Called when the top-level agent naturally stops
2495
+ onAgentStop: async (input, invocation) => {
2496
+ if (!input.stopHookActive && needsMoreWork()) {
2497
+ return {
2498
+ decision: "block",
2499
+ reason: "Run the final validation and fix any failures.",
2500
+ };
2501
+ }
2502
+ },
2361
2503
 
2362
- // Called when a sub-agent completes a turn
2363
- onSubagentStop: (input, invocation) => {
2364
- console.log(`${input.agentName} replied: ${input.response}`);
2365
- // Return { decision: "block", reason: "Continue checking the file." }
2366
- // to request another child turn instead.
2367
- return { modifiedResponse: `Reviewed: ${input.response}` };
2504
+ // Called before a sub-agent's first turn (the input identifies the parent session)
2505
+ onSubagentStart: (input, invocation) => {
2506
+ console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2507
+ return { additionalContext: "Check the requested file before reporting back." };
2508
+ },
2509
+
2510
+ // Called when a sub-agent completes a turn
2511
+ onSubagentStop: (input, invocation) => {
2512
+ console.log(`${input.agentName} replied: ${input.response}`);
2513
+ // Return { decision: "block", reason: "Continue checking the file." }
2514
+ // to request another child turn instead.
2515
+ return { modifiedResponse: `Reviewed: ${input.response}` };
2516
+ },
2368
2517
  },
2369
2518
  },
2370
2519
  });
@@ -2376,87 +2525,89 @@ const session = await client.createSession({
2376
2525
  const session = await client.createSession({
2377
2526
  model: "gpt-5",
2378
2527
  hooks: {
2379
- // Called before each tool execution
2380
- onPreToolUse: async (input, invocation) => {
2381
- console.log(`About to run tool: ${input.toolName}`);
2382
- // Return permission decision and optionally modify args
2383
- return {
2384
- permissionDecision: "allow", // "allow", "deny", or "ask"
2385
- modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2386
- additionalContext: "Extra context for the model",
2387
- };
2388
- },
2389
-
2390
- // Called after each successful tool execution
2391
- onPostToolUse: async (input, invocation) => {
2392
- console.log(`Tool ${input.toolName} completed`);
2393
- // Optionally modify the result or add context
2394
- return {
2395
- additionalContext: "Post-execution notes",
2396
- };
2397
- },
2528
+ handlers: {
2529
+ // Called before each tool execution
2530
+ onPreToolUse: async (input, invocation) => {
2531
+ console.log(`About to run tool: ${input.toolName}`);
2532
+ // Return permission decision and optionally modify args
2533
+ return {
2534
+ permissionDecision: "allow", // "allow", "deny", or "ask"
2535
+ modifiedArgs: input.toolArgs, // Optionally modify tool arguments
2536
+ additionalContext: "Extra context for the model",
2537
+ };
2538
+ },
2398
2539
 
2399
- // Called after a tool execution whose result was "failure".
2400
- // onPostToolUse does NOT fire for failed tool calls — register this
2401
- // hook to observe them. Input includes `error` (the failure message
2402
- // extracted from the tool's result), not the full result object.
2403
- onPostToolUseFailure: async (input, invocation) => {
2404
- console.log(`Tool ${input.toolName} failed: ${input.error}`);
2405
- // Optionally append hidden guidance to the model.
2406
- return { additionalContext: "Suggest checking inputs and retrying." };
2407
- },
2540
+ // Called after each successful tool execution
2541
+ onPostToolUse: async (input, invocation) => {
2542
+ console.log(`Tool ${input.toolName} completed`);
2543
+ // Optionally modify the result or add context
2544
+ return {
2545
+ additionalContext: "Post-execution notes",
2546
+ };
2547
+ },
2408
2548
 
2409
- // Called when user submits a prompt
2410
- onUserPromptSubmitted: async (input, invocation) => {
2411
- console.log(`User prompt: ${input.prompt}`);
2412
- return {
2413
- modifiedPrompt: input.prompt, // Optionally modify the prompt
2414
- };
2415
- },
2549
+ // Called after a tool execution whose result was "failure".
2550
+ // onPostToolUse does NOT fire for failed tool calls — register this
2551
+ // hook to observe them. Input includes `error` (the failure message
2552
+ // extracted from the tool's result), not the full result object.
2553
+ onPostToolUseFailure: async (input, invocation) => {
2554
+ console.log(`Tool ${input.toolName} failed: ${input.error}`);
2555
+ // Optionally append hidden guidance to the model.
2556
+ return { additionalContext: "Suggest checking inputs and retrying." };
2557
+ },
2416
2558
 
2417
- // Called when session starts
2418
- onSessionStart: async (input, invocation) => {
2419
- console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2420
- return {
2421
- additionalContext: "Session initialization context",
2422
- };
2423
- },
2559
+ // Called when user submits a prompt
2560
+ onUserPromptSubmitted: async (input, invocation) => {
2561
+ console.log(`User prompt: ${input.prompt}`);
2562
+ return {
2563
+ modifiedPrompt: input.prompt, // Optionally modify the prompt
2564
+ };
2565
+ },
2424
2566
 
2425
- // Called when session ends
2426
- onSessionEnd: async (input, invocation) => {
2427
- console.log(`Session ended: ${input.reason}`);
2428
- },
2567
+ // Called when session starts
2568
+ onSessionStart: async (input, invocation) => {
2569
+ console.log(`Session started from: ${input.source}`); // "startup", "resume", "new"
2570
+ return {
2571
+ additionalContext: "Session initialization context",
2572
+ };
2573
+ },
2429
2574
 
2430
- // Called when an error occurs
2431
- onErrorOccurred: async (input, invocation) => {
2432
- console.error(`Error in ${input.errorContext}: ${input.error}`);
2433
- return {
2434
- errorHandling: "retry", // "retry", "skip", or "abort"
2435
- };
2436
- },
2575
+ // Called when session ends
2576
+ onSessionEnd: async (input, invocation) => {
2577
+ console.log(`Session ended: ${input.reason}`);
2578
+ },
2437
2579
 
2438
- // Called when the top-level agent naturally stops
2439
- onAgentStop: async (input, invocation) => {
2440
- if (!input.stopHookActive && needsMoreWork()) {
2580
+ // Called when an error occurs
2581
+ onErrorOccurred: async (input, invocation) => {
2582
+ console.error(`Error in ${input.errorContext}: ${input.error}`);
2441
2583
  return {
2442
- decision: "block",
2443
- reason: "Run the final validation and fix any failures.",
2584
+ errorHandling: "retry", // "retry", "skip", or "abort"
2444
2585
  };
2445
- }
2446
- },
2586
+ },
2447
2587
 
2448
- // Called before a sub-agent's first turn (the input identifies the parent session)
2449
- onSubagentStart: (input, invocation) => {
2450
- console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2451
- return { additionalContext: "Check the requested file before reporting back." };
2452
- },
2588
+ // Called when the top-level agent naturally stops
2589
+ onAgentStop: async (input, invocation) => {
2590
+ if (!input.stopHookActive && needsMoreWork()) {
2591
+ return {
2592
+ decision: "block",
2593
+ reason: "Run the final validation and fix any failures.",
2594
+ };
2595
+ }
2596
+ },
2453
2597
 
2454
- // Called when a sub-agent completes a turn
2455
- onSubagentStop: (input, invocation) => {
2456
- console.log(`${input.agentName} replied: ${input.response}`);
2457
- // Return { decision: "block", reason: "Continue checking the file." }
2458
- // to request another child turn instead.
2459
- return { modifiedResponse: `Reviewed: ${input.response}` };
2598
+ // Called before a sub-agent's first turn (the input identifies the parent session)
2599
+ onSubagentStart: (input, invocation) => {
2600
+ console.log(`Starting ${input.agentDisplayName ?? input.agentName}`);
2601
+ return { additionalContext: "Check the requested file before reporting back." };
2602
+ },
2603
+
2604
+ // Called when a sub-agent completes a turn
2605
+ onSubagentStop: (input, invocation) => {
2606
+ console.log(`${input.agentName} replied: ${input.response}`);
2607
+ // Return { decision: "block", reason: "Continue checking the file." }
2608
+ // to request another child turn instead.
2609
+ return { modifiedResponse: `Reviewed: ${input.response}` };
2610
+ },
2460
2611
  },
2461
2612
  },
2462
2613
  });