@arnilo/prism-hosts 0.13.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/a2a/README.md +195 -0
  3. package/a2a/src/card.ts +208 -0
  4. package/a2a/src/codec.ts +523 -0
  5. package/a2a/src/connect.ts +415 -0
  6. package/a2a/src/errors.ts +87 -0
  7. package/a2a/src/index.ts +40 -0
  8. package/a2a/src/limits.ts +43 -0
  9. package/a2a/src/pending.ts +28 -0
  10. package/a2a/src/proxy.ts +526 -0
  11. package/a2a/src/serve.ts +886 -0
  12. package/acp/README.md +3 -1
  13. package/acp/src/limits.ts +3 -16
  14. package/acp/src/mapper.ts +26 -5
  15. package/acp/src/serve.ts +6 -5
  16. package/ag-ui/README.md +2 -1
  17. package/ag-ui/src/a2ui.ts +8 -31
  18. package/ag-ui/src/ag-ui-mapper.ts +27 -1
  19. package/ag-ui/src/encrypted-value.ts +3 -3
  20. package/ag-ui/src/handler.ts +4 -4
  21. package/ag-ui/src/index.ts +0 -33
  22. package/ag-ui/src/limits.ts +5 -88
  23. package/ag-ui/src/projectors.ts +8 -6
  24. package/ag-ui/src/renderer/bind.ts +2 -1
  25. package/channels/README.md +61 -5
  26. package/channels/src/discord-gateway.ts +354 -0
  27. package/channels/src/discord.ts +873 -0
  28. package/channels/src/index.ts +4 -2
  29. package/channels/src/limits.ts +3 -19
  30. package/channels/src/pairing.ts +1 -2
  31. package/channels/src/runtime-turn.ts +10 -2
  32. package/channels/src/signal.ts +11 -19
  33. package/channels/src/slack.ts +854 -0
  34. package/channels/src/telegram.ts +22 -44
  35. package/channels/src/types.ts +5 -2
  36. package/devtools/README.md +1 -1
  37. package/driver-process/src/driver.ts +3 -1
  38. package/driver-process/src/testing.ts +1 -1
  39. package/driver-process/src/turn.ts +5 -1
  40. package/evals/README.md +11 -7
  41. package/evals/src/calibration.ts +5 -13
  42. package/evals/src/compare-experiments.ts +1 -2
  43. package/evals/src/comparison.ts +7 -25
  44. package/evals/src/curate.ts +3 -9
  45. package/evals/src/dataset.ts +0 -2
  46. package/evals/src/index.ts +3 -20
  47. package/evals/src/injection.ts +33 -6
  48. package/evals/src/judge.ts +9 -13
  49. package/evals/src/limits.ts +0 -17
  50. package/evals/src/rubric-judge.ts +5 -10
  51. package/evals/src/scenario-runner.ts +8 -4
  52. package/evals/src/scenarios.ts +5 -5
  53. package/evals/src/score.ts +3 -5
  54. package/evals/src/stats.ts +0 -2
  55. package/evals/src/threshold.ts +3 -3
  56. package/evals/src/toolless-session.ts +7 -3
  57. package/evals/src/trace.ts +8 -14
  58. package/evals/src/trajectory.ts +45 -11
  59. package/evals/src/types.ts +2 -2
  60. package/evals/src/user-simulator.ts +1 -7
  61. package/evals/src/util.ts +3 -9
  62. package/headless/README.md +20 -1
  63. package/headless/src/authority.ts +14 -1
  64. package/headless/src/errors.ts +3 -1
  65. package/headless/src/index.ts +10 -1
  66. package/headless/src/limits.ts +2 -2
  67. package/headless/src/pending.ts +4 -3
  68. package/headless/src/recover.ts +126 -0
  69. package/headless/src/resume.ts +1 -1
  70. package/host-builder/data/api.json +1271 -1360
  71. package/host-builder/data/errors.json +199 -185
  72. package/host-builder/data/examples/a2a-client.ts +125 -0
  73. package/host-builder/data/examples/a2a-server.ts +133 -0
  74. package/host-builder/data/examples/autonomous-coding-loop.ts +1 -1
  75. package/host-builder/data/examples/build-workflow.ts +2 -2
  76. package/host-builder/data/examples/caveman-ponytail.ts +1 -1
  77. package/host-builder/data/examples/channel-discord.ts +176 -0
  78. package/host-builder/data/examples/channel-slack.ts +146 -0
  79. package/host-builder/data/examples/continue-after-failure.ts +80 -0
  80. package/host-builder/data/examples/custom-adapter.ts +1 -1
  81. package/host-builder/data/examples/decision-models.ts +1 -1
  82. package/host-builder/data/examples/define-package.ts +1 -1
  83. package/host-builder/data/examples/delegate.ts +74 -9
  84. package/host-builder/data/examples/durable-loops-and-approvals.ts +11 -10
  85. package/host-builder/data/examples/governance-deny.ts +1 -1
  86. package/host-builder/data/examples/guardrail-content.ts +126 -0
  87. package/host-builder/data/examples/headless-host.ts +1 -1
  88. package/host-builder/data/examples/long-running-job.ts +129 -0
  89. package/host-builder/data/examples/long-term-memory.ts +1 -1
  90. package/host-builder/data/examples/mcp-oauth.ts +197 -0
  91. package/host-builder/data/examples/mcp-trust.ts +1 -1
  92. package/host-builder/data/examples/memory-and-wiki.ts +2 -2
  93. package/host-builder/data/examples/memory-system.ts +19 -9
  94. package/host-builder/data/examples/model-router-aggregate-budgets.ts +1 -1
  95. package/host-builder/data/examples/parallel-tools.ts +70 -0
  96. package/host-builder/data/examples/remote-agent.ts +1 -1
  97. package/host-builder/data/examples/serve-tools.ts +1 -1
  98. package/host-builder/data/examples/session-memory.ts +18 -16
  99. package/host-builder/data/examples/side-call.ts +1 -1
  100. package/host-builder/data/examples/sqlite-resume.ts +1 -1
  101. package/host-builder/data/examples/structured-output.ts +57 -0
  102. package/host-builder/data/examples.json +14 -4
  103. package/host-builder/skills/prism-host-builder/SKILL.md +1 -1
  104. package/host-builder/skills/prism-host-builder/references/choosing.md +14 -10
  105. package/host-builder/skills/prism-host-builder/references/pitfalls.md +5 -3
  106. package/host-builder/skills/prism-host-builder/references/recipes.md +5 -5
  107. package/host-builder/skills/prism-host-builder/references/verification.md +1 -1
  108. package/host-builder/src/check/runner.ts +2 -3
  109. package/host-builder/src/server.ts +2 -2
  110. package/mcp-server/README.md +3 -3
  111. package/mcp-server/src/bounds.ts +3 -3
  112. package/mcp-server/src/serve-tools.ts +2 -9
  113. package/mcp-server/src/serve.ts +2 -4
  114. package/mcp-server/src/server.ts +10 -20
  115. package/package.json +12 -6
  116. package/remote/README.md +7 -4
  117. package/remote/src/channel.ts +6 -2
  118. package/remote/src/connect.ts +9 -3
  119. package/remote/src/errors.ts +3 -1
  120. package/remote/src/limits.ts +3 -13
  121. package/remote/src/mirror.ts +2 -1
  122. package/remote/src/pending.ts +4 -3
  123. package/remote/src/protocol.ts +3 -0
  124. package/remote/src/serve.ts +43 -5
  125. package/remote/src/session-proxy.ts +28 -5
  126. package/remote/src/testing.ts +3 -1
  127. package/remote/src/wire.ts +74 -14
