@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-alpha.1

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 (105) hide show
  1. package/CONSUMER_GUIDE.md +60 -26
  2. package/package.json +5 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/agent/native-operations.ts +1 -0
  5. package/src/agent-session.ts +11 -2
  6. package/src/agent.ts +4 -1
  7. package/src/index.ts +2 -0
  8. package/src/native/capabilities.ts +2 -2
  9. package/src/native/connection.ts +1 -1
  10. package/src/native/controller.ts +2 -1
  11. package/src/native/host-config.ts +2 -0
  12. package/src/native/host.ts +10 -0
  13. package/src/native/mcp.ts +47 -0
  14. package/src/native/recovery.ts +8 -7
  15. package/src/native/reminders/routine-guard.ts +4 -3
  16. package/src/native/reminders/routine-wire.ts +1 -1
  17. package/src/native-harness/README.md +58 -1
  18. package/src/native-harness/package.json +4 -0
  19. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  20. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  21. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  22. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  23. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  24. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  25. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  26. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  27. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  28. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  29. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  30. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  31. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  32. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  33. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  38. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  39. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  40. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  41. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  42. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  44. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  45. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  46. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  47. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  48. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  49. package/src/native-harness/src/contracts/agent.ts +3 -1
  50. package/src/native-harness/src/contracts/attachments.ts +62 -0
  51. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  52. package/src/native-harness/src/contracts/context.ts +1 -1
  53. package/src/native-harness/src/contracts/events.ts +2 -2
  54. package/src/native-harness/src/contracts/loop.ts +3 -3
  55. package/src/native-harness/src/contracts/mcp.ts +22 -0
  56. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  57. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  58. package/src/native-harness/src/contracts/protocol.ts +20 -4
  59. package/src/native-harness/src/contracts/session-file.ts +2 -1
  60. package/src/native-harness/src/contracts/session.ts +6 -1
  61. package/src/native-harness/src/contracts/storage.ts +23 -5
  62. package/src/native-harness/src/contracts/tools.ts +2 -0
  63. package/src/native-harness/src/contracts/web.ts +16 -0
  64. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  65. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  66. package/src/native-harness/src/index.ts +43 -11
  67. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  68. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  69. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  70. package/src/native-harness/src/interfaces/client.ts +8 -2
  71. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  72. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  73. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  74. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  75. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  76. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  77. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  78. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  79. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  80. package/src/native-harness/src/kernel/channels.ts +19 -11
  81. package/src/native-harness/src/kernel/loop.ts +1 -1
  82. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  83. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  84. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  85. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  86. package/src/native-harness/src/state/storage/archive.ts +95 -12
  87. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  88. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  89. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  90. package/src/native-harness/src/state/storage/engine.ts +194 -34
  91. package/src/native-harness/src/state/storage/inference.ts +30 -2
  92. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  93. package/src/native-harness/src/state/storage/memory.ts +18 -3
  94. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  95. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  96. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  97. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  98. package/src/native-harness/src/testing.ts +150 -55
  99. package/src/native-harness/src/util/attachment-input.ts +42 -0
  100. package/src/native-harness/src/util/config.ts +59 -12
  101. package/src/native-harness/src/util/mcp-config.ts +102 -0
  102. package/src/native-harness/src/util/web-config.ts +34 -0
  103. package/src/native-harness/src/util/web-usage.ts +33 -0
  104. package/src/steering/combine.ts +1 -0
  105. package/src/steering/contracts.ts +3 -0
