@github/copilot-sdk 1.0.0-beta.1 → 1.0.0-beta.11

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,11 +39,17 @@ 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;
@@ -66,53 +72,56 @@ export declare class CopilotClient {
66
72
  * @throws Error if the client is not connected
67
73
  */
68
74
  get rpc(): ReturnType<typeof createServerRpc>;
69
- /**
70
- * Internal RPC surface (e.g. handshake helpers). Not part of the public API.
71
- * @internal
72
- */
73
- private get internalRpc();
74
75
  /**
75
76
  * Creates a new CopilotClient instance.
76
77
  *
77
78
  * @param options - Configuration options for the client
78
- * @throws Error if mutually exclusive options are provided (e.g., cliUrl with useStdio or cliPath)
79
79
  *
80
80
  * @example
81
81
  * ```typescript
82
- * // Default options - spawns CLI server using stdio
82
+ * // Default: spawns the bundled runtime over stdio
83
83
  * const client = new CopilotClient();
84
84
  *
85
- * // Connect to an existing server
86
- * 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
+ * });
87
94
  *
88
- * // Custom CLI path with specific log level
95
+ * // Use a custom runtime binary
89
96
  * const client = new CopilotClient({
90
- * cliPath: "/usr/local/bin/copilot",
91
- * logLevel: "debug"
97
+ * connection: RuntimeConnection.forStdio({ path: "/usr/local/bin/copilot" }),
98
+ * logLevel: "debug",
92
99
  * });
93
100
  * ```
94
101
  */
95
102
  constructor(options?: CopilotClientOptions);
103
+ private connectionExtraArgs;
96
104
  /**
97
105
  * Parse CLI URL into host and port
98
106
  * Supports formats: "host:port", "http://host:port", "https://host:port", or just "port"
99
107
  */
100
108
  private parseCliUrl;
101
109
  private validateSessionFsConfig;
110
+ private setupSessionFs;
102
111
  /**
103
112
  * Starts the CLI server and establishes a connection.
104
113
  *
105
114
  * If connecting to an external server (via cliUrl), only establishes the connection.
106
115
  * Otherwise, spawns the CLI server process and then connects.
107
116
  *
108
- * 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.
109
118
  *
110
119
  * @returns A promise that resolves when the connection is established
111
120
  * @throws Error if the server fails to start or the connection fails
112
121
  *
113
122
  * @example
114
123
  * ```typescript
115
- * const client = new CopilotClient({ autoStart: false });
124
+ * const client = new CopilotClient();
116
125
  * await client.start();
117
126
  * // Now ready to create sessions
118
127
  * ```
@@ -142,6 +151,19 @@ export declare class CopilotClient {
142
151
  * ```
143
152
  */
144
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>;
145
167
  /**
146
168
  * Forcefully stops the CLI server without graceful cleanup.
147
169
  *
@@ -168,35 +190,26 @@ export declare class CopilotClient {
168
190
  * ```
169
191
  */
170
192
  forceStop(): Promise<void>;
193
+ /** Mode-specific defaults spread under the caller's config (app values win). */
194
+ private configDefaultsForMode;
171
195
  /**
172
- * Creates a new conversation session with the Copilot CLI.
173
- *
174
- * Sessions maintain conversation state, handle events, and manage tool execution.
175
- * If the client is not connected and `autoStart` is enabled, this will automatically
176
- * start the connection.
177
- *
178
- * @param config - Optional configuration for the session
179
- * @returns A promise that resolves with the created session
180
- * @throws Error if the client is not connected and autoStart is disabled
181
- *
182
- * @example
183
- * ```typescript
184
- * // Basic session
185
- * 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.
186
207
  *
187
- * // Session with model and tools
188
- * const session = await client.createSession({
189
- * onPermissionRequest: approveAll,
190
- * model: "gpt-4",
191
- * tools: [{
192
- * name: "get_weather",
193
- * description: "Get weather for a location",
194
- * parameters: { type: "object", properties: { location: { type: "string" } } },
195
- * handler: async (args) => ({ temperature: 72 })
196
- * }]
197
- * });
198
- * ```
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.
199
211
  */
212
+ private updateSessionOptionsForMode;
200
213
  createSession(config: SessionConfig): Promise<CopilotSession>;
201
214
  /**
202
215
  * Resumes an existing conversation session by its ID.
@@ -223,19 +236,6 @@ export declare class CopilotClient {
223
236
  * ```
224
237
  */
225
238
  resumeSession(sessionId: string, config: ResumeSessionConfig): Promise<CopilotSession>;
226
- /**
227
- * Gets the current connection state of the client.
228
- *
229
- * @returns The current connection state: "disconnected", "connecting", "connected", or "error"
230
- *
231
- * @example
232
- * ```typescript
233
- * if (client.getState() === "connected") {
234
- * const session = await client.createSession({ onPermissionRequest: approveAll });
235
- * }
236
- * ```
237
- */
238
- getState(): ConnectionState;
239
239
  /**
240
240
  * Sends a ping request to the server to verify connectivity.
241
241
  *
@@ -251,7 +251,7 @@ export declare class CopilotClient {
251
251
  */
252
252
  ping(message?: string): Promise<{
253
253
  message: string;
254
- timestamp: number;
254
+ timestamp: string;
255
255
  protocolVersion?: number;
256
256
  }>;
257
257
  /**
@@ -398,7 +398,7 @@ export declare class CopilotClient {
398
398
  * @example
399
399
  * ```typescript
400
400
  * // Listen for when a session becomes foreground in TUI
401
- * const unsubscribe = client.on("session.foreground", (event) => {
401
+ * const unsubscribe = client.onLifecycle("session.foreground", (event) => {
402
402
  * console.log(`Session ${event.sessionId} is now displayed in TUI`);
403
403
  * });
404
404
  *
@@ -406,7 +406,7 @@ export declare class CopilotClient {
406
406
  * unsubscribe();
407
407
  * ```
408
408
  */
409
- on<K extends SessionLifecycleEventType>(eventType: K, handler: TypedSessionLifecycleHandler<K>): () => void;
409
+ onLifecycle<K extends SessionLifecycleEventType>(eventType: K, handler: TypedSessionLifecycleHandler<K>): () => void;
410
410
  /**
411
411
  * Subscribes to all session lifecycle events.
412
412
  *
@@ -415,7 +415,7 @@ export declare class CopilotClient {
415
415
  *
416
416
  * @example
417
417
  * ```typescript
418
- * const unsubscribe = client.on((event) => {
418
+ * const unsubscribe = client.onLifecycle((event) => {
419
419
  * switch (event.type) {
420
420
  * case "session.foreground":
421
421
  * console.log(`Session ${event.sessionId} is now in foreground`);
@@ -430,7 +430,7 @@ export declare class CopilotClient {
430
430
  * unsubscribe();
431
431
  * ```
432
432
  */
433
- on(handler: SessionLifecycleHandler): () => void;
433
+ onLifecycle(handler: SessionLifecycleHandler): () => void;
434
434
  /**
435
435
  * Start the CLI server process
436
436
  */
@@ -455,18 +455,8 @@ export declare class CopilotClient {
455
455
  private handleSessionEventNotification;
456
456
  private handleSessionLifecycleNotification;
457
457
  private handleUserInputRequest;
458
+ private handleExitPlanModeRequest;
459
+ private handleAutoModeSwitchRequest;
458
460
  private handleHooksInvoke;
459
461
  private handleSystemMessageTransform;
460
- /**
461
- * Handles a v2-style tool.call RPC request from the server.
462
- * Looks up the session and tool handler, executes it, and returns the result
463
- * in the v2 response format.
464
- */
465
- private handleToolCallRequestV2;
466
- /**
467
- * Handles a v2-style permission.request RPC request from the server.
468
- */
469
- private handlePermissionRequestV2;
470
- private normalizeToolResultV2;
471
- private isToolResultObject;
472
462
  }