@microsoft/copilot-sdk 0.0.0-stage → 2.0.0-preview.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +2531 -2
  2. package/dist/canvas.d.ts +135 -0
  3. package/dist/canvas.js +51 -0
  4. package/dist/cjs/canvas.js +77 -0
  5. package/dist/cjs/cliVersion.js +31 -0
  6. package/dist/cjs/client.js +3941 -0
  7. package/dist/cjs/copilotRequestHandler.js +815 -0
  8. package/dist/cjs/decisions.js +139 -0
  9. package/dist/cjs/entra.js +83 -0
  10. package/dist/cjs/extension.js +79 -0
  11. package/dist/cjs/ffiRuntimeHost.js +400 -0
  12. package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
  13. package/dist/cjs/generated/rpc.js +5883 -0
  14. package/dist/cjs/generated/session-events.js +16 -0
  15. package/dist/cjs/host.js +83 -0
  16. package/dist/cjs/index.js +100 -0
  17. package/dist/cjs/installationConfirmation.js +98 -0
  18. package/dist/cjs/jsonrpcTypes.js +41 -0
  19. package/dist/cjs/localModelJson.js +103 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/cjs/providerConfiguration.js +39 -0
  22. package/dist/cjs/rpcCancellation.js +49 -0
  23. package/dist/cjs/runtimeArtifacts.js +255 -0
  24. package/dist/cjs/schema.js +40 -0
  25. package/dist/cjs/sdkProtocolVersion.js +33 -0
  26. package/dist/cjs/session.js +2764 -0
  27. package/dist/cjs/sessionFsProvider.js +283 -0
  28. package/dist/cjs/taskAnalyticsJson.js +47 -0
  29. package/dist/cjs/telemetry.js +35 -0
  30. package/dist/cjs/toolSet.js +107 -0
  31. package/dist/cjs/types.js +204 -0
  32. package/dist/cjs/workflow.js +278 -0
  33. package/dist/cliVersion.d.ts +2 -0
  34. package/dist/cliVersion.js +6 -0
  35. package/dist/client.d.ts +576 -0
  36. package/dist/client.js +3924 -0
  37. package/dist/copilotRequestHandler.d.ts +91 -0
  38. package/dist/copilotRequestHandler.js +787 -0
  39. package/dist/decisions.d.ts +65 -0
  40. package/dist/decisions.js +113 -0
  41. package/dist/entra.d.ts +3 -0
  42. package/dist/entra.js +59 -0
  43. package/dist/extension.d.ts +69 -0
  44. package/dist/extension.js +59 -0
  45. package/dist/ffiRuntimeHost.d.ts +44 -0
  46. package/dist/ffiRuntimeHost.js +366 -0
  47. package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
  48. package/dist/generated/lifecycle-diagnostics.js +0 -0
  49. package/dist/generated/rpc.d.ts +47706 -0
  50. package/dist/generated/rpc.js +5854 -0
  51. package/dist/generated/session-events.d.ts +17349 -0
  52. package/dist/generated/session-events.js +0 -0
  53. package/dist/host.d.ts +143 -0
  54. package/dist/host.js +59 -0
  55. package/dist/index.d.ts +23 -0
  56. package/dist/index.js +74 -0
  57. package/dist/installationConfirmation.d.ts +19 -0
  58. package/dist/installationConfirmation.js +74 -0
  59. package/dist/jsonrpcTypes.d.ts +16 -0
  60. package/dist/jsonrpcTypes.js +17 -0
  61. package/dist/localModelJson.d.ts +1 -0
  62. package/dist/localModelJson.js +69 -0
  63. package/dist/providerConfiguration.d.ts +3 -0
  64. package/dist/providerConfiguration.js +15 -0
  65. package/dist/rpcCancellation.d.ts +3 -0
  66. package/dist/rpcCancellation.js +25 -0
  67. package/dist/runtimeArtifacts.d.ts +18 -0
  68. package/dist/runtimeArtifacts.js +233 -0
  69. package/dist/schema.d.ts +4 -0
  70. package/dist/schema.js +14 -0
  71. package/dist/sdkProtocolVersion.d.ts +10 -0
  72. package/dist/sdkProtocolVersion.js +8 -0
  73. package/dist/session.d.ts +524 -0
  74. package/dist/session.js +2751 -0
  75. package/dist/sessionFsProvider.d.ts +130 -0
  76. package/dist/sessionFsProvider.js +257 -0
  77. package/dist/taskAnalyticsJson.d.ts +8 -0
  78. package/dist/taskAnalyticsJson.js +12 -0
  79. package/dist/telemetry.d.ts +14 -0
  80. package/dist/telemetry.js +11 -0
  81. package/dist/toolSet.d.ts +75 -0
  82. package/dist/toolSet.js +82 -0
  83. package/dist/types.d.ts +3864 -0
  84. package/dist/types.js +169 -0
  85. package/dist/workflow.d.ts +413 -0
  86. package/dist/workflow.js +248 -0
  87. package/docs/agent-author.md +372 -0
  88. package/docs/examples.md +747 -0
  89. package/docs/extensions.md +121 -0
  90. package/docs/workflows.md +303 -0
  91. package/package.json +135 -5