@@ -1,6 +1,6 @@
1
1
  import { RemoteError } from "./errors.js";
2
2
 
3
- /** Defaults. A host may narrow them, never raise them past the hard maxima. */
3
+ /** Defaults. The host sets each (`limits`); its value is the cap (plan 239 Task 5). */
4
4
  export const REMOTE_LIMITS = {
5
5
  maxFrameBytes: 1024 * 1024,
6
6
  maxConnections: 64,
@@ -10,15 +10,6 @@ export const REMOTE_LIMITS = {
10
10
  maxQueuedEvents: 1_000,
11
11
  } as const;
12
12
 
13
- const HARD = {
14
- maxFrameBytes: 16 * 1024 * 1024,
15
- maxConnections: 1_024,
16
- keepAliveMs: 60_000,
17
- maxConcurrentRequests: 256,
18
- maxPendingRequests: 1_024,
19
- maxQueuedEvents: 100_000,
20
- } as const;
21
-
22
13
  export type RemoteLimitName = keyof typeof REMOTE_LIMITS;
23
14
 
24
15
  export type RemoteLimitOptions = { readonly [K in RemoteLimitName]?: number };
@@ -34,10 +25,9 @@ export function resolveRemoteLimits(options: RemoteLimitOptions = {}): ResolvedR
34
25
  }