@@ -0,0 +1,16 @@
1
+ /** Immutable non-secret dispatch evidence, committed before external effects. */
2
+ export type WebDispatchEvidence = { backend: "exa"; operation: "web_search" | "web_fetch"; paid: true } | { backend: "http"; operation: "web_fetch"; paid: false };
3
+ /** Provider-reported metadata; committed atomically with the paired result. */
4
+ export interface WebResultUsage { requestId?: string; usd?: number }
5
+ export interface StoredWebDispatch { turnId: number; callId: string; evidence: WebDispatchEvidence }
6
+ export type WebCost = { kind: "none" } | { kind: "unknown" } | { kind: "provider_estimate"; usd: number };
7
+ export interface WebUsageView { backend?: "exa" | "http"; operation?: "web_search" | "web_fetch"; requestId?: string; cost: WebCost }
8
+ export type WebToolError = "blocked_destination" | "unsupported_content" | "invalid_arguments" | "rate_limited" | "provider_error" | "tool_timeout" | "page_unavailable" | "result_too_large" | "tool_interrupted" | "response_too_large";
9
+ export type WebToolResponse = { ok: true; content: string; usage: WebResultUsage } | { ok: false; code: WebToolError; message: string; usage: WebResultUsage };
10
+ /** Trusted local tool assembly; dispatch metadata is frozen for this open. */
11
+ export interface CheckedWebRegistration {
12
+ definition: import("./loop.ts").ToolDefinition;
13
+ validate(args: unknown): string | undefined;
14
+ dispatch: WebDispatchEvidence;
15
+ execute(args: unknown, signal: AbortSignal): Promise<WebToolResponse>;
16
+ }
@@ -88,7 +88,7 @@ export async function dispatchWithPolicy(options: {
88
88
  * available, invalid arguments), or undefined. Read before authorization
89
89
  * and again at the dispatch boundary. Policy denial retains precedence. */
90
90
  refuse?(): { code: string; detail?: string } | undefined;
91
- }): Promise<{ content: string; dispatched: boolean; outcome?: ToolOutcome }> {
91
+ }): Promise<{ content: string; dispatched: boolean; outcome?: ToolOutcome; usage?: import("../../contracts/web.ts").WebResultUsage }> {
92
92
  const { call, signal, suspension } = options;
93
93
  const skip = (code: string, detail?: string) => { const content = skipped(code, detail); options.recordSkip(content, code); return { content, dispatched: false }; };
94
94
  signal.throwIfAborted();
@@ -117,6 +117,13 @@ export async function dispatchWithPolicy(options: {
117
117
  if (request && !request.discard("tool_unavailable")) return { content: "", dispatched: false };
118
118
  return skip(late.code, late.detail);
119
119
  }
120
+ const currentRule = options.decide();
121
+ if (currentRule === "deny") {
122
+ if (request && !request.discard("tool_unavailable")) return { content: "", dispatched: false };
123
+ return skip("policy_denied");
124
+ }
125
+ // A rule that became ask cannot reuse an earlier allow without a grant.
126
+ if (rule === "allow" && currentRule === "ask") return dispatchWithPolicy(options);
120
127
  if (request && !request.consume()) return { content: "", dispatched: false };
121
128
  try { options.mark(); } catch (error) { request?.dispatchFailed(); throw error; }
122
129
  let result: ReturnType<typeof options.execute>;
@@ -125,5 +132,5 @@ export async function dispatchWithPolicy(options: {
125
132
  options.started();
126
133
  request?.dispatchClosed();
127
134
  const settled = await result;
128
- return typeof settled === "string" ? { content: settled, dispatched: true } : { content: settled.content, dispatched: true, outcome: settled.outcome };
135
+ return typeof settled === "string" ? { content: settled, dispatched: true } : { content: settled.content, dispatched: true, outcome: settled.outcome, ...(settled.usage ? { usage: settled.usage } : {}) };
129
136
  }
@@ -11,6 +11,10 @@ export function resolvePolicy(config: ManagedConfig, explicit?: string | null, c
11
11
  }
12
12
  /** A taken input contributes all its policy names; no pending input is passed. */
13
13
  export function toolDecision(config: ManagedConfig, references: readonly string[], tool: string): ToolDecision {
14
+ if (tool.startsWith("mcp__")) {
15
+ return references.length > 0 && references.every(name => name !== "__legacy_allow" &&
16
+ Object.hasOwn(config.policies, name) && config.policies[name]?.mcp === "allow") ? "allow" : "deny";
17
+ }
14
18
  if (!references.length) throw new Error("Cannot authorize a turn without taken-input policies");
15
19
  let result: ToolDecision = "allow";
16
20
  for (const reference of new Set(references)) {
@@ -27,6 +31,7 @@ export function policyFingerprint(config: ManagedConfig, references: readonly st
27
31
  return JSON.stringify([...new Set(references)].sort().map(name => {
28
32
  if (!Object.hasOwn(config.policies, name)) throw new PolicyError(name);
29
33
  const policy = config.policies[name]!;
30
- return [name, policy.fallback, Object.keys(policy.tools).sort().map(tool => [tool, policy.tools[tool]])];
34
+ return [name, policy.fallback, Object.keys(policy.tools).sort().map(tool => [tool, policy.tools[tool]]),
35
+ ...(policy.mcp === undefined ? [] : [["mcp-v1", policy.mcp]])];
31
36
  }));
32
37
  }
@@ -1,3 +1,4 @@
1
+ import { isWebTool } from "./capabilities/tools/web/definitions.ts";
1
2
  import { guardedReminderDefinitions, executeReminderTool, isReminderTool, reminderAction, reminderDefinitions } from "./capabilities/tools/reminders/index.ts";
2
3
  import { createReminderRuntime } from "./runtime/reminders.ts";
3
4
  import { wallReminderClock } from "./runtime/reminder-timer.ts";
@@ -80,12 +81,21 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
80
81
  };
81
82
  const config = owner.value ?? { version: 1 as const, system: options.systemPrompt, model: { protocol: "scripted" as const, script: "legacy" },
82
83
  defaultPolicy: "__legacy_allow", policies: { __legacy_allow: { fallback: "allow" as const, tools: {} } } };
84
+ if (options.imageInput && (config.model.protocol === "openai-compatible" || config.model.imageInput !== true)) throw new Error("Image input requires explicit model configuration");
85
+ if (options.config?.mcpServers !== undefined) {
86
+ const canonical = (value: unknown) => JSON.stringify(value, (_key, object) =>
87
+ object && typeof object === "object" && !Array.isArray(object)
88
+ ? Object.fromEntries(Object.keys(object).sort().map(key => [key, object[key]])) : object);
89
+ store.bindMcpCatalog?.(canonical([options.config.mcpServers,
90
+ [...(options.mcpTools?.values() ?? [])].map(tool => tool.definition).sort((a, b) => a.name.localeCompare(b.name))]));
91
+ }
83
92
  // ---- Tools, decision 0021. The catalog's definitions come from the open;
84
93
  // the revoked set mirrors storage; the executor belongs to the connection.
85
- const revoked = options.catalog ? store.readRevokedTools() : undefined;
94
+ const catalogInput = options.catalog ?? ((options.webTools?.length || options.mcpTools?.size) ? { catalog: [] } : undefined);
95
+ const revoked = catalogInput ? store.readRevokedTools() : undefined;
86
96
  if (revoked && !revoked.ok) throw new Error(revoked.error.message);
87
- if (options.catalog?.catalog.some(tool => isTimelineTool(tool.name) || isReminderTool(tool.name))) throw new Error("Native tool names are reserved");
88
- const catalog = options.catalog ? createToolCatalog(options.catalog, revoked?.value ?? []) : undefined;
97
+ if (options.catalog?.catalog.some(tool => isTimelineTool(tool.name) || isReminderTool(tool.name) || isWebTool(tool.name) || tool.name.startsWith("mcp__"))) throw new Error("Native tool names are reserved");
98
+ const catalog = catalogInput ? createToolCatalog(catalogInput, revoked?.value ?? []) : undefined;
89
99
  const limits = { ...TOOL_LIMITS, ...options.toolLimits };
90
100
  let executor: FunctionExecutor | undefined;
91
101
  /** What each running turn is doing now. Process state, cleared when the turn's run ends. */
@@ -112,7 +122,8 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
112
122
  const offer = (policies: readonly string[]): { tools: ToolDefinition[]; fixedToolCount?: number } => {
113
123
  const allowed = <T extends ToolDefinition>(tools: readonly T[]) => tools.filter(tool => toolDecision(config, policies, tool.name) !== "deny");
114
124
  const definition = ({ name, description, parameters }: ToolDefinition): ToolDefinition => ({ name, description, parameters });
115
- const builtins = allowed([...services.tools.filter(tool => tool.name !== "notify_channel" && !isTimelineTool(tool.name) && !isReminderTool(tool.name)), notifyChannelDefinition, ...sessionReminderDefinitions,
125
+ const builtins = allowed([...services.tools.filter(tool => tool.name !== "notify_channel" && !isTimelineTool(tool.name) && !isReminderTool(tool.name) && !isWebTool(tool.name) && !tool.name.startsWith("mcp__")), notifyChannelDefinition, ...sessionReminderDefinitions, ...(options.webTools ?? []).map(value => value.definition),
126
+ ...[...(options.mcpTools?.values() ?? [])].filter(tool => tool.available()).map(tool => tool.definition),
116
127
  ...((owner.value === undefined ? options.timelineTools : config.timelineTools) ? timelineDefinitions : [])]);
117
128
  if (!catalog) { offered = new Set(builtins.map(tool => tool.name)); return { tools: [...builtins] }; }
118
129
  const available = catalog.offered();
@@ -137,7 +148,9 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
137
148
  append,
138
149
  dispatchTool(call, execute) {
139
150
  const registration = catalog?.get(call.name), reader = !!catalog && call.name === READ_TOOL_RESULT;
140
- const retrieval = isTimelineTool(call.name), reminder = isReminderTool(call.name);
151
+ const retrieval = isTimelineTool(call.name), reminder = isReminderTool(call.name), webName = isWebTool(call.name);
152
+ const mcpName = call.name.startsWith("mcp__"), mcp = options.mcpTools?.get(call.name);
153
+ const web = options.webTools?.find(value => value.definition.name === call.name);
141
154
  const action = reminder ? reminderAction(call.name, JSON.parse(call.arguments)) : undefined;
142
155
  const id = invocationId(turn.turnId, call.id);
143
156
  let policies: readonly string[];
@@ -146,8 +159,19 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
146
159
  decide: () => toolDecision(config, policies = policySnapshot(), call.name),
147
160
  // Catalog tools and the reader must have been offered by this request,
148
161
  // still be available, and carry arguments their definition accepts.
149
- ...(registration || reader || retrieval || reminder ? { refuse: () => {
162
+ ...(registration || reader || retrieval || reminder || webName || mcpName ? { refuse: () => {
150
163
  if (!offered.has(call.name)) return { code: "tool_unavailable", detail: "it was not offered for this request" };
164
+ if (mcpName) {
165
+ if (!mcp?.available()) return { code: "tool_unavailable", detail: "MCP binding is unavailable" };
166
+ let args: unknown; try { args = JSON.parse(call.arguments); } catch { return { code: "invalid_arguments", detail: "Invalid JSON" }; }
167
+ return mcp.accepts(args) ? undefined : { code: "invalid_arguments", detail: "MCP schema rejected arguments" };
168
+ }
169
+ if (webName) {
170
+ if (!web) return { code: "tool_unavailable", detail: "web backend is disabled" };
171
+ let args: unknown; try { args = JSON.parse(call.arguments); } catch { return { code: "invalid_arguments", detail: "Invalid JSON" }; }
172
+ const problem = web.validate(args);
173
+ return problem ? { code: "invalid_arguments", detail: problem } : undefined;
174
+ }
151
175
  if (reminder) return action ? undefined : { code: "invalid_arguments", detail: "Invalid reminder arguments" };
152
176
  if (retrieval) {
153
177
  const detail = timelineArgumentsProblem(call.name, JSON.parse(call.arguments));
@@ -159,7 +183,15 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
159
183
  const problem = schemaProblem(registration.parameters, JSON.parse(call.arguments));
160
184
  return problem ? { code: "invalid_arguments", detail: problem } : undefined;
161
185
  } } : {}),
162
- execute: reminder ? async () => {
186
+ execute: mcp ? async (_call, signal) => {
187
+ const result = await mcp.call(JSON.parse(call.arguments), signal ?? port.signal);
188
+ return { content: result.content, outcome: result.code ? { status: "failed", code: result.code } : { status: "succeeded" } };
189
+ } : web ? async (_call, signal) => {
190
+ const result = await web.execute(JSON.parse(call.arguments), signal ?? port.signal);
191
+ const usage = web.dispatch.paid && Object.keys(result.usage).length ? { usage: result.usage } : {};
192
+ return result.ok ? { content: result.content, outcome: { status: "succeeded" as const }, ...usage }
193
+ : { content: JSON.stringify({ ok: false, code: result.code, message: result.message }), outcome: { status: "failed" as const, code: result.code }, ...usage };
194
+ } : reminder ? async () => {
163
195
  if (!action) throw new Error("Invalid reminder arguments");
164
196
  return executeReminderTool(store, action, turn.channelId, turn.turnId, id, policies, reminderClock.now(),
165
197
  (event, revision) => emit({ channel: turn.channelId, event, revision }));
@@ -176,13 +208,13 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
176
208
  catch (error) { return JSON.stringify({ ok: false, error: String(error) }); }
177
209
  } : execute,
178
210
  recordSkip: (content, code) => {
179
- append({ role: "tool", callId: call.id, content, outcome: { status: "skipped", code } });
211
+ append({ role: "tool", callId: call.id, content, outcome: { status: "skipped", code }, ...(webName ? { webNoDispatch: true as const } : {}) });
180
212
  // Built-in tools keep their event stream as it was: a skip is silent.
181
- if (registration || reader || retrieval || reminder) emit({ channel: turn.channelId, ...(recorded ? { revision: recorded.revision } : {}),
213
+ if (registration || reader || retrieval || reminder || webName || mcpName) emit({ channel: turn.channelId, ...(recorded ? { revision: recorded.revision } : {}),
182
214
  event: { type: "tool_call", turnId: String(turn.turnId), id: call.id, name: call.name, status: "skipped", output: content, invocationId: id } });
183
215
  },
184
216
  mark: () => {
185
- const result = store.markToolDispatched(turn.turnId, call.id); if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
217
+ const result = store.markToolDispatched(turn.turnId, call.id, web?.dispatch); if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
186
218
  phase(turn.turnId, "tool", id);
187
219
  },
188
220
  started: () => emit({ channel: turn.channelId, event: { type: "tool_call", turnId: String(turn.turnId), id: call.id, name: call.name, status: "started", input: call.arguments, invocationId: id } }) });
@@ -232,7 +264,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
232
264
  }
233
265
  }, services.executeTool).finally(() => { phases.delete(turn.turnId); });
234
266
  };
235
- const scheduler = createChannelScheduler(store, options.wrapTurn?.(run) ?? run, emit, lifecycle.publish, CONTEXT_LIMITS);
267
+ const scheduler = createChannelScheduler(store, options.wrapTurn?.(run) ?? run, emit, lifecycle.publish, CONTEXT_LIMITS, options.imageInput === true);
236
268
  agent = scheduler.agent;
237
269
  /** Status with each running turn's phase, which only this process knows. */
238
270
  const status = () => {
@@ -1,6 +1,11 @@
1
+ import { openMcpRegistry } from "../../capabilities/tools/mcp/registry.ts";
2
+ import { createWebRegistry, directWebFetch } from "../../capabilities/tools/web/registry.ts";
3
+ import { exaHttpsTransport } from "../../capabilities/tools/web/exa-transport.ts";
4
+ import { compatibleInferenceKey } from "../../runtime/config/inference-key.ts";
1
5
  import { createHash } from "node:crypto";
2
- import { existsSync } from "node:fs";
6
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
3
7
  import { dirname, join } from "node:path";
8
+ import { tmpdir } from "node:os";
4
9
  import { createSession } from "../../index.ts";
5
10
  import type { Model } from "../../contracts/loop.ts";
6
11
  import type { PersistentSession, TurnServices } from "../../contracts/session.ts";
@@ -8,7 +13,7 @@ import { openRouter } from "../../capabilities/model/openrouter.ts";
8
13
  import { loadScenario, scriptedCompatibilityKey } from "../../capabilities/model/scenario-file.ts";
9
14
  import { scenarioAttempt } from "../../capabilities/model/scenario-attempt.ts";
10
15
  import { bindModelAttempt } from "../../capabilities/model/attempt.ts";
11
- import { openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
16
+ import { openAICompatibleAttempt, openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
12
17
  import { currentTimeDefinition, executeCurrentTime } from "../../capabilities/tools/builtin/current-time.ts";
13
18
  import { debugToolDefinitions, debugToolHandlers } from "../../capabilities/tools/debug/index.ts";
14
19
  import { notifyChannelDefinition } from "../../capabilities/tools/builtin/notify-channel.ts";
@@ -18,7 +23,9 @@ import { createInspection } from "../inspector/state.ts";
18
23
  import { observeModel, observeSession } from "../inspector/observe.ts";
19
24
  import type { ManagedConfig } from "../../contracts/config-permissions.ts";
20
25
  import { chooseManagedConfig } from "../../runtime/config/paths.ts";
21
- import { resolveCredential, validateManagedConfig } from "../../runtime/config/managed.ts";
26
+ import { resolveCompatibleCredential, resolveCredential, validateManagedConfig } from "../../runtime/config/managed.ts";
27
+ import { createManagedAttachmentService } from "../../capabilities/attachments/service.ts";
28
+ import { imageValidationAvailable, validateManagedImage } from "../../capabilities/attachments/image-validation.ts";
22
29
 
23
30
  export interface DevelopmentOptions {
24
31
  systemPrompt: string;
@@ -26,6 +33,8 @@ export interface DevelopmentOptions {
26
33
  instructions?: string;
27
34
  /** SQLite file for a durable session; memory when omitted. */
28
35
  database?: string;
36
+ /** Managed session media root; explicit databases default to PATH.media. */
37
+ mediaRoot?: string;
29
38
  /** Expected ID for a named session, or the ID to assign on creation. */
30
39
  sessionId?: string;
31
40
  /** Create the database (it must not exist) instead of opening it. */
@@ -40,6 +49,8 @@ export interface DevelopmentOptions {
40
49
  managedConfig?: ManagedConfig;
41
50
  /** Provider injection and environment are useful for offline tests and hosts. */
42
51
  providerFactory?: (apiKey: string, model: string, onRequest?: (body: string) => void) => Model;
52
+ /** Trusted offline test assembly; unavailable through managed config. */
53
+ webTransport?: import("../../capabilities/tools/web/exa.ts").ExaTransport;
43
54
  /** Expose safe diagnostic tools for this process. */
44
55
  debugTools?: boolean;
45
56
  timelineTools?: boolean;
@@ -52,8 +63,8 @@ export interface DevelopmentOptions {
52
63
  * listener: storage, real or scripted inference, tools and the
53
64
  * inspector's view. Opening executes nothing; the caller starts or resumes. */
54
65
  export async function openDevelopment(options: DevelopmentOptions) {
55
- const sqlite = options.database ? createSqliteStorageAdapter(options.database) : undefined;
56
- const adapter = sqlite ?? createMemoryStorageAdapter();
66
+ const sqlite = options.database ? createSqliteStorageAdapter(options.database, { mediaRoot: options.mediaRoot ?? `${options.database}.media` }) : undefined;
67
+ let adapter = sqlite ?? createMemoryStorageAdapter();
57
68
  let sessionId = options.sessionId ?? "development";
58
69
  if (options.database && !options.create && !existsSync(options.database))
59
70
  throw new Error(`No session database at ${options.database}. Pass --create to create it.`);
@@ -82,64 +93,108 @@ export async function openDevelopment(options: DevelopmentOptions) {
82
93
  managedConfig = { ...managedConfig, system: options.debugInstructions };
83
94
  const systemPrompt = options.instructions ?? options.debugInstructions ?? managedConfig?.system ?? options.systemPrompt;
84
95
  const scriptPath = managedConfig?.model.protocol === "scripted" ? managedConfig.model.script : undefined;
96
+ const compatible = managedConfig?.model.protocol === "openai-compatible" ? managedConfig.model : undefined;
97
+ const creating = !options.database || !!options.create;
98
+ const environment = options.environment ?? process.env;
99
+ let compatibleKey = compatible && creating ? resolveCompatibleCredential(compatible, environment) : undefined;
85
100
  const providerModel = managedConfig?.model.protocol === "openrouter" ? managedConfig.model : undefined;
86
101
  const apiKey = providerModel ? (useLegacyCredential ? options.provider!.apiKey : resolveCredential(providerModel, options.environment ?? process.env)) : undefined;
87
102
  if (providerModel && !apiKey) throw new Error(`config.model.apiKeyEnv: environment variable ${providerModel.apiKeyEnv} is missing or empty`);
88
103
  const script = scriptPath ? await loadScenario(scriptPath) : undefined;
89
- if (!script && !providerModel) throw new Error("Development needs provider credentials or a script");
104
+ if (!script && !providerModel && !compatible) throw new Error("Development needs provider credentials or a script");
90
105
  const scriptedTools = script ? options.scriptedTools : undefined;
91
106
  const tools = [currentTimeDefinition, ...(scriptedTools?.tools ?? []),
92
107
  ...(options.debugTools ? debugToolDefinitions : []), notifyChannelDefinition];
93
- const compatibilityKey = script ? scriptedCompatibilityKey(script.modelDigest, systemPrompt)
94
- : createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name)])).digest("hex");
108
+ let imageInput = managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true && (managedConfig.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
109
+ const compatibilityKey = compatible ? compatibleInferenceKey(compatible, systemPrompt, tools.map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, systemPrompt + (managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true ? "\n[image-input-enabled]" : ""))
110
+ : createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name), ...(managedConfig?.model.protocol !== "openai-compatible" && managedConfig?.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
111
+ const tempMedia = sqlite ? undefined : mkdtempSync(join(tmpdir(), "harness-media-"));
112
+ const mediaRoot = options.database ? options.mediaRoot ?? `${options.database}.media` : join(tempMedia!, "media");
113
+ if (!sqlite) adapter = createMemoryStorageAdapter({ mediaRoot });
114
+ const makeWebTools = () => {
115
+ const result = createWebRegistry(managedConfig ?? {}, environment, { exa: options.webTransport ?? exaHttpsTransport, http: directWebFetch });
116
+ if (!result.ok) throw new Error(`${result.error.code}: ${result.error.message}`);
117
+ return result.value;
118
+ };
119
+ let webTools = creating ? makeWebTools() : undefined;
95
120
  const opened = adapter.open({ mode: options.database && !options.create ? "open" : "create",
96
121
  identity: { sessionId, compatibilityKey }, config: managedConfig, requiredScriptDigest: script?.modelDigest });
97
- if (!opened.ok) throw new Error(`Cannot open session storage (${opened.error.code}): ${opened.error.message}`);
122
+ if (!opened.ok) { if (tempMedia) rmSync(tempMedia, { recursive: true, force: true }); throw new Error(`Cannot open session storage (${opened.error.code}): ${opened.error.message}`); }
98
123
  const storage = opened.value;
99
- if (savedConfig) {
100
- const saved = storage.saveConfig(savedConfig);
101
- if (!saved.ok && saved.error.code !== "incompatible") { storage.close(); throw new Error(`Cannot save config: ${saved.error.message}`); }
102
- }
124
+ let mcp: Awaited<ReturnType<typeof openMcpRegistry>> | undefined;
125
+ let attachments: ReturnType<typeof createManagedAttachmentService> | undefined;
126
+ try {
127
+ const execution = storage.executionCompatible();
128
+ if (!execution.ok) throw new Error(execution.error.message);
129
+ if (!execution.value) imageInput = false;
130
+ else {
131
+ if (!creating) { if (compatible) compatibleKey = resolveCompatibleCredential(compatible, environment); webTools = makeWebTools(); }
132
+ if (managedConfig?.mcpServers) mcp = await openMcpRegistry(managedConfig, environment);
133
+ attachments = createManagedAttachmentService(mediaRoot, storage, validateManagedImage);
134
+ }
135
+ if (savedConfig) {
136
+ const saved = storage.saveConfig(savedConfig);
137
+ if (!saved.ok && saved.error.code !== "incompatible") throw new Error(`Cannot save config: ${saved.error.message}`);
138
+ }
103
139
 
104
- const inspection = createInspection(systemPrompt, tools, storage, options.database ?? "memory");
105
- const captureScript = (options.environment ?? process.env).HARNESS_CAPTURE_SCRIPT_REQUESTS === "1";
106
- const session: PersistentSession = createSession({
107
- systemPrompt, storage, config: managedConfig, captureContext: (!script || captureScript) ? inspection.capture : undefined,
108
- observeModelCall: inspection.modelCall,
109
- configureTurn(turn) {
110
- const model = observeModel(inspection, turn.channelId, onRequest => {
111
- if (script) return async () => { throw new Error("Scripted model requires a reserved attempt"); };
112
- const provider = (options.providerFactory ?? openRouter)(apiKey!, providerModel!.model, onRequest);
113
- return provider;
114
- }, turn.turnId);
115
- if (script) {
116
- bindModelAttempt(model, { scripted: true, create: step => {
117
- const next = scenarioAttempt(script, turn.channelId, step!);
118
- return async function* (request, signal) {
119
- if (captureScript)
120
- inspection.request(turn.channelId, JSON.stringify(request), turn.turnId);
121
- for await (const event of next(request, signal)) { if (event.type === "response") inspection.response(turn.channelId, event.response); yield event; }
122
- };
140
+ let session: PersistentSession;
141
+ const inspection = createInspection(systemPrompt, [...tools, ...(webTools ?? []).map(value => value.definition),
142
+ ...[...(mcp?.bindings.values() ?? [])].map(value => value.definition)], storage, options.database ?? "memory",
143
+ turnId => session.tools?.invocations(turnId) ?? []);
144
+ const captureScript = (options.environment ?? process.env).HARNESS_CAPTURE_SCRIPT_REQUESTS === "1";
145
+ session = createSession({
146
+ systemPrompt, storage, config: managedConfig, imageInput, webTools, mcpTools: mcp?.bindings, captureContext: (!script || captureScript) ? inspection.capture : undefined,
147
+ observeModelCall: inspection.modelCall,
148
+ configureTurn(turn) {
149
+ const model = observeModel(inspection, turn.channelId, onRequest => {
150
+ if (script || compatible) return async () => { throw new Error("Model requires a reserved attempt"); };
151
+ const provider = (options.providerFactory ?? openRouter)(apiKey!, providerModel!.model, onRequest);
152
+ return provider;
153
+ }, turn.turnId);
154
+ if (script) {
155
+ bindModelAttempt(model, { scripted: true, create: step => {
156
+ const next = scenarioAttempt(script, turn.channelId, step!);
157
+ return async function* (request, signal) {
158
+ if (captureScript)
159
+ inspection.request(turn.channelId, JSON.stringify(request), turn.turnId);
160
+ for await (const event of next(request, signal)) { if (event.type === "response") inspection.response(turn.channelId, event.response); yield event; }
161
+ };
162
+ } });
163
+ } else if (compatible) {
164
+ bindModelAttempt(model, { scripted: false, create: () => openAICompatibleAttempt(compatible.baseUrl, compatible.model, compatibleKey, fetch,
165
+ body => inspection.request(turn.channelId, body, turn.turnId), attachments ? id => {
166
+ const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
167
+ } : undefined) });
168
+ } else if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => {
169
+ const next = openRouterAttempt(apiKey!, providerModel!.model, fetch, body => inspection.request(turn.channelId, body, turn.turnId),
170
+ attachments ? { supported: imageInput, metadata(id) { const result = storage.readManagedAttachment(id); return result.ok ? result.value?.metadata : undefined; },
171
+ read(metadata) { return attachments!.readForInference(turn.channelId, metadata.id); },
172
+ verify(metadata, signal) { return attachments!.verifyForInference(turn.channelId, metadata.id, signal); } } : undefined);
173
+ return async function* (request, signal) { for await (const event of next(request, signal)) { if (event.type === "response") inspection.response(turn.channelId, event.response); yield event; } };
123
174
  } });
124
- } else if (!options.providerFactory) bindModelAttempt(model, { scripted: false, create: () => {
125
- const next = openRouterAttempt(apiKey!, providerModel!.model, fetch, body => inspection.request(turn.channelId, body, turn.turnId));
126
- return async function* (request, signal) { for await (const event of next(request, signal)) { if (event.type === "response") inspection.response(turn.channelId, event.response); yield event; } };
127
- } });
128
- return { model, tools, executeTool: (call, signal) => {
129
- const debug = options.debugTools ? debugToolHandlers.get(call.name) : undefined;
130
- if (debug) return debug(call, signal);
131
- return call.name === currentTimeDefinition.name || !scriptedTools
132
- ? executeCurrentTime(call, signal) : scriptedTools.executeTool(call, signal);
133
- } };
134
- },
135
- });
136
- const observed = observeSession(session, inspection);
137
- const stop = session.stop;
138
- session.stop = reason => { const result = stop(reason); inspection.stopped(); return result; };
139
- return {
140
- session, inspection, storage: options.database ?? "memory",
141
- /** The session as local clients use it: acceptance also refreshes the inspector. */
142
- local: { agent: observed.agent, subscribe: session.subscribe },
143
- close() { session.reminders?.releaseTimer(); observed.stop(); const closed = storage.close(); if (!closed.ok) throw new Error(`Cannot close session storage (${closed.error.code}): ${closed.error.message}`); },
144
- };
175
+ return { model, tools, executeTool: (call, signal) => {
176
+ const debug = options.debugTools ? debugToolHandlers.get(call.name) : undefined;
177
+ if (debug) return debug(call, signal);
178
+ return call.name === currentTimeDefinition.name || !scriptedTools
179
+ ? executeCurrentTime(call, signal) : scriptedTools.executeTool(call, signal);
180
+ } };
181
+ },
182
+ });
183
+ const observed = observeSession(session, inspection);
184
+ const stop = session.stop;
185
+ session.stop = reason => { const result = stop(reason); inspection.stopped(); return result; };
186
+ return {
187
+ session, inspection, attachments, imageInput, storage: options.database ?? "memory",
188
+ /** The session as local clients use it: acceptance also refreshes the inspector. */
189
+ local: { agent: observed.agent, subscribe: session.subscribe },
190
+ async close() { if (mcp) await mcp.close(); session.reminders?.releaseTimer(); observed.stop(); attachments?.close(); const closed = storage.close(); if (tempMedia) rmSync(tempMedia, { recursive: true, force: true }); if (!closed.ok) throw new Error(`Cannot close session storage (${closed.error.code}): ${closed.error.message}`); },
191
+ };
192
+ } catch (error) {
193
+ const rollback = [() => mcp?.close(), () => attachments?.close(), () => storage.close(),
194
+ () => { if (tempMedia) rmSync(tempMedia, { recursive: true, force: true }); }];
195
+ for (const cleanup of rollback) {
196
+ try { await cleanup(); } catch { /* Preserve the original startup failure. */ }
197
+ }
198
+ throw error;
199
+ }
145
200
  }
@@ -7,7 +7,7 @@ import { join } from "node:path";
7
7
  * HARNESS_TEST_* settings support deterministic offline process tests. */
8
8
  export async function serve(home?: string) {
9
9
  const { server } = createScriptedServer({ home: home ?? join(homedir(), ".harness"), fault: process.env.HARNESS_TEST_FAULT, effects: process.env.HARNESS_TEST_EFFECTS,
10
- requests: process.env.HARNESS_TEST_REQUESTS, attempts: process.env.HARNESS_TEST_ATTEMPTS, snapshotLog: process.env.HARNESS_TEST_SNAPSHOT_LOG, stallChannel: process.env.HARNESS_TEST_STALL_CHANNEL,
10
+ requests: process.env.HARNESS_TEST_REQUESTS, attempts: process.env.HARNESS_TEST_ATTEMPTS, snapshotLog: process.env.HARNESS_TEST_SNAPSHOT_LOG, stallChannel: process.env.HARNESS_TEST_STALL_CHANNEL, providerEndpoint: process.env.HARNESS_TEST_PROVIDER_ENDPOINT, webEndpoint: process.env.HARNESS_TEST_WEB_ENDPOINT,
11
11
  streamResponses: process.env.HARNESS_TEST_STREAM_RESPONSES === "1",
12
12
  reminderTime: process.env.HARNESS_TEST_REMINDER_TIME === undefined ? undefined : Number(process.env.HARNESS_TEST_REMINDER_TIME),
13
13
  modelTimeoutMs: process.env.HARNESS_TEST_MODEL_TIMEOUT_MS === undefined ? undefined : Number(process.env.HARNESS_TEST_MODEL_TIMEOUT_MS) });
@@ -16,6 +16,6 @@ export async function serve(home?: string) {
16
16
  output.write(bytes);
17
17
  await output.flush();
18
18
  });
19
- server.dispose();
19
+ await server.dispose();
20
20
  await output.end();
21
21
  }
@@ -48,7 +48,7 @@ export async function start(options: StartOptions = {}) {
48
48
  inspectorPort: Number(process.env.HARNESS_INSPECTOR_PORT ?? 3000), webChatPort: Number(process.env.HARNESS_CHAT_PORT ?? 3001) } : agentConfiguration();
49
49
  if (config.managedDirectory) await mkdir(config.managedDirectory, { recursive: true, mode: 0o700 });
50
50
  if (managed && create) await mkdir(managed.directory, { recursive: true, mode: 0o700 });
51
- const development = await openDevelopment({ systemPrompt, database, sessionId, create, script, managedConfig, instructions,
51
+ const development = await openDevelopment({ systemPrompt, database, ...(managed ? { mediaRoot: join(managed.directory, "media") } : {}), sessionId, create, script, managedConfig, instructions,
52
52
  debugTools: options.debug || options.debugTools,
53
53
  timelineTools: options.timelineTools,
54
54
  debugInstructions: options.debug && instructions === undefined ? loadInstructions("agent-demo") : undefined,
@@ -70,14 +70,14 @@ export async function start(options: StartOptions = {}) {
70
70
  inspector = bindWebPort(port, "HARNESS_INSPECTOR_PORT", chosen => serveInspector(inspection, chosen));
71
71
  // Lifecycle control stays on the owner's Unix socket; the LAN chat gets messages only.
72
72
  const handleChat = createChannelHandler(local, outputs);
73
- webChat = bindWebPort(config.webChatPort, "HARNESS_CHAT_PORT", chosen => serveWebChat(handleChat, chosen));
73
+ webChat = bindWebPort(config.webChatPort, "HARNESS_CHAT_PORT", chosen => serveWebChat(handleChat, chosen, undefined,
74
+ { attachments: development.attachments, ensureChannel(id) { const result = session.channels.create({ channelId: id }); if (!result.ok) throw new Error(result.error.message); } }));
74
75
  } catch (error) {
75
76
  // Startup is all-or-nothing: do not leave an agent listening if the inspector
76
77
  // could not bind its port and the command reports a startup failure.
77
- stopOutput();
78
- await server?.stop(true);
79
- await inspector?.stop(true);
80
- development.close();
78
+ for (const cleanup of [stopOutput, () => server?.stop(true), () => inspector?.stop(true), () => development.close()]) {
79
+ try { await cleanup(); } catch { /* Preserve the original startup failure. */ }
80
+ }
81
81
  throw error;
82
82
  }
83
83
  const status = session.status();
@@ -95,12 +95,21 @@ export async function start(options: StartOptions = {}) {
95
95
  session.start();
96
96
  }
97
97
  console.log("Ctrl+C stops the agent: running turns are recorded as interrupted. Run `bun run suspend` first to pause cleanly.");
98
- const stop = () => {
98
+ let stopping: Promise<void> | undefined;
99
+ const stop = () => stopping ??= (async () => {
99
100
  // Stop is immediate and is not suspension; a cleanly suspended session keeps its checkpoints.
100
- session.stop("Agent process stopped");
101
- stopOutput(); server?.stop(true); inspector?.stop(true); webChat.server.stop(true);
102
- development.close();
103
- };
104
- process.once("SIGINT", stop);
105
- process.once("SIGTERM", stop);
101
+ try {
102
+ session.stop("Agent process stopped");
103
+ stopOutput();
104
+ await Promise.allSettled([server?.stop(true), inspector?.stop(true), webChat.server.stop(true)]);
105
+ } finally {
106
+ await development.close();
107
+ }
108
+ })();
109
+ const onSignal = () => { void stop().catch(() => {
110
+ console.error("Failed to close the development session.");
111
+ process.exitCode = 1;
112
+ }); };
113
+ process.once("SIGINT", onSignal);
114
+ process.once("SIGTERM", onSignal);
106
115
  }
@@ -19,7 +19,7 @@ export type ResultReader = (read: ResultRead) => Promise<ResultPage> | ResultPag
19
19
  type Calls = Methods & DurableMethods;
20
20
 
21
21
  export class HarnessClientError extends Error {
22
- constructor(public readonly code: string, message: string) { super(message); this.name = "HarnessClientError"; }
22
+ constructor(public readonly code: string, message: string, public readonly expectedOffset?: number) { super(message); this.name = "HarnessClientError"; }
23
23
  }
24
24
 
25
25
  /**
@@ -52,7 +52,7 @@ export class HarnessClient {
52
52
  if (message.id === null) return;
53
53
  const waiting = this.waiting.get(message.id);
54
54
  if (!waiting) return;
55
- if ("error" in message) waiting.reject(new HarnessClientError(message.error.data.code, message.error.message));
55
+ if ("error" in message) waiting.reject(new HarnessClientError(message.error.data.code, message.error.message, message.error.data.expectedOffset));
56
56
  else waiting.resolve(message.result);
57
57
  }
58
58
  });
@@ -129,6 +129,12 @@ export class HarnessClient {
129
129
  return this.request("initialize", params);
130
130
  }
131
131
  createSession(params: CreateParams) { return this.request("session/create", params); }
132
+ beginAttachment(params: Calls["attachment/begin"]["params"]) { return this.request("attachment/begin", params); }
133
+ attachmentStatus(params: Calls["attachment/status"]["params"]) { return this.request("attachment/status", params); }
134
+ writeAttachment(params: Calls["attachment/write"]["params"]) { return this.request("attachment/write", params); }
135
+ finalizeAttachment(params: Calls["attachment/finalize"]["params"]) { return this.request("attachment/finalize", params); }
136
+ abortAttachment(params: Calls["attachment/abort"]["params"]) { return this.request("attachment/abort", params); }
137
+ readAttachment(params: Calls["attachment/read"]["params"]) { return this.request("attachment/read", params); }
132
138
  /** Decision 0021. Serve `functions/call` requests. Set before `initialize`
133
139
  * advertises handler names. One handler routes by `call.handler`. */
134
140
  serveFunctions(handler: FunctionHandler, reader?: ResultReader) { this.functionHandler = handler; this.resultReader = reader; }
@@ -187,7 +187,7 @@
187
187
  loadCalls.disabled = true;
188
188
  try {
189
189
  const data = await endpoint('/calls?id=' + encodeURIComponent(id));
190
- if (version === viewVersion) { callDetails = { id, modelCalls: data.modelCalls }; fetchError = ''; }
190
+ if (version === viewVersion) { callDetails = { id, modelCalls: data.modelCalls, webUsage: data.webUsage }; fetchError = ''; }
191
191
  } catch (error) { if (version === viewVersion) fetchError = String(error); }
192
192
  finally { if (version === viewVersion) render(); }
193
193
  };
@@ -206,6 +206,12 @@
206
206
  for (const [turnId, requests] of turns) {
207
207
  main.append(node('h2', turnId === 'unknown' ? 'New turn' : 'Turn ' + turnId, 'turn-divider'));
208
208
  const calls = modelCalls.filter(call => call.turnId === String(turnId));
209
+ const webUsage = callDetails?.id === selected ? (callDetails.webUsage ?? []).filter(value => value.turnId === String(turnId)) : [];
210
+ for (const usage of webUsage) {
211
+ const details = node('details'); details.dataset.key = channel.id + ':web-usage:' + usage.invocationId;
212
+ details.open = expanded.has(details.dataset.key);
213
+ details.append(node('summary', 'Web usage · ' + usage.tool), json(usage.webUsage)); main.append(details);
214
+ }
209
215
  for (const call of calls) {
210
216
  const details = node('details');
211
217
  details.dataset.key = channel.id + ':model-call:' + call.callId;
@@ -24,7 +24,8 @@ function read<T>(result: StorageResult<T>) {
24
24
  /** Capture state is process-local. A notification marks the requested view
25
25
  * dirty. Only HTTP reads request data from storage. */
26
26
  export function createInspection(systemPrompt: string, tools: readonly ToolDefinition[],
27
- reads: InspectionStorageReads, storage: string) {
27
+ reads: InspectionStorageReads, storage: string,
28
+ webInvocations?: (turnId: number) => import("../../contracts/tools.ts").ToolInvocation[]) {
28
29
  const instructions = composeSystemPrompt(systemPrompt);
29
30
  const captures = new Map<string, { turnId: number; metadata: NonNullable<InspectedInference["context"]> }>();
30
31
  const channels = new Map<string, InspectedInference[]>();
@@ -55,7 +56,10 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
55
56
  modelCalls(id: string) {
56
57
  const result = reads.readInspectionCalls(id);
57
58
  if (!result.ok) throw new Error(result.error.message);
58
- return { modelCalls: result.value };
59
+ const turns = [...new Set(result.value.map(call => Number(call.turnId)))];
60
+ const webUsage = turns.flatMap(turnId => webInvocations?.(turnId) ?? []).filter(value => value.webUsage)
61
+ .map(({ invocationId, turnId, tool, webUsage }) => ({ invocationId, turnId, tool, webUsage }));
62
+ return { modelCalls: result.value, webUsage };
59
63
  },
60
64
  subscribe(listener: () => void) {
61
65
  listeners.add(listener);
@@ -1,6 +1,7 @@
1
1
  import type { ItemStatus, LoadResult, StatusResult, StoredMessage, TurnStatus } from "../../contracts/protocol.ts";
2
2
  import type { SessionStatus } from "../../contracts/session.ts";
3
3
  import type { StorageSnapshot, StoredTurn } from "../../contracts/storage.ts";
4
+ import { parseAttachmentFailure } from "../../contracts/attachments.ts";
4
5
  import { MAX_FRAME_BYTES } from "./framing.ts";
5
6
 
6
7
  /** Room left in a frame for the JSON-RPC envelope around a result. */
@@ -11,7 +12,8 @@ export class FrameLimit extends Error {}
11
12
  export function turnStatus(turn: StoredTurn): TurnStatus {
12
13
  const state = turn.state;
13
14
  return { turnId: String(turn.turnId), channel: turn.channelId, items: turn.itemIds, state: state.status,
14
- ...(state.status === "failed" || state.status === "interrupted" ? { reason: state.reason, uncertainCalls: state.uncertainCallIds } : {}) };
15
+ ...(state.status === "failed" || state.status === "interrupted" ? { reason: state.reason, uncertainCalls: state.uncertainCallIds,
16
+ ...(parseAttachmentFailure(state.reason) ? { attachmentFailure: parseAttachmentFailure(state.reason) } : {}) } : {}) };
15
17
  }
16
18
 
17
19
  export function wireStatus(status: SessionStatus, view: Pick<StorageSnapshot, "turns">): StatusResult {