@qlairoslabs/acp-client 0.13.3-alpha.1 → 0.13.4-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
@@ -1209,15 +1209,28 @@ 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
+ Set `harness.config.model.contextBudget` on OpenRouter or OpenAI-compatible models
1221
+ to fit a larger inference request. For example, a model with a 128,000-token
1222
+ window can use `contextBudget: { contextWindowTokens: 128_000, outputReserveTokens: 4096 }`.
1223
+ The reserve only affects local fitting. Set `maxOutputTokens` to also request an
1224
+ upstream cap. This uses `max_tokens` with OpenRouter and
1225
+ `max_completion_tokens` with a custom Chat Completions endpoint that supports it.
1226
+ The estimate uses UTF-8 request size for text and a separate image allowance.
1227
+ Use `estimationMarginTokens` to leave extra room. The independent serialized
1228
+ request cap defaults to 64 MiB and can be lowered with `maxRequestBytes`.
1229
+ The harness fits optional history around the complete policy-filtered offer.
1230
+ A failed turn reports `context_limit` and leaves the channel usable. The
1231
+ underlying `NativeTurnError.contextFailure` gives the applicable limit and,
1232
+ for local token and byte limits, the measured budget.
1233
+
1221
1234
  ```ts
1222
1235
  import { NativeInputStoppedError, type Agent, type ItemsReceipt } from "@qlairoslabs/acp-client";
1223
1236
 
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.4-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,17 +1,41 @@
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
- import { createHash } from "node:crypto";
2
+ import { imageDataPrefix, readVerifiedImage, VisionInputError, type AttachmentLookup } from "../attachments/vision.ts";
3
+ import { ATTACHMENT_LIMITS, type AttachmentMetadata } from "../../contracts/attachments.ts";
4
+ import { chatRequestSizer, prepareChatRequest } from "./chat-request.ts";
5
+ import { exceededContextBudget } from "../../util/context-budget.ts";
6
6
 
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;
7
+ const providerContextFailure = { type: "failure", kind: "invalid_request", message: "Provider rejected the request context length",
8
+ contextFailure: { limit: "provider_context" } } as const;
9
+
10
+ function isProviderContextError(value: unknown): boolean {
11
+ if (!value || typeof value !== "object" || !("error" in value) || !value.error || typeof value.error !== "object") return false;
12
+ const error = value.error;
13
+ if ("code" in error && ["context_length_exceeded", "context_window_exceeded", "max_context_length_exceeded"].includes(String(error.code))) return true;
14
+ return "message" in error && typeof error.message === "string" && /maximum context length|context window (?:has been |is )?exceeded/i.test(error.message);
15
+ }
16
+
17
+ /** Error bodies are only needed for classification. Read a small prefix and
18
+ * release the response even if the endpoint sends an unbounded body. */
19
+ async function readContextError(response: Response): Promise<boolean> {
20
+ if (!response.body) return false;
21
+ const reader = response.body.getReader(), decoder = new TextDecoder();
22
+ let value = "", remaining = 16 * 1024;
23
+ try {
24
+ while (remaining > 0) {
25
+ const chunk = await reader.read();
26
+ if (chunk.done) return isProviderContextError(JSON.parse(value + decoder.decode()));
27
+ value += decoder.decode(chunk.value.subarray(0, remaining), { stream: true });
28
+ remaining -= chunk.value.byteLength;
29
+ }
30
+ return isProviderContextError(JSON.parse(value + decoder.decode()));
31
+ } catch { return false; }
32
+ finally { void reader.cancel().catch(() => {}); reader.releaseLock(); }
11
33
  }
34
+
12
35
  /** OpenRouter SSE translation stays at the provider boundary; tool fragments are
13
36
  * 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> };
37
+ type Vision = { supported: boolean; metadata: AttachmentLookup; read: (metadata: AttachmentMetadata) => Uint8Array;
38
+ verify?: (metadata: AttachmentMetadata, signal: AbortSignal) => Promise<void> };
15
39
  export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, vision?: Vision): ModelAttempt {
16
40
  return chatAttempt(apiKey, model, fetcher, onRequest, undefined, vision);
17
41
  }
@@ -22,47 +46,60 @@ export function openAICompatibleAttempt(baseUrl: string, model: string, apiKey?:
22
46
  function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void, endpoint?: string, vision?: Vision): ModelAttempt {
23
47
  return async function* (request, signal) {
24
48
  const imageUrls: string[] = [];
25
- let messages: unknown[];
49
+ const compatible = endpoint !== undefined;
50
+ const profile = request.contextBudget;
51
+ const wire = prepareChatRequest(model, compatible, request.tools, profile?.maxOutputTokens);
52
+ let budget, messages: string;
26
53
  try {
27
54
  let imageBytes = 0;
28
55
  const unavailable = new Set<string>();
29
- const images = new Map<string, ReturnType<NonNullable<typeof vision>["metadata"]>>();
56
+ const images = new Map<string, AttachmentMetadata>(), references = new Map<string, AttachmentMetadata>();
30
57
  for (const message of request.messages) if (message.role === "user" && message.parts) {
31
58
  if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
32
59
  for (const part of message.parts) if (part.type === "attachment") {
33
60
  const metadata = vision.metadata(part.id);
34
61
  if (!metadata) unavailable.add(part.id);
35
- else if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
62
+ else {
63
+ references.set(part.id, metadata);
64
+ if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
65
+ }
36
66
  }
37
67
  }
38
68
  if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
39
69
  if (endpoint && images.size) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
40
70
  if (imageBytes > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
41
71
  if (images.size && !vision!.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
72
+ const metadata = vision && ((id: string) => references.get(id));
73
+ if (profile) {
74
+ budget = chatRequestSizer(model, compatible, profile, metadata)(request.tools)(request.messages);
75
+ const contextFailure = exceededContextBudget(budget);
76
+ if (contextFailure) {
77
+ yield { type: "failure", kind: "invalid_request", message: "Request exceeds the configured context budget", contextFailure };
78
+ return;
79
+ }
80
+ }
42
81
  const bytes = new Map<string, Uint8Array>();
43
82
  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);
83
+ await vision!.verify?.(metadata, signal);
84
+ bytes.set(id, readVerifiedImage(metadata, vision!.read));
48
85
  } catch { unavailable.add(id); }
49
86
  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 };
87
+ messages = wire.messages(request.messages, metadata, compatible ? undefined : image => {
88
+ const url = imageDataPrefix(image.mediaType) + Buffer.from(bytes.get(image.id)!).toString("base64");
89
+ imageUrls.push(url);
90
+ return url;
59
91
  });
60
92
  } catch (error) {
61
93
  if (error instanceof VisionInputError) { yield { type: "failure", kind: "invalid_request", code: error.code, attachmentIds: error.attachmentIds, message: error.message }; return; }
62
94
  throw error;
63
95
  }
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" } : {}) } : {}) });
96
+ const requestBytes = wire.fixedBytes + Buffer.byteLength(messages);
97
+ if (budget && requestBytes > budget.maxRequestBytes) {
98
+ yield { type: "failure", kind: "invalid_request", message: "Encoded request exceeds the byte cap",
99
+ contextFailure: { limit: "request_bytes", budget: { ...budget, requestBytes } } };
100
+ return;
101
+ }
102
+ const body = wire.body(messages);
66
103
  const redact = (text: string) => {
67
104
  let safe = apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text;
68
105
  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]"); }
@@ -75,11 +112,21 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
75
112
  catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
76
113
  if (!response.ok) {
77
114
  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; }
115
+ if (response.status >= 300 && response.status < 400) {
116
+ void response.body?.cancel().catch(() => {});
117
+ yield { type: "failure", kind: "provider", message: "redirect_refused" }; return;
118
+ }
119
+ if (await readContextError(response)) { yield providerContextFailure; return; }
80
120
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
81
121
  }
82
- const text = redact(await response.text());
122
+ if (profile) {
123
+ if (await readContextError(response)) { yield providerContextFailure; return; }
124
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request",
125
+ message: `OpenRouter HTTP ${response.status}` }; return;
126
+ }
127
+ const raw = await response.text();
128
+ try { if (isProviderContextError(JSON.parse(raw))) { yield providerContextFailure; return; } } catch { /* Non-JSON error body. */ }
129
+ const text = redact(raw);
83
130
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
84
131
  }
85
132
  const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
@@ -99,6 +146,7 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
99
146
  const data = line.slice(5).trim(); if (!data || data === "[DONE]") continue;
100
147
  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
148
  try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: endpoint ? "Malformed Chat Completions stream" : "Malformed OpenRouter stream" }; return; }
149
+ if (isProviderContextError(payload)) { yield providerContextFailure; return; }
102
150
  if (!providerId && payload.id) providerId = safeRequestId(payload.id);
103
151
  // A parsed response frame, unlike an HTTP success header, is evidence
104
152
  // the provider has accepted the inference request.
@@ -130,6 +178,6 @@ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof
130
178
  ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
131
179
  yield event;
132
180
  } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; }
133
- finally { if (endpoint) void reader.cancel().catch(() => {}); reader.releaseLock(); }
181
+ finally { if (endpoint || profile) void reader.cancel().catch(() => {}); reader.releaseLock(); }
134
182
  };
135
183
  }
@@ -5,7 +5,8 @@ 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) { super(message); this.name = "ModelCallError"; }
9
10
  }
10
11
  class ModelStorageError extends Error {}
11
12
  function take<T>(result: StorageResult<T>): T {
@@ -42,11 +43,12 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
42
43
  options.started?.(call.callId);
43
44
  let deadline = 0, output = false;
44
45
  const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
45
- attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure): never => {
46
+ attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure,
47
+ contextFailure?: import("../../contracts/context.ts").ContextLimitFailure): never => {
46
48
  const result = options.store.finishCall(call.callId, outcome);
47
49
  if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
48
50
  if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
49
- throw new ModelCallError(outcome, detail, attachmentFailure);
51
+ throw new ModelCallError(outcome, detail, attachmentFailure, contextFailure);
50
52
  };
51
53
  for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
52
54
  if (options.signal?.aborted) return finish("interrupted");
@@ -105,6 +107,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
105
107
  take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
106
108
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
107
109
  if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
110
+ if (terminal?.type === "failure" && terminal.contextFailure) return finish("failed", terminal.message, undefined, terminal.contextFailure);
108
111
  if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) return finish(failure === "incomplete" ? "incomplete" : "failed");
109
112
  if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
110
113
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
@@ -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,17 @@ 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 };
10
18
  /** Decision 0035: independent portable web backends, with credential names only. */
11
19
  export interface ExaSearchConfig { backend: "exa"; apiKeyEnv?: string; maxResults?: number; excerptBytes?: number; deadlineMs?: number }
12
20
  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,8 @@ 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 };
34
37
  /** One attempt emits exactly one terminal response or failure unless aborted;
35
38
  * EOF without a terminal is incomplete. A consumer ignores events after the
36
39
  * 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
  }
@@ -13,6 +13,8 @@ import type { EventSink, SessionEventSink } from "./contracts/events.ts";
13
13
  import type { SessionStorage } from "./contracts/storage.ts";
14
14
  import { createMemoryStorageAdapter } from "./state/storage/memory.ts";
15
15
  import { CONTEXT_LIMITS, createSessionContext } from "./capabilities/context/session.ts";
16
+ import { chatRequestSizer } from "./capabilities/model/chat-request.ts";
17
+ import type { ContextLimitFailure } from "./contracts/context.ts";
16
18
  import { createChannelScheduler } from "./kernel/channels.ts";
17
19
  import { runTurn } from "./kernel/loop.ts";
18
20
  import { ModelCallError, runModelCall } from "./capabilities/model/runner.ts";
@@ -69,8 +71,16 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
69
71
  const sessionReminderDefinitions = unattended.value === undefined ? reminderDefinitions : guardedReminderDefinitions;
70
72
  const identity = store.readSession();
71
73
  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" });
74
+ const modelConfig = owner.value?.model;
75
+ const contextBudget = modelConfig?.protocol !== "scripted" ? modelConfig?.contextBudget : undefined;
76
+ const sizeRequest = modelConfig && modelConfig.protocol !== "scripted" && contextBudget
77
+ ? chatRequestSizer(modelConfig.model, modelConfig.protocol === "openai-compatible", contextBudget, id => {
78
+ const attachment = store.readManagedAttachment?.(id);
79
+ return attachment?.ok ? attachment.value?.metadata : undefined;
80
+ }) : undefined;
81
+ const context = createSessionContext(store, identity.value.sessionId, options.systemPrompt, CONTEXT_LIMITS, options.captureContext, sizeRequest);
82
+ const limitError = (detail?: ContextLimitFailure) => Object.assign(new Error("Required inference material exceeds the context budget"),
83
+ { outcome: detail ? `context_limit:${JSON.stringify(detail)}` : "context_limit" });
74
84
  const position = (channel: string, seq: string) => messagePosition(identity.value.sessionId, channel, Number(seq));
75
85
  const emit: EventSink = value => {
76
86
  const { channel, event } = value;
@@ -111,7 +121,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
111
121
  const policySnapshot = () => {
112
122
  const read = store.readInferencePolicies(turn.turnId, CONTEXT_LIMITS);
113
123
  if (!read.ok) throw new Error(read.error.message);
114
- if ("code" in read.value) throw limitError();
124
+ if ("code" in read.value) throw limitError(contextBudget ? { limit: "required_storage" } : undefined);
115
125
  return read.value;
116
126
  };
117
127
  /** The names offered by this turn's latest inference: what a call must match. */
@@ -230,13 +240,14 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
230
240
  },
231
241
  }, async signal => {
232
242
  const built = context.build(turn, offer);
233
- if (!built.ok) throw limitError();
243
+ if (!built.ok) throw limitError(built.detail);
234
244
  const { tools, fixedToolCount, messages, takenItemIds, representedItemIds: itemIds } = built.value;
235
245
  phase(turn.turnId, "model");
236
246
  const binding = getModelAttempt(services.model);
237
247
  let draftId: string | undefined;
238
248
  try {
239
- const result = await runModelCall({ turnId: String(turn.turnId), itemIds, request: { messages, tools, takenItemIds, ...(fixedToolCount === undefined ? {} : { fixedToolCount }) },
249
+ const result = await runModelCall({ turnId: String(turn.turnId), itemIds, request: { messages, tools, takenItemIds,
250
+ ...(contextBudget ? { contextBudget } : {}), ...(fixedToolCount === undefined ? {} : { fixedToolCount }) },
240
251
  started: callId => {
241
252
  phase(turn.turnId, "model", callId);
242
253
  try { options.observeModelCall?.(turn.channelId, turn.turnId, callId); } catch { /* best-effort observation */ }
@@ -258,6 +269,7 @@ export function createSession(options: Omit<PersistentSessionOptions, "storage">
258
269
  // A storage failure can occur after a draft was published but before the
259
270
  // runner can write a normal terminal outcome. The draft must still end.
260
271
  if (error instanceof ModelCallError && error.message === "script_exhausted") throw Object.assign(new Error(error.message), { outcome: "script_exhausted" });
272
+ if (error instanceof ModelCallError && error.contextFailure) throw limitError(error.contextFailure);
261
273
  if (draftId && !(error instanceof ModelCallError)) emit({ channel: turn.channelId,
262
274
  event: { type: "text_incomplete", turnId: String(turn.turnId), messageId: draftId, reason: "failed" } });
263
275
  throw error;
@@ -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,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 type { ManagedConfig, ModelContextBudget, ToolDecision, 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,16 +66,16 @@ 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 }) };
78
+ model: name(model.model, "config.model.model"), baseUrl: baseUrl(model.baseUrl), ...(reference === undefined ? {} : { apiKeyEnv: reference }), ...modelContextBudget(model.contextBudget) };
60
79
  } else return fail("config.model.protocol", "expected scripted, openrouter or openai-compatible");
61
80
  const isLegacy = legacy && raw.defaultPolicy === undefined && raw.policies === undefined;
62
81
  const defaultPolicy = isLegacy ? LEGACY_POLICY : name(raw.defaultPolicy, "config.defaultPolicy");
@@ -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
+ }