@arnilo/prism 0.5.6 → 0.6.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 (64) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +10 -10
  3. package/dist/agent-approval.js +7 -6
  4. package/dist/agent-loops.js +51 -12
  5. package/dist/agent-session/session.d.ts +1 -0
  6. package/dist/agent-session/session.js +20 -2
  7. package/dist/agent-tool-dispatch.js +5 -4
  8. package/dist/content.d.ts +3 -16
  9. package/dist/content.js +9 -99
  10. package/dist/context-budget.d.ts +12 -1
  11. package/dist/context-budget.js +42 -19
  12. package/dist/contracts-core/agent.d.ts +11 -0
  13. package/dist/contracts-core/agent.js +4 -1
  14. package/dist/index.d.ts +4 -4
  15. package/dist/index.js +3 -3
  16. package/dist/input.d.ts +6 -0
  17. package/dist/input.js +12 -1
  18. package/dist/media-types.d.ts +34 -0
  19. package/dist/media-types.js +158 -0
  20. package/dist/pinned-fetch.d.ts +2 -2
  21. package/dist/pinned-fetch.js +11 -12
  22. package/dist/redaction.js +74 -1
  23. package/dist/session-stores.d.ts +11 -0
  24. package/dist/session-stores.js +23 -8
  25. package/docs/acp.md +1 -1
  26. package/docs/ag-ui.md +4 -2
  27. package/docs/agent-events.md +2 -0
  28. package/docs/agent-loops.md +1 -1
  29. package/docs/agent-session-runtime.md +3 -1
  30. package/docs/browser-automation.md +5 -2
  31. package/docs/contributing.md +37 -0
  32. package/docs/core.md +2 -0
  33. package/docs/document-reader.md +2 -0
  34. package/docs/documents.md +1 -1
  35. package/docs/graft.md +3 -1
  36. package/docs/history/release-handoffs.md +33 -0
  37. package/docs/host-security.md +2 -2
  38. package/docs/index.md +27 -14
  39. package/docs/input-and-prompt-assembly.md +4 -4
  40. package/docs/language-intelligence.md +1 -1
  41. package/docs/migrate-to-0.5.md +7 -2
  42. package/docs/migrate-to-0.6.md +89 -0
  43. package/docs/migration.md +30 -0
  44. package/docs/model-registry.md +1 -1
  45. package/docs/multimodal-content.md +1 -1
  46. package/docs/obscura.md +3 -1
  47. package/docs/options-index.md +286 -0
  48. package/docs/peer-dependencies.md +94 -0
  49. package/docs/performance.md +34 -2
  50. package/docs/ponytail.md +2 -0
  51. package/docs/postgres-persistence.md +3 -1
  52. package/docs/provider-conformance.md +1 -1
  53. package/docs/provider-packages.md +21 -21
  54. package/docs/provider-primitives.md +2 -1
  55. package/docs/providers/ai-sdk.md +5 -2
  56. package/docs/public-contracts.md +2 -2
  57. package/docs/release-and-install.md +75 -55
  58. package/docs/server.md +1 -1
  59. package/docs/session-stores.md +3 -1
  60. package/docs/sqlite-persistence.md +2 -0
  61. package/docs/testing.md +38 -0
  62. package/docs/tools.md +1 -1
  63. package/docs/wiki.md +1 -1
  64. package/package.json +5 -5
