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

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
@@ -79,18 +79,17 @@ new CopilotClient(options?: CopilotClientOptions)
79
79
 
80
80
  **Options:**
81
81
 
82
- - `cliPath?: string` - Path to CLI executable (default: uses COPILOT_CLI_PATH env var or bundled instance)
83
- - `cliArgs?: string[]` - Extra arguments prepended before SDK-managed flags (e.g. `["./dist-cli/index.js"]` when using `node`)
84
- - `cliUrl?: string` - URL of existing CLI server to connect to (e.g., `"localhost:8080"`, `"http://127.0.0.1:9000"`, or just `"8080"`). When provided, the client will not spawn a CLI process.
85
- - `port?: number` - Server port (default: 0 for random)
86
- - `useStdio?: boolean` - Use stdio transport instead of TCP (default: true)
87
- - `logLevel?: string` - Log level (default: "info")
88
- - `autoStart?: boolean` - Auto-start server (default: true)
82
+ - `connection?: RuntimeConnection` - How to connect to the Copilot runtime. Construct via the factory functions on `RuntimeConnection`:
83
+ - `RuntimeConnection.forStdio({ path?, args? })` (default) — spawn the runtime and communicate over its stdin/stdout.
84
+ - `RuntimeConnection.forTcp({ port?, connectionToken?, path?, args? })` — spawn the runtime as a TCP server.
85
+ - `RuntimeConnection.forUri(url, { connectionToken? })` — connect to an already-running runtime (mutually exclusive with `gitHubToken`/`useLoggedInUser`).
86
+ - `cwd?: string` - Working directory for the runtime process (default: current process cwd).
87
+ - `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`.
88
+ - `logLevel?: string` - Log level. When omitted, the runtime uses its own default (currently `"info"`).
89
89
  - `gitHubToken?: string` - GitHub token for authentication. When provided, takes priority over other auth methods.
90
- - `useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `gitHubToken` is provided). Cannot be used with `cliUrl`.
91
- - `copilotHome?: string` - Base directory for Copilot data (session state, config, etc.). Sets `COPILOT_HOME` on the spawned CLI process. When not set, the CLI defaults to `~/.copilot`. Useful in restricted environments where only specific directories are writable. Ignored when using `cliUrl`.
92
- - `telemetry?: TelemetryConfig` - OpenTelemetry configuration for the CLI process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
93
- - `onGetTraceContext?: TraceContextProvider` - Advanced: callback for linking your application's own OpenTelemetry spans into the same distributed trace as the CLI's spans. Not needed for normal telemetry collection. See [Telemetry](#telemetry) below.
90
+ - `useLoggedInUser?: boolean` - Whether to use logged-in user for authentication (default: true, but false when `gitHubToken` is provided). Cannot be used with `RuntimeConnection.forUri`.
91
+ - `telemetry?: TelemetryConfig` - OpenTelemetry configuration for the runtime process. Providing this object enables telemetry — no separate flag needed. See [Telemetry](#telemetry) below.
92
+ - `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.
94
93
 
95
94
  #### Methods
96
95
 
@@ -132,10 +131,6 @@ Resume an existing session. Returns the session with `workspacePath` populated i
132
131
 
133
132
  Ping the server to check connectivity.
134
133
 
135
- ##### `getState(): ConnectionState`
136
-
137
- Get current connection state.
138
-
139
134
  ##### `listSessions(filter?: SessionListFilter): Promise<SessionMetadata[]>`
140
135
 
141
136
  List all available sessions. Optionally filter by working directory context.
@@ -173,7 +168,7 @@ Request the TUI to switch to displaying the specified session. Only available in
173
168
  Subscribe to a specific session lifecycle event type. Returns an unsubscribe function.
174
169
 
175
170
  ```typescript
176
- const unsubscribe = client.on("session.foreground", (event) => {
171
+ const unsubscribe = client.onLifecycle("session.foreground", (event) => {
177
172
  console.log(`Session ${event.sessionId} is now in foreground`);
178
173
  });
179
174
  ```
