@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.
- package/README.md +2531 -2
- package/dist/canvas.d.ts +135 -0
- package/dist/canvas.js +51 -0
- package/dist/cjs/canvas.js +77 -0
- package/dist/cjs/cliVersion.js +31 -0
- package/dist/cjs/client.js +3941 -0
- package/dist/cjs/copilotRequestHandler.js +815 -0
- package/dist/cjs/decisions.js +139 -0
- package/dist/cjs/entra.js +83 -0
- package/dist/cjs/extension.js +79 -0
- package/dist/cjs/ffiRuntimeHost.js +400 -0
- package/dist/cjs/generated/lifecycle-diagnostics.js +16 -0
- package/dist/cjs/generated/rpc.js +5883 -0
- package/dist/cjs/generated/session-events.js +16 -0
- package/dist/cjs/host.js +83 -0
- package/dist/cjs/index.js +100 -0
- package/dist/cjs/installationConfirmation.js +98 -0
- package/dist/cjs/jsonrpcTypes.js +41 -0
- package/dist/cjs/localModelJson.js +103 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/providerConfiguration.js +39 -0
- package/dist/cjs/rpcCancellation.js +49 -0
- package/dist/cjs/runtimeArtifacts.js +255 -0
- package/dist/cjs/schema.js +40 -0
- package/dist/cjs/sdkProtocolVersion.js +33 -0
- package/dist/cjs/session.js +2764 -0
- package/dist/cjs/sessionFsProvider.js +283 -0
- package/dist/cjs/taskAnalyticsJson.js +47 -0
- package/dist/cjs/telemetry.js +35 -0
- package/dist/cjs/toolSet.js +107 -0
- package/dist/cjs/types.js +204 -0
- package/dist/cjs/workflow.js +278 -0
- package/dist/cliVersion.d.ts +2 -0
- package/dist/cliVersion.js +6 -0
- package/dist/client.d.ts +576 -0
- package/dist/client.js +3924 -0
- package/dist/copilotRequestHandler.d.ts +91 -0
- package/dist/copilotRequestHandler.js +787 -0
- package/dist/decisions.d.ts +65 -0
- package/dist/decisions.js +113 -0
- package/dist/entra.d.ts +3 -0
- package/dist/entra.js +59 -0
- package/dist/extension.d.ts +69 -0
- package/dist/extension.js +59 -0
- package/dist/ffiRuntimeHost.d.ts +44 -0
- package/dist/ffiRuntimeHost.js +366 -0
- package/dist/generated/lifecycle-diagnostics.d.ts +232 -0
- package/dist/generated/lifecycle-diagnostics.js +0 -0
- package/dist/generated/rpc.d.ts +47706 -0
- package/dist/generated/rpc.js +5854 -0
- package/dist/generated/session-events.d.ts +17349 -0
- package/dist/generated/session-events.js +0 -0
- package/dist/host.d.ts +143 -0
- package/dist/host.js +59 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +74 -0
- package/dist/installationConfirmation.d.ts +19 -0
- package/dist/installationConfirmation.js +74 -0
- package/dist/jsonrpcTypes.d.ts +16 -0
- package/dist/jsonrpcTypes.js +17 -0
- package/dist/localModelJson.d.ts +1 -0
- package/dist/localModelJson.js +69 -0
- package/dist/providerConfiguration.d.ts +3 -0
- package/dist/providerConfiguration.js +15 -0
- package/dist/rpcCancellation.d.ts +3 -0
- package/dist/rpcCancellation.js +25 -0
- package/dist/runtimeArtifacts.d.ts +18 -0
- package/dist/runtimeArtifacts.js +233 -0
- package/dist/schema.d.ts +4 -0
- package/dist/schema.js +14 -0
- package/dist/sdkProtocolVersion.d.ts +10 -0
- package/dist/sdkProtocolVersion.js +8 -0
- package/dist/session.d.ts +524 -0
- package/dist/session.js +2751 -0
- package/dist/sessionFsProvider.d.ts +130 -0
- package/dist/sessionFsProvider.js +257 -0
- package/dist/taskAnalyticsJson.d.ts +8 -0
- package/dist/taskAnalyticsJson.js +12 -0
- package/dist/telemetry.d.ts +14 -0
- package/dist/telemetry.js +11 -0
- package/dist/toolSet.d.ts +75 -0
- package/dist/toolSet.js +82 -0
- package/dist/types.d.ts +3864 -0
- package/dist/types.js +169 -0
- package/dist/workflow.d.ts +413 -0
- package/dist/workflow.js +248 -0
- package/docs/agent-author.md +372 -0
- package/docs/examples.md +747 -0
- package/docs/extensions.md +121 -0
- package/docs/workflows.md +303 -0
- package/package.json +135 -5
package/dist/workflow.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
const WORKFLOW_TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
3
|
+
"completed",
|
|
4
|
+
"halted",
|
|
5
|
+
"paused",
|
|
6
|
+
"cancelled",
|
|
7
|
+
"error"
|
|
8
|
+
]);
|
|
9
|
+
function isWorkflowRunTerminal(status) {
|
|
10
|
+
return WORKFLOW_TERMINAL_STATUSES.has(status);
|
|
11
|
+
}
|
|
12
|
+
const WORKFLOW_AGENT_OPTION_KEYS = [
|
|
13
|
+
"label",
|
|
14
|
+
"schema",
|
|
15
|
+
"model",
|
|
16
|
+
"reasoningEffort",
|
|
17
|
+
"contextTier",
|
|
18
|
+
"agent",
|
|
19
|
+
"timeoutSeconds"
|
|
20
|
+
];
|
|
21
|
+
class WorkflowResumeError extends Error {
|
|
22
|
+
constructor(code, message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.name = "WorkflowResumeError";
|
|
26
|
+
}
|
|
27
|
+
code;
|
|
28
|
+
}
|
|
29
|
+
const workflowHandles = /* @__PURE__ */ new WeakMap();
|
|
30
|
+
const workflowAgentReferences = /* @__PURE__ */ new WeakSet();
|
|
31
|
+
const MAX_WORKFLOW_TIMEOUT_SECONDS = 2147483647e-3;
|
|
32
|
+
const NANO_AIU_PER_AIU = 1e9;
|
|
33
|
+
function deepFreeze(value) {
|
|
34
|
+
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
35
|
+
Object.freeze(value);
|
|
36
|
+
for (const nested of Object.values(value)) {
|
|
37
|
+
deepFreeze(nested);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function canonicalJson(value) {
|
|
43
|
+
const compareUtf8 = (left, right) => Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
|
|
44
|
+
const canonicalize = (nested) => {
|
|
45
|
+
if (Array.isArray(nested)) {
|
|
46
|
+
return nested.map(canonicalize);
|
|
47
|
+
}
|
|
48
|
+
if (nested !== null && typeof nested === "object") {
|
|
49
|
+
return Object.fromEntries(
|
|
50
|
+
Object.entries(nested).filter(([, child]) => child !== void 0).sort(([left], [right]) => compareUtf8(left, right)).map(([key, child]) => [key, canonicalize(child)])
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
return nested;
|
|
54
|
+
};
|
|
55
|
+
return JSON.stringify(canonicalize(value));
|
|
56
|
+
}
|
|
57
|
+
function sha256(value) {
|
|
58
|
+
return createHash("sha256").update(value, "utf8").digest("hex");
|
|
59
|
+
}
|
|
60
|
+
function validateRequiredWorkflowAgentString(value, field) {
|
|
61
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
62
|
+
throw new Error(`Workflow agent "${field}" must not be empty`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function validateOptionalWorkflowAgentString(value, field) {
|
|
66
|
+
if (value !== void 0 && (typeof value !== "string" || value.trim().length === 0)) {
|
|
67
|
+
throw new Error(`Workflow agent "${field}" must be a non-empty string when provided`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function normalizeWorkflowAgent(config) {
|
|
71
|
+
if (config === null || typeof config !== "object" || Array.isArray(config)) {
|
|
72
|
+
throw new Error("Workflow agent configuration must be an object");
|
|
73
|
+
}
|
|
74
|
+
const allowed = /* @__PURE__ */ new Set(["name", "displayName", "description", "prompt", "tools", "infer"]);
|
|
75
|
+
for (const field of Object.keys(config)) {
|
|
76
|
+
if (!allowed.has(field)) {
|
|
77
|
+
throw new Error(`Workflow agent field "${field}" is not supported`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
validateRequiredWorkflowAgentString(config.name, "name");
|
|
81
|
+
validateRequiredWorkflowAgentString(config.prompt, "prompt");
|
|
82
|
+
validateOptionalWorkflowAgentString(config.displayName, "displayName");
|
|
83
|
+
validateOptionalWorkflowAgentString(config.description, "description");
|
|
84
|
+
if (config.infer !== false) {
|
|
85
|
+
throw new Error('Workflow agent "infer" must be false');
|
|
86
|
+
}
|
|
87
|
+
if (config.tools !== void 0 && (!Array.isArray(config.tools) || config.tools.length !== 0)) {
|
|
88
|
+
throw new Error("Workflow agents must not declare tools");
|
|
89
|
+
}
|
|
90
|
+
return deepFreeze({
|
|
91
|
+
name: config.name,
|
|
92
|
+
...config.displayName !== void 0 ? { displayName: config.displayName } : {},
|
|
93
|
+
...config.description !== void 0 ? { description: config.description } : {},
|
|
94
|
+
prompt: config.prompt,
|
|
95
|
+
tools: [],
|
|
96
|
+
infer: false
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
function workflowRegistration(meta, agents) {
|
|
100
|
+
if (agents === void 0) {
|
|
101
|
+
return {
|
|
102
|
+
registration: meta,
|
|
103
|
+
agents: Object.freeze({}),
|
|
104
|
+
agentReferences: /* @__PURE__ */ new Map()
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (agents === null || typeof agents !== "object" || Array.isArray(agents)) {
|
|
108
|
+
throw new Error("Workflow agents must be a named object map");
|
|
109
|
+
}
|
|
110
|
+
const definitions = Object.entries(agents).map(([key, config]) => {
|
|
111
|
+
if (key.trim().length === 0) {
|
|
112
|
+
throw new Error("Workflow agent map keys must not be empty");
|
|
113
|
+
}
|
|
114
|
+
const definition = normalizeWorkflowAgent(config);
|
|
115
|
+
const reference = Object.freeze({});
|
|
116
|
+
workflowAgentReferences.add(reference);
|
|
117
|
+
return { key, reference, definition };
|
|
118
|
+
});
|
|
119
|
+
if (definitions.length === 0) {
|
|
120
|
+
return {
|
|
121
|
+
registration: meta,
|
|
122
|
+
agents: Object.freeze({}),
|
|
123
|
+
agentReferences: /* @__PURE__ */ new Map()
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const names = /* @__PURE__ */ new Set();
|
|
127
|
+
for (const { definition } of definitions) {
|
|
128
|
+
if (names.has(definition.name)) {
|
|
129
|
+
throw new Error(`Workflow agent "${definition.name}" is declared more than once`);
|
|
130
|
+
}
|
|
131
|
+
names.add(definition.name);
|
|
132
|
+
}
|
|
133
|
+
definitions.sort(
|
|
134
|
+
(left, right) => Buffer.compare(
|
|
135
|
+
Buffer.from(left.definition.name, "utf8"),
|
|
136
|
+
Buffer.from(right.definition.name, "utf8")
|
|
137
|
+
)
|
|
138
|
+
);
|
|
139
|
+
const roleDefinitionHash = sha256(
|
|
140
|
+
canonicalJson(definitions.map(({ definition }) => definition))
|
|
141
|
+
);
|
|
142
|
+
const agentReferences = /* @__PURE__ */ new Map();
|
|
143
|
+
const contextAgentEntries = [];
|
|
144
|
+
const privateRoles = definitions.map(({ key, reference: agentReference, definition }) => {
|
|
145
|
+
const wireReference = sha256(
|
|
146
|
+
`workflow-role\0${meta.name}\0${definition.name}\0${roleDefinitionHash}`
|
|
147
|
+
);
|
|
148
|
+
agentReferences.set(agentReference, wireReference);
|
|
149
|
+
contextAgentEntries.push([key, agentReference]);
|
|
150
|
+
return { reference: wireReference, ...definition };
|
|
151
|
+
});
|
|
152
|
+
return {
|
|
153
|
+
registration: deepFreeze({
|
|
154
|
+
...meta,
|
|
155
|
+
privateRoles,
|
|
156
|
+
roleDefinitionHash
|
|
157
|
+
}),
|
|
158
|
+
agents: Object.freeze(Object.fromEntries(contextAgentEntries)),
|
|
159
|
+
agentReferences
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
function validateLimits(meta) {
|
|
163
|
+
const limits = meta.limits;
|
|
164
|
+
if (!limits) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
for (const field of ["maxConcurrentSubagents", "maxTotalSubagents"]) {
|
|
168
|
+
const value = limits[field];
|
|
169
|
+
if (value !== void 0 && (!Number.isInteger(value) || value <= 0)) {
|
|
170
|
+
throw new Error(`Workflow limit "${field}" must be a positive integer`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (limits.timeoutSeconds !== void 0 && (!Number.isFinite(limits.timeoutSeconds) || limits.timeoutSeconds <= 0)) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
'Workflow limit "timeoutSeconds" must be a positive, finite number of seconds'
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
if (limits.timeoutSeconds !== void 0 && limits.timeoutSeconds > MAX_WORKFLOW_TIMEOUT_SECONDS) {
|
|
179
|
+
throw new Error(
|
|
180
|
+
`Workflow limit "timeoutSeconds" must not exceed ${MAX_WORKFLOW_TIMEOUT_SECONDS} seconds`
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
if (limits.maxAiCredits !== void 0) {
|
|
184
|
+
const maxNanoAiu = Math.round(limits.maxAiCredits * NANO_AIU_PER_AIU);
|
|
185
|
+
if (!Number.isFinite(limits.maxAiCredits) || limits.maxAiCredits <= 0 || !Number.isSafeInteger(maxNanoAiu) || maxNanoAiu < 1) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
'Workflow limit "maxAiCredits" must be a positive, finite number that rounds to a safe positive integer nano-AIU ceiling'
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function validatePhases(meta) {
|
|
193
|
+
const titles = /* @__PURE__ */ new Set();
|
|
194
|
+
for (const phase of meta.phases) {
|
|
195
|
+
if (phase.title.trim().length === 0) {
|
|
196
|
+
throw new Error("Workflow phase titles must not be empty");
|
|
197
|
+
}
|
|
198
|
+
if (titles.has(phase.title)) {
|
|
199
|
+
throw new Error(`Workflow phase title "${phase.title}" is declared more than once`);
|
|
200
|
+
}
|
|
201
|
+
titles.add(phase.title);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function defineWorkflow(definition) {
|
|
205
|
+
const meta = deepFreeze(structuredClone(definition.meta));
|
|
206
|
+
validateLimits(meta);
|
|
207
|
+
validatePhases(meta);
|
|
208
|
+
const { registration, agents, agentReferences } = workflowRegistration(meta, definition.agents);
|
|
209
|
+
const stored = {
|
|
210
|
+
meta,
|
|
211
|
+
registration,
|
|
212
|
+
agents,
|
|
213
|
+
agentReferences,
|
|
214
|
+
run: definition.run
|
|
215
|
+
};
|
|
216
|
+
const handle = Object.freeze({ meta });
|
|
217
|
+
workflowHandles.set(handle, stored);
|
|
218
|
+
return handle;
|
|
219
|
+
}
|
|
220
|
+
function getWorkflowDefinition(handle) {
|
|
221
|
+
const definition = workflowHandles.get(handle);
|
|
222
|
+
if (!definition) {
|
|
223
|
+
throw new Error("Invalid workflow handle");
|
|
224
|
+
}
|
|
225
|
+
return definition;
|
|
226
|
+
}
|
|
227
|
+
function getWorkflowRegistration(handle) {
|
|
228
|
+
return getWorkflowDefinition(handle).registration;
|
|
229
|
+
}
|
|
230
|
+
function getWorkflowAgentReference(workflow, agent) {
|
|
231
|
+
if (!workflowAgentReferences.has(agent)) {
|
|
232
|
+
throw new Error("Invalid workflow agent reference");
|
|
233
|
+
}
|
|
234
|
+
const reference = workflow.agentReferences.get(agent);
|
|
235
|
+
if (!reference) {
|
|
236
|
+
throw new Error("Workflow agent reference is not declared by this workflow");
|
|
237
|
+
}
|
|
238
|
+
return reference;
|
|
239
|
+
}
|
|
240
|
+
export {
|
|
241
|
+
WORKFLOW_AGENT_OPTION_KEYS,
|
|
242
|
+
WorkflowResumeError,
|
|
243
|
+
defineWorkflow,
|
|
244
|
+
getWorkflowAgentReference,
|
|
245
|
+
getWorkflowDefinition,
|
|
246
|
+
getWorkflowRegistration,
|
|
247
|
+
isWorkflowRunTerminal
|
|
248
|
+
};
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
# Agent Extension Authoring Guide
|
|
2
|
+
|
|
3
|
+
A precise, step-by-step reference for agents writing Copilot CLI extensions programmatically.
|
|
4
|
+
|
|
5
|
+
## Workflow
|
|
6
|
+
|
|
7
|
+
### Step 1: Scaffold the extension
|
|
8
|
+
|
|
9
|
+
Use the `extensions_manage` tool with `operation: "scaffold"`:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
extensions_manage({ operation: "scaffold", name: "my-extension" })
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
This creates `.github/extensions/my-extension/extension.mjs` with a working skeleton.
|
|
16
|
+
For user-scoped extensions (persist across all repos), add `location: "user"`.
|
|
17
|
+
|
|
18
|
+
### Step 2: Edit the extension file
|
|
19
|
+
|
|
20
|
+
Modify the generated `extension.mjs` using `edit` or `create` tools. The file must:
|
|
21
|
+
|
|
22
|
+
- Be named `extension.mjs`, `extension.cjs` or `extension.js` (the scaffold creates `extension.mjs`)
|
|
23
|
+
- Use ES module syntax (`import`/`export`) in `.mjs` files, or CommonJS (`require`) in `.cjs` files
|
|
24
|
+
- Call `joinSession({ ... })`
|
|
25
|
+
|
|
26
|
+
### Step 3: Reload extensions
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
extensions_reload({})
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
This refreshes discovery and running extensions. [Opted-in dormant extensions](extensions.md#opting-into-request-driven-activation) remain unstarted until requested; their declared tools are immediately discoverable.
|
|
33
|
+
|
|
34
|
+
### Step 4: Verify
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
extensions_manage({ operation: "list" })
|
|
38
|
+
extensions_manage({ operation: "inspect", name: "my-extension" })
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Check that the extension loaded successfully and isn't marked as "failed".
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## File Structure
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
.github/extensions/<name>/extension.mjs
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Discovery rules:
|
|
52
|
+
|
|
53
|
+
- The CLI scans `.github/extensions/` relative to the git root
|
|
54
|
+
- It also scans the user's copilot config extensions directory
|
|
55
|
+
- Only immediate subdirectories are checked (not recursive)
|
|
56
|
+
- Each subdirectory must contain a file named `extension.mjs`, `extension.cjs` or `extension.js`
|
|
57
|
+
- Project extensions shadow user extensions on name collision
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Minimal Skeleton
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
import { joinSession } from "@microsoft/copilot-sdk/extension";
|
|
65
|
+
|
|
66
|
+
await joinSession({
|
|
67
|
+
tools: [], // Optional — custom tools
|
|
68
|
+
hooks: {}, // Optional — lifecycle hooks
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Registering Tools
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
tools: [
|
|
78
|
+
{
|
|
79
|
+
name: "tool_name", // Required. Must be globally unique across all extensions.
|
|
80
|
+
description: "What it does", // Required. Shown to the agent in tool descriptions.
|
|
81
|
+
parameters: {
|
|
82
|
+
// Optional. JSON Schema for the arguments.
|
|
83
|
+
type: "object",
|
|
84
|
+
properties: {
|
|
85
|
+
arg1: { type: "string", description: "..." },
|
|
86
|
+
},
|
|
87
|
+
required: ["arg1"],
|
|
88
|
+
},
|
|
89
|
+
handler: async (args, invocation) => {
|
|
90
|
+
// args: parsed arguments matching the schema
|
|
91
|
+
// invocation.sessionId: current session ID
|
|
92
|
+
// invocation.toolCallId: unique call ID
|
|
93
|
+
// invocation.toolName: this tool's name
|
|
94
|
+
//
|
|
95
|
+
// Return value: string or ToolResultObject
|
|
96
|
+
// string → treated as success
|
|
97
|
+
// { textResultForLlm, resultType } → structured result
|
|
98
|
+
// resultType: "success" | "failure" | "rejected" | "denied" | "timeout"
|
|
99
|
+
return `Result: ${args.arg1}`;
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
**Constraints:**
|
|
106
|
+
|
|
107
|
+
- Tool names must be unique across ALL loaded extensions. Collisions cause the second extension to fail to load.
|
|
108
|
+
- Handler must return a string or `{ textResultForLlm: string, resultType: "success" | "failure" | "rejected" | "denied" | "timeout" }`. `resultType` is required: an object without a recognized `resultType` is not a structured result, and the model receives it serialized as JSON text.
|
|
109
|
+
- Handler receives `(args, invocation)` — the second argument has `sessionId`, `toolCallId`, `toolName`.
|
|
110
|
+
- Use `session.log()` to surface messages to the user. Don't use `console.log()` (stdout is reserved for JSON-RPC).
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## Registering Hooks
|
|
115
|
+
|
|
116
|
+
```js
|
|
117
|
+
hooks: {
|
|
118
|
+
onUserPromptSubmitted: async (input, invocation) => { ... },
|
|
119
|
+
onUserPromptTransformed: async (input, invocation) => { ... },
|
|
120
|
+
onPreToolUse: async (input, invocation) => { ... },
|
|
121
|
+
onPreMcpToolCall: async (input, invocation) => { ... },
|
|
122
|
+
onPostToolUse: async (input, invocation) => { ... },
|
|
123
|
+
onPostToolUseFailure: async (input, invocation) => { ... },
|
|
124
|
+
onSessionStart: async (input, invocation) => { ... },
|
|
125
|
+
onSessionEnd: async (input, invocation) => { ... },
|
|
126
|
+
onErrorOccurred: async (input, invocation) => { ... },
|
|
127
|
+
onAgentStop: async (input, invocation) => { ... },
|
|
128
|
+
onSubagentStart: async (input, invocation) => { ... },
|
|
129
|
+
onSubagentStop: async (input, invocation) => { ... },
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
All hook inputs include `sessionId`, `timestamp` (`Date`) and `workingDirectory`.
|
|
134
|
+
Tool hooks also receive `toolCallId` when the runtime supplies one; correlate a call's hooks with `(input.sessionId, input.toolCallId)`.
|
|
135
|
+
All handlers receive `invocation: { sessionId: string }` as the second argument.
|
|
136
|
+
All handlers may return `void`/`undefined` (no-op) or an output object.
|
|
137
|
+
|
|
138
|
+
### onUserPromptSubmitted
|
|
139
|
+
|
|
140
|
+
**Input:** `{ prompt: string, timestamp, workingDirectory }`
|
|
141
|
+
|
|
142
|
+
**Output (all fields optional):**
|
|
143
|
+
| Field | Type | Effect |
|
|
144
|
+
|-------|------|--------|
|
|
145
|
+
| `modifiedPrompt` | `string` | Replaces the user's prompt |
|
|
146
|
+
| `additionalContext` | `string` | Appended as hidden context the agent sees |
|
|
147
|
+
| `decision` | `"block"` | Refuses the prompt: no model turn runs and no user message is recorded |
|
|
148
|
+
| `reason` | `string` | Why the prompt was blocked, carried by the ephemeral `session.warning` (`warningType: "policy_blocked"`) |
|
|
149
|
+
|
|
150
|
+
### onUserPromptTransformed
|
|
151
|
+
|
|
152
|
+
Fires after the runtime adds generated context to the submitted prompt, before
|
|
153
|
+
the result is stored in session history or sent to the model. `prompt` is the
|
|
154
|
+
prompt after `onUserPromptSubmitted`; `transformedPrompt` also carries the
|
|
155
|
+
runtime-generated context.
|
|
156
|
+
|
|
157
|
+
**Input:** `{ prompt: string, transformedPrompt: string, timestamp, workingDirectory }`
|
|
158
|
+
|
|
159
|
+
**Output (all fields optional):**
|
|
160
|
+
| Field | Type | Effect |
|
|
161
|
+
|-------|------|--------|
|
|
162
|
+
| `modifiedTransformedPrompt` | `string` | Replaces the content stored in session history and sent to the model |
|
|
163
|
+
|
|
164
|
+
### onPreToolUse
|
|
165
|
+
|
|
166
|
+
**Input:** `{ toolCallId?: string, toolName: string, toolArgs: unknown, timestamp, workingDirectory }`
|
|
167
|
+
|
|
168
|
+
**Output (all fields optional):**
|
|
169
|
+
| Field | Type | Effect |
|
|
170
|
+
|-------|------|--------|
|
|
171
|
+
| `permissionDecision` | `"allow" \| "deny" \| "ask"` | Override the permission check |
|
|
172
|
+
| `permissionDecisionReason` | `string` | Shown to user if denied |
|
|
173
|
+
| `modifiedArgs` | `unknown` | Replaces the tool arguments |
|
|
174
|
+
| `additionalContext` | `string` | Injected into the conversation |
|
|
175
|
+
|
|
176
|
+
### onPreMcpToolCall
|
|
177
|
+
|
|
178
|
+
Fires before a tool call is sent to an MCP server. It controls only the `_meta`
|
|
179
|
+
object sent with the request; to allow, deny or change the call itself, use
|
|
180
|
+
`onPreToolUse`.
|
|
181
|
+
|
|
182
|
+
**Input:** `{ toolCallId?: string, serverName: string, toolName: string, arguments: unknown, _meta?: Record<string, unknown>, timestamp, workingDirectory }`
|
|
183
|
+
|
|
184
|
+
**Output (all fields optional):**
|
|
185
|
+
| Field | Type | Effect |
|
|
186
|
+
|-------|------|--------|
|
|
187
|
+
| `metaToUse` | `Record<string, unknown> \| null` | An object becomes the request's `_meta`; `null` omits it, except for the runtime's `com.github.copilot/toolCallId` and `com.github.copilot/turnId` keys; leaving it out keeps the current `_meta` |
|
|
188
|
+
|
|
189
|
+
### onPostToolUse
|
|
190
|
+
|
|
191
|
+
**Input:** `{ toolCallId?: string, toolName: string, toolArgs: unknown, toolResult: ToolResultObject, timestamp, workingDirectory }`
|
|
192
|
+
|
|
193
|
+
Fires only when the tool returned a successful result. To observe non-success
|
|
194
|
+
outcomes, register `onPostToolUseFailure` as well.
|
|
195
|
+
|
|
196
|
+
**Output (all fields optional):**
|
|
197
|
+
| Field | Type | Effect |
|
|
198
|
+
|-------|------|--------|
|
|
199
|
+
| `modifiedResult` | `ToolResultObject` | Replaces the tool result |
|
|
200
|
+
| `additionalContext` | `string` | Injected into the conversation |
|
|
201
|
+
|
|
202
|
+
### onPostToolUseFailure
|
|
203
|
+
|
|
204
|
+
**Input:** `{ toolCallId?: string, toolName: string, toolArgs: unknown, error: string, timestamp, workingDirectory }`
|
|
205
|
+
|
|
206
|
+
Fires after a tool execution whose result was `"failure"`. `onPostToolUse`
|
|
207
|
+
does **not** fire for these outcomes, so register this handler to observe or
|
|
208
|
+
react to them — useful for telemetry, replay buffers, fault-injection tests,
|
|
209
|
+
or pairing pre/post tool tracking that would otherwise leak when the tool
|
|
210
|
+
fails. Note the input shape differs from `onPostToolUse`: only `error` (the
|
|
211
|
+
stringified failure message) is provided, not the full `toolResult`.
|
|
212
|
+
|
|
213
|
+
**Output (all fields optional):**
|
|
214
|
+
| Field | Type | Effect |
|
|
215
|
+
|-------|------|--------|
|
|
216
|
+
| `additionalContext` | `string` | Appended as hidden guidance the model sees alongside the failed tool result |
|
|
217
|
+
|
|
218
|
+
Note: only `"failure"` results trigger this hook. Other non-success
|
|
219
|
+
`resultType` values (`"rejected"`, `"denied"`, `"timeout"`) do not currently
|
|
220
|
+
fire it.
|
|
221
|
+
|
|
222
|
+
### onSessionStart
|
|
223
|
+
|
|
224
|
+
**Input:** `{ source: "startup" \| "resume" \| "new", initialPrompt?: string, timestamp, workingDirectory }`
|
|
225
|
+
|
|
226
|
+
**Output (all fields optional):**
|
|
227
|
+
| Field | Type | Effect |
|
|
228
|
+
|-------|------|--------|
|
|
229
|
+
| `additionalContext` | `string` | Injected as initial context |
|
|
230
|
+
|
|
231
|
+
### onSessionEnd
|
|
232
|
+
|
|
233
|
+
**Input:** `{ reason: "complete" \| "error" \| "abort" \| "timeout" \| "user_exit", finalMessage?: string, error?: string, timestamp, workingDirectory }`
|
|
234
|
+
|
|
235
|
+
**Output (all fields optional):**
|
|
236
|
+
| Field | Type | Effect |
|
|
237
|
+
|-------|------|--------|
|
|
238
|
+
| `sessionSummary` | `string` | Summary for session persistence |
|
|
239
|
+
| `cleanupActions` | `string[]` | Cleanup descriptions |
|
|
240
|
+
|
|
241
|
+
### onErrorOccurred
|
|
242
|
+
|
|
243
|
+
**Input:** `{ error: string, errorContext: "model_call" \| "tool_execution" \| "system" \| "user_input", recoverable: boolean, timestamp, workingDirectory }`
|
|
244
|
+
|
|
245
|
+
**Output (all fields optional):**
|
|
246
|
+
| Field | Type | Effect |
|
|
247
|
+
|-------|------|--------|
|
|
248
|
+
| `errorHandling` | `"retry" \| "skip" \| "abort"` | How to handle the error |
|
|
249
|
+
| `retryCount` | `number` | Max retries (when errorHandling is "retry") |
|
|
250
|
+
| `userNotification` | `string` | Message shown to the user |
|
|
251
|
+
|
|
252
|
+
### onAgentStop
|
|
253
|
+
|
|
254
|
+
Fires when the top-level agent reaches a natural terminal stop: it went idle
|
|
255
|
+
without pending work and was not aborted. Sub-agents fire `onSubagentStop`
|
|
256
|
+
instead.
|
|
257
|
+
|
|
258
|
+
**Input:** `{ stopReason?: string, transcriptPath?: string, stopHookActive?: boolean, timestamp, workingDirectory }`
|
|
259
|
+
|
|
260
|
+
`stopHookActive` is `true` when this stop follows an earlier `"block"` from this
|
|
261
|
+
hook; check it to avoid blocking indefinitely. The runtime also caps
|
|
262
|
+
consecutive blocks.
|
|
263
|
+
|
|
264
|
+
**Output (optional):**
|
|
265
|
+
| Field | Type | Effect |
|
|
266
|
+
|-------|------|--------|
|
|
267
|
+
| `decision` and `reason` | `"block"` and `string` | Keep the agent running; `reason` is enqueued as its next user message |
|
|
268
|
+
|
|
269
|
+
### onSubagentStart
|
|
270
|
+
|
|
271
|
+
Fires before a sub-agent's first turn. The input's `sessionId` and the
|
|
272
|
+
invocation's `sessionId` identify the parent session, not the child.
|
|
273
|
+
|
|
274
|
+
**Input:** `{ sessionId: string, transcriptPath: string, agentName: string, agentDisplayName?: string, agentDescription?: string, timestamp, workingDirectory }`
|
|
275
|
+
|
|
276
|
+
**Output (optional):**
|
|
277
|
+
| Field | Type | Effect |
|
|
278
|
+
|-------|------|--------|
|
|
279
|
+
| `additionalContext` | `string` | Prepended to the child's initial prompt |
|
|
280
|
+
|
|
281
|
+
### onSubagentStop
|
|
282
|
+
|
|
283
|
+
Fires after a sub-agent completes a turn. The input includes the child's last
|
|
284
|
+
assistant `response` and the parent's session metadata. `agentId` is available
|
|
285
|
+
when the task registry supplies one. This is distinct from `onAgentStop`, which
|
|
286
|
+
only runs for the top-level agent.
|
|
287
|
+
|
|
288
|
+
**Input:** `{ sessionId: string, transcriptPath: string, agentName: string, agentDisplayName?: string, agentDescription?: string, agentId?: string, agentType: string, stopReason: "end_turn", response: string, timestamp, workingDirectory }`
|
|
289
|
+
|
|
290
|
+
**Output (choose one, or return nothing):**
|
|
291
|
+
| Field | Type | Effect |
|
|
292
|
+
|-------|------|--------|
|
|
293
|
+
| `decision` and `reason` | `"block"` and `string` | Continue the child for another turn using `reason` |
|
|
294
|
+
| `modifiedResponse` | `string` | Replace the child's response reported to the parent |
|
|
295
|
+
|
|
296
|
+
## Session Object
|
|
297
|
+
|
|
298
|
+
After `joinSession()`, the returned `session` provides:
|
|
299
|
+
|
|
300
|
+
### session.send(options)
|
|
301
|
+
|
|
302
|
+
Send a message programmatically:
|
|
303
|
+
|
|
304
|
+
```js
|
|
305
|
+
await session.send({ prompt: "Analyze the test results." });
|
|
306
|
+
await session.send({
|
|
307
|
+
prompt: "Review this file",
|
|
308
|
+
attachments: [{ type: "file", path: "./src/index.ts" }],
|
|
309
|
+
});
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
### session.sendAndWait(options, timeout?)
|
|
313
|
+
|
|
314
|
+
Send and block until the agent finishes (resolves on `session.idle`):
|
|
315
|
+
|
|
316
|
+
```js
|
|
317
|
+
const response = await session.sendAndWait({ prompt: "What is 2+2?" });
|
|
318
|
+
// response?.data.content contains the agent's reply
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
### session.log(message, options?)
|
|
322
|
+
|
|
323
|
+
Log to the CLI timeline:
|
|
324
|
+
|
|
325
|
+
```js
|
|
326
|
+
await session.log("Extension ready");
|
|
327
|
+
await session.log("Rate limit approaching", { level: "warning" });
|
|
328
|
+
await session.log("Connection failed", { level: "error" });
|
|
329
|
+
await session.log("Processing...", { ephemeral: true }); // transient, not persisted
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### session.on(eventType, handler)
|
|
333
|
+
|
|
334
|
+
Subscribe to session events. Returns an unsubscribe function.
|
|
335
|
+
|
|
336
|
+
```js
|
|
337
|
+
const unsub = session.on("tool.execution_complete", (event) => {
|
|
338
|
+
// event.data.success, event.data.result
|
|
339
|
+
});
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### Key Event Types
|
|
343
|
+
|
|
344
|
+
| Event | Key Data Fields |
|
|
345
|
+
| ------------------------- | ------------------------------------------ |
|
|
346
|
+
| `assistant.message` | `content`, `messageId` |
|
|
347
|
+
| `tool.execution_start` | `toolCallId`, `toolName`, `arguments` |
|
|
348
|
+
| `tool.execution_complete` | `toolCallId`, `success`, `result`, `error` |
|
|
349
|
+
| `user.message` | `content`, `attachments`, `source` |
|
|
350
|
+
| `session.idle` | `aborted` |
|
|
351
|
+
| `session.error` | `errorType`, `message`, `stack` |
|
|
352
|
+
| `permission.requested` | `requestId`, `permissionRequest.kind` |
|
|
353
|
+
| `session.shutdown` | `shutdownType`, `totalPremiumRequests` |
|
|
354
|
+
|
|
355
|
+
### session.workspacePath
|
|
356
|
+
|
|
357
|
+
Path to the session workspace directory (checkpoints, plan.md, files/). `undefined` if infinite sessions disabled.
|
|
358
|
+
|
|
359
|
+
### session.rpc
|
|
360
|
+
|
|
361
|
+
Low-level typed RPC access to all session APIs (model, mode, plan, workspace, etc.).
|
|
362
|
+
|
|
363
|
+
---
|
|
364
|
+
|
|
365
|
+
## Gotchas
|
|
366
|
+
|
|
367
|
+
- **stdout is reserved for JSON-RPC.** Don't use `console.log()` — it will corrupt the protocol. Use `session.log()` to surface messages to the user.
|
|
368
|
+
- **Tool name collisions are fatal.** If two extensions register the same tool name, the second extension fails to initialize.
|
|
369
|
+
- **Don't call `session.send()` synchronously from `onUserPromptSubmitted`.** Use `setTimeout(() => session.send(...), 0)` to avoid infinite loops.
|
|
370
|
+
- **Extensions are reloaded on `/clear`.** Any in-memory state is lost between sessions.
|
|
371
|
+
- **The entry file must be `.mjs`, `.cjs` or `.js`.** TypeScript (`.ts`) is not yet supported.
|
|
372
|
+
- **The handler's return value is the tool result.** Returning `undefined` sends an empty success. Throwing sends a failure with the error message.
|