package/CHANGELOG.md CHANGED
@@ -1,3 +1,40 @@
1
+ ## [0.6.0] - 2026-09-12 (plans 070, 071)
2
+
3
+ > **0.5.7 was never published.** This release folds that cut's content (durable concurrent tool rounds, strict-provider tool results, host-tunable knobs, peer/options truth, the dependency refresh, and the module splits) together with the 0.6.0 changes below, so a host on 0.5.6 upgrades once. See [docs/migrate-to-0.6.md](docs/migrate-to-0.6.md).
4
+
5
+ ### Fixed
6
+ - **Concurrent tool dispatch dropped sibling results.** With `toolConcurrency > 1` a failed or aborted call threw before the round's results were appended, so every successful sibling result was lost and the next provider request carried unanswered `tool_use` blocks. Results are now persisted before the round fails: successes as-is, the failing call as a real redacted `tool_execution_failed` error, and calls that never started as `tool_call_not_dispatched`. Run-level control errors (`ERR_PRISM_AGENT_RUN_SUSPENDED`, `ERR_PRISM_DELEGATION_SUSPENDED`, `ERR_PRISM_LOOP_*`) still skip synthetic results so durable recovery re-dispatches instead of double-appending.
7
+ - **Content-less tool results serialized as an empty payload.** A `ToolResult` with no `content`/`result` now folds to `EMPTY_TOOL_RESULT_TEXT` (`(tool completed with no output)`) through the shared `serializeToolResultJson` seam (OpenAI-compatible, Alibaba, DeepSeek, Kimi/Moonshot, NeuralWatt, OpenCode-Go), so strict providers stop rejecting zero-length tool payloads.
8
+ - **A failing coverage child hid its own error.** `npm run test:coverage` reported a crashed or failed workspace suite as a bare `no coverage data (suite failed)`, with the child's output discarded (the diagnostic gap that made a one-off `@arnilo/prism-memory` flake unreadable). The summary now prints the child's output tail under the failing row and records `status`/`exitCode`/`tail` on its artifact row — redacted through the public `createSecretRedactor` (repo root and home become placeholders, credential-shaped env values become `[REDACTED]`) and char-bounded (last 40 lines, 8 KiB) so one pathological line cannot bloat the artifact. Passing rows are byte-identical to before.
9
+ - **Memory patch merge aliased caller objects.** `packages/memory`'s `mergeJsonObjects` deep-merged in place; it now delegates to core `mergeConfigLayers` (deep copy, strict JSON validation — `undefined`/`Date`/function values fail closed — with the `MemoryValidationError` taxonomy preserved).
10
+ - **`redactSecrets` was O(n·m) in needles.** A guarded single-pass alternation fast path handles large inputs (≥16 KiB, 2–32 non-overlapping needles) with byte-identical output (~13× faster on 1 MiB transcripts); the ordered loop remains the fallback for overlapping needle sets and small inputs.
11
+ - **Peer manifest resolution broke for packages that do not export `./package.json`** (e.g. `@dietrichgebert/ponytail`): upstream resolvers now resolve the package entry point and walk up to the manifest.
12
+
13
+ ### Added
14
+ - **Host-tunable context assembly:** `AssembleProviderInputOptions.tokenEstimator?: (text: string) => number` replaces the built-in UTF-16/4 heuristic for eviction accounting (byte caps stay estimator-independent).
15
+ - **Host-tunable session snapshot cache:** `AgentSessionConfig.snapshotCacheTtlMs` — `DEFAULT_SNAPSHOT_CACHE_TTL_MS` (1000), `HARD_MAX_SNAPSHOT_CACHE_TTL_MS` (30000), `0` disables the branch-rebuild cache.
16
+ - **Host-tunable memory-session search caps:** `createMemorySessionStore(entries, { search: { maxLinearSessions, maxLinearEntries, maxLinearBytes } })`, validated against the same hard bounds as the defaults.
17
+ - **SSRF allow-list:** `SsrfPolicy.allowedCidrs` accepts IPv4 and IPv6 CIDR entries so a host can explicitly reach a private range; hostname denials (metadata endpoints), credential checks, and the fail-closed unparseable-CIDR behavior are unchanged.
18
+ - **Browser run lifetime:** `BrowserLimitOptions.idleRunTtlMs` (default `0`, `HARD_IDLE_RUN_TTL_MS` 30 min) reaps runs with nothing queued; any interaction resets the idle clock.
19
+ - **Host onboarding docs:** [`docs/peer-dependencies.md`](docs/peer-dependencies.md) (every third-party peer declaration with range, optionality, subpath, install line, and network footprint) and [`docs/options-index.md`](docs/options-index.md) (123 public option/limits/config surfaces routed to the page that documents them), both gated by `live-doc-check` against the manifests and the source.
20
+ - **Real-peer and ACP round-trip coverage:** contract smoke tests for the `@dietrichgebert/ponytail` and `@nanonets/graft` layouts, and stdio round-trip tests driving a spawned ACP agent with the real `@agentclientprotocol/sdk` client (spawn→close, mode negotiation, config options, refused/cancelled permissions).
21
+ - **Release-truth gates:** `scripts/version-literal-gate.test.mjs` asserts every release-claim surface (manifests, internal ranges, `package-lock.json`, the `src/index.ts` version constant, the `docs/index.md` current line, `release.yml` tag lists, `scripts/package-truth.json`) equals the root manifest, so a half-finished cut fails the suite instead of shipping; `scripts/workflow-liveness.test.mjs` resolves every workflow script/workspace/`uses:` reference and requires 40-hex SHA pins for actions; `scripts/wiki-scratch-isolation.test.mjs` proves the memory wiki suites leave tracked fixtures and the repository root untouched; `scripts/run-all-tests.mjs` runs every test stage without short-circuiting, and the startup import budget now asserts a machine-relative ratio (absolute 250 ms ceiling only off-load) so a busy machine no longer reports a false regression.
22
+
23
+ ### Changed
24
+ - **Node floor raised to `>=22`** in all ten publishable packages (`@types/node` `^20.19.0` → `^22.20.0`; the `node20-compat` release leg becomes `node22-compat` on Node 22). Node 20 is upstream EOL since 2026-04-30; Node 24 stays the CI default. This is the host-breaking support-matrix change that the unreleased 0.5.7 deliberately deferred to a minor.
25
+ - **Dependency refresh:** `pg` 8.23, `playwright-core` 1.63.0, `zod` ^4.6.2, `@ai-sdk/provider` 4.0.13 (`@ai-sdk/openai` 4.0.65 with a new supported-version matrix entry), `@office-open/*` 0.14.5 (adapters use the `*Sync` parse variants), `@biomejs/biome` 2.5.13, `@agentclientprotocol/sdk` exact-pinned 1.4.0, and the `@arnilo/prism-memory` `@nanonets/graft` peer range widened to `^0.16.0 || ^0.18.0`.
26
+ - **Examples are Node-20-floor safe:** four runnable examples used `import.meta.main` (Node ≥22.18/≥24.2) on a Node-20 floor; they now use the house `import.meta.url` + `process.argv[1]` guard.
27
+ - **Release gate:** lockstep cuts now require every internal `@arnilo/*` range to be the cut version exactly (`0.6.0` or `^0.6.0`) instead of merely satisfying it, so one release line cannot resolve two first-party minors.
28
+ - **Test/coverage tooling:** the npm test chain runs every stage through `scripts/run-all-tests.mjs` (no short-circuit, one summary), coverage discovery finds nested `dist/**/__tests__` in all 9 workspace packages, `coverage-thresholds.json` may no longer name retired packages, and protected legs use one blocked-gate shape (`scripts/blocked-gate.mjs`) with env **names** only in the release evidence.
29
+ - **Internal structure, additive-only surface:** `runtime/server/artifacts.ts` split into four modules, `enterprise/postgres/model-router.ts` split into a directory (`util`/`circuit`/`capacity`/`reservations`/`expiry`/`state-store`), MCP OAuth discovery extracted to `oauth-metadata.ts`, one abort-aware `Semaphore` shared across `@arnilo/prism-coding-tools` (sandbox error types preserved), shared upstream persona primitives in `@arnilo/prism-coding-tools/src/upstream/`, shared provider HTTP retry primitives (`@arnilo/prism-providers/src/shared/retry-http.ts`), and the `content.ts` ↔ `pinned-fetch.ts` ESM cycle broken via the leaf module `src/media-types.ts`. Compat baselines were regenerated (`--update-baseline`): **69 added declarations, zero removals** — the five new host-tunable surfaces plus the helpers the moved modules now export from their new files.
30
+
31
+ ### Removed
32
+ - **`@arnilo/prism-office` optional `playwright-core` peer** (test-only: `/diagrams` drives a host-supplied iframe). Hosts no longer install a browser for office; see [`docs/peer-dependencies.md`](docs/peer-dependencies.md).
33
+
34
+ ### Notes
35
+ - **Lockstep `0.5.6` → `0.6.0` bump:** all 10 publishable manifests move to `0.6.0` with internal ranges `^0.6.0`; the predecessor published release is **0.5.6** (0.5.7 was never published and is superseded by this cut).
36
+ - **Retired-gate and test-truth fixes** landed in the same window (plans 070/071): frozen-era version markers derive from the root manifest, retired doc paths resolve through the frozen lineage, the packed-consumer enterprise journey no longer inherits a Postgres env var (the `pg` peer is not installed in a packed consumer), the `sandbox-browser` workflow references live packages again, the secret scan is operator-independent (tracked files only), the LSP restart-budget test awaits the exhaustion transition instead of racing a write, and the release workflow tag lists carry every published tag.
37
+
1
38
  ## [0.5.6] - 2026-09-09 (plan 069)
