@useavalon/caelence-agent 0.3.0 → 0.4.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.
@@ -340,3 +340,88 @@ describe("runTurn", () => {
340
340
  }
341
341
  });
342
342
  });
343
+
344
+ describe("tool confirm", () => {
345
+ function confirmTool(reason: (input: Record<string, unknown>) => string | undefined) {
346
+ const ran: Array<Record<string, unknown>> = [];
347
+ return {
348
+ ran,
349
+ tool: {
350
+ name: "web_click",
351
+ description: "click",
352
+ inputSchema: { type: "object", properties: {} },
353
+ annotations: {
354
+ readOnlyHint: false,
355
+ destructiveHint: false,
356
+ idempotentHint: false,
357
+ openWorldHint: false,
358
+ },
359
+ confirm: reason,
360
+ async handler(input: Record<string, unknown>) {
361
+ ran.push(input);
362
+ return { content: [{ type: "text" as const, text: "clicked" }] };
363
+ },
364
+ },
365
+ };
366
+ }
367
+
368
+ async function run(
369
+ tool: ReturnType<typeof confirmTool>["tool"],
370
+ ask: (req: { reason?: string }) => Promise<boolean>,
371
+ ) {
372
+ const constructAgent: ConstructAgent = (input) => ({
373
+ async run() {
374
+ await input.tools[0]?.invoke({ element: "Post" });
375
+ await input.tools[0]?.invoke({ element: "Cancel" });
376
+ },
377
+ });
378
+ const events: AgentEvent[] = [];
379
+ const deps: RunTurnDeps = {
380
+ cwd: "/tmp",
381
+ name: "t",
382
+ systemPrompt: "s",
383
+ tools: [tool],
384
+ approval: createExecApprovalGate({ policy: "prompt", emit: (e) => events.push(e), ask }),
385
+ store: createFileSessionStore(await mkdtemp(join(tmpdir(), "confirm-"))),
386
+ provider: fakeProvider,
387
+ constructAgent,
388
+ };
389
+ await runTurn(deps, { message: "go" }, (e) => events.push(e));
390
+ return events;
391
+ }
392
+
393
+ test("asks only for calls the tool flags, and runs the rest", async () => {
394
+ const { tool, ran } = confirmTool((input) =>
395
+ input.element === "Post" ? "Click Post" : undefined,
396
+ );
397
+ const reasons: Array<string | undefined> = [];
398
+ await run(tool, async (req) => {
399
+ reasons.push(req.reason);
400
+ return true;
401
+ });
402
+ expect(reasons).toEqual(["Click Post"]);
403
+ expect(ran).toEqual([{ element: "Post" }, { element: "Cancel" }]);
404
+ });
405
+
406
+ test("a refused call is not run, and the next call is still judged on its own", async () => {
407
+ const { tool, ran } = confirmTool((input) =>
408
+ input.element === "Post" ? "Click Post" : undefined,
409
+ );
410
+ const events = await run(tool, async () => false);
411
+ expect(ran).toEqual([{ element: "Cancel" }]);
412
+ const ends = events.filter((e) => e.kind === "tool_call_end") as Array<{ success: boolean }>;
413
+ expect(ends.map((e) => e.success)).toEqual([false, true]);
414
+ });
415
+
416
+ test("a tool without confirm is unchanged", async () => {
417
+ const { tool, ran } = confirmTool(() => undefined);
418
+ delete (tool as { confirm?: unknown }).confirm;
419
+ let asked = 0;
420
+ await run(tool, async () => {
421
+ asked += 1;
422
+ return true;
423
+ });
424
+ expect(asked).toBe(0);
425
+ expect(ran).toHaveLength(2);
426
+ });
427
+ });
@@ -35,12 +35,48 @@ import type { AgentTool, ConstructAgent, ConstructedAgent } from "./strands.ts";
35
35
  const REJECTED_TOOL_MESSAGE = "was denied approval and was not invoked";
36
36
 
