@github/copilot-sdk 0.3.0 → 1.0.0-beta.10

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/dist/cjs/types.js CHANGED
@@ -18,7 +18,8 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var types_exports = {};
20
20
  __export(types_exports, {
21
- SYSTEM_PROMPT_SECTIONS: () => SYSTEM_PROMPT_SECTIONS,
21
+ RuntimeConnection: () => RuntimeConnection,
22
+ SYSTEM_MESSAGE_SECTIONS: () => SYSTEM_MESSAGE_SECTIONS,
22
23
  approveAll: () => approveAll,
23
24
  convertMcpCallToolResult: () => convertMcpCallToolResult,
24
25
  createSessionFsAdapter: () => import_sessionFsProvider.createSessionFsAdapter,
@@ -27,6 +28,34 @@ __export(types_exports, {
27
28
  });
28
29
  module.exports = __toCommonJS(types_exports);
29
30
  var import_sessionFsProvider = require("./sessionFsProvider.js");
31
+ const RuntimeConnection = {
32
+ /**
33
+ * Spawn a runtime child process and communicate over its stdin/stdout.
34
+ * This is the default if no {@link CopilotClientOptions.connection} is set.
35
+ */
36
+ forStdio(opts = {}) {
37
+ return { kind: "stdio", path: opts.path, args: opts.args };
38
+ },
39
+ /**
40
+ * Spawn a runtime child process that listens on a TCP socket and connect to it.
41
+ */
42
+ forTcp(opts = {}) {
43
+ return {
44
+ kind: "tcp",
45
+ port: opts.port,
46
+ connectionToken: opts.connectionToken,
47
+ path: opts.path,
48
+ args: opts.args
49
+ };
50
+ },
51
+ /**
52
+ * Connect to an already-running runtime at the given URL. The SDK does not
53
+ * spawn a process in this mode.
54
+ */
55
+ forUri(url, opts = {}) {
56
+ return { kind: "uri", url, connectionToken: opts.connectionToken };
57
+ }
58
+ };
30
59
  function convertMcpCallToolResult(callResult) {
31
60
  const textParts = [];
32
61
  const binaryResults = [];
@@ -51,9 +80,10 @@ function convertMcpCallToolResult(callResult) {
51
80
  textParts.push(block.resource.text);
52
81
  }
53
82
  if (block.resource?.blob) {
83
+ const mimeType = block.resource.mimeType;
54
84
  binaryResults.push({
55
85
  data: block.resource.blob,
56
- mimeType: block.resource.mimeType ?? "application/octet-stream",
86
+ mimeType: typeof mimeType === "string" && mimeType ? mimeType : "application/octet-stream",
57
87
  type: "resource",
58
88
  description: block.resource.uri
59
89
  });
@@ -71,7 +101,7 @@ function convertMcpCallToolResult(callResult) {
71
101
  function defineTool(name, config) {
72
102
  return { name, ...config };
73
103
  }
74
- const SYSTEM_PROMPT_SECTIONS = {
104
+ const SYSTEM_MESSAGE_SECTIONS = {
75
105
  identity: { description: "Agent identity preamble and mode statement" },
76
106
  tone: { description: "Response style, conciseness rules, output formatting preferences" },
77
107
  tool_efficiency: { description: "Tool usage patterns, parallel calling, batching guidelines" },
@@ -81,6 +111,9 @@ const SYSTEM_PROMPT_SECTIONS = {
81
111
  safety: { description: "Environment limitations, prohibited actions, security policies" },
82
112
  tool_instructions: { description: "Per-tool usage instructions" },
83
113
  custom_instructions: { description: "Repository and organization custom instructions" },
114
+ runtime_instructions: {
115
+ description: "Runtime-provided context and instructions (e.g. system notifications, memories, workspace context, mode-specific instructions, content-exclusion policy)"
116
+ },
84
117
  last_instructions: {
85
118
  description: "End-of-prompt instructions: parallel tool calling, persistence, task completion"
86
119
  }
@@ -91,7 +124,8 @@ const defaultJoinSessionPermissionHandler = () => ({
91
124
  });
92
125
  // Annotate the CommonJS export names for ESM import in node:
93
126
  0 && (module.exports = {
94
- SYSTEM_PROMPT_SECTIONS,
127
+ RuntimeConnection,
128
+ SYSTEM_MESSAGE_SECTIONS,
95
129
  approveAll,
96
130
  convertMcpCallToolResult,
97
131
  createSessionFsAdapter,
package/dist/client.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createServerRpc } from "./generated/rpc.js";
2
2
  import { CopilotSession } from "./session.js";
3
- import type { ConnectionState, CopilotClientOptions, GetAuthStatusResponse, GetStatusResponse, ModelInfo, ResumeSessionConfig, SessionConfig, SessionLifecycleEventType, SessionLifecycleHandler, SessionListFilter, SessionMetadata, TypedSessionLifecycleHandler } from "./types.js";
3
+ import type { CopilotClientOptions, GetAuthStatusResponse, GetStatusResponse, ModelInfo, ResumeSessionConfig, SessionConfig, SessionLifecycleEventType, SessionLifecycleHandler, SessionListFilter, SessionMetadata, TypedSessionLifecycleHandler } from "./types.js";
4
4
  /**
5
5
  * Main client for interacting with the Copilot CLI.
6
6
  *
@@ -16,7 +16,7 @@ import type { ConnectionState, CopilotClientOptions, GetAuthStatusResponse, GetS
16
16
  * const client = new CopilotClient();
17
17
  *
18
18
  * // Or connect to an existing server
19
- * const client = new CopilotClient({ cliUrl: "localhost:3000" });
19
+ * const client = new CopilotClient({ connection: RuntimeConnection.forUri("localhost:3000") });
20
20
  *
21
21
  * // Create a session
22
22
  * const session = await client.createSession({ onPermissionRequest: approveAll, model: "gpt-4" });
@@ -39,14 +39,22 @@ export declare class CopilotClient {
39
39
  private cliProcess;
40
40
  private connection;
41
41
  private socket;
42
- private actualPort;
42
+ private runtimePort;
43
43
  private actualHost;
44
44
  private state;
45
45
  private sessions;
46
46
  private stderrBuffer;
47
+ /** Resolved connection mode chosen in the constructor. */
48
+ private connectionConfig;
49
+ /** Resolved path to the runtime executable (only used for child-process kinds). */
50
+ private resolvedCliPath;
51
+ /** Resolved environment passed to the spawned runtime. */
52
+ private resolvedEnv;
47
53
  private options;
48
54
  private isExternalServer;
49
55
  private forceStopping;
56
+ /** Token sent in `connect`; auto-generated when the SDK spawns its own CLI in TCP mode. */
57
+ private effectiveConnectionToken?;
50
58
  private onListModels?;
51
59
  private onGetTraceContext?;
52
60
  private modelsCache;
@@ -54,6 +62,7 @@ export declare class CopilotClient {
54
62
  private sessionLifecycleHandlers;
55
63
  private typedLifecycleHandlers;
56
64
  private _rpc;
65
+ private _internalRpc;
57
66
  private processExitPromise;
58
67
  private negotiatedProtocolVersion;
59
68
  /** Connection-level session filesystem config, set via constructor option. */
@@ -67,44 +76,52 @@ export declare class CopilotClient {
67
76
  * Creates a new CopilotClient instance.
68
77
  *
69
78
  * @param options - Configuration options for the client
70
- * @throws Error if mutually exclusive options are provided (e.g., cliUrl with useStdio or cliPath)
71
79
  *
72
80
  * @example
73
81
  * ```typescript
74
- * // Default options - spawns CLI server using stdio
82
+ * // Default: spawns the bundled runtime over stdio
75
83
  * const client = new CopilotClient();
76
84
  *
77
- * // Connect to an existing server
78
- * const client = new CopilotClient({ cliUrl: "localhost:3000" });
85
+ * // Connect to an existing runtime
86
+ * const client = new CopilotClient({
87
+ * connection: RuntimeConnection.forUri("localhost:3000"),
88
+ * });
89
+ *
90
+ * // Spawn the runtime over TCP on a chosen port
91
+ * const client = new CopilotClient({
92
+ * connection: RuntimeConnection.forTcp({ port: 9001 }),
93
+ * });
79
94
  *
80
- * // Custom CLI path with specific log level
95
+ * // Use a custom runtime binary
81
96
  * const client = new CopilotClient({
82
- * cliPath: "/usr/local/bin/copilot",
83
- * logLevel: "debug"
97
+ * connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
98
+ * logLevel: "debug",
84
99
  * });
85
100
  * ```
86
101
  */
87
102
  constructor(options?: CopilotClientOptions);
103
+ private connectionExtraArgs;
88
104
  /**
89
105
  * Parse CLI URL into host and port
90
106
  * Supports formats: "host:port", "http://host:port", "https://host:port", or just "port"
91
107
  */
92
108
  private parseCliUrl;
93
109
  private validateSessionFsConfig;
110
+ private setupSessionFs;
94
111
  /**
95
112
  * Starts the CLI server and establishes a connection.
96
113
  *
97
114
  * If connecting to an external server (via cliUrl), only establishes the connection.
98
115
  * Otherwise, spawns the CLI server process and then connects.
99
116
  *
100
- * This method is called automatically when creating a session if `autoStart` is true (default).
117
+ * This method is called automatically the first time you create or resume a session.
101
118
  *
102
119
  * @returns A promise that resolves when the connection is established
103
120
  * @throws Error if the server fails to start or the connection fails
104
121
  *
105
122
  * @example
106
123
  * ```typescript
107
- * const client = new CopilotClient({ autoStart: false });
124
+ * const client = new CopilotClient();
108
125
  * await client.start();
109
126
  * // Now ready to create sessions
110
127
  * ```
@@ -134,6 +151,19 @@ export declare class CopilotClient {
134
151
  * ```
135
152
  */
136
153
  stop(): Promise<Error[]>;
154
+ /**
155
+ * Alias for {@link stop} that lets `CopilotClient` participate in `await using`
156
+ * blocks for automatic cleanup.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * await using client = new CopilotClient();
161
+ * const session = await client.createSession({ onPermissionRequest: approveAll });
162
+ * await session.sendAndWait("Hello");
163
+ * // client.stop() is called automatically when the block exits.
164
+ * ```
165
+ */
166
+ [Symbol.asyncDispose](): Promise<void>;
137
167
  /**
138
168
  * Forcefully stops the CLI server without graceful cleanup.
139
169
  *
@@ -160,35 +190,26 @@ export declare class CopilotClient {
160
190
  * ```
161
191
  */
162
192
  forceStop(): Promise<void>;
193
+ /** Mode-specific defaults spread under the caller's config (app values win). */
194
+ private configDefaultsForMode;
163
195
  /**
164
- * Creates a new conversation session with the Copilot CLI.
165
- *
166
- * Sessions maintain conversation state, handle events, and manage tool execution.
167
- * If the client is not connected and `autoStart` is enabled, this will automatically
168
- * start the connection.
169
- *
170
- * @param config - Optional configuration for the session
171
- * @returns A promise that resolves with the created session
172
- * @throws Error if the client is not connected and autoStart is disabled
173
- *
174
- * @example
175
- * ```typescript
176
- * // Basic session
177
- * const session = await client.createSession({ onPermissionRequest: approveAll });
196
+ * Returns the systemMessage config to use, adjusted for the current mode.
197
+ * In empty mode we ensure the environment_context section is removed
198
+ * unless the app has already taken control of it. `append` (and
199
+ * unspecified) mode is promoted to `customize` so we can also strip
200
+ * environment_context; the caller's `content` is preserved verbatim
201
+ * because the runtime appends it as additional instructions in both
202
+ * customize and append modes.
203
+ */
204
+ private getSystemMessageConfigForMode;
205
+ /**
206
+ * Mode-specific options applied via session.options.update after create/resume.
178
207
  *
179
- * // Session with model and tools
180
- * const session = await client.createSession({
181
- * onPermissionRequest: approveAll,
182
- * model: "gpt-4",
183
- * tools: [{
184
- * name: "get_weather",
185
- * description: "Get weather for a location",
186
- * parameters: { type: "object", properties: { location: { type: "string" } } },
187
- * handler: async (args) => ({ temperature: 72 })
188
- * }]
189
- * });
190
- * ```
208
+ * In empty mode, defaults the four overridable feature flags to safe values
209
+ * (caller values from `config` win). `installedPlugins=[]` is unconditional
210
+ * in empty mode — apps that need custom plugins should switch modes.
191
211
  */
212
+ private updateSessionOptionsForMode;
192
213
  createSession(config: SessionConfig): Promise<CopilotSession>;
193
214
  /**
194
215
  * Resumes an existing conversation session by its ID.
@@ -215,19 +236,6 @@ export declare class CopilotClient {
215
236
  * ```
216
237
  */
217
238
  resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>;
218
- /**
219
- * Gets the current connection state of the client.
220
- *
221
- * @returns The current connection state: "disconnected", "connecting", "connected", or "error"
222
- *
223
- * @example
224
- * ```typescript
225
- * if (client.getState() === "connected") {
226
- * const session = await client.createSession({ onPermissionRequest: approveAll });
227
- * }
228
- * ```
229
- */
230
- getState(): ConnectionState;
231
239
  /**
232
240
  * Sends a ping request to the server to verify connectivity.
233
241
  *
@@ -243,7 +251,7 @@ export declare class CopilotClient {
243
251
  */
244
252
  ping(message?: string): Promise<{
245
253
  message: string;
246
- timestamp: number;
254
+ timestamp: string;
247
255
  protocolVersion?: number;
248
256
  }>;
249
257
  /**
@@ -267,8 +275,9 @@ export declare class CopilotClient {
267
275
  */
268
276
  listModels(): Promise<ModelInfo[]>;
269
277
  /**
270
- * Verify that the server's protocol version is within the supported range
271
- * and store the negotiated version.
278
+ * Send the `connect` handshake (carrying the optional token) and verify the
279
+ * server's protocol version. Falls back to `ping` against legacy servers
280
+ * that don't implement `connect`.
272
281
  */
273
282
  private verifyProtocolVersion;
274
283
  /**
@@ -389,7 +398,7 @@ export declare class CopilotClient {
389
398
  * @example
390
399
  * ```typescript
391
400
  * // Listen for when a session becomes foreground in TUI
392
- * const unsubscribe = client.on("session.foreground", (event) => {
401
+ * const unsubscribe = client.onLifecycle("session.foreground", (event) => {
393
402
  * console.log(`Session ${event.sessionId} is now displayed in TUI`);
394
403
  * });
395
404
  *
@@ -397,7 +406,7 @@ export declare class CopilotClient {
397
406
  * unsubscribe();
398
407
  * ```
399
408
  */
400
- on<K extends SessionLifecycleEventType>(eventType: K, handler: TypedSessionLifecycleHandler<K>): () => void;
409
+ onLifecycle<K extends SessionLifecycleEventType>(eventType: K, handler: TypedSessionLifecycleHandler<K>): () => void;
401
410
  /**
402
411
  * Subscribes to all session lifecycle events.
403
412
  *
@@ -406,7 +415,7 @@ export declare class CopilotClient {
406
415
  *
407
416
  * @example
408
417
  * ```typescript
409
- * const unsubscribe = client.on((event) => {
418
+ * const unsubscribe = client.onLifecycle((event) => {
410
419
  * switch (event.type) {
411
420
  * case "session.foreground":
412
421
  * console.log(`Session ${event.sessionId} is now in foreground`);
@@ -421,7 +430,7 @@ export declare class CopilotClient {
421
430
  * unsubscribe();
422
431
  * ```
423
432
  */
424
- on(handler: SessionLifecycleHandler): () => void;
433
+ onLifecycle(handler: SessionLifecycleHandler): () => void;
425
434
  /**
426
435
  * Start the CLI server process
427
436
  */
@@ -446,18 +455,8 @@ export declare class CopilotClient {
446
455
  private handleSessionEventNotification;
447
456
  private handleSessionLifecycleNotification;
448
457
  private handleUserInputRequest;
458
+ private handleExitPlanModeRequest;
459
+ private handleAutoModeSwitchRequest;
449
460
  private handleHooksInvoke;
450
461
  private handleSystemMessageTransform;
451
- /**
452
- * Handles a v2-style tool.call RPC request from the server.
453
- * Looks up the session and tool handler, executes it, and returns the result
454
- * in the v2 response format.
455
- */
456
- private handleToolCallRequestV2;
457
- /**
458
- * Handles a v2-style permission.request RPC request from the server.
459
- */
460
- private handlePermissionRequestV2;
461
- private normalizeToolResultV2;
462
- private isToolResultObject;
463
462
  }