2
39
 
3
40
  ### Added
package/README.md CHANGED
@@ -162,16 +162,16 @@ printf '{"id":"1","command":"prompt","params":{"input":"Hi"}}\n' \
162
162
 
163
163
  | package | version | notes |
164
164
  | --- | --- | --- |
165
- | `@arnilo/prism` | 0.5.6 | core — runtime, CLI/RPC, templates, docs |
166
- | `@arnilo/prism-coding-tools` | 0.5.6 | family — /agent, /security, /document-reader, /openapi, /computer-use-linux, /dev, /caveman, /ponytail, /impeccable subpaths |
167
- | `@arnilo/prism-core` | 0.5.6 | family — /runtime, /sessions, /governance, /credentials, /enterprise, /work, /validation subpaths |
168
- | `@arnilo/prism-providers` | 0.5.6 | family — all provider adapters as `/<adapter>` subpaths |
169
- | `@arnilo/prism-acp-agent` | 0.5.6 | capability — ACP adapter |
170
- | `@arnilo/prism-ag-ui` | 0.5.6 | capability — AG-UI/A2A/A2UI adapter |
171
- | `@arnilo/prism-mcp` | 0.5.6 | capability — MCP client/server/OAuth interop |
172
- | `@arnilo/prism-memory` | 0.5.6 | capability — memory plus /rag, /compaction/*, /graft, /wiki subpaths |
173
- | `@arnilo/prism-office` | 0.5.6 | capability — /documents, /sheets, /diagrams subpaths |
174
- | `@arnilo/prism-web-tools` | 0.5.6 | capability — Brave/Exa/Firecrawl plus peer-gated /browser and /obscura subpaths |
165
+ | `@arnilo/prism` | 0.6.0 | core — runtime, CLI/RPC, templates, docs |
166
+ | `@arnilo/prism-coding-tools` | 0.6.0 | family — /agent, /security, /document-reader, /openapi, /computer-use-linux, /dev, /caveman, /ponytail, /impeccable subpaths |
167
+ | `@arnilo/prism-core` | 0.6.0 | family — /runtime, /sessions, /governance, /credentials, /enterprise, /work, /validation subpaths |
168
+ | `@arnilo/prism-providers` | 0.6.0 | family — all provider adapters as `/<adapter>` subpaths |
169
+ | `@arnilo/prism-acp-agent` | 0.6.0 | capability — ACP adapter |
170
+ | `@arnilo/prism-ag-ui` | 0.6.0 | capability — AG-UI/A2A/A2UI adapter |
171
+ | `@arnilo/prism-mcp` | 0.6.0 | capability — MCP client/server/OAuth interop |
172
+ | `@arnilo/prism-memory` | 0.6.0 | capability — memory plus /rag, /compaction/*, /graft, /wiki subpaths |
173
+ | `@arnilo/prism-office` | 0.6.0 | capability — /documents, /sheets, /diagrams subpaths |
174
+ | `@arnilo/prism-web-tools` | 0.6.0 | capability — Brave/Exa/Firecrawl plus peer-gated /browser and /obscura subpaths |
175
175
  <!-- generated:package-truth:inventory end -->
176
176
 
177
177
  ## Scripts
@@ -37,8 +37,9 @@ export function assertValidAgentRunResume(resume) {
37
37
  if (!Number.isSafeInteger(resume.expectedVersion) || resume.expectedVersion <= 0) {
38
38
  throw invalid("Resume expectedVersion must be a positive safe integer");
39
39
  }
40
+ const decisions = resume.decisions;
40
41
  const hasDecision = resume.decision !== undefined;
41
- const hasDecisions = resume.decisions !== undefined;
42
+ const hasDecisions = decisions !== undefined;
42
43
  if (hasDecision && hasDecisions)
43
44
  throw invalid("Resume accepts exactly one of decision or decisions");
44
45
  if (!hasDecision && !hasDecisions)
@@ -49,7 +50,6 @@ export function assertValidAgentRunResume(resume) {
49
50
  }
50
51
  return;
51
52
  }
52
- const decisions = resume.decisions;
53
53
  if (!Array.isArray(decisions))
54
54
  throw invalid("Decision batch must be an array");
55
55
  if (decisions.length === 0)
@@ -242,10 +242,11 @@ export function decisionScopesEqual(a, b) {
242
242
  return false;
243
243
  if (a.actionConstraints === undefined || b.actionConstraints === undefined)
244
244
  return a.actionConstraints === b.actionConstraints;
245
- const keys = Object.keys(a.actionConstraints);
246
- return (keys.length === Object.keys(b.actionConstraints).length &&
247
- keys.every((key) => key in b.actionConstraints &&
248
- canonicalToolEffectJson(a.actionConstraints[key]) === canonicalToolEffectJson(b.actionConstraints[key])));
245
+ const aConstraints = a.actionConstraints;
246
+ const bConstraints = b.actionConstraints;
247
+ const keys = Object.keys(aConstraints);
248
+ return (keys.length === Object.keys(bConstraints).length &&
249
+ keys.every((key) => key in bConstraints && canonicalToolEffectJson(aConstraints[key]) === canonicalToolEffectJson(bConstraints[key])));
249
250
  }
250
251
  export function nestedOutcomeToolResult(outcome, toolCallId, name) {
251
252
  return outcome.status === "completed"
@@ -1,6 +1,7 @@
1
1
  import { AgentLoopStateError } from "./contracts.js";
2
2
  import { createId } from "./ids.js";
3
3
  import { inputMessages, toToolResultMessage } from "./input.js";
4
+ import { errorToErrorInfo } from "./redaction.js";
4
5
  import { artifactStructuredOutputRequest, withoutStructuredOutput } from "./structured-output.js";
5
6
  function throwIfAborted(signal) {
6
7
  if (signal.aborted)
@@ -207,12 +208,13 @@ export function generateValidateReviseLoop(opts) {
207
208
  : { ok: true, value: text };
208
209
  // Parse failure consumes revision budget like a validation failure; the
209
210
  // repairer receives `undefined` value plus a synthetic parse issue.
210
- const parseFailure = !parsed.ok || parsed.value === undefined
211
- ? { ok: false, errors: [{ path: "$", message: parsed.error ?? "artifact parse failed" }], metadata: { reason: "parse_error" } }
212
- : undefined;
211
+ const candidate = parsed.ok && parsed.value !== undefined ? { ok: true, value: parsed.value } : undefined;
213
212
  const attempt = ++attempts;
214
213
  ctx.emit({ type: "artifact_validation_started", sessionId: ctx.sessionId, runId: ctx.runId, turn, attempt });
215
- const result = parseFailure ?? (await opts.validator(parsed.value, artifactCtx));
214
+ const result = candidate
215
+ ? await opts.validator(candidate.value, artifactCtx)
216
+ : { ok: false, errors: [{ path: "$", message: parsed.error ?? "artifact parse failed" }], metadata: { reason: "parse_error" } };
217
+ const parseFailure = candidate ? undefined : result;
216
218
  ctx.emit({ type: "artifact_validation_finished", sessionId: ctx.sessionId, runId: ctx.runId, turn, attempt, result });
217
219
  if (result.ok) {
218
220
  ctx.emit({ type: "artifact_finished", sessionId: ctx.sessionId, runId: ctx.runId, turn, attempt, result });
@@ -271,39 +273,76 @@ export async function dispatchToolCallsInOrder(calls, ctx) {
271
273
  let nextIndex = 0;
272
274
  let stopped = false;
273
275
  let firstFailure;
274
- const recordFailure = (error) => {
276
+ let failureIndex = -1;
277
+ const recordFailure = (error, index) => {
275
278
  if (stopped)
276
279
  return;
277
280
  stopped = true;
278
281
  firstFailure = error;
282
+ failureIndex = index;
279
283
  };
280
284
  const workers = Array.from({ length: concurrency }, async () => {
281
285
  for (;;) {
282
286
  if (stopped)
283
287
  return;
288
+ let index = -1;
284
289
  try {
285
290
  throwIfAborted(ctx.signal);
286
- const index = nextIndex;
291
+ index = nextIndex;
287
292
  nextIndex += 1;
288
293
  if (index >= calls.length)
289
294
  return;
290
295
  results[index] = await ctx.dispatchToolCall(calls[index]);
291
296
  }
292
297
  catch (error) {
293
- recordFailure(error);
298
+ recordFailure(error, index >= 0 && index < calls.length ? index : -1);
294
299
  return;
295
300
  }
296
301
  }
297
302
  });
298
303
  await Promise.allSettled(workers);
304
+ // Persist before rethrowing: a stopped batch must not leave the branch with `tool_call`
305
+ // ids that never got a `tool_result` (providers reject that history on the next turn).
306
+ // ponytail: synthetic rows carry `errorToErrorInfo` output only — no cause chain; the
307
+ // store redacts entries again at `appendEntry`, and `ctx.history` mirrors the run error.
308
+ const claimed = Math.min(nextIndex, calls.length);
309
+ for (let index = 0; index < calls.length; index += 1) {
310
+ const result = results[index];
311
+ if (result) {
312
+ await appendToolResultMessage(result, ctx);
313
+ continue;
314
+ }
315
+ // Suspension/loop-state errors are not tool outcomes: their machinery appends the real
316
+ // result on resume, so a synthetic row here would duplicate it.
317
+ if (index === failureIndex && isRunControlError(firstFailure))
318
+ continue;
319
+ const call = calls[index];
320
+ if (call === undefined)
321
+ continue;
322
+ await appendToolResultMessage(syntheticFailureResult(call, index < claimed ? firstFailure : undefined), ctx);
323
+ }
299
324
  if (stopped)
300
325
  throw firstFailure;
301
- for (const result of results) {
302
- throwIfAborted(ctx.signal);
303
- if (!result)
304
- continue;
305
- await appendToolResultMessage(result, ctx);
326
+ }
327
+ /** Run-level control errors rethrown by `dispatchToolCall` (mirrors `src/tools.ts`). */
328
+ function isRunControlError(error) {
329
+ const code = error?.code;
330
+ return (typeof code === "string" &&
331
+ (code === "ERR_PRISM_AGENT_RUN_SUSPENDED" || code === "ERR_PRISM_DELEGATION_SUSPENDED" || code.startsWith("ERR_PRISM_LOOP_")));
332
+ }
333
+ function syntheticFailureResult(call, failure) {
334
+ if (failure === undefined) {
335
+ return {
336
+ toolCallId: call.id,
337
+ name: call.name,
338
+ error: {
339
+ code: "tool_call_not_dispatched",
340
+ message: "Tool call was not dispatched: the batch stopped after an earlier call failed or the run was aborted.",
341
+ },
342
+ };
306
343
  }
344
+ const info = errorToErrorInfo(failure);
345
+ return { toolCallId: call.id, name: call.name, error: { name: info.name, message: info.message, code: info.code } };
307
346
  }
