@intentic/extension-api 1.431.0 → 1.433.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 (63) hide show
  1. package/README.md +138 -4
  2. package/dist/api.d.ts +1 -0
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/backend-reach.d.ts +24 -0
  5. package/dist/backend-reach.d.ts.map +1 -0
  6. package/dist/backend-reach.js +262 -0
  7. package/dist/backend-reach.js.map +1 -0
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +1 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/runtime.d.ts +12 -2
  13. package/dist/runtime.d.ts.map +1 -1
  14. package/dist/runtime.js +111 -132
  15. package/dist/runtime.js.map +1 -1
  16. package/dist/server-reach.d.ts +72 -0
  17. package/dist/server-reach.d.ts.map +1 -0
  18. package/dist/server-reach.js +2 -0
  19. package/dist/server-reach.js.map +1 -0
  20. package/dist/server.d.ts +190 -1
  21. package/dist/server.d.ts.map +1 -1
  22. package/dist/sleep-fake.d.ts +15 -0
  23. package/dist/sleep-fake.d.ts.map +1 -0
  24. package/dist/sleep-fake.js +99 -0
  25. package/dist/sleep-fake.js.map +1 -0
  26. package/dist/sleep-reach.d.ts +7 -0
  27. package/dist/sleep-reach.d.ts.map +1 -0
  28. package/dist/sleep-reach.js +104 -0
  29. package/dist/sleep-reach.js.map +1 -0
  30. package/dist/testing.d.ts +82 -9
  31. package/dist/testing.d.ts.map +1 -1
  32. package/dist/testing.js +367 -13
  33. package/dist/testing.js.map +1 -1
  34. package/dist/turn-reach.d.ts +7 -0
  35. package/dist/turn-reach.d.ts.map +1 -0
  36. package/dist/turn-reach.js +140 -0
  37. package/dist/turn-reach.js.map +1 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.d.ts.map +1 -1
  40. package/dist/version.js +1 -1
  41. package/dist/version.js.map +1 -1
  42. package/dist/wire.d.ts +1 -1
  43. package/dist/wire.d.ts.map +1 -1
  44. package/dist/wire.js +2 -0
  45. package/dist/wire.js.map +1 -1
  46. package/package.json +4 -4
  47. package/src/api.ts +3 -0
  48. package/src/backend-reach.integration.test.ts +203 -0
  49. package/src/backend-reach.ts +365 -0
  50. package/src/caller.integration.test.ts +108 -0
  51. package/src/index.ts +1 -0
  52. package/src/runtime.ts +185 -157
  53. package/src/server-reach.ts +138 -0
  54. package/src/server.ts +374 -3
  55. package/src/sleep-fake.ts +140 -0
  56. package/src/sleep-reach.integration.test.ts +119 -0
  57. package/src/sleep-reach.ts +147 -0
  58. package/src/surface.json +15583 -0
  59. package/src/testing.ts +601 -23
  60. package/src/turn-reach.integration.test.ts +166 -0
  61. package/src/turn-reach.ts +198 -0
  62. package/src/version.ts +129 -1
  63. package/src/wire.ts +4 -0