@@ -183,7 +178,7 @@ const unsubscribe = client.on("session.foreground", (event) => {
183
178
  Subscribe to all session lifecycle events. Returns an unsubscribe function.
184
179
 
185
180
  ```typescript
186
- const unsubscribe = client.on((event) => {
181
+ const unsubscribe = client.onLifecycle((event) => {
187
182
  console.log(`${event.type}: ${event.sessionId}`);
188
183
  });
189
184
  ```
@@ -277,7 +272,7 @@ unsubscribe();
277
272
 
278
273
  Abort the currently processing message in this session.
279
274
 
280
- ##### `getMessages(): Promise<SessionEvent[]>`
275
+ ##### `getEvents(): Promise<SessionEvent[]>`
281
276
 
282
277
  Get all events/messages from this session.
283
278
 
@@ -415,7 +410,7 @@ Note: `assistant.message` and `assistant.reasoning` (final events) are always se
415
410
  ### Manual Server Control
416
411
 
417
412
  ```typescript
418
- const client = new CopilotClient({ autoStart: false });
413
+ const client = new CopilotClient({});
419
414
 
420
415
  // Start manually
421
416
  await client.start();
@@ -574,8 +569,8 @@ The SDK auto-injects environment context, tool instructions, and security guardr
574
569
  Use `mode: "customize"` to selectively override individual sections of the prompt while preserving the rest:
575
570
 
576
571
  ```typescript
577
- import { SYSTEM_PROMPT_SECTIONS } from "@github/copilot-sdk";
578
- import type { SectionOverride, SystemPromptSection } from "@github/copilot-sdk";
572
+ import { SYSTEM_MESSAGE_SECTIONS } from "@github/copilot-sdk";
573
+ import type { SectionOverride, SystemMessageSection } from "@github/copilot-sdk";
579
574
 
580
575
  const session = await client.createSession({
581
576
  model: "gpt-5",
@@ -598,7 +593,7 @@ const session = await client.createSession({
598
593
  });
599
594
  ```
600
595
 
601
- Available section IDs: `identity`, `tone`, `tool_efficiency`, `environment_context`, `code_change_rules`, `guidelines`, `safety`, `tool_instructions`, `custom_instructions`, `last_instructions`. Use the `SYSTEM_PROMPT_SECTIONS` constant for descriptions of each section.
596
+ Available section IDs: `identity`, `tone`, `tool_efficiency`, `environment_context`, `code_change_rules`, `guidelines`, `safety`, `tool_instructions`, `custom_instructions`, `runtime_instructions`, `last_instructions`. Use the `SYSTEM_MESSAGE_SECTIONS` constant for descriptions of each section.
602
597
 
603
598
  Each section override supports four actions:
604
599
 
@@ -856,15 +851,15 @@ const session = await client.createSession({
856
851
 
857
852
  The handler must return one of the `PermissionDecision` shapes (or `{ kind: "no-result" }`). Approval scopes are present-tense — they describe the decision to apply, not the outcome reported back on session events:
858
853
 
859
- | Kind | Meaning | Extra fields |
860
- | ------------------------ | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
861
- | `"approve-once"` | Allow this single request | — |
862
- | `"approve-for-session"` | Allow this request and remember the approval for the rest of the session | `approval?` (rule to remember), `domain?` (for URL approvals) |
854
+ | Kind | Meaning | Extra fields |
855
+ | ------------------------ | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
856
+ | `"approve-once"` | Allow this single request | — |
857
+ | `"approve-for-session"` | Allow this request and remember the approval for the rest of the session | `approval?` (rule to remember), `domain?` (for URL approvals) |
863
858
  | `"approve-for-location"` | Allow this request and persist the approval for this project location (git root or cwd) | `approval` (rule to persist), `locationKey` (location to persist under) |
864
859
  | `"approve-permanently"` | Allow this request and persist the approval across sessions (currently used for URL domains) | `domain` (URL domain to approve) |
865
- | `"reject"` | Deny the request | `feedback?` (optional string surfaced to the agent) |
866
- | `"user-not-available"` | Deny the request because no user is available to confirm it | — |
867
- | `"no-result"` | Leave the request unanswered (only valid with protocol v1; rejected by protocol v2 servers) | — |
860
+ | `"reject"` | Deny the request | `feedback?` (optional string surfaced to the agent) |
861
+ | `"user-not-available"` | Deny the request because no user is available to confirm it | — |
862
+ | `"no-result"` | Leave the request unanswered (only valid with protocol v1; rejected by protocol v2 servers) | — |
868
863
 
869
864
  ### Resuming Sessions
870
865
 
@@ -1026,7 +1021,7 @@ try {
1026
1021
  ## Requirements
1027
1022
 
1028
1023
  - Node.js >= 18.0.0
1029
- - GitHub Copilot CLI installed and in PATH (or provide custom `cliPath`)
1024
+ - GitHub Copilot CLI installed and in PATH (or provide a custom `connection`)
1030
1025
 
1031
1026
  ## License
1032
1027
 
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Extension-owned canvases declared via
3
+ * `joinSession({ canvases: [createCanvas({...})] })`.
4
+ *
5
+ * The runtime sends provider callbacks directly as `canvas.open`,
6
+ * `canvas.close`, and `canvas.action.invoke` JSON-RPC requests. The SDK
7
+ * routes those requests by `canvasId` to the in-process handlers bound by
8
+ * `createCanvas`. Re-opening with an existing `instanceId` is how the host
9
+ * focuses an existing panel; reload is a renderer-only concern.
10
+ */
11
+ /** JSON Schema object used for canvas inputs. */
12
+ export type CanvasJsonSchema = Record<string, unknown>;
13
+ /**
14
+ * A single agent-callable action contributed by a canvas. The metadata
15
+ * (`name`, `description`, `inputSchema`) is serialized over the wire on
16
+ * `session.create` / `session.resume`; the `handler` closure is stripped
17
+ * before the declaration is sent and dispatched in-process by the SDK.
18
+ *
19
+ * Names MUST NOT start with `canvas.` — that prefix is reserved for
20
+ * lifecycle verbs.
21
+ */
22
+ export interface CanvasAction {
23
+ /** Action identifier, unique within the canvas. */
24
+ name: string;
25
+ /** Description shown to the model when picking an action. */
26
+ description?: string;
27
+ /** Optional JSON Schema for the action's `input` payload. */
28
+ inputSchema?: CanvasJsonSchema;
29
+ /** Required per-action dispatch handler. */
30
+ handler: (ctx: CanvasActionContext) => Promise<unknown> | unknown;
31
+ }
32
+ /**
33
+ * Declarative metadata for a single canvas, serialized over the wire on
34
+ * `session.create` / `session.resume`.
35
+ */
36
+ export interface CanvasDeclaration {
37
+ /** Canvas id, unique within the declaring connection. */
38
+ id: string;
39
+ /** Human-readable label shown in discovery and host UI chrome. */
40
+ displayName: string;
41
+ /** Short, single-sentence description shown to the agent in canvas catalogs. */
42
+ description: string;
43
+ /** Optional JSON Schema for the `input` payload accepted by `canvas.open`. */
44
+ inputSchema?: CanvasJsonSchema;
45
+ /** Agent-invocable actions exposed via `invoke_canvas_action`. */
46
+ actions?: Omit<CanvasAction, "handler">[];
47
+ }
48
+ /** Response returned from `open`. */
49
+ export interface CanvasOpenResponse {
50
+ /** URL the host should render. Optional for native canvases. */
51
+ url?: string;
52
+ /** Provider-supplied title shown in host chrome. */
53
+ title?: string;
54
+ /** Provider-supplied status text shown in host chrome. */
55
+ status?: string;
56
+ }
57
+ /** Host capabilities passed to canvas callbacks. */
58
+ export interface CanvasHostContext {
59
+ capabilities?: {
60
+ canvases?: boolean;
61
+ };
62
+ }
63
+ /** Context handed to a canvas's `open` handler. */
64
+ export interface CanvasOpenContext {
65
+ /** Session that requested the canvas. */
66
+ sessionId: string;
67
+ /** Extension id that owns the canvas. */
68
+ extensionId: string;
69
+ /** Canvas id (matches the declaring `CanvasDeclaration.id`). */
70
+ canvasId: string;
71
+ /** Stable instance id supplied by the runtime. */
72
+ instanceId: string;
73
+ /** Validated `input` payload, shaped by `CanvasDeclaration.inputSchema`. */
74
+ input: unknown;
75
+ /** Host capabilities supplied by the runtime. */
76
+ host?: CanvasHostContext;
77
+ }
78
+ /** Context handed to a canvas action handler. */
79
+ export interface CanvasActionContext {
80
+ /** Session that invoked the action. */
81
+ sessionId: string;
82
+ /** Extension id that owns the canvas. */
83
+ extensionId: string;
84
+ /** Canvas id targeted by the action. */
85
+ canvasId: string;
86
+ /** Instance id targeted by the action. */
87
+ instanceId: string;
88
+ /** Action name from `CanvasAction.name`. */
89
+ actionName: string;
90
+ /** Validated `input` payload, shaped by the action's `inputSchema`. */
91
+ input: unknown;
92
+ /** Host capabilities supplied by the runtime. */
93
+ host?: CanvasHostContext;
94
+ }
95
+ /** Context handed to a canvas's `onClose` handler. */
96
+ export interface CanvasLifecycleContext {
97
+ /** Session owning the canvas instance. */
98
+ sessionId: string;
99
+ /** Extension id that owns the canvas. */
100
+ extensionId: string;
101
+ /** Canvas id (matches the declaring `CanvasDeclaration.id`). */
102
+ canvasId: string;
103
+ /** Instance id this lifecycle event applies to. */
104
+ instanceId: string;
105
+ /** Host capabilities supplied by the runtime. */
106
+ host?: CanvasHostContext;
107
+ }
108
+ /** Structured error returned from canvas handlers. */
109
+ export declare class CanvasError extends Error {
110
+ readonly code: string;
111
+ constructor(code: string, message: string);
112
+ /** Default error when an action is declared but no `handler` is wired. */
113
+ static noHandler(): CanvasError;
114
+ }
115
+ /**
116
+ * Options accepted by {@link createCanvas}. Combines the declarative
117
+ * {@link CanvasDeclaration} fields with the in-process handler closures.
118
+ */
119
+ export interface CanvasOptions {
120
+ /** @see CanvasDeclaration.id */
121
+ id: string;
122
+ /** @see CanvasDeclaration.displayName */
123
+ displayName: string;
124
+ /** @see CanvasDeclaration.description */
125
+ description: string;
126
+ /** @see CanvasDeclaration.inputSchema */
127
+ inputSchema?: CanvasJsonSchema;
128
+ /**
129
+ * Agent-invocable actions exposed via `invoke_canvas_action`. Each action
130
+ * carries its own required `handler`; the action's wire metadata
131
+ * (`name`, `description`, `inputSchema`) is what reaches the runtime.
132
+ */
133
+ actions?: CanvasAction[];
134
+ /** Required. Open a new canvas instance. */
135
+ open: (ctx: CanvasOpenContext) => Promise<CanvasOpenResponse> | CanvasOpenResponse;
136
+ /**
137
+ * Optional. Notified when a canvas instance is closed by the user, the
138
+ * agent, or the host. Fire-and-forget: the return value is ignored and
139
+ * errors are logged but not surfaced to the runtime.
140
+ */
141
+ onClose?: (ctx: CanvasLifecycleContext) => Promise<void> | void;
142
+ }
143
+ /** A registered canvas: declarative metadata + in-process handler closures.
144
+ *
145
+ * Node intentionally uses a per-canvas factory pattern (mirroring
146
+ * {@link https://github.com/github/copilot-sdk | `DefineTool`}'s co-location
147
+ * ergonomics) where other SDKs (Rust, Python, Go, .NET) expose a single
148
+ * `CanvasHandler` per session that switches on `canvasId`. Both shapes target
149
+ * the same JSON-RPC wire protocol; the divergence is API ergonomics only.
150
+ */
151
+ export declare class Canvas {
152
+ readonly declaration: CanvasDeclaration;
153
+ readonly open: NonNullable<CanvasOptions["open"]>;
154
+ readonly onClose?: CanvasOptions["onClose"];
155
+ }
156
+ /** Create a canvas declaration with bound in-process handlers.
157
+ *
158
+ * Node intentionally uses this per-canvas factory pattern (mirroring
159
+ * `DefineTool`'s co-location ergonomics) where other SDKs (Rust, Python, Go,
160
+ * .NET) expose a single `CanvasHandler` per session that switches on
161
+ * `canvasId`. Both shapes target the same JSON-RPC wire protocol.
162
+ */
163
+ export declare function createCanvas(options: CanvasOptions): Canvas;
package/dist/canvas.js ADDED
@@ -0,0 +1,92 @@
1
+ class CanvasError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.code = code;
5
+ this.name = "CanvasError";
6
+ }
7
+ /** Default error when an action is declared but no `handler` is wired. */
8
+ static noHandler() {
9
+ return new CanvasError(
10
+ "canvas_action_no_handler",
11
+ "No handler implemented for this canvas action"
12
+ );
13
+ }
14
+ }
15
+ class Canvas {
16
+ declaration;
17
+ open;
18
+ onClose;
19
+ /** @internal */
20
+ actionHandlers;
21
+ /** @internal */
22
+ constructor(options) {
23
+ const actionHandlers = /* @__PURE__ */ new Map();
24
+ const wireActions = options.actions?.map(
25
+ ({ handler, ...wire }) => {
26
+ actionHandlers.set(wire.name, handler);
27
+ return wire;
28
+ }
29
+ );
30
+ this.declaration = {
31
+ id: options.id,
32
+ displayName: options.displayName,
33
+ description: options.description,
34
+ inputSchema: options.inputSchema,
35
+ actions: wireActions
36
+ };
37
+ this.open = options.open;
38
+ this.onClose = options.onClose;
39
+ this.actionHandlers = actionHandlers;
40
+ }
41
+ }
42
+ function createCanvas(options) {
43
+ return new Canvas(options);
44
+ }
45
+ async function dispatchCanvasProviderRequest(canvas, actionName, params) {
46
+ switch (actionName) {
47
+ case "canvas.open": {
48
+ const result = await canvas.open({
49
+ sessionId: params.sessionId,
50
+ extensionId: params.extensionId,
51
+ canvasId: params.canvasId,
52
+ instanceId: params.instanceId,
53
+ input: params.input,
54
+ host: params.host
55
+ });
56
+ return result ?? {};
57
+ }
58
+ case "canvas.close": {
59
+ if (canvas.onClose) {
60
+ await canvas.onClose({
61
+ sessionId: params.sessionId,
62
+ extensionId: params.extensionId,
63
+ canvasId: params.canvasId,
64
+ instanceId: params.instanceId,
65
+ host: params.host
66
+ });
67
+ }
68
+ return void 0;
69
+ }
70
+ default: {
71
+ const perAction = canvas.actionHandlers.get(actionName);
72
+ if (!perAction) {
73
+ throw CanvasError.noHandler();
74
+ }
75
+ return perAction({
76
+ sessionId: params.sessionId,
77
+ extensionId: params.extensionId,
78
+ canvasId: params.canvasId,
79
+ instanceId: params.instanceId,
80
+ actionName,
81
+ input: params.input,
82
+ host: params.host
83
+ });
84
+ }
85
+ }
86
+ }
87
+ export {
88
+ Canvas,
89
+ CanvasError,
90
+ createCanvas,
91
+ dispatchCanvasProviderRequest
92
+ };
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var canvas_exports = {};
20
+ __export(canvas_exports, {
21
+ Canvas: () => Canvas,
22
+ CanvasError: () => CanvasError,
23
+ createCanvas: () => createCanvas,
24
+ dispatchCanvasProviderRequest: () => dispatchCanvasProviderRequest
25
+ });
26
+ module.exports = __toCommonJS(canvas_exports);
27
+ class CanvasError extends Error {
28
+ constructor(code, message) {
29
+ super(message);
30
+ this.code = code;
31
+ this.name = "CanvasError";
32
+ }
33
+ /** Default error when an action is declared but no `handler` is wired. */
34
+ static noHandler() {
35
+ return new CanvasError(
36
+ "canvas_action_no_handler",
37
+ "No handler implemented for this canvas action"
38
+ );
39
+ }
40
+ }
41
+ class Canvas {
42
+ declaration;
43
+ open;
44
+ onClose;
45
+ /** @internal */
46
+ actionHandlers;
47
+ /** @internal */
48
+ constructor(options) {
49
+ const actionHandlers = /* @__PURE__ */ new Map();
50
+ const wireActions = options.actions?.map(
51
+ ({ handler, ...wire }) => {
52
+ actionHandlers.set(wire.name, handler);
53
+ return wire;
54
+ }
55
+ );
56
+ this.declaration = {
57
+ id: options.id,
58
+ displayName: options.displayName,
59
+ description: options.description,
60
+ inputSchema: options.inputSchema,
61
+ actions: wireActions
62
+ };
63
+ this.open = options.open;
64
+ this.onClose = options.onClose;
65
+ this.actionHandlers = actionHandlers;
66
+ }
67
+ }
68
+ function createCanvas(options) {
69
+ return new Canvas(options);
70
+ }
71
+ async function dispatchCanvasProviderRequest(canvas, actionName, params) {
72
+ switch (actionName) {
73
+ case "canvas.open": {
74
+ const result = await canvas.open({
75
+ sessionId: params.sessionId,
76
+ extensionId: params.extensionId,
77
+ canvasId: params.canvasId,
78
+ instanceId: params.instanceId,
79
+ input: params.input,
80
+ host: params.host
81
+ });
82
+ return result ?? {};
83
+ }
84
+ case "canvas.close": {
85
+ if (canvas.onClose) {
86
+ await canvas.onClose({
87
+ sessionId: params.sessionId,
88
+ extensionId: params.extensionId,
89
+ canvasId: params.canvasId,
90
+ instanceId: params.instanceId,
91
+ host: params.host
92
+ });
93
+ }
94
+ return void 0;
95
+ }
96
+ default: {
97
+ const perAction = canvas.actionHandlers.get(actionName);
98
+ if (!perAction) {
99
+ throw CanvasError.noHandler();
100
+ }
101
+ return perAction({
102
+ sessionId: params.sessionId,
103
+ extensionId: params.extensionId,
104
+ canvasId: params.canvasId,
105
+ instanceId: params.instanceId,
106
+ actionName,
107
+ input: params.input,
108
+ host: params.host
109
+ });
110
+ }
111
+ }
112
+ }
113
+ // Annotate the CommonJS export names for ESM import in node:
114
+ 0 && (module.exports = {
115
+ Canvas,
116
+ CanvasError,
117
+ createCanvas,
118
+ dispatchCanvasProviderRequest
119
+ });