308
347
  async function appendToolResultMessage(result, ctx) {
309
348
  // Approval-gated calls return a marker instead of a real result; the transcript must not
@@ -60,6 +60,7 @@ export declare class RuntimeAgentSession implements AgentSession {
60
60
  private ledgerFailure;
61
61
  private snapshotGeneration;
62
62
  private snapshotCache?;
63
+ private readonly snapshotCacheTtlMs;
63
64
  constructor(config: AgentSessionConfig & {
64
65
  readonly agent: Agent;
65
66
  });
@@ -1,7 +1,7 @@
1
1
  /** session (0.2.5 plan 025 Task 1 split). Moved verbatim from agent-session.ts; public surface unchanged behind the barrel. */
2
2
  import { policyList } from "../agent-tool-dispatch.js";
3
3
  import { createDefaultCompactionStrategy, isCompactionEntryData } from "../compaction.js";
4
- import { DEFAULT_MAX_PENDING_STEER_BYTES, DEFAULT_MAX_PENDING_STEERS } from "../contracts.js";
4
+ import { DEFAULT_MAX_PENDING_STEER_BYTES, DEFAULT_MAX_PENDING_STEERS, DEFAULT_SNAPSHOT_CACHE_TTL_MS, HARD_MAX_SNAPSHOT_CACHE_TTL_MS, } from "../contracts.js";
5
5
  import { GuardrailError, runGuardrails } from "../guardrails.js";
6
6
  import { applyDefaultProviderRequestOptions, createProviderRequestPolicyChain, normalizeProviderRequestPolicyResult, } from "../provider-request-policy.js";
7
7
  import { redactAgentEvent, redactProviderRequest, redactRunLedgerRecord, redactSecrets, redactSessionEntry } from "../redaction.js";
@@ -78,12 +78,14 @@ export class RuntimeAgentSession {
78
78
  ledgerFailure;
79
79
  snapshotGeneration = 0;
80
80
  snapshotCache;
81
+ snapshotCacheTtlMs;
81
82
  constructor(config) {
82
83
  this.id = config.id ?? randomId("session");
83
84
  this.agent = config.agent;
84
85
  this.metadata = config.metadata;
85
86
  this.store = config.store ?? config.agent.config.store ?? createMemorySessionStore();
86
87
  this.currentLeafId = config.leafId;
88
+ this.snapshotCacheTtlMs = resolveSnapshotCacheTtlMs(config.snapshotCacheTtlMs);
87
89
  }
88
90
  get leafId() {
89
91
  return this.currentLeafId;
@@ -470,8 +472,24 @@ export class RuntimeAgentSession {
470
472
  const value = reader
471
473
  ? await rebuildSessionContext(reader, { sessionId: this.id, leafId: this.currentLeafId })
472
474
  : rebuildSessionContext(await this.store.list(this.id), { leafId: this.currentLeafId });
473
- this.snapshotCache = { leafId: this.currentLeafId, generation: this.snapshotGeneration, expiresAt: now + 1_000, value };
475
+ this.snapshotCache = {
476
+ leafId: this.currentLeafId,
477
+ generation: this.snapshotGeneration,
478
+ expiresAt: now + this.snapshotCacheTtlMs,
479
+ value,
480
+ };
474
481
  return value;
475
482
  }
476
483
  }
484
+ /**
485
+ * `snapshotCacheTtlMs` resolution: `0` disables the branch cache (a host that needs a
486
+ * fresh store read per snapshot), otherwise a safe integer up to the hard cap.
487
+ */
488
+ function resolveSnapshotCacheTtlMs(value) {
489
+ const ttl = value ?? DEFAULT_SNAPSHOT_CACHE_TTL_MS;
490
+ if (!Number.isSafeInteger(ttl) || ttl < 0 || ttl > HARD_MAX_SNAPSHOT_CACHE_TTL_MS) {
491
+ throw new TypeError(`AgentSessionConfig.snapshotCacheTtlMs must be a safe integer from 0 to ${HARD_MAX_SNAPSHOT_CACHE_TTL_MS}`);
492
+ }
493
+ return ttl;
494
+ }
477
495
  //# sourceMappingURL=session.js.map
@@ -51,8 +51,9 @@ export async function validateElicitationPayload(agent, state, target, payload,
51
51
  // Tool-declared answer-shape validation, re-derived from the current registry (never persisted).
52
52
  const call = state.pendingCalls?.find((entry) => entry.call.id === target.toolCallId)?.call;
53
53
  const tool = call ? activeTools(agent.config.tools).registry.get(call.name) : undefined;
54
- const validate = tool?.elicitation && call
55
- ? safeToolElicitationValidate(tool, call.arguments, {
54
+ const elicitation = tool?.elicitation;
55
+ const validate = elicitation && call
56
+ ? safeToolElicitationValidate(elicitation, call.arguments, {
56
57
  sessionId: state.sessionId,
57
58
  runId: state.runId,
58
59
  toolCallId: target.toolCallId ?? "elicitation",
@@ -68,9 +69,9 @@ export async function validateElicitationPayload(agent, state, target, payload,
68
69
  }
69
70
  }
70
71
  }
71
- function safeToolElicitationValidate(tool, args, context) {
72
+ function safeToolElicitationValidate(elicitation, args, context) {
72
73
  try {
73
- return tool.elicitation(args, context)?.validate;
74
+ return elicitation(args, context)?.validate;
74
75
  }
75
76
  catch {
76
77
  return undefined;
package/dist/content.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import type { ContentBlock, ImageContent, Message, ModelConfig, ResourceLoadContext, ResourceLoader, VideoContent } from "./contracts.js";
2
+ import { type MediaHostAddress, type MediaHostnameResolver, type SsrfPolicy } from "./media-types.js";
3
+ export type { MediaHostAddress, MediaHostnameResolver, SsrfPolicy } from "./media-types.js";
4
+ export { assertSsrfAllowedUrl, MediaContentError } from "./media-types.js";
2
5
  /** Known model input capability tags for `ModelCapabilities.input`. */
3
6
  export declare const MODEL_INPUT_CAPABILITIES: readonly ["text", "image", "audio", "file", "document", "video"];
4
7
  export type ModelInputCapability = (typeof MODEL_INPUT_CAPABILITIES)[number];
@@ -53,21 +56,10 @@ export interface MediaContentBounds {
53
56
  readonly maxAudioDurationMs?: number;
54
57
  readonly fetchTimeoutMs?: number;
55
58
  }
56
- export interface SsrfPolicy {
57
- /** When true (default), deny private/link-local/metadata hostnames and IPs. */
58
- readonly denyPrivateHosts?: boolean;
59
- /** Optional hostname allow-list. When set, only listed hosts are permitted. */
60
- readonly allowedHostnames?: readonly string[];
61
- }
62
59
  export interface MediaMimePolicy {
63
60
  /** Reject when magic bytes disagree with declared media type. Default `true`. */
64
61
  readonly strictMagicValidation?: boolean;
65
62
  }
66
- export interface MediaHostAddress {
67
- readonly address: string;
68
- readonly family: 4 | 6;
69
- }
70
- export type MediaHostnameResolver = (hostname: string, signal: AbortSignal) => Promise<readonly MediaHostAddress[]>;
71
63
  export interface MediaUrlRequest {
72
64
  readonly url: URL;
73
65
  readonly address: MediaHostAddress;
@@ -103,16 +95,11 @@ export declare class UnsupportedModalityError extends Error {
103
95
  readonly model: string;
104
96
  constructor(modality: ModelInputCapability, model: ModelConfig);
105
97
  }
106
- export declare class MediaContentError extends Error {
107
- readonly code: "ambiguous_source" | "missing_source" | "item_too_large" | "request_too_large" | "too_many_items" | "audio_too_long" | "invalid_base64" | "ssrf_denied" | "redirect" | "fetch_failed" | "fetch_timeout" | "resource_required" | "mime_mismatch" | "unsupported_url_scheme";
108
- constructor(code: MediaContentError["code"], message: string, options?: ErrorOptions);
109
- }
110
98
  export declare function contentBlockInputModality(block: ContentBlock): ModelInputCapability | undefined;
111
99
  export declare function collectMessageContentBlocks(messages: readonly Message[]): ContentBlock[];
112
100
  export declare function assertModelSupportsContentBlocks(model: ModelConfig, blocks: readonly ContentBlock[]): void;
113
101
  export declare function assertMessagesSupportModelCapabilities(model: ModelConfig, messages: readonly Message[]): void;
114
102
  export declare function assertMediaBlocksWithinBounds(blocks: readonly MediaContentBlock[], bounds?: MediaContentBounds): void;
115
- export declare function assertSsrfAllowedUrl(url: string, policy?: SsrfPolicy): void;
116
103
  export declare function sniffMediaMimeType(bytes: Uint8Array): string | undefined;
117
104
  export declare function assertDeclaredMediaTypeMatches(declaredMediaType: string, bytes: Uint8Array, policy?: MediaMimePolicy): void;
118
105
  export declare function resolveMediaContentBlock(block: MediaContentBlock, options?: ResolveMediaContentOptions): Promise<ResolvedMediaContent>;
package/dist/content.js CHANGED
@@ -1,7 +1,13 @@
1
1
  import { lookup as dnsLookup } from "node:dns/promises";
2
2
  import { isIP } from "node:net";
3
+ import { assertSsrfAllowedUrl, isAllowedByCidr, isBlockedIp, MediaContentError, normalizeHostname, } from "./media-types.js";
3
4
  import { pinnedFetch } from "./pinned-fetch.js";
4
5
  import { assertPermission } from "./security.js";
6
+ // SSRF policy, host/address types, `MediaContentError`, and the URL gate live in the leaf
7
+ // module shared with `pinned-fetch.ts` (plan 070 Task 10); re-exported here so the
8
+ // `@arnilo/prism` surface and the error-class identity are unchanged. `normalizeHostname`
9
+ // is imported for internal use only — it is public through `pinned-fetch.ts`, not here.
10
+ export { assertSsrfAllowedUrl, MediaContentError } from "./media-types.js";
5
11
  /** Known model input capability tags for `ModelCapabilities.input`. */
6
12
  export const MODEL_INPUT_CAPABILITIES = ["text", "image", "audio", "file", "document", "video"];
7
13
  /** Default per-item media byte ceiling (10 MB; aligns with coding-agent image bounds). */
@@ -26,14 +32,6 @@ export class UnsupportedModalityError extends Error {
26
32
  this.model = model.model;
27
33
  }
28
34
  }
29
- export class MediaContentError extends Error {
30
- code;
31
- constructor(code, message, options) {
32
- super(message, options);
33
- this.name = "MediaContentError";
34
- this.code = code;
35
- }
36
- }
37
35
  export function contentBlockInputModality(block) {
38
36
  switch (block.type) {
39
37
  case "image":
@@ -90,41 +88,6 @@ export function assertMediaBlocksWithinBounds(blocks, bounds = {}) {
90
88
  }
91
89
  }
92
90
  }
93
- export function assertSsrfAllowedUrl(url, policy = {}) {
94
- let parsed;
95
- try {
96
- parsed = new URL(url);
97
- }
98
- catch {
99
- throw new MediaContentError("ssrf_denied", "Media URL is not a valid absolute URL");
100
- }
101
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
102
- throw new MediaContentError("unsupported_url_scheme", `Media URL scheme ${parsed.protocol} is not allowed`);
103
- }
104
- if (parsed.username || parsed.password) {
105
- throw new MediaContentError("ssrf_denied", "Media URL must not embed credentials");
106
- }
107
- const hostname = normalizeHostname(parsed.hostname);
108
- if (policy.allowedHostnames?.length) {
109
- if (!policy.allowedHostnames.some((allowed) => hostname === normalizeHostname(allowed))) {
110
- throw new MediaContentError("ssrf_denied", `Media URL host ${hostname} is not allow-listed`);
111
- }
112
- return;
113
- }
114
- if (policy.denyPrivateHosts === false)
115
- return;
116
- if (hostname === "localhost" ||
117
- hostname.endsWith(".localhost") ||
118
- hostname.endsWith(".local") ||
119
- hostname === "metadata" ||
120
- hostname === "metadata.google.internal" ||
121
- hostname === "instance-data") {
122
- throw new MediaContentError("ssrf_denied", `Media URL host ${hostname} is not allowed`);
123
- }
124
- if (isBlockedIp(hostname)) {
125
- throw new MediaContentError("ssrf_denied", `Media URL host ${hostname} is not allowed`);
126
- }
127
- }
128
91
  export function sniffMediaMimeType(bytes) {
129
92
  if (startsWith(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d]))
130
93
  return "application/pdf";
@@ -364,7 +327,9 @@ async function resolvePublicAddress(hostname, resolver, signal, policy) {
364
327
  if (addresses.length > 32)
365
328
  throw new MediaContentError("fetch_failed", "Media hostname resolved to too many addresses");
366
329
  if (policy?.denyPrivateHosts !== false && !policy?.allowedHostnames?.length) {
367
- if (addresses.some(({ address }) => isBlockedIp(normalizeHostname(address)))) {
330
+ // An allow-listed CIDR covers resolved answers too, but only the private-IP block.
331
+ const blocked = addresses.some(({ address }) => isBlockedIp(normalizeHostname(address)) && !isAllowedByCidr(address, policy?.allowedCidrs));
332
+ if (blocked) {
368
333
  throw new MediaContentError("ssrf_denied", `Media URL host ${hostname} resolved to a private address`);
369
334
  }
370
335
  }
@@ -450,61 +415,6 @@ function mediaTypesCompatible(declared, sniffed) {
450
415
  return true;
451
416
  return false;
452
417
  }
453
- function normalizeHostname(hostname) {
454
- const normalized = hostname.toLowerCase().replace(/^\[|\]$/g, "");
455
- return normalized.endsWith(".") ? normalized.slice(0, -1) : normalized;
456
- }
457
- function isBlockedIp(hostname) {
458
- const normalized = normalizeHostname(hostname);
459
- const family = isIP(normalized);
460
- if (family === 4)
461
- return isBlockedIpv4(normalized);
462
- if (family === 6)
463
- return isBlockedIpv6(normalized);
464
- return false;
465
- }
466
- function isBlockedIpv4(address) {
467
- const [a, b] = address.split(".").map(Number);
468
- return (a === 0 ||
469
- a === 10 ||
470
- a === 127 ||
471
- (a === 100 && b >= 64 && b <= 127) ||
472
- (a === 169 && b === 254) ||
473
- (a === 172 && b >= 16 && b <= 31) ||
474
- (a === 192 && (b === 0 || b === 168)) ||
475
- (a === 198 && (b === 18 || b === 19 || b === 51)) ||
476
- (a === 203 && b === 0) ||
477
- a >= 224);
478
- }
479
- function isBlockedIpv6(address) {
480
- const words = parseIpv6Words(address);
481
- if (!words)
482
- return true;
483
- if (words.every((word) => word === 0) || (words.slice(0, 7).every((word) => word === 0) && words[7] === 1))
484
- return true;
485
- if ((words[0] & 0xfe00) === 0xfc00)
486
- return true;
487
- if ((words[0] & 0xffc0) === 0xfe80 || (words[0] & 0xffc0) === 0xfec0)
488
- return true;
489
- if ((words[0] & 0xff00) === 0xff00)
490
- return true;
491
- if (words[0] === 0x2001 && words[1] === 0x0db8)
492
- return true;
493
- const mapped = words.slice(0, 5).every((word) => word === 0) && (words[5] === 0 || words[5] === 0xffff);
494
- return mapped && isBlockedIpv4(`${words[6] >> 8}.${words[6] & 0xff}.${words[7] >> 8}.${words[7] & 0xff}`);
495
- }
496
- function parseIpv6Words(address) {
497
- const parts = address.split("::");
498
- if (parts.length > 2)
499
- return undefined;
500
- const left = parts[0] ? parts[0].split(":") : [];
501
- const right = parts[1] ? parts[1].split(":") : [];
502
- const missing = 8 - left.length - right.length;
503
- if (missing < 0 || (parts.length === 1 && missing !== 0))
504
- return undefined;
505
- const words = [...left, ...Array.from({ length: missing }, () => "0"), ...right].map((part) => Number.parseInt(part, 16));
506
- return words.length === 8 && words.every((word) => Number.isInteger(word) && word >= 0 && word <= 0xffff) ? words : undefined;
507
- }
508
418
  function startsWith(bytes, prefix) {
509
419
  if (bytes.length < prefix.length)
510
420
  return false;
@@ -1,10 +1,21 @@
1
1
  import type { ContextBlock, InputAssemblyLayout, Message, ProviderRequest, Skill, ToolDefinition } from "./contracts.js";
2
2
  import { type LoadedSkillSet, type SkillsDisclosure } from "./skill-disclosure.js";
3
+ /**
4
+ * Host-supplied token estimator. Budget-only: it never reaches billing, provider
5
+ * usage, or the wire — it decides what the assembler evicts and nothing else.
6
+ */
7
+ export type TokenEstimator = (text: string) => number;
3
8
  /** Assembler-time input budget. At least one max required when present. */
4
9
  export interface ContextBudget {
5
10
  readonly maxInputTokens?: number;
6
11
  readonly maxInputBytes?: number;
7
12
  readonly reportOmissions?: boolean;
13
+ /**
14
+ * Overrides the built-in UTF-16/4 heuristic for eviction accounting. Must return a
15
+ * non-negative finite token count (a NaN/negative/absent return fails the assembly
16
+ * closed with a `TypeError`). Byte caps are estimator-independent and always enforced.
17
+ */
18
+ readonly tokenEstimator?: TokenEstimator;
8
19
  }
9
20
  export type ContextBudgetOmissionKind = "skills" | "skill_body" | "context" | "history" | "tool_results" | "summaries" | "attachments" | "tools";
10
21
  export interface ContextBudgetOmission {
@@ -43,7 +54,7 @@ export declare function isContextBudgetError(error: unknown): error is ContextBu
43
54
  /** UTF-16 code units / 4. Estimate only — not billing. */
44
55
  export declare function estimateTextTokens(text: string): number;
45
56
  export declare function estimateTextBytes(text: string): number;
46
- export declare function estimateMessageTokens(message: Message): number;
57
+ export declare function estimateMessageTokens(message: Message, estimateTokens?: TokenEstimator): number;
47
58
  export declare function estimateMessageBytes(message: Message): number;
48
59
  export declare function estimateAssemblyTokens(messages: readonly Message[]): number;
49
60
  export declare function resolveContextBudget(budget: ContextBudget): Required<Pick<ContextBudget, "reportOmissions">> & ContextBudget;