35
26
 
36
27
  function validate(name: RemoteLimitName, value: number): number {
37
- const hard = HARD[name];
38
28
  const minimum = name === "maxFrameBytes" ? 1024 : 1;
39
- if (!Number.isSafeInteger(value) || value < minimum || value > hard) {
40
- throw new RemoteError("limit", `${name} must be a safe integer from ${minimum} through ${hard}`);
29
+ if (!Number.isSafeInteger(value) || value < minimum) {
30
+ throw new RemoteError("limit", `${name} must be a safe integer of at least ${minimum}`);
41
31
  }
42
32
  return value;
43
33
  }
@@ -51,7 +51,8 @@ export function createSessionMirror(options: MirrorOptions): SessionMirror {
51
51
  ...(tip !== undefined ? { parentId: tip } : {}),
52
52
  metadata: stamp,
53
53
  };
54
- await store.append(full, tip !== undefined ? { expectedParentId: tip } : undefined);
54
+ // A linear append: a second writer on the mirrored session fails the mirror instead of forking it (plan 230 Task 2).
55
+ await store.append(full, tip !== undefined ? { expectedParentId: tip, tip: true } : undefined);
55
56
  tip = full.id;
56
57
  };
57
58
 
@@ -1,4 +1,4 @@
1
- import { type PendingDecision, parseSuspendedRunEntry, type SessionEntry } from "@arnilo/prism";
1
+ import { type PendingDecision, parseSuspendedRunEntry, type RunStateBounds, type SessionEntry } from "@arnilo/prism";
2
2
 
3
3
  /**
4
4
  * The decisions a session's branch is waiting on. `pendingSuspensionOf` is not public, so this applies its
@@ -6,14 +6,15 @@ import { type PendingDecision, parseSuspendedRunEntry, type SessionEntry } from
6
6
  * `suspended_run`. Anything appended after it means that suspension was resolved or abandoned. A malformed
7
7
  * entry yields nothing, so it never resumes.
8
8
  */