@@ -0,0 +1,747 @@
1
+ # Copilot CLI Extension Examples
2
+
3
+ A practical guide to writing extensions using the `@microsoft/copilot-sdk` extension API.
4
+
5
+ ## Extension Skeleton
6
+
7
+ Every extension starts with the same boilerplate:
8
+
9
+ ```js
10
+ import { joinSession } from "@microsoft/copilot-sdk/extension";
11
+
12
+ const session = await joinSession({
13
+ hooks: {
14
+ /* ... */
15
+ },
16
+ tools: [
17
+ /* ... */
18
+ ],
19
+ });
20
+ ```
21
+
22
+ `joinSession` returns a `CopilotSession` object you can use to send messages and subscribe to events.
23
+
24
+ > **Platform notes (Windows vs macOS/Linux):**
25
+ >
26
+ > - Use `process.platform === "win32"` to detect Windows at runtime.
27
+ > - Clipboard: `pbcopy` on macOS, `clip` on Windows.
28
+ > - Never interpolate tool arguments into `exec()` or shell command strings. Use `execFile()` or `spawn()` with argument arrays.
29
+ > - On Windows, `.cmd` and `.bat` wrappers require a shell. Invoke the actual executable or use the library's Node.js API instead.
30
+ > - PowerShell stderr redirection uses `*>&1` instead of `2>&1`.
31
+
32
+ ---
33
+
34
+ ## Logging to the Timeline
35
+
36
+ Use `session.log()` to surface messages to the user in the CLI timeline:
37
+
38
+ ```js
39
+ const session = await joinSession({
40
+ hooks: {
41
+ onSessionStart: async () => {
42
+ await session.log("My extension loaded");
43
+ },
44
+ onPreToolUse: async (input) => {
45
+ if (input.toolName === "bash") {
46
+ await session.log(`Running: ${input.toolArgs?.command}`, { ephemeral: true });
47
+ }
48
+ },
49
+ },
50
+ tools: [],
51
+ });
52
+ ```
53
+
54
+ Levels: `"info"` (default), `"warning"`, `"error"`. Set `ephemeral: true` for transient messages that aren't persisted.
55
+
56
+ ---
57
+
58
+ ## Registering Custom Tools
59
+
60
+ Tools are functions the agent can call. Define them with a name, description, JSON Schema parameters, and a handler.
61
+
62
+ ### Basic tool
63
+
64
+ ```js
65
+ tools: [
66
+ {
67
+ name: "my_tool",
68
+ description: "Does something useful",
69
+ parameters: {
70
+ type: "object",
71
+ properties: {
72
+ input: { type: "string", description: "The input value" },
73
+ },
74
+ required: ["input"],
75
+ },
76
+ handler: async (args) => {
77
+ return `Processed: ${args.input}`;
78
+ },
79
+ },
80
+ ];
81
+ ```
82
+
83
+ ### Tool that invokes an external shell command
84
+
85
+ ```js
86
+ import { execFile } from "node:child_process";
87
+
88
+ {
89
+ name: "run_command",
90
+ description: "Runs a shell command and returns its output",
91
+ parameters: {
92
+ type: "object",
93
+ properties: {
94
+ command: { type: "string", description: "The command to run" },
95
+ },
96
+ required: ["command"],
97
+ },
98
+ handler: async (args) => {
99
+ const isWindows = process.platform === "win32";
100
+ const shell = isWindows ? "powershell" : "bash";
101
+ const shellArgs = isWindows
102
+ ? ["-NoProfile", "-Command", args.command]
103
+ : ["-c", args.command];
104
+ return new Promise((resolve) => {
105
+ execFile(shell, shellArgs, (err, stdout, stderr) => {
106
+ if (err) resolve(`Error: ${stderr || err.message}`);
107
+ else resolve(stdout);
108
+ });
109
+ });
110
+ },
111
+ }
112
+ ```
113
+
114
+ ### Tool that calls an external API
115
+
116
+ ```js
117
+ {
118
+ name: "fetch_data",
119
+ description: "Fetches data from an API endpoint",
120
+ parameters: {
121
+ type: "object",
122
+ properties: {
123
+ url: { type: "string", description: "The URL to fetch" },
124
+ },
125
+ required: ["url"],
126
+ },
127
+ handler: async (args) => {
128
+ const res = await fetch(args.url);
129
+ if (!res.ok) return `Error: HTTP ${res.status}`;
130
+ return await res.text();
131
+ },
132
+ }
133
+ ```
134
+
135
+ ### Tool handler invocation context
136
+
137
+ The handler receives a second argument with invocation metadata:
138
+
139
+ ```js
140
+ handler: async (args, invocation) => {
141
+ // invocation.sessionId — current session ID
142
+ // invocation.toolCallId — unique ID for this tool call
143
+ // invocation.toolName — name of the tool being called
144
+ return "done";
145
+ };
146
+ ```
147
+
148
+ ---
149
+
150
+ ## Hooks
151
+
152
+ Hooks intercept and modify behavior at key lifecycle points. Register them in the `hooks` option.
153
+
154
+ ### Available Hooks
155
+
156
+ | Hook | Fires When | Can Modify |
157
+ | ------------------------- | -------------------------------------------- | ------------------------------------------- |
158
+ | `onUserPromptSubmitted` | User sends a message | The prompt text, add context |
159
+ | `onUserPromptTransformed` | Runtime has transformed the submitted prompt | The transformed prompt |
160
+ | `onPreToolUse` | Before a tool executes | Tool args, permission decision, add context |
161
+ | `onPreMcpToolCall` | Before an MCP tool call is sent | The request's `_meta` |
162
+ | `onPostToolUse` | After a tool executes successfully | Tool result, add context |
163
+ | `onPostToolUseFailure` | After a tool execution returns a failure | Add hidden guidance to the model |
164
+ | `onSessionStart` | Session starts or resumes | Add context |
165
+ | `onSessionEnd` | Session ends | Cleanup actions, summary |
166
+ | `onErrorOccurred` | An error occurs | Error handling strategy (retry/skip/abort) |
167
+ | `onAgentStop` | Top-level agent naturally stops | Block the stop and request another turn |
168
+ | `onSubagentStart` | Before a sub-agent's first turn | Add context to its prompt |
169
+ | `onSubagentStop` | After a sub-agent completes a turn | Request another turn, replace its response |
170
+
171
+ All hook inputs include `timestamp` (`Date`) and `workingDirectory`.
172
+
173
+ ### Modifying the user's message
174
+
175
+ Use `onUserPromptSubmitted` to rewrite or augment what the user typed before the agent sees it.
176
+
177
+ ```js
178
+ hooks: {
179
+ onUserPromptSubmitted: async (input) => {
180
+ // Rewrite the prompt
181
+ return { modifiedPrompt: input.prompt.toUpperCase() };
182
+ },
183
+ }
184
+ ```
185
+
186
+ ### Injecting additional context into every message
187
+
188
+ Return `additionalContext` to silently append instructions the agent will follow.
189
+
190
+ ```js
191
+ hooks: {
192
+ onUserPromptSubmitted: async (input) => {
193
+ return {
194
+ additionalContext: "Always respond in bullet points. Follow our team coding standards.",
195
+ };
196
+ },
197
+ }
198
+ ```
199
+
200
+ ### Sending a follow-up message based on a keyword
201
+
202
+ Use `session.send()` to programmatically inject a new user message.
203
+
204
+ ```js
205
+ hooks: {
206
+ onUserPromptSubmitted: async (input) => {
207
+ if (/\burgent\b/i.test(input.prompt)) {
208
+ // Fire-and-forget a follow-up message
209
+ setTimeout(() => session.send({ prompt: "Please prioritize this." }), 0);
210
+ }
211
+ },
212
+ }
213
+ ```
214
+
215
+ > **Tip:** Guard against infinite loops if your follow-up message could re-trigger the same hook.
216
+
217
+ ### Blocking dangerous tool calls
218
+
219
+ Use `onPreToolUse` to inspect and optionally deny tool execution.
220
+
221
+ ```js
222
+ hooks: {
223
+ onPreToolUse: async (input) => {
224
+ if (input.toolName === "bash") {
225
+ const cmd = String(input.toolArgs?.command || "");
226
+ if (/rm\s+-rf/i.test(cmd) || /Remove-Item\s+.*-Recurse/i.test(cmd)) {
227
+ return {
228
+ permissionDecision: "deny",
229
+ permissionDecisionReason: "Destructive commands are not allowed.",
230
+ };
231
+ }
232
+ }
233
+ // Allow everything else
234
+ return { permissionDecision: "allow" };
235
+ },
236
+ }
237
+ ```
238
+
239
+ ### Modifying tool arguments before execution
240
+
241
+ ```js
242
+ hooks: {
243
+ onPreToolUse: async (input) => {
244
+ if (input.toolName === "bash") {
245
+ const redirect = process.platform === "win32" ? "*>&1" : "2>&1";
246
+ return {
247
+ modifiedArgs: {
248
+ ...input.toolArgs,
249
+ command: `${input.toolArgs.command} ${redirect}`,
250
+ },
251
+ };
252
+ }
253
+ },
254
+ }
255
+ ```
256
+
257
+ ### Reacting when the agent creates or edits a file
258
+
259
+ Use `onPostToolUse` to run side effects after a tool completes.
260
+
261
+ On macOS and Linux, install the `code` command in your `PATH`. On Windows,
262
+ set `VSCODE_EXECUTABLE` to the absolute path of your installed `Code.exe`
263
+ (for example, `C:\Users\you\AppData\Local\Programs\Microsoft VS Code\Code.exe`),
264
+ not the `code.cmd` wrapper. This is trusted extension configuration, not a
265
+ tool argument.
266
+
267
+ ```js
268
+ import { spawn } from "node:child_process";
269
+ import { isAbsolute, resolve } from "node:path";
270
+
271
+ const isWindows = process.platform === "win32";
272
+ const vscodeExecutable = isWindows ? process.env.VSCODE_EXECUTABLE : "code";
273
+ if (!vscodeExecutable || (isWindows && !isAbsolute(vscodeExecutable))) {
274
+ throw new Error("Set VSCODE_EXECUTABLE to the absolute path of Code.exe.");
275
+ }
276
+ const editorEnv = { ...process.env };
277
+ // The native editor must open the file, not run it as a Node.js script.
278
+ delete editorEnv.ELECTRON_RUN_AS_NODE;
279
+
280
+ hooks: {
281
+ onPostToolUse: async (input) => {
282
+ if (input.toolName === "create" || input.toolName === "edit") {
283
+ const filePath = input.toolArgs?.path;
284
+ if (typeof filePath === "string" && filePath) {
285
+ try {
286
+ const child = spawn(vscodeExecutable, [resolve(filePath)], {
287
+ detached: true,
288
+ stdio: "ignore",
289
+ env: editorEnv,
290
+ });
291
+ child.on("error", (err) => console.error("Could not open file in VS Code:", err.message));
292
+ child.unref();
293
+ } catch (err) {
294
+ console.error("Could not open file in VS Code:", err.message);
295
+ }
296
+ }
297
+ }
298
+ },
299
+ }
300
+ ```
301
+
302
+ ### Reacting when a tool fails
303
+
304
+ `onPostToolUse` only fires for successful tool executions. To observe or react
305
+ to failures, register `onPostToolUseFailure`. The input includes
306
+ `input.error` (the stringified failure message); only `additionalContext` on
307
+ the return value is consumed by the runtime, and it is appended as hidden
308
+ guidance alongside the failed tool result.
309
+
310
+ ```js
311
+ hooks: {
312
+ onPostToolUseFailure: async (input) => {
313
+ if (input.toolName === "bash") {
314
+ return {
315
+ additionalContext: "The command failed. Try a different approach.",
316
+ };
317
+ }
318
+ },
319
+ }
320
+ ```
321
+
322
+ ### Running a linter after every file edit
323
+
324
+ Install ESLint in the session's working directory (`npm install --save-dev eslint`)
325
+ and configure it for TypeScript. Only run this hook in workspaces whose ESLint
326
+ configuration and plugins you trust. Use its Node.js API rather than `npx`:
327
+ an extension's `process.execPath` can be the Copilot single-executable binary,
328
+ not a general-purpose Node.js interpreter.
329
+
330
+ ```js
331
+ import { createRequire } from "node:module";
332
+ import { resolve } from "node:path";
333
+ import { pathToFileURL } from "node:url";
334
+
335
+ const require = createRequire(import.meta.url);
336
+
337
+ hooks: {
338
+ onPostToolUse: async (input) => {
339
+ if (input.toolName === "edit") {
340
+ const filePath = input.toolArgs?.path;
341
+ if (typeof filePath === "string" && filePath.endsWith(".ts")) {
342
+ try {
343
+ const eslintModule = require.resolve("eslint", { paths: [process.cwd()] });
344
+ const { ESLint } = await import(pathToFileURL(eslintModule).href);
345
+ const eslint = new ESLint({ cwd: process.cwd(), globInputPaths: false });
346
+ const results = await eslint.lintFiles([resolve(filePath)]);
347
+ const formatter = await eslint.loadFormatter("stylish");
348
+ return { additionalContext: `Lint result: ${formatter.format(results) || "No lint errors."}` };
349
+ } catch (err) {
350
+ return { additionalContext: `Lint failed: ${err.message}` };
351
+ }
352
+ }
353
+ }
354
+ },
355
+ }
356
+ ```
357
+
358
+ ### Handling errors with retry logic
359
+
360
+ ```js
361
+ hooks: {
362
+ onErrorOccurred: async (input) => {
363
+ if (input.recoverable && input.errorContext === "model_call") {
364
+ return { errorHandling: "retry", retryCount: 2 };
365
+ }
366
+ return {
367
+ errorHandling: "abort",
368
+ userNotification: `An error occurred: ${input.error}`,
369
+ };
370
+ },
371
+ }
372
+ ```
373
+
374
+ ### Session lifecycle hooks
375
+
376
+ ```js
377
+ hooks: {
378
+ onSessionStart: async (input) => {
379
+ // input.source is "startup", "resume", or "new"
380
+ return { additionalContext: "Remember to write tests for all changes." };
381
+ },
382
+ onSessionEnd: async (input) => {
383
+ // input.reason is "complete", "error", "abort", "timeout", or "user_exit"
384
+ },
385
+ }
386
+ ```
387
+
388
+ ---
389
+
390
+ ## Session Events
391
+
392
+ After calling `joinSession`, use `session.on()` to react to events in real time.
393
+
394
+ ### Listening to a specific event type
395
+
396
+ ```js
397
+ session.on("assistant.message", (event) => {
398
+ // event.data.content has the agent's response text
399
+ });
400
+ ```
401
+
402
+ ### Listening to all events
403
+
404
+ ```js
405
+ session.on((event) => {
406
+ // event.type and event.data are available for all events
407
+ });
408
+ ```
409
+
410
+ ### Unsubscribing from events
411
+
412
+ `session.on()` returns an unsubscribe function:
413
+
414
+ ```js
415
+ const unsubscribe = session.on("tool.execution_complete", (event) => {
416
+ // event.data.success, event.data.result, event.data.error
417
+ });
418
+
419
+ // Later, stop listening
420
+ unsubscribe();
421
+ ```
422
+
423
+ ### Example: Auto-copy agent responses to clipboard
424
+
425
+ Combine a hook (to detect a keyword) with a session event (to capture the response):
426
+
427
+ ```js
428
+ import { execFile } from "node:child_process";
429
+
430
+ let copyNextResponse = false;
431
+
432
+ function copyToClipboard(text) {
433
+ const cmd = process.platform === "win32" ? "clip" : "pbcopy";
434
+ const proc = execFile(cmd, [], () => {});
435
+ proc.stdin.write(text);
436
+ proc.stdin.end();
437
+ }
438
+
439
+ const session = await joinSession({
440
+ hooks: {
441
+ onUserPromptSubmitted: async (input) => {
442
+ if (/\bcopy\b/i.test(input.prompt)) {
443
+ copyNextResponse = true;
444
+ }
445
+ },
446
+ },
447
+ tools: [],
448
+ });
449
+
450
+ session.on("assistant.message", (event) => {
451
+ if (copyNextResponse) {
452
+ copyNextResponse = false;
453
+ copyToClipboard(event.data.content);
454
+ }
455
+ });
456
+ ```
457
+
458
+ ### Top 10 Most Useful Event Types
459
+
460
+ | Event Type | Description | Key Data Fields |
461
+ | --------------------------- | ------------------------------------------------ | ------------------------------------------------------ |
462
+ | `assistant.message` | Agent's final response | `content`, `messageId`, `toolRequests` |
463
+ | `assistant.message_delta` | Message content chunks (ephemeral) | `deltaContent` |
464
+ | `tool.execution_start` | A tool is about to run | `toolCallId`, `toolName`, `arguments` |
465
+ | `tool.execution_complete` | A tool finished running | `toolCallId`, `success`, `result`, `error` |
466
+ | `user.message` | User sent a message | `content`, `attachments`, `source` |
467
+ | `session.idle` | Session finished processing a turn | `aborted` |
468
+ | `session.error` | An error occurred | `errorType`, `message`, `stack` |
469
+ | `permission.requested` | Agent needs permission (shell, file write, etc.) | `requestId`, `permissionRequest.kind` |
470
+ | `session.shutdown` | Session is ending | `shutdownType`, `totalPremiumRequests`, `codeChanges` |
471
+ | `assistant.turn_start` | Agent begins a new thinking/response cycle | `turnId` |
472
+
473
+ ### Example: Detecting when the plan file is created or edited
474
+
475
+ Use `session.workspacePath` to locate the session's `plan.md`, then `fs.watchFile` to detect changes.
476
+ Correlate `tool.execution_start` / `tool.execution_complete` events by `toolCallId` to distinguish agent edits from user edits.
477
+
478
+ ```js
479
+ import { existsSync, watchFile, readFileSync } from "node:fs";
480
+ import { join } from "node:path";
481
+ import { joinSession } from "@microsoft/copilot-sdk/extension";
482
+
483
+ const agentEdits = new Set(); // toolCallIds for in-flight agent edits
484
+ const recentAgentPaths = new Set(); // paths recently written by the agent
485
+
486
+ const session = await joinSession();
487
+
488
+ const workspace = session.workspacePath; // e.g. ~/.copilot/session-state/<id>
489
+ if (workspace) {
490
+ const planPath = join(workspace, "plan.md");
491
+ let lastContent = existsSync(planPath) ? readFileSync(planPath, "utf-8") : null;
492
+
493
+ // Track agent edits to suppress false triggers
494
+ session.on("tool.execution_start", (event) => {
495
+ if (
496
+ (event.data.toolName === "edit" || event.data.toolName === "create") &&
497
+ String(event.data.arguments?.path || "").endsWith("plan.md")
498
+ ) {
499
+ agentEdits.add(event.data.toolCallId);
500
+ recentAgentPaths.add(planPath);
501
+ }
502
+ });
503
+ session.on("tool.execution_complete", (event) => {
504
+ if (agentEdits.delete(event.data.toolCallId)) {
505
+ setTimeout(() => {
506
+ recentAgentPaths.delete(planPath);
507
+ lastContent = existsSync(planPath) ? readFileSync(planPath, "utf-8") : null;
508
+ }, 2000);
509
+ }
510
+ });
511
+
512
+ watchFile(planPath, { interval: 1000 }, () => {
513
+ if (recentAgentPaths.has(planPath) || agentEdits.size > 0) return;
514
+ const content = existsSync(planPath) ? readFileSync(planPath, "utf-8") : null;
515
+ if (content === lastContent) return;
516
+ const wasCreated = lastContent === null && content !== null;
517
+ lastContent = content;
518
+ if (content !== null) {
519
+ session.send({
520
+ prompt: `The plan was ${wasCreated ? "created" : "edited"} by the user.`,
521
+ });
522
+ }
523
+ });
524
+ }
525
+ ```
526
+
527
+ ### Example: Reacting when the user manually edits any file in the repo
528
+
529
+ Use `fs.watch` with `recursive: true` on `process.cwd()` to detect file changes.
530
+ Filter out agent edits by tracking `tool.execution_start` / `tool.execution_complete` events.
531
+
532
+ ```js
533
+ import { watch, readFileSync, statSync } from "node:fs";
534
+ import { join, relative, resolve } from "node:path";
535
+ import { joinSession } from "@microsoft/copilot-sdk/extension";
536
+
537
+ const agentEditPaths = new Set();
538
+
539
+ const session = await joinSession();
540
+
541
+ const cwd = process.cwd();
542
+ const IGNORE = new Set(["node_modules", ".git", "dist"]);
543
+
544
+ // Track agent file edits
545
+ session.on("tool.execution_start", (event) => {
546
+ if (event.data.toolName === "edit" || event.data.toolName === "create") {
547
+ const p = String(event.data.arguments?.path || "");
548
+ if (p) agentEditPaths.add(resolve(p));
549
+ }
550
+ });
551
+ session.on("tool.execution_complete", (event) => {
552
+ // Clear after a delay to avoid race with fs.watch
553
+ const p = [...agentEditPaths].find((x) => x); // any tracked path
554
+ setTimeout(() => agentEditPaths.clear(), 3000);
555
+ });
556
+
557
+ const debounce = new Map();
558
+
559
+ watch(cwd, { recursive: true }, (eventType, filename) => {
560
+ if (!filename || eventType !== "change") return;
561
+ if (filename.split(/[\\/]/).some((p) => IGNORE.has(p))) return;
562
+
563
+ if (debounce.has(filename)) clearTimeout(debounce.get(filename));
564
+ debounce.set(filename, setTimeout(() => {
565
+ debounce.delete(filename);
566
+ const fullPath = join(cwd, filename);
567
+ if (agentEditPaths.has(resolve(fullPath))) return;
568
+
569
+ try { if (!statSync(fullPath).isFile()) return; } catch { return; }
570
+ const relPath = relative(cwd, fullPath);
571
+ session.send({
572
+ prompt: `The user edited \`${relPath}\`.`,
573
+ attachments: [{ type: "file", path: fullPath }],
574
+ });
575
+ }, 500));
576
+ });
577
+ ```
578
+
579
+ ---
580
+
581
+ ## Sending Messages Programmatically
582
+
583
+ ### Fire-and-forget
584
+
585
+ ```js
586
+ await session.send({ prompt: "Analyze the test results." });
587
+ ```
588
+
589
+ ### Send and wait for the response
590
+
591
+ ```js
592
+ const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
593
+ // response?.data.content contains the agent's reply
594
+ ```
595
+
596
+ ### Send with file attachments
597
+
598
+ ```js
599
+ await session.send({
600
+ prompt: "Review this file",
601
+ attachments: [{ type: "file", path: "./src/index.ts" }],
602
+ });
603
+ ```
604
+
605
+ ---
606
+
607
+ ## Permission and User Input Handlers
608
+
609
+ ### Custom permission logic
610
+
611
+ ```js
612
+ const session = await joinSession({
613
+ onPermissionRequest: async (request) => {
614
+ if (request.kind === "shell") {
615
+ // request.fullCommandText has the shell command
616
+ return { kind: "approve-once" };
617
+ }
618
+ if (request.kind === "write") {
619
+ return { kind: "approve-once" };
620
+ }
621
+ return { kind: "reject" };
622
+ },
623
+ });
624
+ ```
625
+
626
+ ### Handling agent questions (ask_user)
627
+
628
+ Register `onUserInputRequest` to enable the agent's `ask_user` tool:
629
+
630
+ ```js
631
+ const session = await joinSession({
632
+ onUserInputRequest: async (request) => {
633
+ // request.question has the agent's question
634
+ // request.choices has the options (if multiple choice)
635
+ return { answer: "yes", wasFreeform: false };
636
+ },
637
+ });
638
+ ```
639
+
640
+ ---
641
+
642
+ ## Complete Example: Multi-Feature Extension
643
+
644
+ An extension that combines tools, hooks, and events.
645
+
646
+ Use the same VS Code setup as in
647
+ [Reacting when the agent creates or edits a file](#reacting-when-the-agent-creates-or-edits-a-file).
648
+
649
+ ```js
650
+ import { execFile, spawn } from "node:child_process";
651
+ import { isAbsolute, resolve } from "node:path";
652
+ import { joinSession } from "@microsoft/copilot-sdk/extension";
653
+
654
+ const isWindows = process.platform === "win32";
655
+ const vscodeExecutable = isWindows ? process.env.VSCODE_EXECUTABLE : "code";
656
+ if (!vscodeExecutable || (isWindows && !isAbsolute(vscodeExecutable))) {
657
+ throw new Error("Set VSCODE_EXECUTABLE to the absolute path of Code.exe.");
658
+ }
659
+ const editorEnv = { ...process.env };
660
+ // The native editor must open the file, not run it as a Node.js script.
661
+ delete editorEnv.ELECTRON_RUN_AS_NODE;
662
+ let copyNextResponse = false;
663
+
664
+ function copyToClipboard(text) {
665
+ const proc = execFile(isWindows ? "clip" : "pbcopy", [], () => {});
666
+ proc.stdin.write(text);
667
+ proc.stdin.end();
668
+ }
669
+
670
+ function openInEditor(filePath) {
671
+ try {
672
+ const child = spawn(vscodeExecutable, [resolve(filePath)], {
673
+ detached: true,
674
+ stdio: "ignore",
675
+ env: editorEnv,
676
+ });
677
+ child.on("error", (err) => console.error("Could not open file in VS Code:", err.message));
678
+ child.unref();
679
+ } catch (err) {
680
+ console.error("Could not open file in VS Code:", err.message);
681
+ }
682
+ }
683
+
684
+ const session = await joinSession({
685
+ hooks: {
686
+ onUserPromptSubmitted: async (input) => {
687
+ if (/\bcopy this\b/i.test(input.prompt)) {
688
+ copyNextResponse = true;
689
+ }
690
+ return {
691
+ additionalContext: "Follow our team style guide. Use 4-space indentation.",
692
+ };
693
+ },
694
+ onPreToolUse: async (input) => {
695
+ if (input.toolName === "bash") {
696
+ const cmd = String(input.toolArgs?.command || "");
697
+ if (/rm\s+-rf\s+\//i.test(cmd) || /Remove-Item\s+.*-Recurse/i.test(cmd)) {
698
+ return {
699
+ permissionDecision: "deny",
700
+ permissionDecisionReason: "Destructive commands are not allowed.",
701
+ };
702
+ }
703
+ }
704
+ },
705
+ onPostToolUse: async (input) => {
706
+ if (input.toolName === "create" || input.toolName === "edit") {
707
+ const filePath = input.toolArgs?.path;
708
+ if (typeof filePath === "string" && filePath) openInEditor(filePath);
709
+ }
710
+ },
711
+ },
712
+ tools: [
713
+ {
714
+ name: "copy_to_clipboard",
715
+ description: "Copies text to the system clipboard.",
716
+ parameters: {
717
+ type: "object",
718
+ properties: {
719
+ text: { type: "string", description: "Text to copy" },
720
+ },
721
+ required: ["text"],
722
+ },
723
+ handler: async (args) => {
724
+ return new Promise((resolve) => {
725
+ const proc = execFile(isWindows ? "clip" : "pbcopy", [], (err) => {
726
+ if (err) resolve(`Error: ${err.message}`);
727
+ else resolve("Copied to clipboard.");
728
+ });
729
+ proc.stdin.write(args.text);
730
+ proc.stdin.end();
731
+ });
732
+ },
733
+ },
734
+ ],
735
+ });
736
+
737
+ session.on("assistant.message", (event) => {
738
+ if (copyNextResponse) {
739
+ copyNextResponse = false;
740
+ copyToClipboard(event.data.content);
741
+ }
742
+ });
743
+
744
+ session.on("tool.execution_complete", (event) => {
745
+ // event.data.success, event.data.result
746
+ });
747
+ ```