package/src/testing.ts CHANGED
@@ -1,21 +1,79 @@
1
1
  import { mkdtemp, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
- import { type ExtensionReach, extensionRouteReach } from "@intentic/extension-manifest/permissions";
5
- import { type ExtensionEvent, extensionEventsUrl, extensionSettingsUrl } from "@intentic/sandbox-contract/extension-protocol";
4
+ import { type DeclaredPermissions, declaredReachOf, type ExtensionDeclaredReach, type ExtensionReach, extensionRouteReach } from "@intentic/extension-manifest/permissions";
5
+ import { type PublicRouteContribution, publicRouteAutomationOf, publicRouteFor } from "@intentic/extension-manifest";
6
+ import {
7
+ type ExtensionActivity,
8
+ extensionActivityUrl,
9
+ ExtensionActivitySchema,
10
+ EXTENSION_BROWSER_TOOLS,
11
+ EXTENSION_CALLER_HEADER,
12
+ EXTENSION_CALLER_TTL_MS,
13
+ extensionBrowserUrl,
14
+ ExtensionBrowserCallSchema,
15
+ type ExtensionCallerClaim,
16
+ type ExtensionCallerIdentity,
17
+ EXTENSION_EVENTS_KINDS_PARAM,
18
+ type ExtensionEvent,
19
+ extensionEventsUrl,
20
+ type ExtensionExec,
21
+ type ExtensionExecResult,
22
+ ExtensionExecSchema,
23
+ extensionExecUrl,
24
+ ExtensionJobReportSchema,
25
+ extensionJobsUrl,
26
+ ExtensionJobStartSchema,
27
+ ExtensionNavigateArgumentsSchema,
28
+ ExtensionOwnerBrowserCallSchema,
29
+ extensionOwnerBrowserUrl,
30
+ extensionSettingsUrl,
31
+ extensionWorkHoldUrl,
32
+ ExtensionWorkHoldSchema,
33
+ NO_TOOL_GRANTS,
34
+ readCallerClaim,
35
+ ExtensionIdentitySignSchema,
36
+ type ExtensionIdentitySigned,
37
+ extensionIdentitySignUrl,
38
+ extensionIdentityUrl,
39
+ } from "@intentic/sandbox-contract/extension-protocol";
6
40
  import { EXTENSION_TOKEN_HEADER } from "@intentic/sandbox-contract/headers";
41
+ import {
42
+ canonicalBytes,
43
+ EXTENSION_SIGN_PAYLOAD_MAX_BYTES,
44
+ type ExtensionSignPayload,
45
+ extensionSignDomain,
46
+ extensionSignProblem,
47
+ generateKeySet,
48
+ type S2sKeySet,
49
+ secretKeysOf,
50
+ signExtensionPayload,
51
+ signIdentity,
52
+ } from "@intentic/sandbox-contract/s2s";
53
+ import type { SandboxIdentity } from "@intentic/sandbox-contract/schemas/s2s";
7
54
  import { activateServerModule, createServerApi, deactivateWithin, healthWithin } from "./runtime.js";
55
+ import { type FakeSleep, fakeSleep } from "./sleep-fake.js";
8
56
  import type {
9
57
  ApprovedAction,
10
58
  ApprovedActionOutcome,
59
+ ApprovedPost,
60
+ AutomationFire,
61
+ ExtensionCallerWho,
11
62
  ExtensionHealth,
12
63
  ExtensionServerApi,
13
64
  ExtensionServerModule,
14
65
  ExtensionSettingValues,
66
+ PublicRouteVerification,
67
+ JobEnd,
15
68
  ServerActivation,
69
+ ToolArguments,
16
70
  ToolCard,
17
71
  ToolCallContext,
72
+ ToolCallGrants,
18
73
  ToolDefinition,
74
+ ToolResult,
75
+ WatchCheck,
76
+ WatchCheckAnswer,
19
77
  } from "./server.js";
20
78
 
21
79
  // A backend under test, on the real backend api (runtime.ts) with only the daemon stood in for: every call the extension
@@ -28,12 +86,27 @@ import type {
28
86
  const DAEMON = "http://daemon.fake";
29
87
  const TOKEN = "fake-extension-token";
30
88
 
31
- // The part of a manifest the fake reads: who the extension is and how far it reaches.
89
+ // The part of a manifest the fake reads: who the extension is, how far it reaches, and what else it declares it may
90
+ // hear, hold, run and be woken by (`events`, `work`, `exec`, `fires`), each judged as the daemon judges it.
32
91
  export interface FakeManifest {
33
92
  readonly publisher: string;
34
93
  readonly name: string;
35
- readonly permissions?: { readonly daemon?: readonly string[] };
36
- readonly contributes?: { readonly listener?: { readonly provider: string } };
94
+ readonly permissions?: ({ readonly daemon?: readonly string[] | undefined } & DeclaredPermissions) | undefined;
95
+ readonly contributes?:
96
+ | {
97
+ readonly listener?: { readonly provider: string } | undefined;
98
+ readonly watchKinds?: readonly { readonly id: string }[] | undefined;
99
+ readonly publicRoutes?: readonly Pick<PublicRouteContribution, "path" | "methods" | "automation" | "wakes">[] | undefined;
100
+ }
101
+ | undefined;
102
+ }
103
+
104
+ // Who a request into `/x` comes from, as the daemon's proxy would assert it (a person's `folders` being what their areas
105
+ // come to), and how long ago it was minted (ms): an assertion older than its two-minute window reads as no caller, and
106
+ // the daemon refuses it.
107
+ export interface FakeRouteOptions {
108
+ readonly caller?: ExtensionCallerWho & { readonly folders?: readonly string[] | undefined };
109
+ readonly mintedAgoMs?: number;
37
110
  }
38
111
 
39
112
  export interface FakeExtensionOptions {
@@ -42,6 +115,18 @@ export interface FakeExtensionOptions {
42
115
  // not there.
43
116
  readonly daemon?: (request: Request) => Response | undefined | Promise<Response | undefined>;
44
117
  readonly settings?: ExtensionSettingValues;
118
+ // Answers a command run through `api.exec` whose class the manifest declares; absent, every command exits 0 having
119
+ // printed nothing.
120
+ readonly exec?: (command: ExtensionExec) => ExtensionExecResult | Promise<ExtensionExecResult>;
121
+ // (2026-11-26) What the turn calling a tool holds, unless `callTool`'s context names its own: nothing when absent.
122
+ readonly grants?: ToolCallGrants;
123
+ // (2026-11-26) Answers a call through `api.browser.call` the manifest declares and the call's grants admit, as the
124
+ // turn's browser router would; absent, an empty result. A tool outside the page tools the daemon admits, and a
125
+ // navigation off the account's sites, are refused before it is asked, as the daemon refuses them.
126
+ readonly browser?: (call: FakeBrowserCall) => ToolResult | Promise<ToolResult>;
127
+ // (2026-11-26) Answers a call through `api.ownerBrowser.call` the manifest declares and the grants admit; absent, an
128
+ // empty result.
129
+ readonly ownerBrowser?: (call: FakeOwnerBrowserCall) => ToolResult | Promise<ToolResult>;
45
130
  // Each a fresh temp directory when absent, removed again by `dispose`.
46
131
  readonly workspaceRoot?: string;
47
132
  readonly extensionDir?: string;
@@ -49,33 +134,100 @@ export interface FakeExtensionOptions {
49
134
  readonly cacheDir?: string;
50
135
  }
51
136
 
52
- // What a tool is called with, as ToolDefinition declares it.
53
- type ToolArguments = Parameters<ToolDefinition["call"]>[0];
137
+ // (2026-11-26) A call that reached the turn's browser (`api.browser.call`), as the daemon was asked and admitted it.
138
+ export interface FakeBrowserCall {
139
+ readonly account: string;
140
+ readonly tool: string;
141
+ readonly args: ToolArguments;
142
+ readonly conversationId?: string | undefined;
143
+ }
144
+
145
+ // (2026-11-26) A call that reached the owner's browser (`api.ownerBrowser.call`).
146
+ export interface FakeOwnerBrowserCall {
147
+ readonly browser: string;
148
+ readonly tool: string;
149
+ readonly args: ToolArguments;
150
+ readonly conversationId?: string | undefined;
151
+ }
152
+
153
+ // (2026-11-26) A job a tool started (`api.jobs.start`), as the daemon filed it: what it showed while it ran, its end once
154
+ // its work told it, and whether it was stopped.
155
+ export interface FakeJob {
156
+ readonly id: string;
157
+ readonly conversationId: string;
158
+ readonly command: string;
159
+ readonly description: string;
160
+ readonly lane?: { readonly name: string; readonly key?: string | undefined; readonly most?: number | undefined } | undefined;
161
+ readonly lines: readonly string[];
162
+ readonly end?: JobEnd | undefined;
163
+ readonly stopped: boolean;
164
+ }
54
165
 
55
- // One request the extension sent the daemon, and whether its reach admitted it.
166
+ // One request the extension sent the daemon, whether its reach admitted it, and the caller it carried an assertion of
167
+ // (`api.daemon.asCaller`), as the daemon would believe it.
56
168
  export interface FakeDaemonCall {
57
169
  readonly line: string;
58
170
  readonly admitted: boolean;
171
+ readonly caller?: ExtensionCallerWho | undefined;
59
172
  }
60
173
 
61
174
  export interface FakeExtension {
62
175
  readonly api: ExtensionServerApi;
63
176
  readonly calls: readonly FakeDaemonCall[];
64
177
  readonly logs: readonly string[];
178
+ // The labels of the work it holds now (`api.work.hold`), as the daemon counts them.
179
+ readonly holds: readonly string[];
180
+ // Every command it ran through `api.exec`, as the daemon was asked.
181
+ readonly execs: readonly ExtensionExec[];
182
+ // (2026-11-26) Every row it wrote in the activity feed (`api.activity.append`), as the daemon took it.
183
+ readonly activities: readonly ExtensionActivity[];
184
+ // (2026-11-26) Every call that reached the turn's browser and the owner's, and every job its tools started.
185
+ readonly browserCalls: readonly FakeBrowserCall[];
186
+ readonly ownerBrowserCalls: readonly FakeOwnerBrowserCall[];
187
+ readonly jobs: readonly FakeJob[];
188
+ // (2026-11-27) Hosted sleep (`api.sleep`): `now()` tells every before-sleep watch and resolves with how many answered
189
+ // ready, `boot` is what `api.sleep.boot()` answers, and `wakeUrls` every URL handed out (sleep-fake.ts).
190
+ readonly sleep: Omit<FakeSleep, "door">;
191
+ // (2026-11-28) This sandbox's identity (`api.identity`): a real key set made on the first ask, the document it signed,
192
+ // and every record signed through it (fakeIdentity below). Verify what the backend was handed with the contract's
193
+ // `verifyExtensionPayload` against `identity.document().keys`.
194
+ readonly identity: FakeIdentity;
195
+ // (2026-11-26) The job's end once its work told it, as `wait` hands it to the agent.
196
+ jobEnd(id: string): Promise<JobEnd>;
197
+ // (2026-11-26) The agent or a person stopping the job: its work's signal aborts.
198
+ stopJob(id: string): void;
65
199
  // Activates a server module as the backend host does, keeping what it hands back for `deactivate` and `health`.
66
200
  activate(module: Partial<ExtensionServerModule> & { default?: ExtensionServerModule }): Promise<void>;
67
- // A request into the extension's own /x namespace, `path` relative to it, as the daemon's proxy delivers it.
68
- route(path: string, init?: RequestInit): Promise<Response>;
201
+ // A request into the extension's own /x namespace, `path` relative to it, as the daemon's proxy delivers it: with an
202
+ // assertion of `options.caller` (a person signed in when absent, the owner), which `api.caller` reads.
203
+ route(path: string, init?: RequestInit, options?: FakeRouteOptions): Promise<Response>;
204
+ // A call through one of its public routes (`contributes.publicRoutes`), `path` relative to /door/<id>, as the daemon's
205
+ // door delivers it once its protections passed: rejects for a method and path no declared route answers, which the
206
+ // daemon answers 404 without the backend hearing of it. `verified` fills in or overrides what the door checked.
207
+ publicRoute(path: string, init?: RequestInit, verified?: Partial<PublicRouteVerification>): Promise<Response>;
69
208
  // The tools it serves a card (undefined: the extension-level server), and one call to one of them.
70
209
  tools(card?: ToolCard): Promise<readonly ToolDefinition[]>;
71
210
  // Answers whatever the tool's own `call` answers, as ToolDefinition declares it; the host turns that into what the
72
- // model reads.
211
+ // model reads. (2026-11-26) The call is handed `grants` (the context's, else the options', else none) and a ticket
212
+ // good while it runs, as the daemon's door hands them.
73
213
  callTool(name: string, args?: ToolArguments, card?: ToolCard, context?: Partial<ToolCallContext>): ReturnType<ToolDefinition["call"]>;
74
214
  // An approved action handed over as the daemon's approvals executor hands it, through the host's door.
75
215
  perform(action: ApprovedAction, signal?: AbortSignal): Promise<ApprovedActionOutcome>;
216
+ // (2026-11-26) An approved post handed over as the daemon's approvals executor hands it, through the host's door:
217
+ // rejects when the backend publishes no posts (`api.approvals.publish`). The rest of the post is filled in.
218
+ publish(post: Pick<ApprovedPost, "platform" | "content" | "target"> & Partial<ApprovedPost>, signal?: AbortSignal): Promise<ApprovedActionOutcome>;
219
+ // An automation's fire handed to the handler it names, as the daemon's automations engine hands it through the host's
220
+ // door; the rest of the fire is filled in. Rejects when no handler of that name is registered, which the daemon reads
221
+ // as "not yet" and tries again later.
222
+ fire(handler: string, fire?: Partial<Omit<AutomationFire, "handler">>): Promise<void>;
223
+ // A watch's check handed to the handler served for its kind, as the daemon's automations engine hands it through the
224
+ // host's door; the rest of the check is filled in. Rejects when nothing serves the kind, which the daemon says on the
225
+ // automation's run as a check that could not run.
226
+ check(kind: string, check?: Partial<Omit<WatchCheck, "kind">>, signal?: AbortSignal): Promise<WatchCheckAnswer>;
76
227
  // The owner changing its settings: stored, and told to the extension over its event stream as the daemon would.
77
228
  setSettings(values: ExtensionSettingValues): void;
78
- // A frame on its event stream, as the daemon sends it (`files`, `refs`, `repos`, `settings`).
229
+ // A frame on its event stream, as the daemon sends it (`files`, `refs`, `repos`, `settings`, and `run`, `activity` and
230
+ // (2026-11-26) `ci`, which reach a stream only when the manifest declares them).
79
231
  emit(event: ExtensionEvent): void;
80
232
  // Its own account of itself, as the host reads it under the host's deadline and vocabulary.
81
233
  health(): Promise<ExtensionHealth>;
@@ -91,6 +243,289 @@ const json = <T>(body: T, status = 200): Response => Response.json(body, { statu
91
243
  const changedKeys = (before: ExtensionSettingValues, after: ExtensionSettingValues): string[] =>
92
244
  [...new Set([...Object.keys(before), ...Object.keys(after)])].filter((key) => before[key] !== after[key]).toSorted();
93
245
 
246
+ // The owner, signed in: who a fake request into /x comes from unless the test says otherwise.
247
+ const OWNER: ExtensionCallerIdentity = { kind: "person", email: "owner@example.com", tier: "owner" };
248
+
249
+ // A caller's assertion as the daemon's proxy mints it, signed with the fake's own word in place of the daemon's key: the
250
+ // fake daemon believes only those it minted.
251
+ const fakeAssertion = (claim: ExtensionCallerClaim): string => `${Buffer.from(JSON.stringify(claim), "utf8").toString("base64url")}.fake-daemon-signature`;
252
+
253
+ // A caller as the assertion's claim spells it: a person's lists copied, every other kind as it is.
254
+ const claimOf = (caller: NonNullable<FakeRouteOptions["caller"]>): ExtensionCallerIdentity => {
255
+ if (caller.kind !== "person") {
256
+ return { ...caller };
257
+ }
258
+ const { areas, folders, manages, ...person } = caller;
259
+ const claim: ExtensionCallerIdentity = { ...person };
260
+ if (areas !== undefined) {
261
+ claim.areas = [...areas];
262
+ }
263
+ if (folders !== undefined) {
264
+ claim.folders = [...folders];
265
+ }
266
+ if (manages !== undefined) {
267
+ claim.manages = [...manages];
268
+ }
269
+ return claim;
270
+ };
271
+
272
+ // Who an assertion the fake daemon believed says is calling, without the folders only the backend reads.
273
+ const callerWho = (claim: ExtensionCallerClaim | undefined): ExtensionCallerWho | undefined => {
274
+ if (claim === undefined) {
275
+ return undefined;
276
+ }
277
+ const { folders: _folders, ...who } = claim.caller.kind === "person" ? claim.caller : { ...claim.caller, folders: undefined };
278
+ return who;
279
+ };
280
+
281
+ // ---- the turn a tool's call stands on (2026-11-26) ------------------------------------------------------------------
282
+
283
+ // What a ticket stands for: the grants of the call it was minted for, its conversation, and the job it is, if one.
284
+ interface FakeStanding {
285
+ readonly grants: ToolCallGrants;
286
+ readonly conversationId?: string | undefined;
287
+ readonly job?: string | undefined;
288
+ }
289
+
290
+ // A host as an account's site is matched: lowercased, `www.` dropped; a site's subdomain is on it.
291
+ const onSites = (url: string, sites: readonly string[]): boolean => {
292
+ const host = URL.parse(url)?.hostname.toLowerCase().replace(/^www\./u, "");
293
+ return host !== undefined && host !== "" && sites.some((site) => host === site || host.endsWith(`.${site}`));
294
+ };
295
+
296
+ const EMPTY_RESULT: ToolResult = { content: [] };
297
+ const BROWSER_TOOLS: ReadonlySet<string> = new Set(EXTENSION_BROWSER_TOOLS);
298
+
299
+ // A job as the fake daemon runs it: its record, its stream's controller, and who waits on its end.
300
+ interface RunningFakeJob {
301
+ record: FakeJob;
302
+ readonly stream: ReadableStreamDefaultController<Uint8Array>;
303
+ readonly ended: PromiseWithResolvers<JobEnd>;
304
+ }
305
+
306
+ // The url a navigation names, when it names one.
307
+ const navigationUrl = (args: ToolArguments | undefined): string | undefined => ExtensionNavigateArgumentsSchema.safeParse(args).data?.url;
308
+
309
+ // The daemon's turn doors, judged as it judges them (extensions/turn/tool-turn-doors.ts): the declared power, a live
310
+ // ticket, the grants it stands for, and for an account's browser the page tools and the account's sites; a job filed in
311
+ // the call's conversation, begun at once (no lane waits here), its lines and end kept.
312
+ const fakeTurn = (options: FakeExtensionOptions, declared: readonly string[]) => {
313
+ const tickets = new Map<string, FakeStanding>();
314
+ const browserCalls: FakeBrowserCall[] = [];
315
+ const ownerBrowserCalls: FakeOwnerBrowserCall[] = [];
316
+ const jobs = new Map<string, RunningFakeJob>();
317
+ const encoder = new TextEncoder();
318
+ let minted = 0;
319
+ const mint = (standing: FakeStanding) => {
320
+ minted += 1;
321
+ const ticket = `fake-ticket-${minted}`;
322
+ tickets.set(ticket, standing);
323
+ return { ticket, release: () => void tickets.delete(ticket) };
324
+ };
325
+ // The standing behind a request, or the refusal the daemon answers with.
326
+ const standingOf = (power: string, ticket: string): FakeStanding | Response => {
327
+ if (!declared.includes(power)) {
328
+ return json({ error: `"${power}" is not declared in permissions.turn` }, 403);
329
+ }
330
+ return tickets.get(ticket) ?? json({ error: "no call of this extension's tools, nor a job one started, is running under that ticket" }, 403);
331
+ };
332
+ const browserCall = async (request: Request): Promise<Response> => {
333
+ const asked = ExtensionBrowserCallSchema.parse(await request.json());
334
+ const standing = standingOf("browser", asked.turn);
335
+ if (standing instanceof Response) {
336
+ return standing;
337
+ }
338
+ const account = standing.grants.accounts.find((held) => held.id === asked.account);
339
+ if (account === undefined) {
340
+ return json({ error: `the turn that made this call holds no account "${asked.account}"` }, 403);
341
+ }
342
+ if (!BROWSER_TOOLS.has(asked.tool)) {
343
+ return json({ error: `${asked.tool} is not a browser tool an extension may call` }, 403);
344
+ }
345
+ const url = navigationUrl(asked.arguments);
346
+ if (asked.tool === "browser_navigate" && (url === undefined || !onSites(url, account.sites))) {
347
+ return json({ error: `account "${account.id}" signs in on ${account.sites.join(" or ")}; that url is not on them` }, 403);
348
+ }
349
+ const call: FakeBrowserCall = { account: account.id, tool: asked.tool, args: asked.arguments ?? {}, conversationId: standing.conversationId };
350
+ browserCalls.push(call);
351
+ return json({ result: (await options.browser?.(call)) ?? EMPTY_RESULT });
352
+ };
353
+ const ownerBrowserCall = async (request: Request): Promise<Response> => {
354
+ const asked = ExtensionOwnerBrowserCallSchema.parse(await request.json());
355
+ const standing = standingOf("owner-browser", asked.turn);
356
+ if (standing instanceof Response) {
357
+ return standing;
358
+ }
359
+ if (!standing.grants.browsers.includes(asked.browser)) {
360
+ return json({ error: `the turn that made this call holds no browser of the owner's called "${asked.browser}"` }, 403);
361
+ }
362
+ const call: FakeOwnerBrowserCall = { browser: asked.browser, tool: asked.tool, args: asked.arguments ?? {}, conversationId: standing.conversationId };
363
+ ownerBrowserCalls.push(call);
364
+ return json({ result: (await options.ownerBrowser?.(call)) ?? EMPTY_RESULT });
365
+ };
366
+ const frame = (job: RunningFakeJob, body: Readonly<Record<string, string | number>>): void => {
367
+ try {
368
+ job.stream.enqueue(encoder.encode(`${JSON.stringify(body)}\n`));
369
+ } catch {
370
+ // allow(silent-catch): a stream the extension already let go of takes no more frames
371
+ }
372
+ };
373
+ const close = (job: RunningFakeJob): void => {
374
+ try {
375
+ job.stream.close();
376
+ } catch {
377
+ // allow(silent-catch): already closed by the extension's side, which is the state being reached
378
+ }
379
+ };
380
+ const startJob = async (request: Request): Promise<Response> => {
381
+ const asked = ExtensionJobStartSchema.parse(await request.json());
382
+ const standing = standingOf("jobs", asked.turn);
383
+ if (standing instanceof Response) {
384
+ return standing;
385
+ }
386
+ if (standing.conversationId === undefined) {
387
+ return json({ error: "the turn that made this call has no conversation to file a job in" }, 409);
388
+ }
389
+ const id = `job-${jobs.size + 1}`;
390
+ const ticket = mint({ ...standing, job: id });
391
+ const record: FakeJob = { id, conversationId: standing.conversationId, command: asked.command, description: asked.description, lane: asked.lane, lines: [], stopped: false };
392
+ const body = new ReadableStream<Uint8Array>({
393
+ start: (stream) => {
394
+ const job: RunningFakeJob = { record, stream, ended: Promise.withResolvers<JobEnd>() };
395
+ jobs.set(id, job);
396
+ void job.ended.promise.then(() => ticket.release());
397
+ frame(job, { kind: "filed", id, job: ticket.ticket, ahead: 0 });
398
+ frame(job, { kind: "begin" });
399
+ },
400
+ });
401
+ return new Response(body, { headers: { "content-type": "application/x-ndjson" } });
402
+ };
403
+ const reportJob = async (request: Request, id: string): Promise<Response> => {
404
+ const asked = ExtensionJobReportSchema.parse(await request.json());
405
+ const standing = standingOf("jobs", asked.job);
406
+ const job = jobs.get(id);
407
+ if (standing instanceof Response || standing.job !== id || job === undefined) {
408
+ return json({ error: `no job "${id}" of this extension is running under that ticket` }, 404);
409
+ }
410
+ if (asked.say !== undefined) {
411
+ job.record = { ...job.record, lines: [...job.record.lines, asked.say] };
412
+ }
413
+ if (asked.end !== undefined && job.record.end === undefined) {
414
+ job.record = { ...job.record, end: asked.end };
415
+ job.ended.resolve(asked.end);
416
+ close(job);
417
+ }
418
+ return json({ ok: true });
419
+ };
420
+ const jobsPath = extensionJobsUrl();
421
+ return {
422
+ mint,
423
+ browserCalls,
424
+ ownerBrowserCalls,
425
+ jobs: (): FakeJob[] => [...jobs.values()].map((job) => job.record),
426
+ door: async (request: Request, url: URL): Promise<Response | undefined> => {
427
+ if (url.pathname === extensionBrowserUrl()) {
428
+ return await browserCall(request);
429
+ }
430
+ if (url.pathname === extensionOwnerBrowserUrl()) {
431
+ return await ownerBrowserCall(request);
432
+ }
433
+ if (url.pathname === jobsPath) {
434
+ return await startJob(request);
435
+ }
436
+ return url.pathname.startsWith(`${jobsPath}/`) ? await reportJob(request, decodeURIComponent(url.pathname.slice(jobsPath.length + 1))) : undefined;
437
+ },
438
+ jobEnd: async (id: string): Promise<JobEnd> => {
439
+ const job = jobs.get(id);
440
+ if (job === undefined) {
441
+ throw new Error(`no job "${id}" was started`);
442
+ }
443
+ return await job.ended.promise;
444
+ },
445
+ stopJob: (id: string): void => {
446
+ const job = jobs.get(id);
447
+ if (job === undefined || job.record.end !== undefined) {
448
+ return;
449
+ }
450
+ const end: JobEnd = { ok: false, output: "stopped" };
451
+ job.record = { ...job.record, stopped: true, end };
452
+ frame(job, { kind: "stopped" });
453
+ job.ended.resolve(end);
454
+ close(job);
455
+ },
456
+ };
457
+ };
458
+
459
+ // (2026-11-28) The daemon's side of `api.identity` for `fakeExtensionApi` (below): a real hybrid key set, made on
460
+ // the first ask (an ML-DSA key costs milliseconds no other suite should pay), a document it signs, and signatures made
461
+ // with it under the extension's own domain, refused as the daemon refuses them. So a test verifies what its backend was
462
+ // handed with the contract's own `verifyExtensionPayload` against `document.keys`, as a far sandbox would.
463
+
464
+ // Who the fake sandbox is in its document.
465
+ export const FAKE_SANDBOX_IDENTITY = { sandbox: "fake", name: "Fake sandbox", host: "sandbox-fake.sbx.test" } as const;
466
+
467
+ // A record the extension had signed, as the daemon took it.
468
+ export interface FakeSigned {
469
+ readonly purpose: string;
470
+ readonly payload: ExtensionSignPayload;
471
+ readonly domain: string;
472
+ }
473
+
474
+ export interface FakeIdentity {
475
+ // The fake sandbox's signed document: the one `api.identity.document()` answers and whose keys verify every signature.
476
+ document(): SandboxIdentity;
477
+ // Its key set, secret half included: a test signing as a far sandbox, or checking by hand.
478
+ keySet(): S2sKeySet;
479
+ // Every record signed, in order.
480
+ readonly signed: readonly FakeSigned[];
481
+ }
482
+
483
+ const fakeIdentity = (id: string, declared: ExtensionDeclaredReach) => {
484
+ let made: { readonly keySet: S2sKeySet; readonly document: SandboxIdentity } | undefined;
485
+ const ensure = (): { readonly keySet: S2sKeySet; readonly document: SandboxIdentity } => {
486
+ if (made === undefined) {
487
+ const keySet = generateKeySet();
488
+ made = { keySet, document: signIdentity({ ...FAKE_SANDBOX_IDENTITY, domains: [], issuedAt: Date.now() }, keySet) };
489
+ }
490
+ return made;
491
+ };
492
+ const signed: FakeSigned[] = [];
493
+
494
+ // The two doors as the daemon answers them (own-identity.ts), undefined for a request that is for neither.
495
+ const door = async (request: Request, url: URL): Promise<Response | undefined> => {
496
+ if (request.method === "GET" && url.pathname === extensionIdentityUrl()) {
497
+ return json(ensure().document);
498
+ }
499
+ if (request.method !== "POST" || url.pathname !== extensionIdentitySignUrl()) {
500
+ return undefined;
501
+ }
502
+ if (!declared.identity.includes("sign")) {
503
+ return json({ error: `extension "${id}" did not declare permissions.identity ["sign"], so it signs nothing as this sandbox` }, 403);
504
+ }
505
+ // allow(silent-catch): a body that is not JSON is no record to sign, which the schema refuses just below
506
+ const asked = ExtensionIdentitySignSchema.safeParse(await request.json().catch(() => undefined));
507
+ if (!asked.success) {
508
+ return json({ error: "not a record to sign: the body is { purpose, payload }, the payload any JSON value" }, 400);
509
+ }
510
+ const { purpose, payload } = asked.data;
511
+ const problem = extensionSignProblem(id, purpose);
512
+ if (problem !== undefined) {
513
+ return json({ error: problem }, 400);
514
+ }
515
+ if (canonicalBytes(payload).length > EXTENSION_SIGN_PAYLOAD_MAX_BYTES) {
516
+ return json({ error: `a record to sign is at most ${EXTENSION_SIGN_PAYLOAD_MAX_BYTES} bytes of canonical JSON` }, 413);
517
+ }
518
+ const { keySet, document } = ensure();
519
+ const domain = extensionSignDomain(id, purpose);
520
+ signed.push({ purpose, payload, domain });
521
+ const sig = signExtensionPayload(id, purpose, payload, secretKeysOf(keySet.secret));
522
+ return json({ domain, sig, fingerprint: document.fingerprint, document } satisfies ExtensionIdentitySigned);
523
+ };
524
+
525
+ const identity: FakeIdentity = { document: () => ensure().document, keySet: () => ensure().keySet, signed };
526
+ return { door, identity };
527
+ };
528
+
94
529
  export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<FakeExtension> => {
95
530
  const made: string[] = [];
96
531
  const dirOf = async (given: string | undefined, label: string): Promise<string> => {
@@ -104,8 +539,15 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
104
539
  const workspaceRoot = await dirOf(options.workspaceRoot, "workspace");
105
540
  const id = `${options.manifest.publisher}.${options.manifest.name}`;
106
541
  const reach: ExtensionReach = { permissions: options.manifest.permissions?.daemon ?? [], listener: options.manifest.contributes?.listener?.provider };
542
+ const declared = declaredReachOf(options.manifest.permissions);
107
543
  const calls: FakeDaemonCall[] = [];
108
544
  const logs: string[] = [];
545
+ const holds = new Map<symbol, string>();
546
+ const execs: ExtensionExec[] = [];
547
+ const activities: ExtensionActivity[] = [];
548
+ const turn = fakeTurn(options, declared.turn);
549
+ const sleeping = fakeSleep(id, options.manifest.contributes?.publicRoutes ?? []);
550
+ const identity = fakeIdentity(id, declared);
109
551
  let settings: ExtensionSettingValues = { ...options.settings };
110
552
  // Every event stream the extension holds open, each written to by `emit`. A frame sent while none is open waits for
111
553
  // the next one: the runtime opens its stream a moment after the first listener registers, and a test that listens
@@ -131,6 +573,58 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
131
573
  }
132
574
  };
133
575
 
576
+ // A hold stands while its answer is open, as the daemon's does: a heartbeat at once, then nothing until let go.
577
+ const holdStream = (label: string, signal: AbortSignal | null): Response => {
578
+ const key = Symbol(label);
579
+ holds.set(key, label);
580
+ const release = (): void => void holds.delete(key);
581
+ signal?.addEventListener("abort", release);
582
+ const body = new ReadableStream<Uint8Array>({
583
+ start: (controller) => controller.enqueue(encoder.encode(`${JSON.stringify({ kind: "heartbeat" })}\n`)),
584
+ cancel: release,
585
+ });
586
+ return new Response(body, { headers: { "content-type": "application/x-ndjson" } });
587
+ };
588
+
589
+ // The extension's own doors, judged by what its manifest declares as the daemon judges them (own.routes.ts,
590
+ // own-doors.ts); undefined for a request that is for none of them.
591
+ const ownDoor = async (request: Request, url: URL, signal: AbortSignal | null): Promise<Response | undefined> => {
592
+ if (request.method === "GET" && url.pathname === extensionSettingsUrl()) {
593
+ return json({ settings });
594
+ }
595
+ if (request.method === "GET" && url.pathname === extensionEventsUrl()) {
596
+ const asked = (url.searchParams.get(EXTENSION_EVENTS_KINDS_PARAM) ?? "").split(",").filter((kind) => kind !== "");
597
+ const refused = asked.find((kind) => !declared.events.some((each) => each === kind));
598
+ return refused === undefined ? eventStream(signal) : json({ error: `the event kind "${refused}" is not declared in permissions.events` }, 403);
599
+ }
600
+ if (request.method === "POST" && url.pathname === extensionWorkHoldUrl()) {
601
+ const hold = ExtensionWorkHoldSchema.safeParse(await request.json());
602
+ if (!declared.work || !hold.success) {
603
+ return json({ error: declared.work ? "a hold carries { label }" : "permissions.work is not declared" }, declared.work ? 400 : 403);
604
+ }
605
+ return holdStream(hold.data.label, signal);
606
+ }
607
+ if (request.method === "POST" && url.pathname === extensionExecUrl()) {
608
+ const command = ExtensionExecSchema.parse(await request.json());
609
+ if (!declared.exec.includes(command.class)) {
610
+ return json({ error: `the workload class "${command.class}" is not declared in permissions.exec` }, 403);
611
+ }
612
+ execs.push(command);
613
+ return json((await options.exec?.(command)) ?? { waitedMs: 0, exitCode: 0, stdout: "", stderr: "", truncated: false });
614
+ }
615
+ if (request.method === "POST" && url.pathname === extensionActivityUrl()) {
616
+ const row = ExtensionActivitySchema.safeParse(await request.json());
617
+ if (!row.success) {
618
+ return json({ error: `not an activity row: ${row.error.issues[0]?.message ?? "the body does not parse"}` }, 400);
619
+ }
620
+ activities.push(row.data);
621
+ return json({ ok: true });
622
+ }
623
+ return (
624
+ (await sleeping.door(request, url, signal)) ?? (await identity.door(request, url)) ?? (request.method === "POST" ? await turn.door(request, url) : undefined)
625
+ );
626
+ };
627
+
134
628
  const eventStream = (signal: AbortSignal | null): Response => {
135
629
  let held: ReadableStreamDefaultController<Uint8Array> | undefined;
136
630
  const body = new ReadableStream<Uint8Array>({
@@ -157,6 +651,17 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
157
651
  };
158
652
 
159
653
  // The daemon's side of the wire: the token checked, the reach judged, then the extension's own routes or the test's.
654
+ // The assertions minted for this extension's requests, which alone the fake daemon believes, as the daemon believes
655
+ // only its own key's.
656
+ const minted = new Set<string>();
657
+ const believed = (assertion: string | null): ExtensionCallerClaim | "refused" | undefined => {
658
+ if (assertion === null || assertion === "") {
659
+ return undefined;
660
+ }
661
+ const claim = readCallerClaim(assertion);
662
+ return claim === undefined || !minted.has(assertion) || claim.extension !== id || Date.now() >= claim.expiresAt ? "refused" : claim;
663
+ };
664
+
160
665
  const daemon = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
161
666
  const request = new Request(input, init);
162
667
  const url = new URL(request.url);
@@ -166,17 +671,16 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
166
671
  return json({ error: "unauthorized" }, 401);
167
672
  }
168
673
  const admitted = extensionRouteReach(reach, request.method, url.pathname);
169
- calls.push({ line, admitted });
674
+ const claim = believed(request.headers.get(EXTENSION_CALLER_HEADER));
675
+ if (claim === "refused") {
676
+ calls.push({ line, admitted: false });
677
+ return json({ error: "the caller assertion was not minted for this extension by this daemon, or is past its window" }, 401);
678
+ }
679
+ calls.push({ line, admitted, caller: callerWho(claim) });
170
680
  if (!admitted) {
171
681
  return json({ error: "extension token not valid for this route" }, 403);
172
682
  }
173
- if (request.method === "GET" && url.pathname === extensionSettingsUrl()) {
174
- return json({ settings });
175
- }
176
- if (request.method === "GET" && url.pathname === extensionEventsUrl()) {
177
- return eventStream(init?.signal ?? null);
178
- }
179
- return (await options.daemon?.(request)) ?? json({ error: "not found" }, 404);
683
+ return (await ownDoor(request, url, init?.signal ?? null)) ?? (await options.daemon?.(request)) ?? json({ error: "not found" }, 404);
180
684
  };
181
685
 
182
686
  const slots = createServerApi({
@@ -190,6 +694,8 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
190
694
  cacheDir: await dirOf(options.cacheDir, "cache"),
191
695
  log: (message) => logs.push(message),
192
696
  fetch: daemon,
697
+ declared,
698
+ watchKinds: (options.manifest.contributes?.watchKinds ?? []).map((kind) => kind.id),
193
699
  });
194
700
  let activation: ServerActivation = {};
195
701
 
@@ -197,15 +703,57 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
197
703
  api: slots.api,
198
704
  calls,
199
705
  logs,
706
+ get holds() {
707
+ return [...holds.values()];
708
+ },
709
+ execs,
710
+ activities,
711
+ browserCalls: turn.browserCalls,
712
+ ownerBrowserCalls: turn.ownerBrowserCalls,
713
+ get jobs() {
714
+ return turn.jobs();
715
+ },
716
+ sleep: sleeping,
717
+ identity: identity.identity,
718
+ jobEnd: turn.jobEnd,
719
+ stopJob: turn.stopJob,
200
720
  activate: async (module) => {
201
721
  activation = await activateServerModule(module, slots.api, { extensionId: id });
202
722
  },
203
- route: async (path, init) => {
723
+ route: async (path, init, routeOptions = {}) => {
204
724
  const handler = slots.handler();
205
725
  if (handler === undefined) {
206
726
  return json({ error: `the "${id}" backend serves no routes` }, 404);
207
727
  }
208
- return (await handler(new Request(new URL(path, "http://extension.internal"), init))) ?? json({ error: "not found" }, 404);
728
+ const issuedAt = Date.now() - (routeOptions.mintedAgoMs ?? 0);
729
+ const assertion = fakeAssertion({
730
+ v: 1,
731
+ sandbox: "fake",
732
+ extension: id,
733
+ issuedAt,
734
+ expiresAt: issuedAt + EXTENSION_CALLER_TTL_MS,
735
+ nonce: `${minted.size}`,
736
+ caller: claimOf(routeOptions.caller ?? OWNER),
737
+ });
738
+ minted.add(assertion);
739
+ const headers = new Headers(init?.headers);
740
+ headers.set(EXTENSION_CALLER_HEADER, assertion);
741
+ return (await handler(new Request(new URL(path, "http://extension.internal"), { ...init, headers }))) ?? json({ error: "not found" }, 404);
742
+ },
743
+ publicRoute: async (path, init, verified = {}) => {
744
+ const handler = slots.publicHandler();
745
+ if (handler === undefined) {
746
+ throw new Error(`"${id}" serves no public routes`);
747
+ }
748
+ const url = new URL(path, "http://extension.internal");
749
+ const segments = url.pathname.split("/").filter((segment) => segment !== "");
750
+ const method = init?.method ?? "GET";
751
+ const landed = publicRouteFor(options.manifest.contributes?.publicRoutes ?? [], method, segments);
752
+ if (landed === undefined) {
753
+ throw new Error(`"${id}" declares no public route answering ${method} ${url.pathname}: the daemon answers 404 before the backend hears of it`);
754
+ }
755
+ const verification: PublicRouteVerification = { route: landed.path, at: Date.now(), automationId: publicRouteAutomationOf(landed, segments), ...verified };
756
+ return (await handler(new Request(url, init), verification)) ?? json({ error: "not found" }, 404);
209
757
  },
210
758
  tools: async (card) => (await slots.tools()?.(card)) ?? [],
211
759
  callTool: async (name, args = {}, card, context = {}) => {
@@ -213,7 +761,13 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
213
761
  if (tool === undefined) {
214
762
  throw new Error(`"${id}" serves no tool named ${name}${card === undefined ? "" : ` for card ${card.id}`}`);
215
763
  }
216
- return tool.call(args, { signal: context.signal ?? new AbortController().signal, conversationId: context.conversationId });
764
+ const grants = context.grants ?? options.grants ?? NO_TOOL_GRANTS;
765
+ const standing = turn.mint({ grants, conversationId: context.conversationId });
766
+ try {
767
+ return await tool.call(args, { signal: context.signal ?? new AbortController().signal, conversationId: context.conversationId, grants, ticket: standing.ticket });
768
+ } finally {
769
+ standing.release();
770
+ }
217
771
  },
218
772
  perform: async (action, signal = new AbortController().signal) => {
219
773
  const performer = slots.performer();
@@ -222,6 +776,30 @@ export const fakeExtensionApi = async (options: FakeExtensionOptions): Promise<F
222
776
  }
223
777
  return performer(action, { signal });
224
778
  },
779
+ publish: async (post, signal = new AbortController().signal) => {
780
+ const publisher = slots.publisher();
781
+ if (publisher === undefined) {
782
+ throw new Error(`"${id}" publishes no approved posts`);
783
+ }
784
+ return publisher({ id: `post-${Date.now()}`, approvedAt: Date.now(), actionRules: {}, ...post }, { signal });
785
+ },
786
+ fire: async (handler, fire = {}) => {
787
+ const listener = slots.fireHandler(handler);
788
+ if (listener === undefined) {
789
+ throw new Error(`"${id}" has registered no "${handler}" fire handler`);
790
+ }
791
+ await listener(
792
+ { id: fire.id ?? `fire-${Date.now()}`, automationId: fire.automationId ?? "test-automation", firedAt: fire.firedAt ?? Date.now(), coalesced: fire.coalesced ?? 0, prompt: fire.prompt ?? "", payload: fire.payload, observed: fire.observed, handler },
793
+ { signal: new AbortController().signal },
794
+ );
795
+ },
796
+ check: async (kind, check = {}, signal = new AbortController().signal) => {
797
+ const handler = slots.checkHandler(kind);
798
+ if (handler === undefined) {
799
+ throw new Error(`"${id}" serves no "${kind}" watch kind`);
800
+ }
801
+ return handler({ kind, params: check.params ?? {}, last: check.last, reach: check.reach ?? {}, automationId: check.automationId }, { signal });
802
+ },
225
803
  setSettings: (values) => {
226
804
  const keys = changedKeys(settings, values);
227
805
  settings = { ...values };