9
- export function pendingDecisionsOf(branch: readonly SessionEntry[]): readonly PendingDecision[] {
9
+ /** `bounds` are the agent's run-state bounds (`runStateBounds(resolveCeilings(agent.config.ceilings))`), so a host with raised ceilings reads its own suspensions. */
10
+ export function pendingDecisionsOf(branch: readonly SessionEntry[], bounds?: RunStateBounds): readonly PendingDecision[] {
10
11
  for (let index = branch.length - 1; index >= 0; index -= 1) {
11
12
  const entry = branch[index];
12
13
  if (!entry) continue;
13
14
  if (entry.kind === "package_state") continue;
14
15
  if (entry.kind !== "suspended_run") return [];
15
16
  try {
16
- return parseSuspendedRunEntry(entry).interruption.pendingDecisions ?? [];
17
+ return parseSuspendedRunEntry(entry, bounds).interruption.pendingDecisions ?? [];
17
18
  } catch {
18
19
  return [];
19
20
  }
@@ -15,6 +15,7 @@ export const CLIENT_METHODS = [
15
15
  "sessions.open",
16
16
  "sessions.list",
17
17
  "sessions.resume",
18
+ "sessions.continue",
18
19
  "sessions.messages",
19
20
  "run",
20
21
  "steer",
@@ -66,6 +67,8 @@ export interface RemoteMethods {
66
67
  "sessions.list": { params: { query?: JsonObject }; result: JsonValue };
67
68
  /** `decisions` accepts only `approvalId` (≤ 256), `outcome`, `reason` (≤ 2 KiB), `elicitation` (pending elicitation only), and `modifiedArguments` only when `ServeAgentOptions.allowModifiedArguments: true`. */
68
69
  "sessions.resume": { params: { sessionId: string; decisions: readonly Decision[] }; result: { runId: string } };
70
+ /** `Session.continue` over the wire: a run with no new input on a branch that owes a model turn. Same `options` subset as `run`. */
71
+ "sessions.continue": { params: { sessionId: string; options?: RemoteRunOptions }; result: { runId: string } };
69
72
  "sessions.messages": { params: { sessionId: string }; result: { messages: readonly JsonObject[] } };
70
73
  run: { params: { sessionId: string; input: JsonValue; options?: RemoteRunOptions }; result: { runId: string } };
71
74
  /** `options` accepts only `{ softInterrupt?: boolean }`. */
@@ -12,9 +12,15 @@ import {
12
12
  OwnershipScopeError,
13
13
  type PendingDecision,
14
14
  type Principal,
15
+ resolveCeilings,
16
+ type ResolvedRunLimits,
17
+ resolveRunLimits,
18
+ type RunStateBounds,
19
+ runStateBounds,
15
20
  type RunOptions,
16
21
  type RunResult,
17
22
  type Session,
23
+ SESSION_NOTHING_TO_CONTINUE_CODE,
18
24
  } from "@arnilo/prism";
19
25
  import { createDispatcher, type Dispatcher, type RemoteHandler } from "./dispatcher.js";
20
26
  import { RemoteError } from "./errors.js";
@@ -98,6 +104,12 @@ export interface ServerState {
98
104
  readonly resuming: Set<string>;
99
105
  readonly active: Set<string>;
100
106
  readonly limits: ResolvedRemoteLimits;
107
+ /** The agent's own resolved run limits; a client's `limits` may only narrow them. */
108
+ readonly agentLimits: Readonly<ResolvedRunLimits>;
109
+ /** The agent's `ceilings.pendingDecisions`: most decisions one resume carries. */
110
+ readonly maxDecisions: number;
111
+ /** The agent's run-state bounds, so a raised `ceilings.runStateBytes` still lists its pending decisions. */
112
+ readonly runStateBounds: RunStateBounds;
101
113
  readonly hostUi?: HostUi;
102
114
  }
103
115
 
@@ -143,6 +155,9 @@ export function createServerState(
143
155
  resuming: new Set(),
144
156
  active: new Set(),
145
157
  limits: resolveRemoteLimits(options.limits),
158
+ agentLimits: resolveRunLimits(agent.config?.limits, undefined, resolveCeilings(agent.config?.ceilings)),
159
+ maxDecisions: resolveCeilings(agent.config?.ceilings).pendingDecisions,
160
+ runStateBounds: runStateBounds(resolveCeilings(agent.config?.ceilings)),
146
161
  ...(options.hostUi ? { hostUi: options.hostUi } : {}),
147
162
  };
148
163
  if (options.hostUi) {
@@ -220,6 +235,9 @@ function mapOwnershipError(error: unknown): unknown {
220
235
  if (isSessionNotFound(error) || error instanceof OwnershipScopeError) {
221
236
  return new RemoteError("session_not_found", "session not found");
222
237
  }
238
+ if (error instanceof Error && (error as { code?: unknown }).code === SESSION_NOTHING_TO_CONTINUE_CODE) {
239
+ return new RemoteError("nothing_to_continue", "session has nothing to continue");
240
+ }
223
241
  return error;
224
242
  }
225
243
 
@@ -380,7 +398,7 @@ export function serveConnection(state: ServerState, transport: RemoteTransport,
380
398
  if (state.resuming.has(target.id) || state.active.has(target.id)) return;
381
399
  delivering.add(target.id);
382
400
  try {
383
- const pending: readonly PendingDecision[] = pendingDecisionsOf(await target.entries());
401
+ const pending: readonly PendingDecision[] = pendingDecisionsOf(await target.entries(), state.runStateBounds);
384
402
  if (pending.length === 0) return;
385
403
  const decisions: Decision[] = [];
386
404
  for (const item of pending) {
@@ -457,27 +475,47 @@ export function serveConnection(state: ServerState, transport: RemoteTransport,
457
475
  },
458
476
  async "sessions.list"(params) {
459
477
  const listQuery = parseSessionListQuery(params.query, ownership);
460
- return (await agent.sessions.list(listQuery)) as unknown as JsonValue;
478
+ try {
479
+ return (await agent.sessions.list(listQuery)) as unknown as JsonValue;
480
+ } catch (error) {
481
+ // The store bounds the page by its own `queryLimits.maxListLimit` and refuses a larger one with a TypeError.
482
+ if (error instanceof TypeError && /limit/.test(error.message)) throw new RemoteError("invalid_params", error.message);
483
+ throw error;
484
+ }
461
485
  },
462
486
  async "sessions.messages"(params) {
463
487
  return { messages: (await session(str(params, "sessionId")).messages()) as unknown as JsonValue[] };
464
488
  },
465
489
  async "sessions.resume"(params) {
466
490
  const target = session(str(params, "sessionId"));
467
- const pending = typeof target.entries === "function" ? pendingDecisionsOf(await target.entries()) : [];
491
+ const pending = typeof target.entries === "function" ? pendingDecisionsOf(await target.entries(), state.runStateBounds) : [];
468
492
  return resume(
469
493
  target,
470
494
  parseDecisions(params.decisions, {
471
495
  allowModifiedArguments: state.allowModifiedArguments === true,
472
496
  pending,
497
+ maxDecisions: state.maxDecisions,
473
498
  }),
474
- parseRunOptions(params.options, principal, ownership),
499
+ parseRunOptions(params.options, principal, ownership, state.agentLimits),
475
500
  );
476
501
  },
502
+ async "sessions.continue"(params) {
503
+ const target = session(str(params, "sessionId"));
504
+ const runOptions = parseRunOptions(params.options, principal, ownership, state.agentLimits);
505
+ if (state.resuming.has(target.id) || state.active.has(target.id))
506
+ throw new RemoteError("busy", "session already has a run in progress");
507
+ state.active.add(target.id);
508
+ try {
509
+ return await startRun(target, target.continueStream({ ...runOptions, maxQueuedEvents: limits.maxQueuedEvents }));
510
+ } catch (error) {
511
+ state.active.delete(target.id);
512
+ throw mapOwnershipError(error);
513
+ }
514
+ },
477
515
  async run(params) {
478
516
  const target = session(str(params, "sessionId"));
479
517
  const input = parseInput(params.input);
480
- const runOptions = parseRunOptions(params.options, principal, ownership);
518
+ const runOptions = parseRunOptions(params.options, principal, ownership, state.agentLimits);
481
519
  if (state.resuming.has(target.id) || state.active.has(target.id))
482
520
  throw new RemoteError("busy", "session already has a run in progress");
483
521
  state.active.add(target.id);
@@ -1,4 +1,12 @@
1
- import type { AgentEvent, Decision, Message, RunOptions, RunResult, Session } from "@arnilo/prism";
1
+ import {
2
+ type AgentEvent,
3
+ type Decision,
4
+ type Message,
5
+ type RunOptions,
6
+ type RunResult,
7
+ type Session,
8
+ SessionContinueError,
9
+ } from "@arnilo/prism";
2
10
  import { type AttributionSource, attribute } from "./attribution.js";
3
11
  import { type Channel, createChannel } from "./channel.js";
4
12
  import type { Dispatcher } from "./dispatcher.js";
@@ -132,7 +140,7 @@ export function createSessionProxy(
132
140
 
133
141
  /** Registers the run before the request goes out, so no early notification is lost. */
134
142
  const start = (
135
- method: "run" | "sessions.resume",
143
+ method: "run" | "sessions.resume" | "sessions.continue",
136
144
  body: Record<string, unknown>,
137
145
  options: RunOptions | undefined,
138
146
  withEvents: boolean,
@@ -150,9 +158,17 @@ export function createSessionProxy(
150
158
  if (signal?.aborted) abortRemote();
151
159
  else signal?.addEventListener("abort", abortRemote, { once: true });
152
160
  const wire = wireOptions(options);
153
- void dispatcher
154
- .request(method, { sessionId, ...body, ...(wire ? { options: wire as never } : {}) } as never)
155
- .catch((error) => fail(run, error instanceof Error ? error : new RemoteError("internal_error", "request failed")));
161
+ void dispatcher.request(method, { sessionId, ...body, ...(wire ? { options: wire as never } : {}) } as never).catch((error) =>
162
+ fail(
163
+ run,
164
+ // The kernel's own error type, so `continue()` rejects the same way locally and over the wire.
165
+ error instanceof RemoteError && error.code === "nothing_to_continue"
166
+ ? new SessionContinueError(sessionId)
167
+ : error instanceof Error
168
+ ? error
169
+ : new RemoteError("internal_error", "request failed"),
170
+ ),
171
+ );
156
172
  return run;
157
173
  };
158
174
 
@@ -174,6 +190,10 @@ export function createSessionProxy(
174
190
  },
175
191
  stream: (input: Input, options) => streamOf(start("run", { input }, options, true)),
176
192
  resume: (decisions: readonly Decision[], options) => streamOf(start("sessions.resume", { decisions }, options, true)),
193
+ async continue(options?: RunOptions) {
194
+ return start("sessions.continue", {}, options, false).settled.promise;
195
+ },
196
+ continueStream: (options) => streamOf(start("sessions.continue", {}, options, true)),
177
197
  steer(input: Input, options) {
178
198
  if (!active) throw new RemoteError("invalid_params", "no active run to steer");
179
199
  void dispatcher.request("steer", { sessionId, input, ...(options ? { options } : {}) } as never).catch(() => {});
@@ -214,6 +234,9 @@ export function createSessionProxy(
214
234
  contextMeter() {
215
235
  throw unsupported("contextMeter()");
216
236
  },
237
+ async limits() {
238
+ throw unsupported("limits()");
239
+ },
217
240
  };
218
241
  return { session, handle };
219
242
  }
@@ -6,6 +6,8 @@ import { fileURLToPath } from "node:url";
6
6
  import type { Agent, AgentEvent, HostUi } from "@arnilo/prism";
7
7
  import { connectAgent, remoteHostUi, type ServedAgent, serveAgent } from "./index.js";
8
8
 
9
+ const DEFAULT_TIMEOUT_MS = 2000;
10
+
9
11
  export type ConformanceTransport = "stdio" | "websocket" | "http";
10
12
  export interface RemoteConformanceFactory {
11
13
  readonly module: string;
@@ -208,7 +210,7 @@ export async function remoteConformance(
208
210
  assert.equal(events.at(-1)?.type, "run.completed");
209
211
  }
210
212
  })(),
211
- options.timeoutMs ?? 2000,
213
+ options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
212
214
  `${transport}/${leg}`,
213
215
  );
214
216
  legs.push({ transport, leg, passed: true });
@@ -2,7 +2,6 @@ import {
2
2
  type ApprovalOutcome,
3
3
  type Decision,
4
4
  HARD_MAX_PENDING_DECISIONS,
5
- HARD_MAX_SESSION_LIST_LIMIT,
6
5
  type JsonObject,
7
6
  MAX_DECISION_REASON_BYTES,
8
7
  MAX_SESSION_LINK_ID_LENGTH,
@@ -10,6 +9,9 @@ import {
10
9
  type OwnershipScope,
11
10
  type PendingDecision,
12
11
  type Principal,
12
+ type ResolvedRunLimits,
13
+ resolveRunLimits,
14
+ type RunLimits,
13
15
  type RunOptions,
14
16
  type SessionListQuery,
15
17
  type SessionParentLink,
@@ -49,8 +51,69 @@ export function parseInput(value: unknown): string | Message | readonly Message[
49
51
  throw invalid("input must be a string, a message, or a message list");
50
52
  }
51
53
 
54
+ const NUMERIC_LIMIT_KEYS = [
55
+ "maxTurns",
56
+ "maxProviderAttempts",
57
+ "maxToolRounds",
58
+ "maxToolCalls",
59
+ "maxRepeatedToolRounds",
60
+ "maxWallTimeMs",
61
+ "maxRequestBytes",
62
+ "maxResponseBytes",
63
+ "maxInputTokens",
64
+ "maxOutputTokens",
65
+ "maxTotalTokens",
66
+ "maxContinuations",
67
+ "maxToolTimeMs",
68
+ "maxRunStateBytes",
69
+ ] as const satisfies readonly (keyof RunLimits & keyof ResolvedRunLimits)[];
70
+ const WIRE_LIMIT_KEYS = new Set<string>([...NUMERIC_LIMIT_KEYS, "maxCost", "bufferOutput"]);
71
+
72
+ /**
73
+ * A client's `limits` may only narrow the agent's resolved limits (plan 239 Task 5). The kernel lets a run layer
74
+ * set an axis the agent left at its default, and `null` disables a cap, so the wire checks each axis against the
75
+ * agent's own resolved value: `null`, an unknown axis, or a value above the agent's is `invalid_params`. The error
76
+ * names the axis, never a value.
77
+ */
78
+ export function narrowWireLimits(value: unknown, agentLimits: Readonly<ResolvedRunLimits>): RunLimits {
79
+ if (!isObject(value)) throw invalid("limits must be an object");
80
+ const out: Record<string, unknown> = {};
81
+ for (const [key, raw] of Object.entries(value)) {
82
+ if (!WIRE_LIMIT_KEYS.has(key)) throw invalid(`limits.${key} is not allowed over the wire`);
83
+ if (key === "bufferOutput") {
84
+ if (typeof raw !== "boolean") throw invalid("limits.bufferOutput must be a boolean");
85
+ // `true` at any layer wins, so a client can only make delivery stricter.
86
+ out[key] = raw;
87
+ continue;
88
+ }
89
+ if (key === "maxCost") {
90
+ if (!isObject(raw) || typeof raw.amount !== "number" || !(raw.amount >= 0) || typeof raw.currency !== "string") {
91
+ throw invalid("limits.maxCost must be { amount, currency }");
92
+ }
93
+ const agentCost = agentLimits.maxCost;
94
+ if (agentCost && (raw.currency !== agentCost.currency || raw.amount > agentCost.amount)) {
95
+ throw invalid("limits.maxCost may only narrow the agent's limit");
96
+ }
97
+ out[key] = { amount: raw.amount, currency: raw.currency };
98
+ continue;
99
+ }
100
+ if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0) {
101
+ throw invalid(`limits.${key} must be a non-negative safe integer; null is not allowed over the wire`);
102
+ }
103
+ const agentValue = agentLimits[key as (typeof NUMERIC_LIMIT_KEYS)[number]];
104
+ if (typeof agentValue === "number" && raw > agentValue) throw invalid(`limits.${key} may only narrow the agent's limit`);
105
+ out[key] = raw;
106
+ }
107
+ return out as RunLimits;
108
+ }
109
+
52
110
  /** Wire `RunOptions` is an allow-list: a client never chooses `principal`, `ownership`, `redactor`, `signal`, … */
53
- export function parseRunOptions(value: unknown, principal: Principal | undefined, ownership: OwnershipScope | undefined): RunOptions {
111
+ export function parseRunOptions(
112
+ value: unknown,
113
+ principal: Principal | undefined,
114
+ ownership: OwnershipScope | undefined,
115
+ agentLimits: Readonly<ResolvedRunLimits> = resolveRunLimits(),
116
+ ): RunOptions {
54
117
  const identity: RunOptions = {
55
118
  ...(principal ? { principal } : {}),
56
119
  ...(ownership ? { ownership } : {}),
@@ -62,13 +125,13 @@ export function parseRunOptions(value: unknown, principal: Principal | undefined
62
125
  }
63
126
  const wire = value as RemoteRunOptions;
64
127
  if (wire.metadata !== undefined && !isObject(wire.metadata)) throw invalid("metadata must be an object");
65
- if (wire.limits !== undefined && !isObject(wire.limits)) throw invalid("limits must be an object");
128
+ const limits = wire.limits === undefined ? undefined : narrowWireLimits(wire.limits, agentLimits);
66
129
  if (wire.interactive !== undefined && typeof wire.interactive !== "boolean") {
67
130
  throw invalid("interactive must be a boolean");
68
131
  }
69
132
  return {
70
133
  ...(wire.metadata ? { metadata: wire.metadata } : {}),
71
- ...(wire.limits ? { limits: wire.limits as RunOptions["limits"] } : {}),
134
+ ...(limits ? { limits } : {}),
72
135
  ...(wire.interactive !== undefined ? { interactive: wire.interactive } : {}),
73
136
  ...identity,
74
137
  };
@@ -76,6 +139,8 @@ export function parseRunOptions(value: unknown, principal: Principal | undefined
76
139
 
77
140
  export interface ParseDecisionsOptions {
78
141
  readonly allowModifiedArguments?: boolean;
142
+ /** Most decisions one request carries: the agent's `ceilings.pendingDecisions`. Default 128. */
143
+ readonly maxDecisions?: number;
79
144
  readonly pending?: readonly PendingDecision[];
80
145
  }
81
146
 
@@ -90,9 +155,8 @@ function isApprovalOutcome(value: unknown): value is ApprovalOutcome {
90
155
  */
91
156
  export function parseDecisions(value: unknown, options: ParseDecisionsOptions = {}): readonly Decision[] {
92
157
  if (!Array.isArray(value) || value.length === 0) throw invalid("decisions must be a non-empty list");
93
- if (value.length > HARD_MAX_PENDING_DECISIONS) {
94
- throw invalid(`decisions must contain at most ${HARD_MAX_PENDING_DECISIONS} items`);
95
- }
158
+ const maxDecisions = options.maxDecisions ?? HARD_MAX_PENDING_DECISIONS;
159
+ if (value.length > maxDecisions) throw invalid(`decisions must contain at most ${maxDecisions} items`);
96
160
  const pendingById = options.pending ? new Map(options.pending.map((item) => [item.approvalId, item])) : undefined;
97
161
  const out: Decision[] = [];
98
162
  for (const item of value) {
@@ -179,13 +243,9 @@ export function parseSessionListQuery(value: unknown, ownership?: OwnershipScope
179
243
  }
180
244
  }
181
245
  if (value.limit !== undefined) {
182
- if (
183
- typeof value.limit !== "number" ||
184
- !Number.isSafeInteger(value.limit) ||
185
- value.limit < 1 ||
186
- value.limit > HARD_MAX_SESSION_LIST_LIMIT
187
- ) {
188
- throw invalid(`limit must be an integer from 1 to ${HARD_MAX_SESSION_LIST_LIMIT}`);
246
+ if (typeof value.limit !== "number" || !Number.isSafeInteger(value.limit) || value.limit < 1) {
247
+ // The store checks the page against its own `queryLimits.maxListLimit`, which the host may have raised.
248
+ throw invalid("limit must be a positive integer");
189
249
  }
190
250
  }
191
251
  if (value.cursor !== undefined) {