@qlairoslabs/acp-client 0.13.3-alpha.1 → 0.13.5-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.
package/CONSUMER_GUIDE.md CHANGED
@@ -1172,7 +1172,7 @@ import { Agent, ADAPTERS, type AgentHarnessConfig } from "@qlairoslabs/acp-clien
1172
1172
  export async function openNative(
1173
1173
  directory: string,
1174
1174
  model: AgentHarnessConfig["config"]["model"] = {
1175
- protocol: "openrouter", model: "openai/gpt-4.1-mini", apiKeyEnv: "OPENROUTER_API_KEY",
1175
+ protocol: "openrouter", model: "openai/gpt-6-luna", apiKeyEnv: "OPENROUTER_API_KEY",
1176
1176
  },
1177
1177
  ) {
1178
1178
  return Agent.open({
@@ -1209,15 +1209,44 @@ and passed through unchanged on every open. Besides `scripted` and `openrouter`,
1209
1209
  Completions endpoint chosen by the consumer. `baseUrl` is HTTPS or a literal loopback address over HTTP (`127.x` or `::1`,
1210
1210
  not `localhost`) with no credentials, query or fragment; the harness appends the Chat Completions path and follows no
1211
1211
  redirects; `apiKeyEnv` names a variable in the harness's environment, is optional for keyless endpoints and is read only
1212
- when the session opens. The library accepts and forwards this arm today (compile-time and open-request tests); the harness
1213
- runtime that executes it is still being implemented, so an open with this arm is not yet usable end to end. For an offline
1214
- equivalent, pass `{ protocol: "scripted", script: "/path/to/scenario.jsonl" }`
1212
+ when the session opens. For an offline equivalent, pass
1213
+ `{ protocol: "scripted", script: "/path/to/scenario.jsonl" }`
1215
1214
  as the second argument. Function parameters are JSON Schema. Functions return
1216
1215
  JSON values and receive a context with invocation identity and an abort signal.
1217
1216
  Harness policies grant `allow`, `ask` or `deny` by tool name and define a
1218
1217
  fallback. This host responder grants one call to the read-only lookup.
1219
1218
  Subscribe to `items_receipt` when you need delivery evidence.
1220
1219
 
1220
+ To use an OpenCode Go API key with the native harness, make the key
1221
+ available in the harness process and pass the Go preset to `openNative`.
1222
+
1223
+ ```ts
1224
+ const agent = await openNative(directory, {
1225
+ protocol: "opencode-go",
1226
+ model: "deepseek-v4.1-flash",
1227
+ });
1228
+ ```
1229
+
1230
+ The harness reads `OPENCODE_API_KEY` by default. Set `apiKeyEnv` if your
1231
+ launcher supplies a different variable, such as `OPENCODE_GO_API_KEY`.
1232
+ The preset sends a stable routing header per channel and uses Go's Chat
1233
+ Completions endpoint. DeepSeek V4.1 Flash may require allowing the Global
1234
+ region in the Go workspace. [OpenCode Go model settings](https://opencode.ai/docs/console/go/#enable-restricted-models)
1235
+
1236
+ Set `harness.config.model.contextBudget` on OpenRouter, OpenCode Go or OpenAI-compatible models
1237
+ to fit a larger inference request. For example, a model with a 128,000-token
1238
+ window can use `contextBudget: { contextWindowTokens: 128_000, outputReserveTokens: 4096 }`.
1239
+ The reserve only affects local fitting. Set `maxOutputTokens` to also request an
1240
+ upstream cap. This uses `max_tokens` with OpenRouter and
1241
+ `max_completion_tokens` with a custom Chat Completions endpoint that supports it.
1242
+ The estimate uses UTF-8 request size for text and a separate image allowance.
1243
+ Use `estimationMarginTokens` to leave extra room. The independent serialized
1244
+ request cap defaults to 64 MiB and can be lowered with `maxRequestBytes`.
1245
+ The harness fits optional history around the complete policy-filtered offer.
1246
+ A failed turn reports `context_limit` and leaves the channel usable. The
1247
+ underlying `NativeTurnError.contextFailure` gives the applicable limit and,
1248
+ for local token and byte limits, the measured budget.
1249
+
1221
1250
  ```ts
1222
1251
  import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
1223
1252
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.13.3-alpha.1",
3
+ "version": "0.13.5-alpha.1",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -42,7 +42,8 @@ import type { ChannelPort, ChannelView, NativeHarnessHost } from "./host.ts";
42
42
  export class NativeTurnError extends Error {
43
43
  /** Tool calls recorded with no recorded result. The harness never replays them; neither does the host. */
44
44
  readonly uncertainCalls: readonly string[];
45
- constructor(readonly outcome: "failed" | "interrupted", message: string, uncertainCalls: readonly string[] = []) {
45
+ constructor(readonly outcome: "failed" | "interrupted", message: string, uncertainCalls: readonly string[] = [],
46
+ readonly contextFailure?: TurnStatus["contextFailure"]) {
46
47
  super(message);
47
48
  this.name = "NativeTurnError";
48
49
  this.uncertainCalls = uncertainCalls;
@@ -360,6 +361,7 @@ export class NativeController implements ConversationController, ChannelPort {
360
361
  if (status.state === "running" || status.state === "suspended") return;
361
362
  this.#accept(turn, { type: "turn_ended", turnId: status.turnId, outcome: status.state,
362
363
  ...(status.reason === undefined ? {} : { error: status.reason }),
364
+ ...(status.contextFailure ? { contextFailure: status.contextFailure } : {}),
363
365
  ...(status.uncertainCalls?.length ? { uncertainCalls: status.uncertainCalls } : {}) });
364
366
  };
365
367
 
@@ -503,7 +505,8 @@ export class NativeController implements ConversationController, ChannelPort {
503
505
  cancelled(true);
504
506
  } else {
505
507
  const reason = event.error ?? event.outcome;
506
- finish(() => reject(new NativeTurnError(event.outcome as "failed" | "interrupted", `native turn ${turn.harnessId} ${event.outcome}: ${reason}`, event.uncertainCalls)), true);
508
+ finish(() => reject(new NativeTurnError(event.outcome as "failed" | "interrupted", `native turn ${turn.harnessId} ${event.outcome}: ${reason}`,
509
+ event.uncertainCalls, event.contextFailure)), true);
507
510
  }
508
511
  return;
509
512
  }
@@ -1,45 +1,32 @@
1
1
  import { createHash } from "node:crypto";
2
- import { ATTACHMENT_LIMITS, type AttachmentMetadata, type InputPart } from "../../contracts/attachments.ts";
2
+ import type { AttachmentMetadata, InputPart } from "../../contracts/attachments.ts";
3
3
 
4
4
  export class VisionInputError extends Error {
5
5
  constructor(readonly code: "unsupported_image" | "attachment_unavailable" | "transfer_limit", message: string,
6
6
  readonly attachmentIds: readonly string[] = []) { super(message); }
7
7
  }
8
8
 
9
- /** Resolved bytes are ephemeral and must never be passed to capture/log hooks.
10
- * Caller supplies only active-turn parts. A failed projection returns no partial
11
- * request, and reports all unavailable image references in input order. */
12
- export function projectVisionParts(parts: readonly InputPart[], options: { supported: boolean;
13
- metadata: (id: string) => AttachmentMetadata | undefined;
14
- read: (metadata: AttachmentMetadata) => Uint8Array;
15
- }) {
16
- const resolved: Array<{ part: InputPart; metadata?: AttachmentMetadata; bytes?: Uint8Array }> = [];
17
- const unavailable = new Set<string>();
18
- let total = 0, hasImage = false;
19
- for (const part of parts) {
20
- if (part.type === "text") { resolved.push({ part }); continue; }
21
- const metadata = options.metadata(part.id);
22
- if (!metadata) { unavailable.add(part.id); continue; }
23
- if (!metadata.mediaType.startsWith("image/")) { resolved.push({ part, metadata }); continue; }
24
- hasImage = true;
25
- total += metadata.bytes;
26
- resolved.push({ part, metadata });
27
- }
28
- if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
29
- if (hasImage && !options.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input");
30
- if (total > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
31
- for (const entry of resolved) if (entry.metadata?.mediaType.startsWith("image/")) {
32
- try {
33
- const bytes = options.read(entry.metadata);
34
- if (bytes.length !== entry.metadata.bytes || createHash("sha256").update(bytes).digest("hex") !== entry.metadata.sha256)
35
- throw new Error("Integrity failure");
36
- entry.bytes = bytes;
37
- } catch { unavailable.add(entry.metadata.id); }
38
- }
39
- if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [...unavailable]);
40
- return resolved.map(entry => {
41
- if (entry.part.type === "text") return { type: "text" as const, text: entry.part.text };
42
- if (!entry.bytes) return { type: "text" as const, text: `[Attachment ${entry.metadata!.id}: ${entry.metadata!.filename}, ${entry.metadata!.mediaType}, ${entry.metadata!.bytes} bytes]` };
43
- return { type: "image_url" as const, image_url: { url: `data:${entry.metadata!.mediaType};base64,${Buffer.from(entry.bytes).toString("base64")}` } };
9
+ export type AttachmentLookup = (id: string) => AttachmentMetadata | undefined;
10
+
11
+ export function imageDataPrefix(mediaType: string) { return `data:${mediaType};base64,`; }
12
+
13
+ /** Both sizing and dispatch use this projection. Only dispatch supplies URLs
14
+ * backed by verified bytes. An absent reference is useful only in the estimate. */
15
+ export function projectVisionParts(parts: readonly InputPart[], metadata: AttachmentLookup,
16
+ imageUrl?: (metadata: AttachmentMetadata) => string) {
17
+ return parts.map(part => {
18
+ if (part.type === "text") return { type: "text" as const, text: part.text };
19
+ const reference = metadata(part.id);
20
+ if (!reference) return { type: "text" as const, text: `[Attachment ${part.id}: unavailable]` };
21
+ if (reference.mediaType.startsWith("image/") && imageUrl)
22
+ return { type: "image_url" as const, image_url: { url: imageUrl(reference) } };
23
+ return { type: "text" as const, text: `[Attachment ${reference.id}: ${reference.filename}, ${reference.mediaType}, ${reference.bytes} bytes]` };
44
24
  });
45
25
  }
26
+
27
+ export function readVerifiedImage(metadata: AttachmentMetadata, read: (metadata: AttachmentMetadata) => Uint8Array) {
28
+ const bytes = read(metadata);
29
+ if (bytes.length !== metadata.bytes || createHash("sha256").update(bytes).digest("hex") !== metadata.sha256)
30
+ throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [metadata.id]);
31
+ return bytes;
32
+ }
@@ -1,6 +1,7 @@
1
1
  import { SESSION_INTAKE_LIMITS } from "../../util/intake.ts";
2
2
  import { isTimelineTool } from "../../util/timeline-tool-names.ts";
3
- import type { ContextLimits, InferenceContext, InferenceStorageReads, ContextBuildResult, ContextCapture, ContextTurnOutcome } from "../../contracts/context.ts";
3
+ import type { ContextLimits, InferenceContext, InferenceStorageReads, ContextBuildResult, ContextCapture, ContextTurnOutcome, ContextRequestSizer, ContextLimitFailure } from "../../contracts/context.ts";
4
+ import { exceededContextBudget } from "../../util/context-budget.ts";
4
5
  import { SESSION_INPUT_MAX_BYTES } from "../../contracts/input-limits.ts";
5
6
  import type { ToolDefinition } from "../../contracts/loop.ts";
6
7
  import type { TimelineEntry } from "../../contracts/storage.ts";
@@ -19,22 +20,24 @@ type Offer = { tools: ToolDefinition[]; fixedToolCount?: number };
19
20
  /** One builder per session. Each inference independently captures a committed
20
21
  * read and a tool offer. The runner reuses the resulting request on retry. */
21
22
  export function createSessionContext(storage: InferenceStorageReads, sessionId: string, systemPrompt: string,
22
- limits = CONTEXT_LIMITS, capture?: (value: ContextCapture) => void) {
23
+ limits = CONTEXT_LIMITS, capture?: (value: ContextCapture) => void, sizeRequest?: ContextRequestSizer) {
23
24
  const budget = limits.contextTokens - limits.outputReserveTokens - limits.estimationMarginTokens;
24
25
  if (budget <= 0 || limits.maxInputBytes > limits.maxTakenTextBytes || limits.maxTakenItems < 1)
25
26
  throw new Error("Invalid context budget");
26
27
  const instructions = composeSystemPrompt(systemPrompt);
27
28
  return {
28
29
  build(turn: { channelId: string; turnId: number }, offerTools: (policies: readonly string[]) => Offer): ContextBuildResult {
29
- const overflow = { ok: false, code: "context_limit", message: "Required inference material exceeds the context budget" } as const;
30
+ const overflow = (detail?: ContextLimitFailure) => ({ ok: false, code: "context_limit",
31
+ message: "Required inference material exceeds the context budget", ...(detail ? { detail } : {}) } as const);
30
32
  const read = storage.readInferenceContext({ ...turn, limits });
31
33
  if (!read.ok) throw new Error(read.error.message);
32
- if ("code" in read.value) return overflow;
34
+ if ("code" in read.value) return overflow(sizeRequest ? { limit: "required_storage" } : undefined);
33
35
  const { required, optionalTurn, localHistory, sharedHistory, unfinished, policyNames, takenItemIds } = read.value;
34
36
  const toolOffer = offerTools(policyNames);
35
37
  const active = [...required], local: TimelineEntry[] = [], shared: TimelineEntry[] = [];
36
38
  const groups: TimelineEntry[][] = [];
37
39
  const retrievalCalls = new Set<string>();
40
+ const requiredResults = new Set(sizeRequest ? required.flatMap(row => row.message.role === "tool" ? [row.message.callId] : []) : []);
38
41
  let exchange: TimelineEntry[] | undefined;
39
42
  for (const row of optionalTurn) {
40
43
  if (row.message.role === "assistant") {
@@ -46,31 +49,46 @@ export function createSessionContext(storage: InferenceStorageReads, sessionId:
46
49
  }
47
50
  const outcomes: ContextTurnOutcome[] = [];
48
51
  const render = () => buildContext([...local, ...shared, ...active].sort(order), instructions, turn, outcomes)
49
- .map(message => message.role === "tool" && !retrievalCalls.has(message.callId) && Buffer.byteLength(message.content, "utf8") > 2048
52
+ .map(message => message.role === "tool" && !requiredResults.has(message.callId) && !retrievalCalls.has(message.callId) && Buffer.byteLength(message.content, "utf8") > 2048
50
53
  ? { ...message, content: Buffer.from(message.content).subarray(0, 2048).toString("utf8") + "\n[Tool result shortened]" }
51
54
  : message);
52
- const size = () => bytes({ messages: render(), tools: toolOffer.tools });
53
- if (size() > budget) return overflow;
55
+ const measure = sizeRequest?.(toolOffer.tools);
56
+ const legacyToolBytes = measure ? 0 : bytes(toolOffer.tools) + 22; // {"messages":…,"tools":…}
57
+ const requiredMessages = render();
58
+ const requiredBudget = measure?.(requiredMessages);
59
+ if (requiredBudget) {
60
+ const failure = exceededContextBudget(requiredBudget);
61
+ if (failure) return overflow(failure);
62
+ } else if (legacyToolBytes + bytes(requiredMessages) > budget) return overflow();
63
+
64
+ // Use the tightest remaining resource when dividing optional history.
65
+ const ceiling = requiredBudget?.inputBudgetTokens ?? budget;
66
+ const size = () => {
67
+ const messages = render();
68
+ const measured = measure?.(messages);
69
+ return measured ? Math.max(measured.estimatedInputTokens, Math.ceil(measured.requestBytes / measured.maxRequestBytes * ceiling))
70
+ : legacyToolBytes + bytes(messages);
71
+ };
54
72
  for (const group of groups.reverse()) {
55
73
  active.push(...group);
56
- if (size() > budget) active.length -= group.length;
74
+ if (size() > ceiling) active.length -= group.length;
57
75
  }
58
76
  for (const outcome of unfinished) {
59
77
  outcomes.push(outcome);
60
- if (size() > budget) outcomes.pop();
78
+ if (size() > ceiling) outcomes.pop();
61
79
  }
62
- const available = budget - size();
63
- function fill(rows: TimelineEntry[], candidates: readonly TimelineEntry[], ceiling: number) {
80
+ const available = ceiling - size();
81
+ function fill(rows: TimelineEntry[], candidates: readonly TimelineEntry[], limit: number) {
64
82
  const deferred: TimelineEntry[] = [];
65
83
  for (const row of [...candidates].reverse()) {
66
84
  rows.push(row);
67
- if (size() > ceiling) { rows.pop(); deferred.push(row); }
85
+ if (size() > limit) { rows.pop(); deferred.push(row); }
68
86
  }
69
87
  return deferred;
70
88
  }
71
- const localDeferred = fill(local, localHistory, budget - Math.floor(available / 3));
72
- fill(shared, sharedHistory, budget);
73
- fill(local, localDeferred.reverse(), budget);
89
+ const localDeferred = fill(local, localHistory, ceiling - Math.floor(available / 3));
90
+ fill(shared, sharedHistory, ceiling);
91
+ fill(local, localDeferred.reverse(), ceiling);
74
92
  const value: InferenceContext = { sessionId, ...turn, timelineRevision: read.revision, messages: render(), ...toolOffer,
75
93
  representedItemIds: active.sort(order).flatMap(row => row.itemId === undefined ? [] : [row.itemId]), takenItemIds };
76
94
  // Diagnostics must not be able to mutate or prevent the provider request.
@@ -81,6 +99,7 @@ export function createSessionContext(storage: InferenceStorageReads, sessionId:
81
99
  const trimmed = [...optionalTurn, ...localHistory, ...sharedHistory].map(row => row.seq)
82
100
  .filter(seq => !kept.has(seq)).sort((a, b) => a - b);
83
101
  capture(structuredClone({ context: value, estimatedInputBytes: bytes({ messages: value.messages, tools: value.tools }),
102
+ ...(measure ? { budget: measure(value.messages) } : {}),
84
103
  records: { included, trimmed }, omitted: {
85
104
  active: optionalTurn.length + required.length - active.length,
86
105
  local: localHistory.length - local.length, shared: sharedHistory.length - shared.length,
@@ -0,0 +1,63 @@
1
+ import type { AttachmentMetadata } from "../../contracts/attachments.ts";
2
+ import type { ContextRequestSizer } from "../../contracts/context.ts";
3
+ import type { ModelContextBudget } from "../../contracts/config-permissions.ts";
4
+ import type { Message, ToolDefinition } from "../../contracts/loop.ts";
5
+ import { imageDataPrefix, projectVisionParts, type AttachmentLookup } from "../attachments/vision.ts";
6
+ import { effectiveContextBudget } from "../../util/context-budget.ts";
7
+
8
+ type ImageUrl = (metadata: AttachmentMetadata) => string;
9
+
10
+ function wireMessage(message: Message, compatible: boolean, metadata?: AttachmentLookup, imageUrl?: ImageUrl): unknown {
11
+ if (message.role === "assistant") return (compatible ? undefined : message.providerState) ?? { role: "assistant", content: message.content,
12
+ ...(message.calls.length ? { tool_calls: message.calls.map(c => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) } : {}) };
13
+ if (message.role === "tool") return { role: "tool", content: message.content, tool_call_id: message.callId };
14
+ if (message.role !== "user" || !message.parts || !metadata) return message;
15
+ const separator = message.content.indexOf("\n\n");
16
+ const attribution = message.content.startsWith("Participant: ") && separator >= 0 ? message.content.slice(0, separator + 2) : "";
17
+ const content = projectVisionParts(message.parts, metadata, imageUrl);
18
+ if (compatible) return { role: "user", content: attribution + content.map(part => part.type === "text" ? part.text : "").join("") };
19
+ return { role: "user", content: attribution ? [{ type: "text", text: attribution }, ...content] : content };
20
+ }
21
+
22
+ /** Render the fixed fields only once, so fitting optional history does not
23
+ * repeatedly serialize a large tool catalog. */
24
+ export function prepareChatRequest(model: string, compatible: boolean, tools: readonly ToolDefinition[], maxOutputTokens?: number) {
25
+ const fixed = JSON.stringify({ model, stream: true, stream_options: { include_usage: true },
26
+ ...(maxOutputTokens === undefined ? {} : compatible ? { max_completion_tokens: maxOutputTokens } : { max_tokens: maxOutputTokens }) });
27
+ const prefix = fixed.slice(0, -1) + ',"messages":';
28
+ const offer = tools.length ? JSON.stringify(tools.map(tool => ({ type: "function", function: tool }))) : "";
29
+ const suffix = (offer ? ',"tools":' + offer + (compatible ? ',"tool_choice":"auto"' : "") : "") + "}";
30
+ return {
31
+ messages: (messages: readonly Message[], metadata?: AttachmentLookup, imageUrl?: ImageUrl) =>
32
+ JSON.stringify(messages.map(message => wireMessage(message, compatible, metadata, imageUrl))),
33
+ fixedBytes: Buffer.byteLength(prefix) + Buffer.byteLength(suffix),
34
+ toolDefinitionBytes: Buffer.byteLength(offer),
35
+ body: (messages: string) => prefix + messages + suffix,
36
+ };
37
+ }
38
+
39
+ export function chatRequestSizer(model: string, compatible: boolean, profile: ModelContextBudget,
40
+ metadata?: AttachmentLookup): ContextRequestSizer {
41
+ const effective = effectiveContextBudget(profile);
42
+ return tools => {
43
+ const wire = prepareChatRequest(model, compatible, tools, profile.maxOutputTokens);
44
+ const known = new Map<string, AttachmentMetadata | undefined>();
45
+ const lookup = metadata && ((id: string) => {
46
+ if (!known.has(id)) known.set(id, metadata(id));
47
+ return known.get(id);
48
+ });
49
+ return messages => {
50
+ let imageBytes = 0, imageCount = 0;
51
+ const projected = wire.messages(messages, lookup, compatible ? undefined : image => {
52
+ imageCount += 1;
53
+ // The empty URL placeholder already contributes its JSON quotes.
54
+ imageBytes += Buffer.byteLength(JSON.stringify(imageDataPrefix(image.mediaType))) - 2 + 4 * Math.ceil(image.bytes / 3);
55
+ return "";
56
+ });
57
+ const textBytes = wire.fixedBytes + Buffer.byteLength(projected);
58
+ return { estimator: "chat-completions-utf8-v1", ...effective, toolDefinitionBytes: wire.toolDefinitionBytes,
59
+ estimatedInputTokens: textBytes + imageCount * 4096, requestBytes: textBytes + imageBytes };
60
+ };
61
+ };
62
+ }
63
+
@@ -1,68 +1,133 @@
1
1
  import type { ModelAttempt, ModelAttemptEvent } from "../../contracts/model-execution.ts";
2
- import type { Message } from "../../contracts/loop.ts";
3
- import { projectVisionParts, VisionInputError } from "../attachments/vision.ts";
4
- import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
5
2
  import { createHash } from "node:crypto";
3
+ import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/config-permissions.ts";
4
+ import { imageDataPrefix, readVerifiedImage, VisionInputError, type AttachmentLookup } from "../attachments/vision.ts";
5
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata } from "../../contracts/attachments.ts";
6
+ import { chatRequestSizer, prepareChatRequest } from "./chat-request.ts";
7
+ import { exceededContextBudget } from "../../util/context-budget.ts";
6
8
 
7
- function wireMessage(message: Message, preserveProviderState: boolean): unknown {
8
- if (message.role === "assistant") return (preserveProviderState ? message.providerState : undefined) ?? { role: "assistant", content: message.content,
9
- ...(message.calls.length ? { tool_calls: message.calls.map(c => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) } : {}) };
10
- return message.role === "tool" ? { role: "tool", content: message.content, tool_call_id: message.callId } : message;
9
+ const providerContextFailure = { type: "failure", kind: "invalid_request", message: "Provider rejected the request context length",
10
+ contextFailure: { limit: "provider_context" } } as const;
11
+
12
+ function isProviderContextError(value: unknown): boolean {
13
+ if (!value || typeof value !== "object" || !("error" in value) || !value.error || typeof value.error !== "object") return false;
14
+ const error = value.error;
15
+ if ("code" in error && ["context_length_exceeded", "context_window_exceeded", "max_context_length_exceeded"].includes(String(error.code))) return true;
16
+ return "message" in error && typeof error.message === "string" && /maximum context length|context window (?:has been |is )?exceeded/i.test(error.message);
11
17
  }
18
+
19
+ /** Error bodies are only needed for classification. Read a small prefix and
20
+ * release the response even if the endpoint sends an unbounded body. */
21
+ async function readErrorBody(response: Response): Promise<unknown> {
22
+ if (!response.body) return;
23
+ const reader = response.body.getReader(), decoder = new TextDecoder();
24
+ let value = "", remaining = 16 * 1024;
25
+ try {
26
+ while (remaining > 0) {
27
+ const chunk = await reader.read();
28
+ if (chunk.done) return JSON.parse(value + decoder.decode());
29
+ value += decoder.decode(chunk.value.subarray(0, remaining), { stream: true });
30
+ remaining -= chunk.value.byteLength;
31
+ }
32
+ return JSON.parse(value + decoder.decode());
33
+ } catch { return; }
34
+ finally { void reader.cancel().catch(() => {}); reader.releaseLock(); }
35
+ }
36
+
12
37
  /** OpenRouter SSE translation stays at the provider boundary; tool fragments are
13
38
  * private until a valid terminal response is assembled by the adapter. */
14
- type Vision = Parameters<typeof projectVisionParts>[1] & { verify?: (metadata: import("../../contracts/attachments.ts").AttachmentMetadata, signal: AbortSignal) => Promise<void> };
39
+ type Vision = { supported: boolean; metadata: AttachmentLookup; read: (metadata: AttachmentMetadata) => Uint8Array;
40
+ verify?: (metadata: AttachmentMetadata, signal: AbortSignal) => Promise<void> };
15
41
  export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, vision?: Vision): ModelAttempt {
16
42
  return chatAttempt(apiKey, model, fetcher, onRequest, undefined, vision);
17
43
  }
18
44
  export function openAICompatibleAttempt(baseUrl: string, model: string, apiKey?: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, metadata?: Vision["metadata"]): ModelAttempt {
45
+ return compatibleAttempt(baseUrl, model, apiKey, fetcher, onRequest, metadata);
46
+ }
47
+
48
+ export function managedCompatibleAttempt(model: CompatibleModel, conversation: { sessionId: string; channelId: string },
49
+ apiKey?: string, onRequest?: (body: string) => void, metadata?: Vision["metadata"], fetcher: typeof fetch = fetch): ModelAttempt {
50
+ if (model.protocol === "openai-compatible")
51
+ return compatibleAttempt(model.baseUrl, model.model, apiKey, fetcher, onRequest, metadata);
52
+ // Restarts and retries share the same cache affinity. Separate channels
53
+ // never send each other's identifiers to the provider.
54
+ const affinity = createHash("sha256").update(JSON.stringify(["acp-client/opencode-go/v1", conversation.sessionId, conversation.channelId])).digest("hex");
55
+ return compatibleAttempt(OPENCODE_GO_BASE_URL, model.model, apiKey, fetcher, onRequest, metadata, "ses_" + affinity);
56
+ }
57
+
58
+ function compatibleAttempt(baseUrl: string, model: string, apiKey: string | undefined, fetcher: typeof fetch,
59
+ onRequest?: (body: string) => void, metadata?: Vision["metadata"], goSession?: string): ModelAttempt {
19
60
  const references: Vision | undefined = metadata ? { supported: false, metadata, read: () => { throw new Error("Image bytes unavailable for text-only model"); } } : undefined;
20
- return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references);
61
+ return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references, goSession);
62
+ }
63
+
64
+ function goFailureCode(status: number, body: unknown) {
65
+ const error = body && typeof body === "object" && "error" in body ? body.error : body;
66
+ const fields = error && typeof error === "object" ? error as { code?: unknown; type?: unknown } : undefined;
67
+ if (fields?.code === "MissingSessionID" || fields?.type === "MissingSessionID") return "missing_session_id";
68
+ if (status === 401 || fields?.code === "InvalidAPIKey" || fields?.type === "InvalidAPIKey") return "invalid_api_key";
69
+ if (status === 403) return "access_denied";
70
+ if (status === 429) return "rate_limited";
21
71
  }
22
- function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void, endpoint?: string, vision?: Vision): ModelAttempt {
72
+
73
+ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void,
74
+ endpoint?: string, vision?: Vision, goSession?: string): ModelAttempt {
23
75
  return async function* (request, signal) {
24
76
  const imageUrls: string[] = [];
25
- let messages: unknown[];
77
+ const compatible = endpoint !== undefined;
78
+ const profile = request.contextBudget;
79
+ const wire = prepareChatRequest(model, compatible, request.tools, profile?.maxOutputTokens);
80
+ let budget, messages: string;
26
81
  try {
27
82
  let imageBytes = 0;
28
83
  const unavailable = new Set<string>();
29
- const images = new Map<string, ReturnType<NonNullable<typeof vision>["metadata"]>>();
84
+ const images = new Map<string, AttachmentMetadata>(), references = new Map<string, AttachmentMetadata>();
30
85
  for (const message of request.messages) if (message.role === "user" && message.parts) {
31
86
  if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
32
87
  for (const part of message.parts) if (part.type === "attachment") {
33
88
  const metadata = vision.metadata(part.id);
34
89
  if (!metadata) unavailable.add(part.id);
35
- else if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
90
+ else {
91
+ references.set(part.id, metadata);
92
+ if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
93
+ }
36
94
  }
37
95
  }
38
96
  if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
39
97
  if (endpoint && images.size) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
40
98
  if (imageBytes > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
41
99
  if (images.size && !vision!.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
100
+ const metadata = vision && ((id: string) => references.get(id));
101
+ if (profile) {
102
+ budget = chatRequestSizer(model, compatible, profile, metadata)(request.tools)(request.messages);
103
+ const contextFailure = exceededContextBudget(budget);
104
+ if (contextFailure) {
105
+ yield { type: "failure", kind: "invalid_request", message: "Request exceeds the configured context budget", contextFailure };
106
+ return;
107
+ }
108
+ }
42
109
  const bytes = new Map<string, Uint8Array>();
43
110
  for (const [id, metadata] of images) try {
44
- await vision!.verify?.(metadata!, signal);
45
- const value = vision!.read(metadata!);
46
- if (value.length !== metadata!.bytes || createHash("sha256").update(value).digest("hex") !== metadata!.sha256) throw new Error("Integrity failure");
47
- bytes.set(id, value);
111
+ await vision!.verify?.(metadata, signal);
112
+ bytes.set(id, readVerifiedImage(metadata, vision!.read));
48
113
  } catch { unavailable.add(id); }
49
114
  if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [...unavailable]);
50
- messages = request.messages.map(message => {
51
- if (message.role !== "user" || !message.parts) return wireMessage(message, endpoint === undefined);
52
- if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
53
- const content = projectVisionParts(message.parts, { ...vision, read: metadata => bytes.get(metadata.id)! });
54
- for (const part of content) if (part.type === "image_url") imageUrls.push(part.image_url.url);
55
- const separator = message.content.indexOf("\n\n");
56
- const attribution = message.content.startsWith("Participant: ") && separator >= 0 ? message.content.slice(0, separator + 2) : "";
57
- if (endpoint) return { role: "user", content: attribution + content.map(part => part.type === "text" ? part.text : "").join("") };
58
- return { role: "user", content: attribution ? [{ type: "text", text: attribution }, ...content] : content };
115
+ messages = wire.messages(request.messages, metadata, compatible ? undefined : image => {
116
+ const url = imageDataPrefix(image.mediaType) + Buffer.from(bytes.get(image.id)!).toString("base64");
117
+ imageUrls.push(url);
118
+ return url;
59
119
  });
60
120
  } catch (error) {
61
121
  if (error instanceof VisionInputError) { yield { type: "failure", kind: "invalid_request", code: error.code, attachmentIds: error.attachmentIds, message: error.message }; return; }
62
122
  throw error;
63
123
  }
64
- const body = JSON.stringify({ model, stream: true, stream_options: { include_usage: true }, messages,
65
- ...(request.tools.length ? { tools: request.tools.map(tool => ({ type: "function", function: tool })), ...(endpoint ? { tool_choice: "auto" } : {}) } : {}) });
124
+ const requestBytes = wire.fixedBytes + Buffer.byteLength(messages);
125
+ if (budget && requestBytes > budget.maxRequestBytes) {
126
+ yield { type: "failure", kind: "invalid_request", message: "Encoded request exceeds the byte cap",
127
+ contextFailure: { limit: "request_bytes", budget: { ...budget, requestBytes } } };
128
+ return;
129
+ }
130
+ const body = wire.body(messages);
66
131
  const redact = (text: string) => {
67
132
  let safe = apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text;
68
133
  for (const url of imageUrls) { safe = safe.replaceAll(url, "[REDACTED_IMAGE]"); const encoded = url.slice(url.indexOf(",") + 1); if (encoded) safe = safe.replaceAll(encoded, "[REDACTED_IMAGE]"); }
@@ -71,15 +136,36 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
71
136
  const errorText = (error: unknown) => endpoint ? "Chat Completions transport failed" : redact(String(error));
72
137
  onRequest?.(imageUrls.length ? redact(body) : body);
73
138
  let response: Response;
74
- try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json" }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
139
+ try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: {
140
+ ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json",
141
+ ...(goSession ? { "User-Agent": "acp-client/native-harness", "x-opencode-session": goSession } : {}),
142
+ }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
75
143
  catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
76
144
  if (!response.ok) {
77
145
  if (endpoint) {
78
- void response.body?.cancel().catch(() => {});
79
- if (response.status >= 300 && response.status < 400) { yield { type: "failure", kind: "provider", message: "redirect_refused" }; return; }
146
+ if (response.status >= 300 && response.status < 400) {
147
+ void response.body?.cancel().catch(() => {});
148
+ yield { type: "failure", kind: "provider", message: "redirect_refused",
149
+ ...(goSession ? { providerFailure: `OpenCode Go HTTP ${response.status} (redirect_refused)` } : {}) }; return;
150
+ }
151
+ const upstream = await readErrorBody(response);
152
+ if (isProviderContextError(upstream)) { yield providerContextFailure; return; }
153
+ if (goSession) {
154
+ const code = goFailureCode(response.status, upstream);
155
+ const message = `OpenCode Go HTTP ${response.status}${code ? ` (${code})` : ""}`;
156
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message, providerFailure: message };
157
+ return;
158
+ }
80
159
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
81
160
  }
82
- const text = redact(await response.text());
161
+ if (profile) {
162
+ if (isProviderContextError(await readErrorBody(response))) { yield providerContextFailure; return; }
163
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
164
+ message: `OpenRouter HTTP ${response.status}` }; return;
165
+ }
166
+ const raw = await response.text();
167
+ try { if (isProviderContextError(JSON.parse(raw))) { yield providerContextFailure; return; } } catch { /* Non-JSON error body. */ }
168
+ const text = redact(raw);
83
169
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
84
170
  }
85
171
  const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
@@ -99,6 +185,7 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
99
185
  const data = line.slice(5).trim(); if (!data || data === "[DONE]") continue;
100
186
  let payload: { id?: string; usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }; choices?: { finish_reason?: string | null; delta?: { content?: string | null; reasoning?: string | null; reasoning_details?: unknown[]; tool_calls?: { index: number; id?: string; function?: { name?: string; arguments?: string } }[] } }[] };
101
187
  try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: endpoint ? "Malformed Chat Completions stream" : "Malformed OpenRouter stream" }; return; }
188
+ if (isProviderContextError(payload)) { yield providerContextFailure; return; }
102
189
  if (!providerId && payload.id) providerId = safeRequestId(payload.id);
103
190
  // A parsed response frame, unlike an HTTP success header, is evidence
104
191
  // the provider has accepted the inference request.
@@ -130,6 +217,6 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
130
217
  ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
131
218
  yield event;
132
219
  } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; }
133
- finally { if (endpoint) void reader.cancel().catch(() => {}); reader.releaseLock(); }
220
+ finally { if (endpoint || profile) void reader.cancel().catch(() => {}); reader.releaseLock(); }
134
221
  };
135
222
  }
@@ -5,7 +5,9 @@ import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
5
5
  export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { timeoutMs: 120_000, retryDelayMs: 1_000, maxRetries: 1 };
6
6
  export class ModelCallError extends Error {
7
7
  constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
8
- readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure) { super(message); this.name = "ModelCallError"; }
8
+ readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
9
+ readonly contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
10
+ readonly providerFailure?: string) { super(message); this.name = "ModelCallError"; }
9
11
  }
10
12
  class ModelStorageError extends Error {}
11
13
  function take<T>(result: StorageResult<T>): T {
@@ -42,11 +44,13 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
42
44
  options.started?.(call.callId);
43
45
  let deadline = 0, output = false;
44
46
  const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
45
- attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure): never => {
47
+ attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
48
+ contextFailure?: import("../../contracts/context.ts").ContextLimitFailure,
49
+ providerFailure?: string): never => {
46
50
  const result = options.store.finishCall(call.callId, outcome);
47
51
  if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
48
52
  if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
49
- throw new ModelCallError(outcome, detail, attachmentFailure);
53
+ throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure, providerFailure);
50
54
  };
51
55
  for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
52
56
  if (options.signal?.aborted) return finish("interrupted");
@@ -105,7 +109,11 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
105
109
  take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
106
110
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
107
111
  if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
108
- if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) return finish(failure === "incomplete" ? "incomplete" : "failed");
112
+ if (terminal?.type === "failure" && terminal.contextFailure) return finish("failed", terminal.message, undefined, terminal.contextFailure);
113
+ if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) {
114
+ const providerFailure = terminal?.type === "failure" ? terminal.providerFailure : undefined;
115
+ return finish(failure === "incomplete" ? "incomplete" : "failed", providerFailure, undefined, undefined, providerFailure);
116
+ }
109
117
  if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
110
118
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
111
119
  const done = (result: "ready" | "interrupted") => { clearTimeout(wait); options.signal?.removeEventListener("abort", interrupted); resolve(result); };
@@ -6,7 +6,8 @@ export { createStdioTransport } from "./interfaces/protocol/stdio-client.ts";
6
6
  export type { StdioConnection } from "./contracts/protocol.ts";
7
7
  export type { ChannelEvent } from "./contracts/events.ts";
8
8
  export type { InitializeParams, CreateParams, PushParams, NotifyParams, ProtocolConfig, ClientTransport, PendingChannelChange, ChannelChangeResult, LoadResult, StatusResult, ChannelStatusResult, ItemStatus, TurnStatus, StoredMessage } from "./contracts/protocol.ts";
9
- export type { ManagedConfig, ManagedModel, ToolPolicy, ToolDecision, ItemPolicy, ApprovalRequest, ApprovalAnswer, ApprovalCloseReason } from "./contracts/config-permissions.ts";
9
+ export type { ManagedConfig, ManagedModel, ModelContextBudget, ToolPolicy, ToolDecision, ItemPolicy, ApprovalRequest, ApprovalAnswer, ApprovalCloseReason } from "./contracts/config-permissions.ts";
10
+ export type { ContextLimitFailure, ContextBudgetMeasurement } from "./contracts/context.ts";
10
11
 
11
12
  export type { ModelCallSummary, ModelAttemptSummary, ModelUsage, ModelTextEvent, ModelTextPage } from "./contracts/model-execution.ts";
12
13
  export { aggregateUsage } from "./capabilities/model/usage.ts";
@@ -4,9 +4,26 @@ import type { McpServer } from "./mcp.ts";
4
4
  * Script files and credential environment variables are destination resources. */
5
5
  export type ToolDecision = "allow" | "ask" | "deny";
6
6
  export interface ToolPolicy { fallback: ToolDecision; mcp?: "allow" | "deny"; tools: Record<string, ToolDecision> }
7
+ /** Opt-in request sizing for a managed Chat Completions model. Decision 0037. */
8
+ export interface ModelContextBudget {
9
+ contextWindowTokens: number;
10
+ outputReserveTokens?: number;
11
+ maxOutputTokens?: number;
12
+ estimationMarginTokens?: number;
13
+ maxRequestBytes?: number;
14
+ }
7
15
  export type ManagedModel = { protocol: "scripted"; script: string; imageInput?: boolean }
8
- | { protocol: "openrouter"; model: string; apiKeyEnv: string; imageInput?: boolean }
9
- | { protocol: "openai-compatible"; providerId: string; model: string; baseUrl: string; apiKeyEnv?: string };
16
+ | { protocol: "openrouter"; model: string; apiKeyEnv: string; imageInput?: boolean; contextBudget?: ModelContextBudget }
17
+ | { protocol: "openai-compatible"; providerId: string; model: string; baseUrl: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget }
18
+ | { protocol: "opencode-go"; model: string; apiKeyEnv?: string; contextBudget?: ModelContextBudget };
19
+
20
+ /** Both text-only managed sources use the same Chat Completions client. */
21
+ export type CompatibleModel = Extract<ManagedModel, { protocol: "openai-compatible" | "opencode-go" }>;
22
+ export const OPENCODE_GO_BASE_URL = "https://opencode.ai/inference/go/openai/v1";
23
+ export const OPENCODE_GO_KEY_ENV = "OPENCODE_API_KEY";
24
+ export function isCompatibleModel(model: ManagedModel | undefined): model is CompatibleModel {
25
+ return model?.protocol === "openai-compatible" || model?.protocol === "opencode-go";
26
+ }
10
27
  /** Decision 0035: independent portable web backends, with credential names only. */
11
28
  export interface ExaSearchConfig { backend: "exa"; apiKeyEnv?: string; maxResults?: number; excerptBytes?: number; deadlineMs?: number }
12
29
  export type WebFetchConfig = { backend: "exa"; apiKeyEnv?: string; deadlineMs?: number } | { backend: "http"; deadlineMs?: number };
@@ -46,11 +46,47 @@ export interface InferenceStorageReads {
46
46
  export interface ContextCapture {
47
47
  context: InferenceContext;
48
48
  estimatedInputBytes: number;
49
+ budget?: ContextBudgetMeasurement;
49
50
  /** Sequence numbers of selected and trimmed candidates from the bounded read. */
50
51
  records: { included: number[]; trimmed: number[] };
51
52
  omitted: { active: number; local: number; shared: number };
52
53
  }
53
54
 
55
+ /** Safe numeric accounting of one configured provider-equivalent request. */
56
+ export interface ContextBudgetMeasurement {
57
+ estimator: "chat-completions-utf8-v1";
58
+ contextWindowTokens: number;
59
+ outputReserveTokens: number;
60
+ estimationMarginTokens: number;
61
+ inputBudgetTokens: number;
62
+ estimatedInputTokens: number;
63
+ toolDefinitionBytes: number;
64
+ requestBytes: number;
65
+ maxRequestBytes: number;
66
+ }
67
+
68
+ export type ContextLimitFailure =
69
+ | { limit: "required_storage" | "provider_context" }
70
+ | { limit: "input_tokens" | "request_bytes"; budget: ContextBudgetMeasurement };
71
+
72
+ /** The provider adapter prepares the fixed request fields once per tool offer. */
73
+ export type ContextRequestSizer = (tools: readonly ToolDefinition[]) =>
74
+ (messages: readonly Message[]) => ContextBudgetMeasurement;
75
+
76
+ export function parseContextLimitFailure(reason: string): ContextLimitFailure | undefined {
77
+ if (!reason.startsWith("context_limit:")) return;
78
+ try {
79
+ const value = JSON.parse(reason.slice("context_limit:".length));
80
+ if (value?.limit === "required_storage" || value?.limit === "provider_context") return { limit: value.limit };
81
+ if (!["input_tokens", "request_bytes"].includes(value?.limit) || value?.budget?.estimator !== "chat-completions-utf8-v1") return;
82
+ const fields = ["contextWindowTokens", "outputReserveTokens", "estimationMarginTokens", "inputBudgetTokens",
83
+ "estimatedInputTokens", "toolDefinitionBytes", "requestBytes", "maxRequestBytes"] as const;
84
+ if (fields.some(key => !Number.isSafeInteger(value.budget[key]) || value.budget[key] < 0)) return;
85
+ const budget = Object.fromEntries(fields.map(key => [key, value.budget[key]])) as Omit<ContextBudgetMeasurement, "estimator">;
86
+ return { limit: value.limit, budget: { ...budget, estimator: "chat-completions-utf8-v1" } };
87
+ } catch { return; }
88
+ }
89
+
54
90
  /** One provider-neutral request. A retry reuses this capture. */
55
91
  export interface InferenceContext {
56
92
  readonly sessionId: string;
@@ -67,7 +103,7 @@ export interface InferenceContext {
67
103
 
68
104
  /** Size failures happen before reserving a model call or attempt. */
69
105
  export type ContextBuildResult = { readonly ok: true; readonly value: InferenceContext }
70
- | { readonly ok: false; readonly code: "context_limit"; readonly message: string };
106
+ | { readonly ok: false; readonly code: "context_limit"; readonly message: string; readonly detail?: ContextLimitFailure };
71
107
 
72
108
  /** Attributed agent experience; system instructions are configuration, not events. */
73
109
  export interface ContextEntry {
@@ -38,7 +38,8 @@ export interface ChannelEvent {
38
38
  | (import("./reminders.ts").ReminderChannelEvent & { turnId?: never })
39
39
  | import("./operator-controls.ts").ApprovalClosedEvent
40
40
  | ({ type: "approval_requested" } & import("./config-permissions.ts").ApprovalRequest)
41
- | { type: "turn_ended"; turnId: string; outcome: "completed" | "failed" | "interrupted"; error?: string; uncertainCalls?: string[]; attachmentFailure?: import("./attachments.ts").AttachmentFailure };
41
+ | { type: "turn_ended"; turnId: string; outcome: "completed" | "failed" | "interrupted"; error?: string; uncertainCalls?: string[];
42
+ attachmentFailure?: import("./attachments.ts").AttachmentFailure; contextFailure?: import("./context.ts").ContextLimitFailure };
42
43
  }
43
44
  export type EventSink = (event: ChannelEvent) => void;
44
45
 
@@ -3,6 +3,8 @@ import type { StorageResult, TimelineEntry } from "./storage.ts";
3
3
 
4
4
  /** One immutable logical request, identical across the attempts of a call. */
5
5
  export interface ModelRequest { messages: readonly Message[]; tools: readonly ToolDefinition[];
6
+ /** Effective managed budget for this immutable request. */
7
+ contextBudget?: import("./config-permissions.ts").ModelContextBudget;
6
8
  /** IDs first included at this inference boundary, in take order. The first
7
9
  * boundary includes the initial input group. Later boundaries include inputs
8
10
  * taken since the preceding boundary, including across checkpoint resume.
@@ -30,7 +32,11 @@ export type ModelAttemptEvent =
30
32
  | { type: "usage"; usage: ModelUsage }
31
33
  | { type: "response"; response: ModelResponse; providerRequestId?: string }
32
34
  | { type: "failure"; kind: "transient" | "invalid_request" | "invalid_config" | "provider"; message: string; providerRequestId?: string;
33
- code?: "unsupported_image" | "attachment_unavailable" | "transfer_limit"; attachmentIds?: readonly string[] };
35
+ code?: "unsupported_image" | "attachment_unavailable" | "transfer_limit"; attachmentIds?: readonly string[];
36
+ contextFailure?: import("./context.ts").ContextLimitFailure;
37
+ /** Safe provider diagnosis for the turn outcome. Adapters must construct
38
+ * this from fixed labels and status codes, never from the response body. */
39
+ providerFailure?: string };
34
40
  /** One attempt emits exactly one terminal response or failure unless aborted;
35
41
  * EOF without a terminal is incomplete. A consumer ignores events after the
36
42
  * first terminal, timeout or abort. The adapter assembles and validates tools. */
@@ -130,6 +130,7 @@ export interface TurnStatus {
130
130
  state: "running" | "suspended" | "completed" | "failed" | "interrupted";
131
131
  reason?: string;
132
132
  attachmentFailure?: import("./attachments.ts").AttachmentFailure;
133
+ contextFailure?: import("./context.ts").ContextLimitFailure;
133
134
  /** Recorded calls with no recorded result; never replayed by the harness. */
134
135
  uncertainCalls?: string[];
135
136
  }
@@ -1,3 +1,4 @@
1
+ import { isCompatibleModel } from "./contracts/config-permissions.ts";
1
2
  import { isWebTool } from "./capabilities/tools/web/definitions.ts";
2
3
  import { guardedReminderDefinitions, executeReminderTool, isReminderTool, reminderAction, reminderDefinitions } from "./capabilities/tools/reminders/index.ts";
3
4
  import { createReminderRuntime } from "./runtime/reminders.ts";
@@ -13,6 +14,8 @@ import type { EventSink, SessionEventSink } from "./contracts/events.ts";
13
14
  import type { SessionStorage } from "./contracts/storage.ts";
14
15
  import { createMemoryStorageAdapter } from "./state/storage/memory.ts";
15
16
  import { CONTEXT_LIMITS, createSessionContext } from "./capabilities/context/session.ts";
17
+ import { chatRequestSizer } from "./capabilities/model/chat-request.ts";
18
+ import type { ContextLimitFailure } from "./contracts/context.ts";
16
19
  import { createChannelScheduler } from "./kernel/channels.ts";
17
20
  import { runTurn } from "./kernel/loop.ts";
18
21
  import { ModelCallError, runModelCall } from "./capabilities/model/runner.ts";
@@ -69,8 +72,16 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
69
72
  const sessionReminderDefinitions = unattended.value === undefined ? reminderDefinitions : guardedReminderDefinitions;
70
73
  const identity = store.readSession();
71
74
  if (!identity.ok) throw new Error(identity.error.message);
72
- const context = createSessionContext(store, identity.value.sessionId, options.systemPrompt, CONTEXT_LIMITS, options.captureContext);
73
- const limitError = () => Object.assign(new Error("Required inference material exceeds the context budget"), { outcome: "context_limit" });
75
+ const modelConfig = owner.value?.model;
76
+ const contextBudget = modelConfig?.protocol !== "scripted" ? modelConfig?.contextBudget : undefined;
77
+ const sizeRequest = modelConfig && modelConfig.protocol !== "scripted" && contextBudget
78
+ ? chatRequestSizer(modelConfig.model, isCompatibleModel(modelConfig), contextBudget, id => {
79
+ const attachment = store.readManagedAttachment?.(id);
80
+ return attachment?.ok ? attachment.value?.metadata : undefined;
81
+ }) : undefined;
82
+ const context = createSessionContext(store, identity.value.sessionId, options.systemPrompt, CONTEXT_LIMITS, options.captureContext, sizeRequest);
83
+ const limitError = (detail?: ContextLimitFailure) => Object.assign(new Error("Required inference material exceeds the context budget"),
84
+ { outcome: detail ? `context_limit:${JSON.stringify(detail)}` : "context_limit" });
74
85
  const position = (channel: string, seq: string) => messagePosition(identity.value.sessionId, channel, Number(seq));
75
86
  const emit: EventSink = value => {
76
87
  const { channel, event } = value;
@@ -81,7 +92,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
81
92
  };
82
93
  const config = owner.value ?? { version: 1 as const, system: options.systemPrompt, model: { protocol: "scripted" as const, script: "legacy" },
83
94
  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");
95
+ if (options.imageInput && (isCompatibleModel(config.model) || config.model.imageInput !== true)) throw new Error("Image input requires explicit model configuration");
85
96
  if (options.config?.mcpServers !== undefined) {
86
97
  const canonical = (value: unknown) => JSON.stringify(value, (_key, object) =>
87
98
  object && typeof object === "object" && !Array.isArray(object)
@@ -111,7 +122,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
111
122
  const policySnapshot = () => {
112
123
  const read = store.readInferencePolicies(turn.turnId, CONTEXT_LIMITS);
113
124
  if (!read.ok) throw new Error(read.error.message);
114
- if ("code" in read.value) throw limitError();
125
+ if ("code" in read.value) throw limitError(contextBudget ? { limit: "required_storage" } : undefined);
115
126
  return read.value;
116
127
  };
117
128
  /** The names offered by this turn's latest inference: what a call must match. */
@@ -230,13 +241,14 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
230
241
  },
231
242
  }, async signal => {
232
243
  const built = context.build(turn, offer);
233
- if (!built.ok) throw limitError();
244
+ if (!built.ok) throw limitError(built.detail);
234
245
  const { tools, fixedToolCount, messages, takenItemIds, representedItemIds: itemIds } = built.value;
235
246
  phase(turn.turnId, "model");
236
247
  const binding = getModelAttempt(services.model);
237
248
  let draftId: string | undefined;
238
249
  try {
239
- const result = await runModelCall({ turnId: String(turn.turnId), itemIds, request: { messages, tools, takenItemIds, ...(fixedToolCount === undefined ? {} : { fixedToolCount }) },
250
+ const result = await runModelCall({ turnId: String(turn.turnId), itemIds, request: { messages, tools, takenItemIds,
251
+ ...(contextBudget ? { contextBudget } : {}), ...(fixedToolCount === undefined ? {} : { fixedToolCount }) },
240
252
  started: callId => {
241
253
  phase(turn.turnId, "model", callId);
242
254
  try { options.observeModelCall?.(turn.channelId, turn.turnId, callId); } catch { /* best-effort observation */ }
@@ -258,6 +270,8 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
258
270
  // A storage failure can occur after a draft was published but before the
259
271
  // runner can write a normal terminal outcome. The draft must still end.
260
272
  if (error instanceof ModelCallError && error.message === "script_exhausted") throw Object.assign(new Error(error.message), { outcome: "script_exhausted" });
273
+ if (error instanceof ModelCallError && error.contextFailure) throw limitError(error.contextFailure);
274
+ if (error instanceof ModelCallError && error.providerFailure) throw Object.assign(error, { outcome: error.providerFailure });
261
275
  if (draftId && !(error instanceof ModelCallError)) emit({ channel: turn.channelId,
262
276
  event: { type: "text_incomplete", turnId: String(turn.turnId), messageId: draftId, reason: "failed" } });
263
277
  throw error;
@@ -13,7 +13,7 @@ import { openRouter } from "../../capabilities/model/openrouter.ts";
13
13
  import { loadScenario, scriptedCompatibilityKey } from "../../capabilities/model/scenario-file.ts";
14
14
  import { scenarioAttempt } from "../../capabilities/model/scenario-attempt.ts";
15
15
  import { bindModelAttempt } from "../../capabilities/model/attempt.ts";
16
- import { openAICompatibleAttempt, openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
16
+ import { managedCompatibleAttempt, openRouterAttempt } from "../../capabilities/model/openrouter-stream.ts";
17
17
  import { currentTimeDefinition, executeCurrentTime } from "../../capabilities/tools/builtin/current-time.ts";
18
18
  import { debugToolDefinitions, debugToolHandlers } from "../../capabilities/tools/debug/index.ts";
19
19
  import { notifyChannelDefinition } from "../../capabilities/tools/builtin/notify-channel.ts";
@@ -21,7 +21,7 @@ import { createMemoryStorageAdapter } from "../../state/storage/memory.ts";
21
21
  import { createSqliteStorageAdapter } from "../../state/storage/sqlite.ts";
22
22
  import { createInspection } from "../inspector/state.ts";
23
23
  import { observeModel, observeSession } from "../inspector/observe.ts";
24
- import type { ManagedConfig } from "../../contracts/config-permissions.ts";
24
+ import { isCompatibleModel, type ManagedConfig } from "../../contracts/config-permissions.ts";
25
25
  import { chooseManagedConfig } from "../../runtime/config/paths.ts";
26
26
  import { resolveCompatibleCredential, resolveCredential, validateManagedConfig } from "../../runtime/config/managed.ts";
27
27
  import { createManagedAttachmentService } from "../../capabilities/attachments/service.ts";
@@ -93,7 +93,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
93
93
  managedConfig = { ...managedConfig, system: options.debugInstructions };
94
94
  const systemPrompt = options.instructions ?? options.debugInstructions ?? managedConfig?.system ?? options.systemPrompt;
95
95
  const scriptPath = managedConfig?.model.protocol === "scripted" ? managedConfig.model.script : undefined;
96
- const compatible = managedConfig?.model.protocol === "openai-compatible" ? managedConfig.model : undefined;
96
+ const compatible = isCompatibleModel(managedConfig?.model) ? managedConfig.model : undefined;
97
97
  const creating = !options.database || !!options.create;
98
98
  const environment = options.environment ?? process.env;
99
99
  let compatibleKey = compatible && creating ? resolveCompatibleCredential(compatible, environment) : undefined;
@@ -105,9 +105,9 @@ export async function openDevelopment(options: DevelopmentOptions) {
105
105
  const scriptedTools = script ? options.scriptedTools : undefined;
106
106
  const tools = [currentTimeDefinition, ...(scriptedTools?.tools ?? []),
107
107
  ...(options.debugTools ? debugToolDefinitions : []), notifyChannelDefinition];
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");
108
+ let imageInput = !!managedConfig && !isCompatibleModel(managedConfig.model) && 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 && !isCompatibleModel(managedConfig.model) && managedConfig.model.imageInput === true ? "\n[image-input-enabled]" : ""))
110
+ : createHash("sha256").update(JSON.stringify([systemPrompt, providerModel!.model, tools.map(tool => tool.name), ...(managedConfig && !isCompatibleModel(managedConfig.model) && managedConfig.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
111
111
  const tempMedia = sqlite ? undefined : mkdtempSync(join(tmpdir(), "harness-media-"));
112
112
  const mediaRoot = options.database ? options.mediaRoot ?? `${options.database}.media` : join(tempMedia!, "media");
113
113
  if (!sqlite) adapter = createMemoryStorageAdapter({ mediaRoot });
@@ -161,7 +161,7 @@ export async function openDevelopment(options: DevelopmentOptions) {
161
161
  };
162
162
  } });
163
163
  } else if (compatible) {
164
- bindModelAttempt(model, { scripted: false, create: () => openAICompatibleAttempt(compatible.baseUrl, compatible.model, compatibleKey, fetch,
164
+ bindModelAttempt(model, { scripted: false, create: () => managedCompatibleAttempt(compatible, { sessionId, channelId: turn.channelId }, compatibleKey,
165
165
  body => inspection.request(turn.channelId, body, turn.turnId), attachments ? id => {
166
166
  const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
167
167
  } : undefined) });
@@ -220,19 +220,22 @@
220
220
  main.append(details);
221
221
  }
222
222
  if (!requests.length && !calls.length) main.append(node('p', channel.error ? 'Turn stopped before inference.' : 'Waiting for inference…', 'muted'));
223
+ if (channel.contextFailure) main.append(json(channel.contextFailure));
223
224
  for (const [index, request] of requests.entries()) {
224
225
  const iteration = node('section', undefined, 'iteration');
225
226
  iteration.append(node('p', 'Iteration ' + (index + 1) + ' · ' + request.at, 'muted'));
226
227
  if (request.context) {
227
- const { revision, estimatedInputBytes, omitted, records, offeredTools, modelCallId } = request.context;
228
- iteration.append(node('p', 'Timeline revision ' + revision + ' · ' + estimatedInputBytes + ' estimated input bytes'
228
+ const { revision, estimatedInputBytes, budget, omitted, records, offeredTools, modelCallId } = request.context;
229
+ const inputSize = budget ? budget.estimatedInputTokens + ' estimated input tokens · ' + budget.requestBytes + ' request bytes'
230
+ : estimatedInputBytes + ' estimated input bytes';
231
+ iteration.append(node('p', 'Timeline revision ' + revision + ' · ' + inputSize
229
232
  + ' · Trimmed records ' + omitted.active + ' active, ' + omitted.local + ' local, ' + omitted.shared + ' shared', 'muted'));
230
233
  const inspection = node('details'); inspection.dataset.key = channel.id + ':selection:' + request.number;
231
234
  inspection.open = expanded.has(inspection.dataset.key);
232
235
  const call = modelCalls.find(call => call.callId === modelCallId);
233
236
  inspection.append(node('summary', 'Request evidence'), json({
234
237
  includedTimelinePositions: records.included, trimmedCandidatePositions: records.trimmed, offeredTools,
235
- modelCallId, ...(call ? { outcome: call.outcome, attempts: call.attempts } : {}),
238
+ modelCallId, ...(budget ? { budget } : {}), ...(call ? { outcome: call.outcome, attempts: call.attempts } : {}),
236
239
  }));
237
240
  iteration.append(inspection);
238
241
  }
@@ -1,5 +1,6 @@
1
1
  import type { Message, ToolDefinition } from "../../contracts/loop.ts";
2
2
  import type { ContextCapture } from "../../contracts/context.ts";
3
+ import { parseContextLimitFailure } from "../../contracts/context.ts";
3
4
  import type { InspectionStorageReads } from "../../contracts/inspection.ts";
4
5
  import type { StorageResult } from "../../contracts/storage.ts";
5
6
  import { composeSystemPrompt } from "../../capabilities/context/load-instructions.ts";
@@ -10,7 +11,7 @@ interface InspectedInference {
10
11
  turnId?: number;
11
12
  at: string;
12
13
  body: unknown;
13
- context?: Pick<ContextCapture, "estimatedInputBytes" | "omitted" | "records"> & { revision: number; offeredTools: string[]; modelCallId?: string };
14
+ context?: Pick<ContextCapture, "estimatedInputBytes" | "budget" | "omitted" | "records"> & { revision: number; offeredTools: string[]; modelCallId?: string };
14
15
  response?: Extract<Message, { role: "assistant" }> | { omitted: true };
15
16
  }
16
17
 
@@ -40,8 +41,12 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
40
41
  const execution = stopped ? "stopped" : session.lifecycle !== "running" ? session.lifecycle
41
42
  : status.some(channel => channel.turn === "running" || (channel.lifecycle === "open" && channel.pending > 0)) ? "working" : "idle";
42
43
  return { session: { sessionId: session.sessionId, lifecycle: session.lifecycle, execution, revision, storage },
43
- channels: status.map(channel => ({ ...channel, running: channel.turn === "running",
44
- ...(channel.unresolved ? { error: `Turn ${channel.unresolved.turnId} ${channel.unresolved.status}: ${channel.unresolved.reason}` } : {}) })) };
44
+ channels: status.map(channel => {
45
+ const contextFailure = channel.unresolved && parseContextLimitFailure(channel.unresolved.reason);
46
+ return { ...channel, running: channel.turn === "running",
47
+ ...(channel.unresolved ? { error: `Turn ${channel.unresolved.turnId} ${channel.unresolved.status}: ${contextFailure ? "context_limit" : channel.unresolved.reason}` } : {}),
48
+ ...(contextFailure ? { contextFailure } : {}) };
49
+ }) };
45
50
  },
46
51
  liveContext() {
47
52
  const { entries, unfinished, revision } = read(reads.readInspectionPage());
@@ -68,6 +73,7 @@ export function createInspection(systemPrompt: string, tools: readonly ToolDefin
68
73
  capture(value: ContextCapture) {
69
74
  const { channelId, turnId, timelineRevision } = value.context;
70
75
  captures.set(channelId, { turnId, metadata: { revision: timelineRevision, estimatedInputBytes: value.estimatedInputBytes,
76
+ ...(value.budget ? { budget: value.budget } : {}),
71
77
  omitted: value.omitted, records: value.records, offeredTools: value.context.tools.map(tool => tool.name) } });
72
78
  },
73
79
  modelCall(channelId: string, turnId: number, callId: string) {
@@ -2,6 +2,7 @@ import type { ItemStatus, LoadResult, StatusResult, StoredMessage, TurnStatus }
2
2
  import type { SessionStatus } from "../../contracts/session.ts";
3
3
  import type { StorageSnapshot, StoredTurn } from "../../contracts/storage.ts";
4
4
  import { parseAttachmentFailure } from "../../contracts/attachments.ts";
5
+ import { parseContextLimitFailure } from "../../contracts/context.ts";
5
6
  import { MAX_FRAME_BYTES } from "./framing.ts";
6
7
 
7
8
  /** Room left in a frame for the JSON-RPC envelope around a result. */
@@ -11,8 +12,10 @@ export class FrameLimit extends Error {}
11
12
 
12
13
  export function turnStatus(turn: StoredTurn): TurnStatus {
13
14
  const state = turn.state;
15
+ const contextFailure = state.status === "failed" ? parseContextLimitFailure(state.reason) : undefined;
14
16
  return { turnId: String(turn.turnId), channel: turn.channelId, items: turn.itemIds, state: state.status,
15
- ...(state.status === "failed" || state.status === "interrupted" ? { reason: state.reason, uncertainCalls: state.uncertainCallIds,
17
+ ...(state.status === "failed" || state.status === "interrupted" ? { reason: contextFailure ? "context_limit" : state.reason,
18
+ ...(contextFailure ? { contextFailure } : {}), uncertainCalls: state.uncertainCallIds,
16
19
  ...(parseAttachmentFailure(state.reason) ? { attachmentFailure: parseAttachmentFailure(state.reason) } : {}) } : {}) };
17
20
  }
18
21
 
@@ -4,6 +4,7 @@ import type { EventSink, SessionEventSink } from "../contracts/events.ts";
4
4
  import type { ChannelControls, ChannelStatus, ControlResult, LifecycleResult, SessionStatus } from "../contracts/session.ts";
5
5
  import type { AcceptItem, SessionLifecycle, SessionStorage, StorageError, StorageResult, StorageSnapshot, StoredTurn, TimelineEntry } from "../contracts/storage.ts";
6
6
  import { attachmentFailureReason, parseAttachmentFailure } from "../contracts/attachments.ts";
7
+ import { parseContextLimitFailure } from "../contracts/context.ts";
7
8
  import { attachmentView } from "../contracts/attachments.ts";
8
9
 
9
10
  export interface ChannelScheduler {
@@ -108,8 +109,10 @@ export function createChannelScheduler(
108
109
  }
109
110
  const ended = (turn: StoredTurn, revision: number) => {
110
111
  if (turn.state.status !== "failed" && turn.state.status !== "interrupted") return;
112
+ const contextFailure = parseContextLimitFailure(turn.state.reason);
111
113
  emit({ channel: turn.channelId, revision, event: { type: "turn_ended", turnId: String(turn.turnId), outcome: turn.state.status,
112
- error: turn.state.reason, ...(parseAttachmentFailure(turn.state.reason) ? { attachmentFailure: parseAttachmentFailure(turn.state.reason) } : {}),
114
+ error: contextFailure ? "context_limit" : turn.state.reason, ...(contextFailure ? { contextFailure } : {}),
115
+ ...(parseAttachmentFailure(turn.state.reason) ? { attachmentFailure: parseAttachmentFailure(turn.state.reason) } : {}),
113
116
  ...(turn.state.uncertainCallIds.length ? { uncertainCalls: turn.state.uncertainCallIds } : {}) } });
114
117
  };
115
118
  const takenMessages = (entries: readonly TimelineEntry[]) => entries.flatMap(entry => {
@@ -1,7 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { ManagedModel } from "../../contracts/config-permissions.ts";
2
+ import { OPENCODE_GO_BASE_URL, type CompatibleModel } from "../../contracts/config-permissions.ts";
3
3
 
4
- export function compatibleInferenceKey(model: Extract<ManagedModel, { protocol: "openai-compatible" }>,
4
+ export function compatibleInferenceKey(model: CompatibleModel,
5
5
  system: string, tools: readonly string[]): string {
6
- return createHash("sha256").update(JSON.stringify([model.protocol, model.providerId, model.baseUrl, model.model, system, tools])).digest("hex");
6
+ const source = model.protocol === "opencode-go" ? ["opencode-go", OPENCODE_GO_BASE_URL]
7
+ : [model.protocol, model.providerId, model.baseUrl];
8
+ return createHash("sha256").update(JSON.stringify([...source, model.model, system, tools])).digest("hex");
7
9
  }
@@ -1,3 +1,4 @@
1
+ import { isCompatibleModel } from "./contracts/config-permissions.ts";
1
2
  import { validateMcpRuntimeHeaders } from "./util/mcp-config.ts";
2
3
  import { openMcpRegistry } from "./capabilities/tools/mcp/registry.ts";
3
4
  import { createWebRegistry, directWebFetch } from "./capabilities/tools/web/registry.ts";
@@ -19,7 +20,7 @@ import type { LoadedScenario } from "./contracts/scenario.ts";
19
20
  export type { LoadedScenario, ScenarioHeader, ScenarioModelRecord, ScenarioRecord, ScenarioSend } from "./contracts/scenario.ts";
20
21
  export { loadScenario, parseScenario } from "./capabilities/model/scenario-file.ts";
21
22
  import { bindModelAttempt } from "./capabilities/model/attempt.ts";
22
- import { openAICompatibleAttempt, openRouterAttempt } from "./capabilities/model/openrouter-stream.ts";
23
+ import { managedCompatibleAttempt, openRouterAttempt } from "./capabilities/model/openrouter-stream.ts";
23
24
  import { openRouter } from "./capabilities/model/openrouter.ts";
24
25
  import { notifyChannelDefinition } from "./capabilities/tools/builtin/notify-channel.ts";
25
26
  import { echoDefinition, executeEcho } from "./capabilities/tools/testing/echo.ts";
@@ -143,13 +144,13 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
143
144
  const runtimeHeaders = mcpRuntimeHeaders === undefined ? undefined : validateMcpRuntimeHeaders(mcpRuntimeHeaders, config.mcpServers);
144
145
  const script = config.model.protocol === "scripted" ? await (options.scenarioLoader ?? loadScenario)(config.model.script) : undefined;
145
146
  const credential = config.model.protocol === "openrouter" ? resolveCredential(config.model, options.environment ?? process.env) : undefined;
146
- let imageInput = !!paths && !options.adapter && config.model.protocol !== "openai-compatible" && config.model.imageInput === true && (config.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
147
- const compatible = config.model.protocol === "openai-compatible" ? config.model : undefined;
147
+ let imageInput = !!paths && !options.adapter && !isCompatibleModel(config.model) && config.model.imageInput === true && (config.model.protocol === "scripted" || !options.providerFactory) && imageValidationAvailable();
148
+ const compatible = isCompatibleModel(config.model) ? config.model : undefined;
148
149
  const environment = options.environment ?? process.env;
149
150
  let compatibleKey = compatible && mode === "create" ? resolveCompatibleCredential(compatible, environment) : undefined;
150
- const compatibilityKey = compatible ? compatibleInferenceKey(compatible, config.system, [...BUILTINS, notifyChannelDefinition].map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, config.system + (config.model.protocol !== "openai-compatible" && config.model.imageInput === true ? "\n[image-input-enabled]" : ""))
151
+ const compatibilityKey = compatible ? compatibleInferenceKey(compatible, config.system, [...BUILTINS, notifyChannelDefinition].map(tool => tool.name)) : script ? scriptedCompatibilityKey(script.modelDigest, config.system + (!isCompatibleModel(config.model) && config.model.imageInput === true ? "\n[image-input-enabled]" : ""))
151
152
  : createHash("sha256").update(JSON.stringify([config.system, config.model.protocol === "openrouter" && config.model.model,
152
- [...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(config.model.protocol !== "openai-compatible" && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
153
+ [...BUILTINS, notifyChannelDefinition].map(tool => tool.name), ...(!isCompatibleModel(config.model) && config.model.imageInput === true ? ["image-input-enabled"] : [])])).digest("hex");
153
154
  if (mode === "create" && paths) mkdirSync(paths.directory, { recursive: true });
154
155
  const makeWebTools = () => {
155
156
  const result = createWebRegistry(config, environment, { exa: options.webTransport ?? webFixture ?? exaHttpsTransport, http: options.webHttp ?? directWebFetch });
@@ -196,7 +197,7 @@ export function createScriptedServer(options: ScriptedServerOptions = {}) {
196
197
  const model: Model = async () => { throw new Error("Chat Completions requires a model attempt"); };
197
198
  bindModelAttempt(model, { scripted: false,
198
199
  ...(options.modelTimeoutMs === undefined ? {} : { settings: { timeoutMs: options.modelTimeoutMs } }),
199
- create: () => openAICompatibleAttempt(compatible.baseUrl, compatible.model, compatibleKey, fetch, undefined, attachments ? id => {
200
+ create: () => managedCompatibleAttempt(compatible, { sessionId, channelId: turn.channelId }, compatibleKey, undefined, attachments ? id => {
200
201
  const value = storage.readManagedAttachment(id); return value.ok ? value.value?.metadata : undefined;
201
202
  } : undefined) });
202
203
  return { model, tools: [echoDefinition, recordDefinition, holdDefinition], executeTool };
@@ -1,6 +1,7 @@
1
1
  import { validateMcpServers } from "./mcp-config.ts";
2
2
  import { validateWebConfig } from "./web-config.ts";
3
- import type { ManagedConfig, ToolDecision, ToolPolicy } from "../contracts/config-permissions.ts";
3
+ import { OPENCODE_GO_KEY_ENV, type CompatibleModel, type ManagedConfig, type ModelContextBudget, type ToolDecision, type ToolPolicy } from "../contracts/config-permissions.ts";
4
+ import { effectiveContextBudget, MAX_MODEL_REQUEST_BYTES } from "./context-budget.ts";
4
5
 
5
6
  /** The upgrade preserves the behavior of sessions created before policies existed. */
6
7
  export const LEGACY_POLICY = "__legacy_allow";
@@ -18,6 +19,24 @@ const keys = (value: Record<string, unknown>, allowed: string[], field: string)
18
19
  const name = (value: unknown, field: string): string => typeof value === "string" && value.trim() ? value : fail(field, "expected a nonempty string");
19
20
  const decision = (value: unknown, field: string): ToolDecision => value === "allow" || value === "ask" || value === "deny" ? value : fail(field, "expected allow, ask or deny");
20
21
 
22
+ function modelContextBudget(input: unknown): { contextBudget?: ModelContextBudget } {
23
+ if (input === undefined) return {};
24
+ const field = "config.model.contextBudget", raw = record(input, field);
25
+ const optional = ["outputReserveTokens", "maxOutputTokens", "estimationMarginTokens", "maxRequestBytes"] as const;
26
+ keys(raw, ["contextWindowTokens", ...optional], field);
27
+ function integer(key: keyof ModelContextBudget, min: number, max = Number.MAX_SAFE_INTEGER) {
28
+ const value = raw[key];
29
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max)
30
+ return fail(`${field}.${key}`, `expected an integer from ${min} to ${max}`);
31
+ return value;
32
+ }
33
+ const contextBudget: ModelContextBudget = { contextWindowTokens: integer("contextWindowTokens", 1) };
34
+ for (const key of optional) if (raw[key] !== undefined)
35
+ contextBudget[key] = integer(key, key === "estimationMarginTokens" ? 0 : 1, key === "maxRequestBytes" ? MAX_MODEL_REQUEST_BYTES : undefined);
36
+ if (effectiveContextBudget(contextBudget).inputBudgetTokens <= 0) fail(field, "expected a positive input allowance after reserves");
37
+ return { contextBudget };
38
+ }
39
+
21
40
  function baseUrl(value: unknown): string {
22
41
  const field = "config.model.baseUrl", raw = name(value, field);
23
42
  const match = /^(https?):\/\/([^/]+)(?:\/|$)/i.exec(raw);
@@ -47,17 +66,22 @@ export function validateManagedConfig(input: unknown, legacy = false): ManagedCo
47
66
  keys(model, ["protocol", "script", "imageInput"], "config.model");
48
67
  selectedModel = { protocol: "scripted", script: name(model.script, "config.model.script"), ...imageInput };
49
68
  } else if (model.protocol === "openrouter") {
50
- keys(model, ["protocol", "model", "apiKeyEnv", "imageInput"], "config.model");
69
+ keys(model, ["protocol", "model", "apiKeyEnv", "imageInput", "contextBudget"], "config.model");
51
70
  const reference = model.apiKeyEnv === undefined ? "OPENROUTER_API_KEY" : name(model.apiKeyEnv, "config.model.apiKeyEnv");
52
71
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
53
- selectedModel = { protocol: "openrouter", model: model.model === undefined ? "deepseek/deepseek-v4.1-flash" : name(model.model, "config.model.model"), apiKeyEnv: reference, ...imageInput };
72
+ selectedModel = { protocol: "openrouter", model: model.model === undefined ? "deepseek/deepseek-v4.1-flash" : name(model.model, "config.model.model"), apiKeyEnv: reference, ...imageInput, ...modelContextBudget(model.contextBudget) };
54
73
  } else if (model.protocol === "openai-compatible") {
55
- keys(model, ["protocol", "providerId", "model", "baseUrl", "apiKeyEnv"], "config.model");
74
+ keys(model, ["protocol", "providerId", "model", "baseUrl", "apiKeyEnv", "contextBudget"], "config.model");
56
75
  const reference = model.apiKeyEnv === undefined ? undefined : name(model.apiKeyEnv, "config.model.apiKeyEnv");
57
76
  if (reference !== undefined && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) fail("config.model.apiKeyEnv", "expected an environment variable name");
58
77
  selectedModel = { protocol: "openai-compatible", providerId: name(model.providerId, "config.model.providerId"),
59
- model: name(model.model, "config.model.model"), baseUrl: baseUrl(model.baseUrl), ...(reference === undefined ? {} : { apiKeyEnv: reference }) };
60
- } else return fail("config.model.protocol", "expected scripted, openrouter or openai-compatible");
78
+ model: name(model.model, "config.model.model"), baseUrl: baseUrl(model.baseUrl), ...(reference === undefined ? {} : { apiKeyEnv: reference }), ...modelContextBudget(model.contextBudget) };
79
+ } else if (model.protocol === "opencode-go") {
80
+ keys(model, ["protocol", "model", "apiKeyEnv", "contextBudget"], "config.model");
81
+ const reference = model.apiKeyEnv === undefined ? OPENCODE_GO_KEY_ENV : name(model.apiKeyEnv, "config.model.apiKeyEnv");
82
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(reference)) return fail("config.model.apiKeyEnv", "expected an environment variable name");
83
+ selectedModel = { protocol: "opencode-go", model: name(model.model, "config.model.model"), apiKeyEnv: reference, ...modelContextBudget(model.contextBudget) };
84
+ } else return fail("config.model.protocol", "expected scripted, openrouter, openai-compatible or opencode-go");
61
85
  const isLegacy = legacy && raw.defaultPolicy === undefined && raw.policies === undefined;
62
86
  const defaultPolicy = isLegacy ? LEGACY_POLICY : name(raw.defaultPolicy, "config.defaultPolicy");
63
87
  const policiesInput = isLegacy ? { [LEGACY_POLICY]: { fallback: "allow", tools: {} } } : record(raw.policies, "config.policies");
@@ -104,10 +128,11 @@ export function resolveCredential(model: Extract<ManagedConfig["model"], { proto
104
128
  }
105
129
 
106
130
 
107
- export function resolveCompatibleCredential(model: Extract<ManagedConfig["model"], { protocol: "openai-compatible" }>,
131
+ export function resolveCompatibleCredential(model: CompatibleModel,
108
132
  environment: Record<string, string | undefined>): string | undefined {
109
- if (model.apiKeyEnv === undefined) return;
110
- const value = environment[model.apiKeyEnv];
133
+ const reference = model.apiKeyEnv ?? (model.protocol === "opencode-go" ? OPENCODE_GO_KEY_ENV : undefined);
134
+ if (reference === undefined) return;
135
+ const value = environment[reference];
111
136
  if (!value?.trim() || /[\r\n]/.test(value)) return fail("config.model.apiKeyEnv", "configured credential is missing, empty or invalid");
112
137
  return value;
113
138
  }
@@ -0,0 +1,21 @@
1
+ import type { ModelContextBudget } from "../contracts/config-permissions.ts";
2
+ import type { ContextBudgetMeasurement } from "../contracts/context.ts";
3
+
4
+ export const MAX_MODEL_REQUEST_BYTES = 64 * 1024 * 1024;
5
+
6
+ export function effectiveContextBudget(profile: ModelContextBudget) {
7
+ const outputReserveTokens = Math.max(profile.outputReserveTokens ?? profile.maxOutputTokens ?? 2048, profile.maxOutputTokens ?? 0);
8
+ const estimationMarginTokens = profile.estimationMarginTokens ?? 1024;
9
+ return {
10
+ contextWindowTokens: profile.contextWindowTokens,
11
+ outputReserveTokens,
12
+ estimationMarginTokens,
13
+ inputBudgetTokens: profile.contextWindowTokens - outputReserveTokens - estimationMarginTokens,
14
+ maxRequestBytes: profile.maxRequestBytes ?? MAX_MODEL_REQUEST_BYTES,
15
+ };
16
+ }
17
+
18
+ export function exceededContextBudget(budget: ContextBudgetMeasurement) {
19
+ if (budget.estimatedInputTokens > budget.inputBudgetTokens) return { limit: "input_tokens", budget } as const;
20
+ if (budget.requestBytes > budget.maxRequestBytes) return { limit: "request_bytes", budget } as const;
21
+ }