37
37
  export interface TurnRequest {
38
+ /** What the model sees as the user's message. */
38
39
  message: string;
39
40
  sessionId?: string;
40
41
  model?: string;
41
42
  editUserTurn?: number;
43
+ /**
44
+ * What the transcript stores and titles the chat with, when it differs from `message`. A host
45
+ * can prefix instructions to `message` for the model without them showing up in the chat.
46
+ */
47
+ displayMessage?: string;
48
+ /** Appended to the system prompt for this turn only. */
49
+ systemAppend?: string;
50
+ /** Tool names hidden from the model for this turn only. */
51
+ excludeTools?: readonly string[];
52
+ /** Host data for this turn, passed to `intercept` untouched. */
53
+ hostData?: Record<string, unknown>;
42
54
  }
43
55
 
56
+ /** What a host `intercept` hook can do with a turn. */
57
+ export interface TurnInterceptContext {
58
+ /** What the user typed, without any host prefix. */
59
+ message: string;
60
+ /**
61
+ * A model provider for `modelId`, for hosts that run their own model calls. `title` labels the
62
+ * calls in OpenRouter usage. When the harness was given a fixed provider, every call returns it.
63
+ */
64
+ provider: (modelId: string, title?: string) => MainModelProvider;
65
+ /** The `hostData` the host set for this turn. */
66
+ hostData: Record<string, unknown>;
67
+ history: Array<{ role: "user" | "assistant"; content: string }>;
68
+ toolNames: ReadonlySet<string>;
69
+ emit: AgentEventEmitter;
70
+ signal?: AbortSignal;
71
+ }
72
+
73
+ /**
74
+ * Handle a whole turn without the chat model, for example a computer-use agent. Return a reply
75
+ * to end the turn with it, or undefined to let the normal agent answer. Text sent through
76
+ * `emit` is part of the reply. Throwing falls through to the normal agent.
77
+ */
78
+ export type TurnInterceptor = (ctx: TurnInterceptContext) => Promise<{ reply: string } | undefined>;
79
+
44
80
  export interface RunTurnDeps {
45
81
  cwd: string;
46
82
  name: string;
@@ -51,7 +87,7 @@ export interface RunTurnDeps {
51
87
  store: SessionStore;
52
88
  provider: MainModelProvider;
53
89
  constructAgent: ConstructAgent;
54
- resolveProvider?: (modelId: string) => MainModelProvider;
90
+ resolveProvider?: (modelId: string, title?: string) => MainModelProvider;
55
91
  summarize?: SummarizerFn;
56
92
  contextWindowTokens?: number;
57
93
  maxTokens?: number;
@@ -66,6 +102,8 @@ export interface RunTurnDeps {
66
102
  decisions?: ResolvedDecisions;
67
103
  /** Host judgment of which messages are a direct tool call. Needs `decisions`. */
68
104
  shortcut?: ShortcutPlanner;
105
+ /** Host handler that can answer a whole turn without the chat model. */
106
+ intercept?: TurnInterceptor;
69
107
  }
70
108
 
71
109
  export async function runTurn(
@@ -75,20 +113,21 @@ export async function runTurn(
75
113
  options: { signal?: AbortSignal } = {},
76
114
  ): Promise<Session | undefined> {
77
115
  let session: Session | undefined;
116
+ const stored = req.displayMessage ?? req.message;
78
117
  try {
79
118
  if (req.sessionId) session = await deps.store.get(req.sessionId);
80
119
  if (req.editUserTurn !== undefined) {
81
120
  if (!session) throw new Error("No session to edit.");
82
- session = await deps.store.save(replaceUserTurn(session, req.editUserTurn, req.message));
121
+ session = await deps.store.save(replaceUserTurn(session, req.editUserTurn, stored));
83
122
  } else {
84
123
  session ??= await deps.store.create(deps.systemPrompt, req.model);
85
124
  session = await deps.store.append(session, {
86
125
  kind: "turn",
87
126
  role: "user",
88
- content: req.message,
127
+ content: stored,
89
128
  });
90
129
  if (!session.title || session.title === "New chat") {
91
- session = await deps.store.setTitle(session, titleFromUserMessage(req.message));
130
+ session = await deps.store.setTitle(session, titleFromUserMessage(stored));
92
131
  }
93
132
  }
94
133
  emit({ kind: "session_meta", sessionId: session.id, title: session.title });
@@ -174,40 +213,82 @@ export async function runTurn(
174
213
  }
175
214
  }
176
215
 
177
- const toolDefs = deps.mcp ? deps.mcp.listTools() : deps.tools;
216
+ const appended = req.systemAppend?.trim();
217
+ if (appended) systemPrompt += `\n\n${appended}`;
218
+ const allDefs = deps.mcp ? deps.mcp.listTools() : deps.tools;
219
+ const hidden = new Set(req.excludeTools ?? []);
220
+ const toolDefs = hidden.size > 0 ? allDefs.filter((def) => !hidden.has(def.name)) : allDefs;
178
221
  const tools: AgentTool[] = toolDefs.map((def) =>
179
222
  guardTool(def, deps.approval, capture, obs, deps.hooks),
180
223
  );
181
224
 
182
- if (session && req.editUserTurn === undefined && deps.shortcut && deps.decisions?.shortcuts) {
183
- const outcome = await tryShortcut(deps, req.message, toolDefs, tools, options.signal);
184
- if (outcome?.kind === "answered") {
185
- capture({ kind: "text_delta", text: outcome.reply });
225
+ // End the turn with a reply the chat model did not write. A storage failure while saving it
226
+ // ends the turn with an error instead of rejecting out of the trace callback.
227
+ const finishWithReply = async (decision: string): Promise<Session | undefined> => {
228
+ await persistChain;
229
+ try {
230
+ if (session) session = await finalize(deps, session, assistantText, thoughtText);
231
+ } catch (err) {
232
+ capture({ kind: "error", message: errorMessage(err) });
233
+ root.update({
234
+ level: "ERROR",
235
+ statusMessage: errorMessage(err),
236
+ metadata: { status: "failed", generation_duration: Date.now() - startedAt },
237
+ });
238
+ await obs.flush();
239
+ return session;
240
+ }
241
+ capture({ kind: "completion" });
242
+ root.update({
243
+ output: assistantText,
244
+ metadata: { status: "success", generation_duration: Date.now() - startedAt, decision },
245
+ });
246
+ await obs.flush();
247
+ return session;
248
+ };
249
+
250
+ if (session && req.editUserTurn === undefined && deps.intercept) {
251
+ const outcome = await tryIntercept(
252
+ deps.intercept,
253
+ {
254
+ message: stored,
255
+ provider: (modelId, title) =>
256
+ deps.resolveProvider ? deps.resolveProvider(modelId, title) : deps.provider,
257
+ hostData: req.hostData ?? {},
258
+ history,
259
+ toolNames: new Set(toolDefs.map((def) => def.name)),
260
+ emit: capture,
261
+ signal: options.signal,
262
+ },
263
+ () => assistantText.length > 0,
264
+ );
265
+ if (outcome.kind === "reply") {
266
+ if (!assistantText) capture({ kind: "text_delta", text: outcome.reply });
267
+ return finishWithReply("intercept");
268
+ }
269
+ if (outcome.kind === "failed") {
186
270
  await persistChain;
187
- try {
188
- session = await finalize(deps, session, assistantText, thoughtText);
189
- } catch (err) {
190
- capture({ kind: "error", message: errorMessage(err) });
191
- root.update({
192
- level: "ERROR",
193
- statusMessage: errorMessage(err),
194
- metadata: { status: "failed", generation_duration: Date.now() - startedAt },
195
- });
196
- await obs.flush();
197
- return session;
198
- }
199
- capture({ kind: "completion" });
271
+ if (session)
272
+ session = await finalize(deps, session, assistantText, thoughtText).catch(
273
+ () => session,
274
+ );
275
+ capture({ kind: "error", message: errorMessage(outcome.error) });
200
276
  root.update({
201
- output: assistantText,
202
- metadata: {
203
- status: "success",
204
- generation_duration: Date.now() - startedAt,
205
- decision: "shortcut",
206
- },
277
+ level: "ERROR",
278
+ statusMessage: errorMessage(outcome.error),
279
+ metadata: { status: "failed", generation_duration: Date.now() - startedAt },
207
280
  });
208
281
  await obs.flush();
209
282
  return session;
210
283
  }
284
+ }
285
+
286
+ if (session && req.editUserTurn === undefined && deps.shortcut && deps.decisions?.shortcuts) {
287
+ const outcome = await tryShortcut(deps, stored, toolDefs, tools, options.signal);
288
+ if (outcome?.kind === "answered") {
289
+ capture({ kind: "text_delta", text: outcome.reply });
290
+ return finishWithReply("shortcut");
291
+ }
211
292
  if (outcome?.kind === "continue" && outcome.agentNote) {
212
293
  systemPrompt += `\n\n${outcome.agentNote}`;
213
294
  }
@@ -307,6 +388,29 @@ export async function runTurn(
307
388
  );
308
389
  }
309
390
 
391
+ type InterceptOutcome =
392
+ | { kind: "reply"; reply: string }
393
+ | { kind: "pass" }
394
+ | { kind: "failed"; error: unknown };
395
+
396
+ /**
397
+ * Run the host interceptor. A throw before it produced any output passes the turn to the normal
398
+ * agent. A throw after output has already reached the user is a failure, because answering again
399
+ * would show two answers glued together.
400
+ */
401
+ async function tryIntercept(
402
+ intercept: TurnInterceptor,
403
+ ctx: TurnInterceptContext,
404
+ producedOutput: () => boolean,
405
+ ): Promise<InterceptOutcome> {
406
+ try {
407
+ const result = await intercept(ctx);
408
+ return result ? { kind: "reply", reply: result.reply } : { kind: "pass" };
409
+ } catch (err) {
410
+ return producedOutput() ? { kind: "failed", error: err } : { kind: "pass" };
411
+ }
412
+ }
413
+
310
414
  type ShortcutOutcome =
311
415
  | { kind: "answered"; reply: string }
312
416
  | { kind: "continue"; agentNote?: string };
@@ -436,6 +540,8 @@ async function approvalGranted(
436
540
  callId: string,
437
541
  input: Record<string, unknown>,
438
542
  ): Promise<boolean> {
543
+ const reason = def.confirm?.(input);
544
+ if (reason) return approval.request({ callId, toolName: def.name, input, reason });
439
545
  if (!isRiskyToolCall(def.name) && !isFileWriteTool(def.name)) return true;
440
546
  return approval.request({ callId, toolName: def.name, input });
441
547
  }
@@ -0,0 +1,89 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import {
3
+ type ConstructAgent,
4
+ constructOpenRouterProvider,
5
+ createConstructAgent,
6
+ type StrandsBackedProvider,
7
+ } from "../index.ts";
8
+
9
+ const BASE_URL = "https://openrouter.ai/api/v1";
10
+
11
+ describe("strands exports", () => {
12
+ it("exposes the agent constructor and OpenRouter provider from the package entry", () => {
13
+ expect(typeof createConstructAgent).toBe("function");
14
+ expect(typeof constructOpenRouterProvider).toBe("function");
15
+ });
16
+ });
17
+
18
+ describe("constructOpenRouterProvider", () => {
19
+ it("returns a provider that reports a missing key instead of calling the network", async () => {
20
+ const provider = constructOpenRouterProvider({
21
+ apiKey: " ",
22
+ model: "x-ai/grok",
23
+ baseUrl: BASE_URL,
24
+ });
25
+ expect(provider.modelId).toBe("x-ai/grok");
26
+ const events = [];
27
+ for await (const event of provider.stream({ messages: [{ role: "user", content: "hi" }] })) {
28
+ events.push(event);
29
+ }
30
+ expect(events).toEqual([
31
+ { type: "error", message: "OPENROUTER_API_KEY is not set." },
32
+ { type: "done" },
33
+ ]);
34
+ });
35
+
36
+ it("builds a Strands-backed provider for a real key", () => {
37
+ const provider = constructOpenRouterProvider({
38
+ apiKey: "sk-test",
39
+ model: "x-ai/grok",
40
+ baseUrl: `${BASE_URL}/`,
41
+ }) as StrandsBackedProvider;
42
+ expect(provider.kind).toBe("openrouter");
43
+ expect(provider.sdkModel).toBeDefined();
44
+ expect(typeof provider.takeUsage).toBe("function");
45
+ expect(typeof provider.setReasoningSink).toBe("function");
46
+ });
47
+
48
+ it("reports no usage before any request has completed", () => {
49
+ const provider = constructOpenRouterProvider({
50
+ apiKey: "sk-test",
51
+ model: "x-ai/grok",
52
+ baseUrl: BASE_URL,
53
+ });
54
+ expect(provider.takeUsage?.()).toBeUndefined();
55
+ });
56
+ });
57
+
58
+ describe("createConstructAgent", () => {
59
+ it("refuses a provider that is not backed by the Strands SDK", () => {
60
+ const construct: ConstructAgent = createConstructAgent();
61
+ const plain = constructOpenRouterProvider({ apiKey: "", model: "m", baseUrl: BASE_URL });
62
+ expect(() =>
63
+ construct({ systemPrompt: "s", tools: [], provider: plain, messages: [] }),
64
+ ).toThrow("Strands-backed");
65
+ });
66
+
67
+ it("constructs an agent for a Strands-backed provider without running it", () => {
68
+ const construct = createConstructAgent();
69
+ const provider = constructOpenRouterProvider({
70
+ apiKey: "sk-test",
71
+ model: "m",
72
+ baseUrl: BASE_URL,
73
+ });
74
+ const agent = construct({
75
+ systemPrompt: "You are a test.",
76
+ tools: [
77
+ {
78
+ name: "echo",
79
+ description: "Echo input.",
80
+ inputSchema: { type: "object", properties: {} },
81
+ invoke: async () => ({ content: [{ type: "text", text: "ok" }] }),
82
+ },
83
+ ],
84
+ provider,
85
+ messages: [{ role: "user", content: "earlier" }],
86
+ });
87
+ expect(typeof agent.run).toBe("function");
88
+ });
89
+ });
@@ -153,6 +153,8 @@ export function constructOpenRouterProvider(options: {
153
153
  baseUrl: string;
154
154
  maxTokens?: number;
155
155
  sessionId?: () => string | undefined;
156
+ /** `X-Title` sent to OpenRouter, so usage can be told apart by purpose. Defaults to the product name. */
157
+ title?: string;
156
158
  }): MainModelProvider {
157
159
  if (!options.apiKey.trim()) {
158
160
  return {
@@ -178,7 +180,7 @@ export function constructOpenRouterProvider(options: {
178
180
  baseURL: options.baseUrl.replace(/\/+$/, ""),
179
181
  defaultHeaders: {
180
182
  "HTTP-Referer": "https://caelence.com",
181
- "X-Title": PRODUCT_NAME,
183
+ "X-Title": options.title?.trim() || PRODUCT_NAME,
182
184
  },
183
185
  fetch: createUsageTrackingFetch(
184
186
  (usage) => {
@@ -5,6 +5,11 @@ import type { ResolvedDecisions } from "./config.ts";
5
5
  * ("open example.com"). The harness owns the mechanism: it checks approval, runs the tool,
6
6
  * records the turn, and falls back to the agent on any failure. The host owns the judgment
7
7
  * of which messages qualify, usually with a Jev choice question via {@link decide}.
8
+ *
9
+ * Shortcuts only run when decisions are on (an OpenRouter key, not disabled), since the planner
10
+ * receives the resolved decision settings. A host that does not use a decision model, or must
11
+ * run even when decisions are off, should use `intercept` instead, which has no such gate.
12
+ * `message` is what the user typed, without any host prefix.
8
13
  */
9
14
  export interface ShortcutPlan {
10
15
  toolName: string;
@@ -39,7 +39,7 @@ import { readMediaPrefs } from "../media/prefs.ts";
39
39
  import { isMemoryEnabled, writeMemoryPrefs } from "../memory/prefs.ts";
40
40
  import { deleteFact, isFactPinned, listFacts, pinFact, unpinFact } from "../memory/store.ts";
41
41
  import { PRODUCT_NAME } from "../product.ts";
42
- import { createHarness, type HarnessRuntime } from "../runtime.ts";
42
+ import { type CreateHarnessOptions, createHarness, type HarnessRuntime } from "../runtime.ts";
43
43
  import {
44
44
  buildSkillsPage,
45
45
  cachedPopularSkills,
@@ -55,6 +55,7 @@ import {
55
55
  skillNameFromCatalogId,
56
56
  } from "../skills/registry.ts";
57
57
  import { resolveUnderCwd, toProjectRel } from "../tools/paths.ts";
58
+ import type { BridgeHost, BridgeHostContext, BridgeTurnPlan } from "./host.ts";
58
59
  import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
59
60
  import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
60
61
  import { filePreviewKind, filePreviewMime } from "./preview-kind.ts";
@@ -101,6 +102,10 @@ export interface StartDesktopBridgeOptions {
101
102
  port?: number;
102
103
  token?: string;
103
104
  harness?: HarnessRuntime;
105
+ /** Options for the harness the bridge creates. Ignored when `harness` is given. */
106
+ harnessOptions?: Omit<CreateHarnessOptions, "cwd">;
107
+ /** Extension points for a host app. See {@link BridgeHost}. */
108
+ extensions?: BridgeHost;
104
109
  openUrl?: (url: string) => void;
105
110
  openPath?: (path: string, reveal: boolean) => void;
106
111
  }
@@ -174,8 +179,11 @@ function saveProviderOAuth(body: Record<string, unknown>, kind: "google" | "micr
174
179
  });
175
180
  }
176
181
 
177
- function chatMessages(session: Session | undefined) {
178
- return session ? sessionTranscript(session) : [];
182
+ function chatMessages(session: Session | undefined, shown: (text: string) => string = (t) => t) {
183
+ if (!session) return [];
184
+ return sessionTranscript(session).map((line) =>
185
+ line.kind === "user" || line.kind === "assistant" ? { ...line, text: shown(line.text) } : line,
186
+ );
179
187
  }
180
188
 
181
189
  function json(data: unknown, status = 200, extra?: HeadersInit): Response {
@@ -343,7 +351,11 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
343
351
  const token = options.token ?? randomBytes(24).toString("hex");
344
352
  const openUrl = options.openUrl ?? openSystemBrowser;
345
353
  if (!options.harness) applyStoredOpenRouterKey();
346
- const harness = options.harness ?? (await createHarness({ cwd: options.cwd }));
354
+ const harness =
355
+ options.harness ?? (await createHarness({ ...options.harnessOptions, cwd: options.cwd }));
356
+ const ext: BridgeHost = options.extensions ?? {};
357
+ const hostCtx: BridgeHostContext = { harness };
358
+ const shown = (text: string): string => (ext.displayText ? ext.displayText(text) : text);
347
359
  const openPath =
348
360
  options.openPath ??
349
361
  ((path: string, reveal: boolean) => {
@@ -420,11 +432,16 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
420
432
  };
421
433
 
422
434
  const route_get_models = async (_req: Request, _url: URL): Promise<Response> => {
423
- return json({ items: modelPickerItems(harness.modelId, cachedLiveTargetNames()) });
435
+ const extra = (ext.modelItems?.(hostCtx) ?? []).filter(
436
+ (row) => !HARNESS_MODELS.some((model) => model.id === row.id),
437
+ );
438
+ return json({
439
+ items: [...extra, ...modelPickerItems(harness.modelId, cachedLiveTargetNames())],
440
+ });
424
441
  };
425
442
 
426
443
  const route_get_settings = async (_req: Request, _url: URL): Promise<Response> => {
427
- return json(settingsPayload(harness));
444
+ return json({ ...settingsPayload(harness), ...ext.settings?.(hostCtx) });
428
445
  };
429
446
 
430
447
  const route_get_integrations = async (_req: Request, _url: URL): Promise<Response> => {
@@ -700,9 +717,12 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
700
717
  if (typeof body.memoryEnabled === "boolean") {
701
718
  writeMemoryPrefs({ enabled: body.memoryEnabled });
702
719
  }
720
+ const hostError = await ext.applySettings?.(hostCtx, body);
721
+ if (hostError) return json({ error: hostError }, 400);
703
722
  return json({
704
723
  ok: true,
705
724
  ...settingsPayload(harness),
725
+ ...ext.settings?.(hostCtx),
706
726
  state: snapshot(harness, busy, title),
707
727
  });
708
728
  };
@@ -765,7 +785,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
765
785
  return json({
766
786
  ok: true,
767
787
  state: snapshot(harness, busy, title),
768
- messages: chatMessages(session),
788
+ messages: chatMessages(session, shown),
769
789
  });
770
790
  };
771
791
 
@@ -842,7 +862,7 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
842
862
  return json({
843
863
  ok: true,
844
864
  state: snapshot(harness, busy, title),
845
- messages: chatMessages(session),
865
+ messages: chatMessages(session, shown),
846
866
  });
847
867
  }
848
868
  return json({
@@ -890,7 +910,27 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
890
910
  if (editUserTurn === undefined && incoming.trim().startsWith("/")) {
891
911
  return runSlashTurn(incoming);
892
912
  }
893
- return startTurnStream(message, editUserTurn);
913
+ let plan: BridgeTurnPlan | undefined;
914
+ try {
915
+ plan = await ext.beforeTurn?.(hostCtx, { message, body });
916
+ } catch (err) {
917
+ return json({ error: errorMessage(err) || "Could not start the turn." }, 500);
918
+ }
919
+ if (plan?.reply !== undefined) return replyWithoutModel(plan.reply);
920
+ return startTurnStream(message, editUserTurn, plan);
921
+ };
922
+ /** Stream a host-written reply as a finished turn. Nothing is saved to the chat. */
923
+ const replyWithoutModel = (text: string): Response => {
924
+ const encoder = new TextEncoder();
925
+ const events: AgentEvent[] = [{ kind: "text_delta", text }, { kind: "completion" }];
926
+ const body = events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("");
927
+ return new Response(encoder.encode(body), {
928
+ headers: {
929
+ "content-type": "text/event-stream",
930
+ "cache-control": "no-cache",
931
+ ...CORS_HEADERS,
932
+ },
933
+ });
894
934
  };
895
935
 
896
936
  const parseEditUserTurn = (value: unknown): number | undefined => {
@@ -909,7 +949,11 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
909
949
  return json({ outcome, state: snapshot(harness, busy, title) });
910
950
  };
911
951
 
912
- const startTurnStream = (message: string, editUserTurn?: number): Response => {
952
+ const startTurnStream = (
953
+ message: string,
954
+ editUserTurn?: number,
955
+ plan?: BridgeTurnPlan,
956
+ ): Response => {
913
957
  busy = true;
914
958
  abort = new AbortController();
915
959
  const encoder = new TextEncoder();
@@ -932,7 +976,14 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
932
976
  }
933
977
  }, 4_000);
934
978
  void harness
935
- .runTurn(message, send, {
979
+ .runTurn(plan?.message ?? message, send, {
980
+ ...plan?.options,
981
+ // What the user typed is what the chat stores, whatever the model was shown.
982
+ ...(plan?.displayMessage !== undefined
983
+ ? { displayMessage: plan.displayMessage }
984
+ : plan?.message !== undefined
985
+ ? { displayMessage: message }
986
+ : {}),
936
987
  signal: abort?.signal,
937
988
  approvalAsk: (req: ApprovalRequest) => waitForApproval(pending, req),
938
989
  ...(editUserTurn !== undefined ? { editUserTurn } : {}),
@@ -1022,7 +1073,10 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
1022
1073
  if (readToken(req) !== token) {
1023
1074
  return json({ error: `Unauthorized. Restart ${PRODUCT_NAME}.` }, 401);
1024
1075
  }
1025
- const matched = bridgeRoutes[`${req.method} ${url.pathname}`];
1076
+ const key = `${req.method} ${url.pathname}`;
1077
+ const hostRoute = ext.routes?.[key];
1078
+ if (hostRoute) return hostRoute(hostCtx, req, url);
1079
+ const matched = bridgeRoutes[key];
1026
1080
  if (!matched) return json({ error: "Not found." }, 404);
1027
1081
  return matched(req, url);
1028
1082
  },