@arnilo/prism 0.8.0 → 0.10.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 (141) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/README.md +13 -12
  3. package/dist/agent-approval.d.ts +17 -2
  4. package/dist/agent-approval.js +15 -6
  5. package/dist/agent-event-source.d.ts +9 -1
  6. package/dist/agent-event-source.js +10 -3
  7. package/dist/agent-loops.js +7 -4
  8. package/dist/agent-run-lifecycle.d.ts +15 -1
  9. package/dist/agent-run-lifecycle.js +82 -11
  10. package/dist/agent-run-state.d.ts +47 -6
  11. package/dist/agent-run-state.js +154 -6
  12. package/dist/agent-session/event-subscriber.d.ts +2 -0
  13. package/dist/agent-session/event-subscriber.js +3 -0
  14. package/dist/agent-session/helpers.js +14 -0
  15. package/dist/agent-session/session/assemble.js +281 -32
  16. package/dist/agent-session/session/persist.d.ts +11 -0
  17. package/dist/agent-session/session/persist.js +48 -16
  18. package/dist/agent-session/session/provider-round.d.ts +14 -4
  19. package/dist/agent-session/session/provider-round.js +226 -19
  20. package/dist/agent-session/session/tool-round.d.ts +2 -2
  21. package/dist/agent-session/session/tool-round.js +78 -6
  22. package/dist/agent-session/session/types.d.ts +44 -3
  23. package/dist/agent-session/session.d.ts +100 -5
  24. package/dist/agent-session/session.js +224 -13
  25. package/dist/attention-compiler.d.ts +51 -2
  26. package/dist/attention-compiler.js +282 -21
  27. package/dist/cache-helpers.d.ts +4 -2
  28. package/dist/cache-helpers.js +8 -6
  29. package/dist/checkpoint-restore.d.ts +45 -0
  30. package/dist/checkpoint-restore.js +54 -0
  31. package/dist/context-budget.d.ts +13 -1
  32. package/dist/context-budget.js +57 -4
  33. package/dist/contracts-core/agent.d.ts +52 -1
  34. package/dist/contracts-core/attention.d.ts +95 -0
  35. package/dist/contracts-core/content.d.ts +10 -0
  36. package/dist/contracts-core/extensions.d.ts +3 -0
  37. package/dist/contracts-core/guardrail-packs.d.ts +46 -0
  38. package/dist/contracts-core/guardrail-packs.js +2 -0
  39. package/dist/contracts-core/loop.d.ts +36 -0
  40. package/dist/contracts-core/provider.d.ts +30 -0
  41. package/dist/contracts-core/run-limits.d.ts +29 -1
  42. package/dist/contracts-core/session.d.ts +23 -5
  43. package/dist/contracts-core/session.js +21 -2
  44. package/dist/contracts-core/usage.d.ts +40 -0
  45. package/dist/contracts-core/usage.js +8 -0
  46. package/dist/contracts-core.d.ts +2 -0
  47. package/dist/contracts-core.js +2 -0
  48. package/dist/contracts-protocol.d.ts +81 -5
  49. package/dist/contracts-run-state.d.ts +91 -2
  50. package/dist/contributions.d.ts +2 -1
  51. package/dist/contributions.js +1 -0
  52. package/dist/extensions.d.ts +15 -1
  53. package/dist/extensions.js +68 -0
  54. package/dist/guardrail-packs/coding-standard.d.ts +3 -0
  55. package/dist/guardrail-packs/coding-standard.js +63 -0
  56. package/dist/guardrail-packs/destructive-commands.d.ts +3 -0
  57. package/dist/guardrail-packs/destructive-commands.js +46 -0
  58. package/dist/guardrail-packs/errors.d.ts +7 -0
  59. package/dist/guardrail-packs/errors.js +9 -0
  60. package/dist/guardrail-packs/index.d.ts +4 -0
  61. package/dist/guardrail-packs/index.js +15 -0
  62. package/dist/guardrail-packs/secrets-hygiene.d.ts +3 -0
  63. package/dist/guardrail-packs/secrets-hygiene.js +23 -0
  64. package/dist/guardrail-packs/types.d.ts +26 -0
  65. package/dist/guardrail-packs/types.js +2 -0
  66. package/dist/guardrail-packs/validation-respect.d.ts +3 -0
  67. package/dist/guardrail-packs/validation-respect.js +69 -0
  68. package/dist/guardrails.d.ts +61 -1
  69. package/dist/guardrails.js +377 -0
  70. package/dist/index.d.ts +16 -11
  71. package/dist/index.js +10 -7
  72. package/dist/input.d.ts +8 -1
  73. package/dist/input.js +68 -6
  74. package/dist/middleware.d.ts +37 -2
  75. package/dist/middleware.js +41 -0
  76. package/dist/node/session-store-jsonl.js +18 -3
  77. package/dist/observability.js +6 -0
  78. package/dist/provider-events.d.ts +8 -2
  79. package/dist/provider-events.js +60 -2
  80. package/dist/providers/openai-compatible.js +6 -3
  81. package/dist/run-bundle.d.ts +6 -1
  82. package/dist/run-bundle.js +5 -1
  83. package/dist/run-limits.d.ts +11 -1
  84. package/dist/run-limits.js +59 -0
  85. package/dist/session-stores.d.ts +12 -1
  86. package/dist/session-stores.js +21 -4
  87. package/dist/testing/agent-event-source-conformance.js +41 -2
  88. package/dist/testing/prefix-stability-conformance.d.ts +59 -0
  89. package/dist/testing/prefix-stability-conformance.js +172 -0
  90. package/dist/testing/session-store-conformance.d.ts +3 -2
  91. package/dist/testing/session-store-conformance.js +48 -0
  92. package/dist/tools.d.ts +5 -0
  93. package/dist/tools.js +21 -6
  94. package/dist/usage-estimation.d.ts +29 -0
  95. package/dist/usage-estimation.js +79 -0
  96. package/docs/agent-events.md +75 -4
  97. package/docs/agent-session-runtime.md +10 -6
  98. package/docs/attention-compiler.md +89 -8
  99. package/docs/caveman.md +1 -1
  100. package/docs/coding-agent-tools.md +1 -1
  101. package/docs/compaction-and-retry.md +1 -1
  102. package/docs/compaction-llm.md +2 -0
  103. package/docs/compaction-observational-memory.md +54 -7
  104. package/docs/durable-runs.md +46 -3
  105. package/docs/embeddings.md +9 -0
  106. package/docs/evaluations.md +5 -0
  107. package/docs/execution-timeline.md +79 -1
  108. package/docs/extensions.md +20 -3
  109. package/docs/guardrails.md +50 -4
  110. package/docs/hooks.md +282 -0
  111. package/docs/index.md +37 -15
  112. package/docs/input-and-prompt-assembly.md +4 -4
  113. package/docs/instruction-injection.md +1 -0
  114. package/docs/knowledge-sync.md +4 -0
  115. package/docs/live-testing.md +3 -1
  116. package/docs/memory-fabric.md +28 -0
  117. package/docs/middleware-hooks.md +90 -4
  118. package/docs/migrate-to-0.9.md +210 -0
  119. package/docs/migration.md +26 -0
  120. package/docs/multi-agent-patterns.md +25 -2
  121. package/docs/node-jsonl-session-store.md +7 -1
  122. package/docs/observability.md +7 -3
  123. package/docs/options-index.md +4 -1
  124. package/docs/policy-and-audit.md +26 -1
  125. package/docs/prefix-stability-conformance.md +143 -0
  126. package/docs/provider-caching.md +4 -4
  127. package/docs/provider-conformance.md +16 -0
  128. package/docs/provider-packages.md +20 -20
  129. package/docs/public-contracts.md +3 -2
  130. package/docs/rag.md +188 -3
  131. package/docs/release-and-install.md +45 -40
  132. package/docs/runs-and-usage.md +56 -10
  133. package/docs/scoped-agent-memory.md +270 -0
  134. package/docs/scoped-memory.md +138 -0
  135. package/docs/session-store-conformance.md +1 -2
  136. package/docs/session-stores.md +17 -17
  137. package/docs/supervisors.md +32 -12
  138. package/docs/tools.md +18 -1
  139. package/docs/wiki.md +4 -2
  140. package/docs/workflows.md +5 -0
  141. package/package.json +8 -2
@@ -1,6 +1,44 @@
1
+ import { GuardrailPackError } from "./guardrail-packs/errors.js";
2
+ export { GuardrailPackError } from "./guardrail-packs/errors.js";
3
+ import { BUILT_IN_GUARDRAIL_PACKS } from "./guardrail-packs/index.js";
1
4
  export const MAX_GUARDRAIL_CONCURRENCY = 16;
2
5
  const MAX_REASON_BYTES = 4 * 1024;
3
6
  const MAX_METADATA_BYTES = 16 * 1024;
7
+ /** Guardrail pack compile bounds (plan 092 Task 2). All ceilings are config-shape limits, not runtime budgets. */
8
+ export const MAX_GUARDRAIL_PACKS = 8;
9
+ export const MAX_GUARDRAIL_PACK_RULES = 64;
10
+ const MAX_PACK_ID_BYTES = 96;
11
+ const MAX_RULE_ID_BYTES = 96;
12
+ const MAX_RULE_REASON_BYTES = 512;
13
+ const MAX_RULE_ARG_PATHS = 8;
14
+ const MAX_PATTERN_BYTES = 4 * 1024;
15
+ const MAX_ARG_SCAN_DEPTH = 8;
16
+ const MAX_ARG_SCAN_STRINGS = 64;
17
+ const MAX_ARG_STRING_BYTES = 16 * 1024;
18
+ const MAX_PACK_NAME_BYTES = 128;
19
+ const OBSERVE_RULE_ID = "observe";
20
+ /** Bytes allowed for a rule-naming refusal line, so no rule text can grow a model or host message. */
21
+ const MAX_GUARDRAIL_REFUSAL_BYTES = 200;
22
+ /**
23
+ * Plan 104 T4/T6: the bounded, redacted refusal line for a terminal record that came from a compiled
24
+ * pack rule — `<prefix> by guardrail rule pack:<pack>/<rule>`, plus the pack's own reason when it set
25
+ * one — or `undefined` for any other guardrail, so the caller keeps its own neutral text. Only the
26
+ * compiler writes the `pack`/`rule` metadata, so a host-written guardrail named `pack:…` is never
27
+ * presented as a pack rule. Reasons are redacted where the record is built, pack names are
28
+ * compiler-bounded to 128 bytes (the identity always survives the cap), and a long reason is
29
+ * truncated, so the same derivation serves the tool refusal and decision-time revalidation.
30
+ */
31
+ export function guardrailRefusalText(record, prefix = "Blocked") {
32
+ const pack = record.metadata?.pack;
33
+ const rule = record.metadata?.rule;
34
+ if (typeof pack !== "string" || typeof rule !== "string")
35
+ return undefined;
36
+ const line = `${prefix} by guardrail rule ${record.guardrail}`;
37
+ // The compiler synthesizes `guardrail pack rule <pack>/<rule>` when the rule set no reason; the
38
+ // identity already implies it, so only a real reason is appended.
39
+ const text = record.reason && record.reason !== `guardrail pack rule ${pack}/${rule}` ? `${line}: ${record.reason}` : line;
40
+ return boundText(text, MAX_GUARDRAIL_REFUSAL_BYTES);
41
+ }
4
42
  export class GuardrailError extends Error {
5
43
  code;
6
44
  record;
@@ -60,6 +98,345 @@ export function assertGuardrailsAllowed(result) {
60
98
  if (result.terminal)
61
99
  throw new GuardrailError(result.terminal);
62
100
  }
101
+ const EMPTY_COMPILED_PACKS = { guardrails: undefined, packs: [], snapshotState: () => undefined };
102
+ /**
103
+ * Compiles `guardrailPacks` config onto the existing tool interception seams: one `tool_input`
104
+ * guardrail per rule (`name = pack:<pack>/<rule>`), plus one `tool_output` recorder for packs that
105
+ * observe results. Compiled once per session — patterns are compiled here, never per tool call.
106
+ * Throws `GuardrailPackError` on malformed config (fail closed); returns `undefined` when unset.
107
+ */
108
+ export function compileGuardrailPacks(refs, registry = BUILT_IN_GUARDRAIL_PACKS) {
109
+ return compileGuardrailPacksWithState(refs, registry).guardrails;
110
+ }
111
+ /**
112
+ * Plan 104 Task 2: the internal compile entry behind `compileGuardrailPacks`. Passing `initial`
113
+ * marks a durable restore — rows must then come from the installed registry, match its version, and
114
+ * parse through the pack's own state codec, so a mismatch fails closed instead of restoring a
115
+ * weaker policy. `snapshotState` is the checkpoint-side counterpart.
116
+ */
117
+ export function compileGuardrailPacksWithState(refs, registry = BUILT_IN_GUARDRAIL_PACKS, initial) {
118
+ const packs = resolveGuardrailPacks(refs, registry, initial);
119
+ if (packs.length === 0)
120
+ return EMPTY_COMPILED_PACKS;
121
+ const toolInput = [];
122
+ const toolOutput = [];
123
+ const askGate = [];
124
+ const askBlocks = [];
125
+ for (const pack of packs) {
126
+ if (pack.observe)
127
+ toolOutput.push(observeGuardrail(pack, pack.observe, pack.state));
128
+ for (const resolved of pack.rules) {
129
+ if (resolved.action === "ask") {
130
+ // Plan 104 T3: `ask` is not an ordinary stage decision. A run that can suspend gates the
131
+ // call at charge time (`interrupt` is the record meaning "awaiting a decision"), while a run
132
+ // that cannot suspend evaluates the same rule as a plain block through `activeGuardrails`.
133
+ askGate.push(ruleGuardrail(pack, resolved, pack.state, "interrupt"));
134
+ askBlocks.push(ruleGuardrail(pack, resolved, pack.state, "block"));
135
+ continue;
136
+ }
137
+ toolInput.push(ruleGuardrail(pack, resolved, pack.state));
138
+ }
139
+ }
140
+ return {
141
+ guardrails: toolOutput.length > 0 ? { toolInput, toolOutput } : { toolInput },
142
+ packs: packs.map((pack) => pack.row),
143
+ ...(askGate.length > 0 ? { askGate: { toolInput: askGate }, askBlocks: { toolInput: askBlocks } } : {}),
144
+ snapshotState: () => {
145
+ const state = {};
146
+ for (const pack of packs) {
147
+ // Plan 104 T3: an inline pack now rides the checkpoint as rules, so only the rule shapes
148
+ // that cannot round-trip matter: a closure has no JSON form, and a `RegExp` serializes to
149
+ // `{}`, which would restore as an invalid (or, worse, absent) pattern.
150
+ const unpersistable = pack.inline
151
+ ? pack.rules.find((resolved) => resolved.rule.deny !== undefined || resolved.rule.pattern instanceof RegExp)
152
+ : undefined;
153
+ if (unpersistable) {
154
+ throw new GuardrailPackError(`guardrail pack "${pack.id}" rule "${unpersistable.rule.id}" cannot be persisted (deny predicate or RegExp pattern); use a pattern string or a registered pack id when \`persistSessionState\` is on`);
155
+ }
156
+ const snapshot = pack.stateCodec?.snapshot(pack.state);
157
+ if (snapshot !== undefined)
158
+ state[pack.id] = snapshot;
159
+ }
160
+ return Object.keys(state).length > 0 ? state : undefined;
161
+ },
162
+ };
163
+ }
164
+ /** Stable identity rows for the same config `compileGuardrailPacks` accepts (no state, no guardrails built). */
165
+ export function describeGuardrailPacks(refs, registry = BUILT_IN_GUARDRAIL_PACKS) {
166
+ const rows = [];
167
+ for (const pack of resolveGuardrailPacks(refs, registry)) {
168
+ if (pack.observe)
169
+ rows.push({ name: packRuleName(pack.id, OBSERVE_RULE_ID), stage: "tool_output", revision: packRevision(pack) });
170
+ for (const resolved of pack.rules)
171
+ rows.push({ name: packRuleName(pack.id, resolved.rule.id), stage: "tool_input", revision: packRevision(pack) });
172
+ }
173
+ return rows;
174
+ }
175
+ function packRevision(pack) {
176
+ return `${pack.id}@${pack.version}`;
177
+ }
178
+ function packRuleName(packId, ruleId) {
179
+ return `pack:${packId}/${ruleId}`;
180
+ }
181
+ function resolveGuardrailPacks(refs, registry, initial) {
182
+ if (refs === undefined)
183
+ return [];
184
+ if (!Array.isArray(refs))
185
+ throw new GuardrailPackError("guardrailPacks must be an array of pack ids or pack input objects");
186
+ if (refs.length > MAX_GUARDRAIL_PACKS)
187
+ throw new GuardrailPackError(`guardrailPacks accepts at most ${MAX_GUARDRAIL_PACKS} packs`);
188
+ const restoring = initial !== undefined;
189
+ const seenPacks = new Set();
190
+ return refs.map((ref) => {
191
+ const input = (typeof ref === "string" ? { id: ref } : ref) ?? {};
192
+ if (typeof input.id !== "string" || !input.id.trim() || byteLength(input.id) > MAX_PACK_ID_BYTES) {
193
+ throw new GuardrailPackError(`guardrail pack ids must be non-empty strings of at most ${MAX_PACK_ID_BYTES} bytes`);
194
+ }
195
+ if (seenPacks.has(input.id))
196
+ throw new GuardrailPackError(`duplicate guardrail pack id "${input.id}"`);
197
+ seenPacks.add(input.id);
198
+ if (input.version !== undefined && (!Number.isSafeInteger(input.version) || input.version < 1)) {
199
+ throw new GuardrailPackError(`guardrail pack "${input.id}" version must be a positive integer`);
200
+ }
201
+ const definition = registry.get(input.id);
202
+ if (definition === undefined && input.rules === undefined) {
203
+ throw unknownGuardrailPack(input.id, registry);
204
+ }
205
+ // A restored checkpoint replays rows, so a registered id must still match its installed version
206
+ // while an inline pack needs its pattern rules back (a closure cannot ride a checkpoint, and a
207
+ // pack replaying without it would enforce less than it did).
208
+ if (restoring) {
209
+ if (input.rules === undefined) {
210
+ if (definition === undefined)
211
+ throw unknownGuardrailPack(input.id, registry);
212
+ if (input.version !== definition.version) {
213
+ throw new GuardrailPackError(`guardrail pack "${input.id}" was persisted at version ${input.version} but the installed version is ${definition.version}`);
214
+ }
215
+ }
216
+ else if (input.rules.some((rule) => rule?.deny !== undefined)) {
217
+ throw new GuardrailPackError(`persisted guardrail pack "${input.id}" carries a deny predicate; only pattern rules can be restored`);
218
+ }
219
+ }
220
+ let built;
221
+ if (input.rules !== undefined) {
222
+ if (input.options !== undefined)
223
+ throw new GuardrailPackError(`inline guardrail pack "${input.id}" cannot set options`);
224
+ built = { rules: input.rules };
225
+ }
226
+ else {
227
+ if (definition === undefined)
228
+ throw unknownGuardrailPack(input.id, registry);
229
+ built = definition.build(Object.freeze({ ...input.options }));
230
+ }
231
+ if (!built || !Array.isArray(built.rules) || built.rules.length === 0) {
232
+ throw new GuardrailPackError(`guardrail pack "${input.id}" must declare at least one rule`);
233
+ }
234
+ if (built.rules.length > MAX_GUARDRAIL_PACK_RULES) {
235
+ throw new GuardrailPackError(`guardrail pack "${input.id}" accepts at most ${MAX_GUARDRAIL_PACK_RULES} rules`);
236
+ }
237
+ if (built.observe !== undefined && typeof built.observe !== "function") {
238
+ throw new GuardrailPackError(`guardrail pack "${input.id}" observe must be a function`);
239
+ }
240
+ if (built.state !== undefined && (typeof built.state.snapshot !== "function" || typeof built.state.parse !== "function")) {
241
+ throw new GuardrailPackError(`guardrail pack "${input.id}" state codec must declare snapshot and parse`);
242
+ }
243
+ const seenRules = new Set();
244
+ const rules = built.rules.map((rule) => resolveRule(input.id, rule, seenRules));
245
+ if (built.observe && byteLength(packRuleName(input.id, OBSERVE_RULE_ID)) > MAX_PACK_NAME_BYTES) {
246
+ throw new GuardrailPackError(`guardrail pack "${input.id}" name exceeds ${MAX_PACK_NAME_BYTES} bytes`);
247
+ }
248
+ const version = input.version ?? definition?.version ?? 1;
249
+ const state = {};
250
+ const persisted = initial === undefined ? undefined : initial[input.id];
251
+ if (persisted !== undefined) {
252
+ if (built.state === undefined) {
253
+ throw new GuardrailPackError(`guardrail pack "${input.id}" has persisted state but declares no state codec`);
254
+ }
255
+ Object.assign(state, built.state.parse(persisted));
256
+ }
257
+ return {
258
+ id: input.id,
259
+ version,
260
+ rules,
261
+ state,
262
+ inline: input.rules !== undefined,
263
+ row: {
264
+ id: input.id,
265
+ version,
266
+ ...(input.options !== undefined ? { options: input.options } : {}),
267
+ ...(input.rules !== undefined ? { rules: input.rules } : {}),
268
+ },
269
+ ...(built.observe ? { observe: built.observe } : {}),
270
+ ...(built.state !== undefined ? { stateCodec: built.state } : {}),
271
+ };
272
+ });
273
+ }
274
+ function unknownGuardrailPack(id, registry) {
275
+ return new GuardrailPackError(`unknown guardrail pack "${id}"; known packs: ${[...registry.keys()].join(", ") || "none"}`);
276
+ }
277
+ function resolveRule(packId, rule, seenRules) {
278
+ const where = `guardrail pack "${packId}"`;
279
+ if (!rule || typeof rule.id !== "string" || !rule.id.trim() || byteLength(rule.id) > MAX_RULE_ID_BYTES) {
280
+ throw new GuardrailPackError(`${where} rule ids must be non-empty strings of at most ${MAX_RULE_ID_BYTES} bytes`);
281
+ }
282
+ if (seenRules.has(rule.id))
283
+ throw new GuardrailPackError(`${where} has a duplicate rule id "${rule.id}"`);
284
+ seenRules.add(rule.id);
285
+ const action = rule.action ?? "deny";
286
+ if (action !== "deny" && action !== "tripwire" && action !== "ask") {
287
+ throw new GuardrailPackError(`${where} rule "${rule.id}" action must be "deny", "tripwire", or "ask"`);
288
+ }
289
+ if (action === "ask" && rule.deny !== undefined) {
290
+ throw new GuardrailPackError(`${where} rule "${rule.id}" action "ask" requires "pattern": an opaque deny predicate cannot raise an approval`);
291
+ }
292
+ const hasPattern = rule.pattern !== undefined;
293
+ const hasDeny = rule.deny !== undefined;
294
+ if (hasPattern === hasDeny) {
295
+ throw new GuardrailPackError(`${where} rule "${rule.id}" requires exactly one of "pattern" or "deny"`);
296
+ }
297
+ if (hasDeny && typeof rule.deny !== "function")
298
+ throw new GuardrailPackError(`${where} rule "${rule.id}" deny must be a function`);
299
+ if (rule.reason !== undefined && (typeof rule.reason !== "string" || byteLength(rule.reason) > MAX_RULE_REASON_BYTES)) {
300
+ throw new GuardrailPackError(`${where} rule "${rule.id}" reason must be a string of at most ${MAX_RULE_REASON_BYTES} bytes`);
301
+ }
302
+ let tools;
303
+ if (rule.tool !== undefined) {
304
+ tools = typeof rule.tool === "string" ? [rule.tool] : [...rule.tool];
305
+ if (tools.length === 0 || tools.length > MAX_GUARDRAIL_PACK_RULES || tools.some((name) => typeof name !== "string" || !name.trim())) {
306
+ throw new GuardrailPackError(`${where} rule "${rule.id}" tool must be a non-empty tool name or array of names`);
307
+ }
308
+ }
309
+ if (rule.argPath !== undefined) {
310
+ const paths = typeof rule.argPath === "string" ? [rule.argPath] : [...rule.argPath];
311
+ if (paths.length === 0 || paths.length > MAX_RULE_ARG_PATHS || paths.some((path) => typeof path !== "string" || !path.trim())) {
312
+ throw new GuardrailPackError(`${where} rule "${rule.id}" argPath must be a non-empty dot path or array of paths`);
313
+ }
314
+ }
315
+ if (byteLength(packRuleName(packId, rule.id)) > MAX_PACK_NAME_BYTES) {
316
+ throw new GuardrailPackError(`${where} rule "${rule.id}" name exceeds ${MAX_PACK_NAME_BYTES} bytes`);
317
+ }
318
+ return {
319
+ rule,
320
+ action,
321
+ reason: rule.reason ?? `guardrail pack rule ${packId}/${rule.id}`,
322
+ ...(tools ? { tools } : {}),
323
+ ...(hasPattern ? { regex: compileRulePattern(packId, rule.id, rule.pattern) } : {}),
324
+ };
325
+ }
326
+ function compileRulePattern(packId, ruleId, pattern) {
327
+ const where = `guardrail pack "${packId}" rule "${ruleId}"`;
328
+ if (pattern instanceof RegExp)
329
+ return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
330
+ if (typeof pattern !== "string" || !pattern)
331
+ throw new GuardrailPackError(`${where} pattern must be a non-empty string or RegExp`);
332
+ if (byteLength(pattern) > MAX_PATTERN_BYTES)
333
+ throw new GuardrailPackError(`${where} pattern exceeds ${MAX_PATTERN_BYTES} bytes`);
334
+ try {
335
+ return new RegExp(pattern);
336
+ }
337
+ catch (error) {
338
+ throw new GuardrailPackError(`${where} has an invalid pattern`, { cause: error });
339
+ }
340
+ }
341
+ function ruleGuardrail(pack, resolved, state, askAction = "interrupt") {
342
+ return {
343
+ name: packRuleName(pack.id, resolved.rule.id),
344
+ revision: packRevision(pack),
345
+ stage: "tool_input",
346
+ evaluate(context) {
347
+ if (resolved.tools && !resolved.tools.includes(context.toolName ?? ""))
348
+ return { action: "allow" };
349
+ const args = context.value.arguments;
350
+ const matched = resolved.rule.deny
351
+ ? Boolean(resolved.rule.deny(args, ruleContext(context, state)))
352
+ : patternMatches(resolved.regex, argumentStrings(args, resolved.rule.argPath));
353
+ if (!matched)
354
+ return { action: "allow" };
355
+ return {
356
+ // Pack vocabulary is `deny`/`ask`; the core guardrail actions are `block`/`interrupt`.
357
+ action: resolved.action === "deny" ? "block" : resolved.action === "ask" ? askAction : "tripwire",
358
+ reason: resolved.reason,
359
+ metadata: { pack: pack.id, rule: resolved.rule.id, version: pack.version },
360
+ };
361
+ },
362
+ };
363
+ }
364
+ function observeGuardrail(pack, observe, state) {
365
+ return {
366
+ name: packRuleName(pack.id, OBSERVE_RULE_ID),
367
+ revision: packRevision(pack),
368
+ stage: "tool_output",
369
+ evaluate(context) {
370
+ observe(state, context.value, ruleContext(context, state));
371
+ return { action: "allow" };
372
+ },
373
+ };
374
+ }
375
+ function ruleContext(context, state) {
376
+ return {
377
+ toolName: context.toolName ?? "",
378
+ toolCallId: context.toolCallId ?? "",
379
+ sessionId: context.sessionId,
380
+ runId: context.runId,
381
+ metadata: context.metadata,
382
+ state,
383
+ };
384
+ }
385
+ function patternMatches(regex, values) {
386
+ for (const value of values) {
387
+ if (regex.test(value.length > MAX_ARG_STRING_BYTES ? value.slice(0, MAX_ARG_STRING_BYTES) : value))
388
+ return true;
389
+ }
390
+ return false;
391
+ }
392
+ function argumentStrings(args, argPath) {
393
+ if (argPath === undefined) {
394
+ const all = [];
395
+ for (const value of Object.values(args))
396
+ pushStrings(value, all, 0);
397
+ return all;
398
+ }
399
+ const out = [];
400
+ for (const path of typeof argPath === "string" ? [argPath] : argPath) {
401
+ walkPath(args, path.split("."), out);
402
+ if (out.length >= MAX_ARG_SCAN_STRINGS)
403
+ break;
404
+ }
405
+ return out;
406
+ }
407
+ function walkPath(value, segments, out) {
408
+ if (out.length >= MAX_ARG_SCAN_STRINGS)
409
+ return;
410
+ if (segments.length === 0) {
411
+ pushStrings(value, out, 0);
412
+ return;
413
+ }
414
+ if (Array.isArray(value)) {
415
+ for (const item of value)
416
+ walkPath(item, segments, out);
417
+ return;
418
+ }
419
+ if (value && typeof value === "object") {
420
+ walkPath(value[segments[0]], segments.slice(1), out);
421
+ }
422
+ }
423
+ function pushStrings(value, out, depth) {
424
+ if (out.length >= MAX_ARG_SCAN_STRINGS || depth > MAX_ARG_SCAN_DEPTH)
425
+ return;
426
+ if (typeof value === "string") {
427
+ out.push(value);
428
+ return;
429
+ }
430
+ if (Array.isArray(value)) {
431
+ for (const item of value)
432
+ pushStrings(item, out, depth + 1);
433
+ return;
434
+ }
435
+ if (value && typeof value === "object") {
436
+ for (const item of Object.values(value))
437
+ pushStrings(item, out, depth + 1);
438
+ }
439
+ }
63
440
  function stageGuards(guardrails, stage) {
64
441
  if (!guardrails)
65
442
  return [];
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  export { resolveAgentDefinition } from "./agent-definitions.js";
2
2
  export type { AgentEventSourceErrorCode } from "./agent-event-source.js";
3
- export { AgentEventSourceError, createMemoryAgentEventSource } from "./agent-event-source.js";
3
+ export { AgentEventSourceError, createMemoryAgentEventSource, isTerminalAgentEventType } from "./agent-event-source.js";
4
4
  export { dispatchToolCallsInOrder, generateValidateReviseLoop, isAgentLoopOptions, resolveLoop, resolveToolConcurrency, singleShotLoop, } from "./agent-loops.js";
5
5
  export type { AgentRunLifecycle, AgentRunLifecycleAgent, AgentRunLifecycleOptions, AgentRunLifecycleRequest, AgentRunLifecycleStreamRequest, } from "./agent-run-lifecycle.js";
6
6
  export { createAgentRunLifecycle } from "./agent-run-lifecycle.js";
7
7
  export type { PendingToolCall, StoredAgentRunState } from "./agent-run-state.js";
8
- export { AGENT_RUN_STATE_NAMESPACE, AGENT_RUN_STATE_SCHEMA_VERSION, agentFingerprint, DEFAULT_MAX_AGENT_RUN_STATE_BYTES, HARD_MAX_AGENT_RUN_STATE_BYTES, loadAgentRunState, } from "./agent-run-state.js";
8
+ export { AGENT_RUN_STATE_NAMESPACE, AGENT_RUN_STATE_SCHEMA_VERSION, agentFingerprint, boundCheckpointMetadata, DEFAULT_MAX_AGENT_RUN_STATE_BYTES, HARD_MAX_AGENT_RUN_STATE_BYTES, loadAgentRunState, MAX_AGENT_RUN_METADATA_BYTES, readCheckpointMetadata, resolveCheckpointMetadata, } from "./agent-run-state.js";
9
9
  export { createAgent, createAgentSession, resumeAgentRun, resumeAgentRunStream } from "./agents.js";
10
10
  export type { ArtifactApproval, ArtifactApprovalState, ArtifactBodyErrorCode, ArtifactBodyPresignOptions, ArtifactBodyRef, ArtifactBodyStore, ArtifactBodyTransferOptions, ArtifactCitation, ArtifactDecisionState, ArtifactDeliveryToken, ArtifactRecord, ArtifactRevision, CitationIntegrityReason, CitationIntegrityResult, CitationLiveSource, CitationSupport, } from "./artifacts.js";
11
11
  export { ARTIFACT_BODY_ERROR_CODES, ARTIFACT_CHECKPOINT_NAMESPACE, ArtifactBodyStoreError, ArtifactError, approvalEvidenceIntact, artifactApprovalState, artifactCheckpointKey, checkCitationIntegrity, citationBindingDigest, HARD_CITATION_EXCERPT_BYTES, } from "./artifacts.js";
@@ -17,6 +17,8 @@ export type { CacheTelemetry, CacheTelemetryOptions, CacheTelemetryReport, Cache
17
17
  export { CACHE_TELEMETRY_OVERFLOW_KEY, CacheTelemetryError, createCacheTelemetry, DEFAULT_CACHE_TELEMETRY_CAP, } from "./cache-telemetry.js";
18
18
  export type { ProviderCapture, ProviderCaptureEntry, ProviderCaptureOptions, ProviderCapturePolicy } from "./capture.js";
19
19
  export { createProviderCapture } from "./capture.js";
20
+ export type { CheckpointRestoreAudit, CheckpointRestoreAuditEntry, CheckpointRestoreHook, RunCheckpointRestoreHooksOptions, } from "./checkpoint-restore.js";
21
+ export { CheckpointRestoreError, DEFAULT_CHECKPOINT_RESTORE_TIMEOUT_MS, runCheckpointRestoreHooks } from "./checkpoint-restore.js";
20
22
  export type { MemoryCheckpointStoreOptions } from "./checkpoints.js";
21
23
  export { CHECKPOINT_CONFLICT_CODE, CheckpointConflictError, createMemoryCheckpointStore } from "./checkpoints.js";
22
24
  export type { DefaultCompactionStrategyOptions } from "./compaction.js";
@@ -28,7 +30,7 @@ export { assertDeclaredMediaTypeMatches, assertMediaBlocksWithinBounds, assertMe
28
30
  export type { ContextBudget, ContextBudgetMessageGroups, ContextBudgetOmission, ContextBudgetOmissionKind, ContextBudgetReport, TokenEstimator, } from "./context-budget.js";
29
31
  export { applyContextBudget, CONTEXT_BUDGET_ERROR_CODE, CONTEXT_BUDGET_REPORT_METADATA_KEY, ContextBudgetError, DEFAULT_MAX_CONTEXT_BUDGET_OMISSIONS, estimateAssemblyTokens, estimateMessageBytes, estimateMessageTokens, estimateTextBytes, estimateTextTokens, getContextBudgetReport, HARD_MAX_CONTEXT_BUDGET_BYTES, HARD_MAX_CONTEXT_BUDGET_OMISSIONS, HARD_MAX_CONTEXT_BUDGET_TOKENS, isContextBudgetError, resolveContextBudget, } from "./context-budget.js";
30
32
  export type * from "./contracts.js";
31
- export type { ApprovalOutcome, AttentionCompiler, AttentionCompilerContext, AttentionCompilerOptions, AttentionCompilerSetting, AttentionInputCapOptions, AttentionReport, CompactionTrigger, CompactionTriggerContext, DecisionScope, NestedRunApproval, NestedRunOutcome, NestedRunRef, PendingDecision, PendingDecisionKind, ProviderResolver, RealtimeCaps, RealtimeEvent, RealtimeSession, RealtimeSessionFactory, RealtimeSessionOptions, ResolveShouldCompactInput, ResolveShouldCompactOptions, ResumeNestedRun, RunDecision, RunLimitCounters, RunLimitName, SecureAgentOptions, StickyDecision, ToolCallAuthority, ToolEffectClassifier, ToolEffectDeclaration, ToolEffectIdempotency, ToolEffectKey, ToolEffectKind, ToolEffectRecord, ToolEffectStatus, ToolEffectStore, ToolEffectTransition, ToolElicitationRequest, } from "./contracts.js";
33
+ export type { ApprovalOutcome, AttentionCompiler, AttentionCompilerContext, AttentionCompilerOptions, AttentionCompilerSetting, AttentionInputCapOptions, AttentionReport, CompactionTrigger, CompactionTriggerContext, ContextMeter, DecisionScope, ModelFamily, NestedRunApproval, NestedRunOutcome, NestedRunRef, PendingDecision, PendingDecisionKind, ProviderResolver, RealtimeCaps, RealtimeEvent, RealtimeSession, RealtimeSessionFactory, RealtimeSessionOptions, ResolveShouldCompactInput, ResolveShouldCompactOptions, ResumeNestedRun, RunDecision, RunLimitCounters, RunLimitName, SecureAgentOptions, StickyDecision, TokenEstimate, TokenEstimateConfidence, ToolCallAuthority, ToolEffectClassifier, ToolEffectDeclaration, ToolEffectIdempotency, ToolEffectKey, ToolEffectKind, ToolEffectRecord, ToolEffectStatus, ToolEffectStore, ToolEffectTransition, ToolElicitationRequest, } from "./contracts.js";
32
34
  export { AgentDecisionError, AgentDelegationSuspendedError, AgentLoopStateError, AgentRunError, AgentRunStateError, assertBatchJobsSupported, assertCompactionTrigger, assertEmbeddingsSupported, assertImageGenerationSupported, assertModerationSupported, assertSessionMetadataKey, assertSpeechSupported, assertTranscriptionSupported, assertVideoGenerationSupported, BatchJobsError, DEFAULT_MAX_PENDING_DECISIONS, DEFAULT_MAX_PENDING_STEER_BYTES, DEFAULT_MAX_PENDING_STEERS, DEFAULT_MAX_SESSION_SEARCH_CURSOR_BYTES, DEFAULT_MAX_SESSION_SEARCH_FTS_CANDIDATES, DEFAULT_MAX_SESSION_SEARCH_LINEAR_BYTES, DEFAULT_MAX_SESSION_SEARCH_LINEAR_ENTRIES, DEFAULT_MAX_SESSION_SEARCH_LINEAR_SESSIONS, DEFAULT_MAX_SESSION_SEARCH_QUERY_BYTES, DEFAULT_MAX_SESSION_SEARCH_SNIPPET_BYTES, DEFAULT_MAX_STICKY_DECISIONS, DEFAULT_SESSION_SEARCH_LIMIT, DEFAULT_SNAPSHOT_CACHE_TTL_MS, EmbeddingsError, HARD_MAX_ACTION_CONSTRAINT_BYTES, HARD_MAX_ACTION_CONSTRAINTS, HARD_MAX_DECISION_REASON_BYTES, HARD_MAX_ELICITATION_BYTES, HARD_MAX_PENDING_DECISIONS, HARD_MAX_PENDING_STEER_BYTES, HARD_MAX_PENDING_STEERS, HARD_MAX_SESSION_SEARCH_CURSOR_BYTES, HARD_MAX_SESSION_SEARCH_FTS_CANDIDATES, HARD_MAX_SESSION_SEARCH_LIMIT, HARD_MAX_SESSION_SEARCH_LINEAR_BYTES, HARD_MAX_SESSION_SEARCH_LINEAR_ENTRIES, HARD_MAX_SESSION_SEARCH_LINEAR_SESSIONS, HARD_MAX_SESSION_SEARCH_QUERY_BYTES, HARD_MAX_SESSION_SEARCH_SNIPPET_BYTES, HARD_MAX_SNAPSHOT_CACHE_TTL_MS, HARD_MAX_STICKY_DECISIONS, ImageGenerationError, isBatchJobTerminal, isSessionAppendConflict, isSessionEntryKind, isSessionMetadataConflict, isSessionSearchUnsupported, MAX_ACTION_CONSTRAINT_BYTES, MAX_ACTION_CONSTRAINTS, MAX_ATTRIBUTION_DEPTH, MAX_DECISION_REASON_BYTES, MAX_ELICITATION_BYTES, ModerationError, modelSupportsBatchJobs, modelSupportsEmbeddings, modelSupportsImageGeneration, modelSupportsModeration, modelSupportsSpeech, modelSupportsTranscription, modelSupportsVideoGeneration, pollBatch, resolveSessionSearchQuery, resolveShouldCompact, SESSION_APPEND_CONFLICT_CODE, SESSION_ENTRY_KINDS, SESSION_ENTRY_SCHEMA_VERSION, SESSION_METADATA_CONFLICT_CODE, SESSION_SEARCH_UNSUPPORTED_CODE, SESSION_SEARCH_WORKSPACE_METADATA_KEY, SessionAppendConflictError, SessionMetadataConflictError, SessionSearchUnsupportedError, SpeechError, TranscriptionError, VideoGenerationError, } from "./contracts.js";
33
35
  export { parseAgentFile, parseSkillFile } from "./contribution-parsing.js";
34
36
  export type { ContributionRegistries, ContributionRegistriesOptions, ContributionRegistry, ContributionRegistryOptions, } from "./contributions.js";
@@ -47,14 +49,15 @@ export type { ClaimGroundingEvidence, ClaimGroundingEvidenceExtractor, ClaimGrou
47
49
  export { createClaimGroundingGuardrail } from "./evidence-grounding.js";
48
50
  export type { ExecutionAction, ExecutionDecision, ExecutionPolicy, ExecutionRisk } from "./execution-policy.js";
49
51
  export { applyExecutionDecision, assertExecutionAllowed, checkExecution, ExecutionDeniedError } from "./execution-policy.js";
50
- export type { ActivatedKernelConfig, ExtensionErrorPolicy, ExtensionEventBus, ExtensionEventHandler, ExtensionKernel, ExtensionKernelOptions, ExtensionLoadPolicy, LoadedExtension, } from "./extensions.js";
51
- export { activateKernel, createExtensionEventBus, createExtensionKernel } from "./extensions.js";
52
+ export type { ActivatedKernelConfig, AgentEventBridgeOptions, ExtensionErrorPolicy, ExtensionEventBus, ExtensionEventHandler, ExtensionKernel, ExtensionKernelOptions, ExtensionLoadPolicy, LoadedExtension, } from "./extensions.js";
53
+ export { activateKernel, createExtensionEventBus, createExtensionKernel, forwardAgentEvents } from "./extensions.js";
52
54
  export type { MemoryRunFeedbackStoreOptions, PrepareRunFeedbackOptions, RunFeedbackLimits, RunFeedbackRun, RunFeedbackRunResolver, } from "./feedback.js";
53
55
  export { createMemoryRunFeedbackStore, prepareRunFeedback, RunFeedbackError, requireRunFeedbackOwnership, runFeedbackPageLimit, } from "./feedback.js";
54
56
  export type { ApplyFieldPolicyOptions, AuditFieldRedaction, AuditFieldRedactorLike, AuditFieldRedactorOptions, FieldPolicy, FieldPolicyAction, FieldPolicyDecision, FieldPolicyInput, ProtectedFieldPolicyOptions, } from "./field-policy.js";
55
57
  export { ALLOW_FIELD_POLICY, applyFieldPolicy, createAuditFieldRedactor, createProtectedFieldPolicy, FIELD_POLICY_LIMITS, FieldPolicyError, } from "./field-policy.js";
56
- export type { GuardrailRunResult, RunGuardrailsOptions, } from "./guardrails.js";
57
- export { assertGuardrailsAllowed, GuardrailError, MAX_GUARDRAIL_CONCURRENCY, runGuardrails } from "./guardrails.js";
58
+ export { BUILT_IN_GUARDRAIL_PACK_IDS } from "./guardrail-packs/index.js";
59
+ export type { GuardrailPackRow, GuardrailRunResult, RunGuardrailsOptions, } from "./guardrails.js";
60
+ export { assertGuardrailsAllowed, compileGuardrailPacks, describeGuardrailPacks, GuardrailError, GuardrailPackError, MAX_GUARDRAIL_CONCURRENCY, MAX_GUARDRAIL_PACK_RULES, MAX_GUARDRAIL_PACKS, runGuardrails, } from "./guardrails.js";
58
61
  export type { AgentIdentity, AssertIdentityActiveOptions, IdentityLimits, IdentityVerifier, NarrowIdentityOptions, Principal, ResolvedIdentityLimits, } from "./identity.js";
59
62
  export { assertIdentityActive, assertIdentityMatchesOwnership, assertIdentityPropagation, DEFAULT_IDENTITY_LIMITS, HARD_IDENTITY_LIMITS, IdentityError, identityTelemetryAttributes, narrowIdentity, ownershipFromIdentity, resolveIdentityLimits, resolveRunIdentity, } from "./identity.js";
60
63
  export type { AgentInput, AssembleProviderInputOptions, DefaultInputBuildContext, DefaultInputBuilder, DefaultPromptBuilder, InputAttachment, PromptInstruction, PromptTemplateOptions, ResolveContextOptions, } from "./input.js";
@@ -64,8 +67,8 @@ export { resolveInstructionInjectors, runInstructionInjectors } from "./instruct
64
67
  export { createMemoryLeaseStore, LEASE_CONFLICT_CODE, LeaseConflictError } from "./leases.js";
65
68
  export type { ManifestContributionDeclaration, ManifestContributionKind, ManifestResourceDeclaration, PrismManifest } from "./manifests.js";
66
69
  export { definePrismManifest, parsePrismManifest } from "./manifests.js";
67
- export type { Middleware, MiddlewareHookName, MiddlewareNext, MiddlewareRegistry, MiddlewareRegistryOptions } from "./middleware.js";
68
- export { createMiddlewareRegistry } from "./middleware.js";
70
+ export type { BeforeProviderTurnPayload, DeterministicTurnAnswer, DeterministicTurnProvenance, Middleware, MiddlewareHookName, MiddlewareNext, MiddlewareRegistry, MiddlewareRegistryOptions, } from "./middleware.js";
71
+ export { createMiddlewareRegistry, DeterministicTurnError } from "./middleware.js";
69
72
  export type { MockProviderOptions } from "./mock-provider.js";
70
73
  export { createMockProvider } from "./mock-provider.js";
71
74
  export type { ModelRegistry, ModelRegistryOptions } from "./models.js";
@@ -75,7 +78,7 @@ export { createProviderTurnMetadata, readProviderHttpStatus } from "./observabil
75
78
  export type { ApplyRetentionInput, ApplyRetentionResult, ConsumeTenantQuotaInput, ExportUnderHoldInput, LegalHoldExportItem, LegalHoldQuery, LegalHoldRecord, PersistenceLifecycleStore, PersistenceResourceKind, PutLegalHoldInput, ReleaseLegalHoldInput, SetTenantQuotaInput, TenantQuota, } from "./persistence-lifecycle.js";
76
79
  export { createMemoryPersistenceLifecycle, DEFAULT_LIFECYCLE_PAGE_SIZE, DEFAULT_MAX_HOLD_REASON_BYTES, HARD_LIFECYCLE_PAGE_SIZE, HARD_MAX_HOLD_REASON_BYTES, isResourceHeld, PersistenceLifecycleError, } from "./persistence-lifecycle.js";
77
80
  export { boundResponse, defaultResolver, isLoopbackAddress, isLoopbackHostname, normalizeHostname, type PinnedFetchOptions, pinnedFetch, raceAbort, requestPinned, resolvePinnedAddress, } from "./pinned-fetch.js";
78
- export { providerContentDelta, providerContinuationRequired, providerDone, providerError, providerTextDelta, providerThinkingDelta, providerToolCall, providerToolCallDelta, providerUsage, toolCallContent, toolCallFromArgumentsText, } from "./provider-events.js";
81
+ export { mapProviderStopReason, providerContentDelta, providerContinuationRequired, providerDone, providerError, providerTextDelta, providerThinkingDelta, providerToolCall, providerToolCallDelta, providerUsage, toolCallContent, toolCallFromArgumentsText, } from "./provider-events.js";
79
82
  export { authMethodKey, defineProviderPackage, systemPromptContributionKey } from "./provider-packages.js";
80
83
  export type { ApplyDefaultProviderRequestOptionsContext, SessionCachePolicyOptions } from "./provider-request-policy.js";
81
84
  export { applyDefaultProviderRequestOptions, createProviderRequestPolicyChain, createSessionCachePolicy, mergeProviderRequestOptions, ProviderRequirementError, } from "./provider-request-policy.js";
@@ -123,8 +126,10 @@ export { createActiveToolSet, createSearchToolsTool, createToolSearchIndex, crea
123
126
  export type { DispatchToolCallOptions, ToolArgumentValidationError, ToolArgumentValidationResult, ToolArgumentValidator, ToolFilter, ToolFilterInput, ToolParameterValidatorOptions, ToolRegistryOptions, ToolValidator, } from "./tools.js";
124
127
  export { createToolParameterValidator, createToolRegistry, dispatchToolCall, filterTools } from "./tools.js";
125
128
  export { trimTrailingSlashes } from "./trim-trailing-slashes.js";
129
+ export type { ModelFamilyTokens } from "./usage-estimation.js";
130
+ export { MODEL_FAMILY_TOKENS, resolveModelFamily } from "./usage-estimation.js";
126
131
  export type { ResolvedUseCaseModel, ResolveUseCaseModelInput, UseCaseModelBinding, } from "./use-case-model.js";
127
132
  export { resolveUseCaseModel, resolveUseCaseModelBinding, useCaseCredentialProviderId, } from "./use-case-model.js";
128
133
  export declare const name = "prism";
129
- export declare const version = "0.8.0";
134
+ export declare const version = "0.10.0";
130
135
  export declare const description = "Agent harness for AI providers, agents, sessions, and tools.";
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  export { resolveAgentDefinition } from "./agent-definitions.js";
2
- export { AgentEventSourceError, createMemoryAgentEventSource } from "./agent-event-source.js";
2
+ export { AgentEventSourceError, createMemoryAgentEventSource, isTerminalAgentEventType } from "./agent-event-source.js";
3
3
  export { dispatchToolCallsInOrder, generateValidateReviseLoop, isAgentLoopOptions, resolveLoop, resolveToolConcurrency, singleShotLoop, } from "./agent-loops.js";
4
4
  export { createAgentRunLifecycle } from "./agent-run-lifecycle.js";
5
- export { AGENT_RUN_STATE_NAMESPACE, AGENT_RUN_STATE_SCHEMA_VERSION, agentFingerprint, DEFAULT_MAX_AGENT_RUN_STATE_BYTES, HARD_MAX_AGENT_RUN_STATE_BYTES, loadAgentRunState, } from "./agent-run-state.js";
5
+ export { AGENT_RUN_STATE_NAMESPACE, AGENT_RUN_STATE_SCHEMA_VERSION, agentFingerprint, boundCheckpointMetadata, DEFAULT_MAX_AGENT_RUN_STATE_BYTES, HARD_MAX_AGENT_RUN_STATE_BYTES, loadAgentRunState, MAX_AGENT_RUN_METADATA_BYTES, readCheckpointMetadata, resolveCheckpointMetadata, } from "./agent-run-state.js";
6
6
  export { createAgent, createAgentSession, resumeAgentRun, resumeAgentRunStream } from "./agents.js";
7
7
  export { ARTIFACT_BODY_ERROR_CODES, ARTIFACT_CHECKPOINT_NAMESPACE, ArtifactBodyStoreError, ArtifactError, approvalEvidenceIntact, artifactApprovalState, artifactCheckpointKey, checkCitationIntegrity, citationBindingDigest, HARD_CITATION_EXCERPT_BYTES, } from "./artifacts.js";
8
8
  export { ATTENTION_BUDGET_ERROR_CODE, AttentionBudgetError, createAttentionCompiler, createAttentionTruncationTrigger, DEFAULT_ATTENTION_COMPACT_RATIO, DEFAULT_ATTENTION_KEEP_LAST, DEFAULT_ATTENTION_RESERVE_TOKENS, DEFAULT_ATTENTION_THINKING_KEEP_TURNS, DEFAULT_ATTENTION_TRIGGER_RATIO, DEFAULT_ATTENTION_TRUNCATION_THRESHOLD, isAttentionBudgetError, resolveAttentionReserveTokens, resolveInputCap, resolveRunAttentionCompiler, } from "./attention-compiler.js";
9
9
  export { applyCacheControl, cacheHitRate, cacheSavings, cacheUsageReport, mapCacheRetention, resolveBreakpoint, sanitizeCacheKey, systemCacheControlField, } from "./cache-helpers.js";
10
10
  export { CACHE_TELEMETRY_OVERFLOW_KEY, CacheTelemetryError, createCacheTelemetry, DEFAULT_CACHE_TELEMETRY_CAP, } from "./cache-telemetry.js";
11
11
  export { createProviderCapture } from "./capture.js";
12
+ export { CheckpointRestoreError, DEFAULT_CHECKPOINT_RESTORE_TIMEOUT_MS, runCheckpointRestoreHooks } from "./checkpoint-restore.js";
12
13
  export { CHECKPOINT_CONFLICT_CODE, CheckpointConflictError, createMemoryCheckpointStore } from "./checkpoints.js";
13
14
  export { createDefaultCompactionStrategy, isCompactionEntryData } from "./compaction.js";
14
15
  export { assertJsonObject, isJsonObject, loadConfigLayers, mergeConfigLayers } from "./config.js";
@@ -24,23 +25,24 @@ export { acceptDeviceChunk, assertDeviceAdmit, DEFAULT_DEVICE_MAX_CHUNK_BYTES, D
24
25
  export { createEventMultiplexer, EVENT_MULTIPLEXER_SINGLE_CONSUMER_CODE, EventMultiplexerError } from "./event-multiplexer.js";
25
26
  export { createClaimGroundingGuardrail } from "./evidence-grounding.js";
26
27
  export { applyExecutionDecision, assertExecutionAllowed, checkExecution, ExecutionDeniedError } from "./execution-policy.js";
27
- export { activateKernel, createExtensionEventBus, createExtensionKernel } from "./extensions.js";
28
+ export { activateKernel, createExtensionEventBus, createExtensionKernel, forwardAgentEvents } from "./extensions.js";
28
29
  export { createMemoryRunFeedbackStore, prepareRunFeedback, RunFeedbackError, requireRunFeedbackOwnership, runFeedbackPageLimit, } from "./feedback.js";
29
30
  export { ALLOW_FIELD_POLICY, applyFieldPolicy, createAuditFieldRedactor, createProtectedFieldPolicy, FIELD_POLICY_LIMITS, FieldPolicyError, } from "./field-policy.js";
30
- export { assertGuardrailsAllowed, GuardrailError, MAX_GUARDRAIL_CONCURRENCY, runGuardrails } from "./guardrails.js";
31
+ export { BUILT_IN_GUARDRAIL_PACK_IDS } from "./guardrail-packs/index.js";
32
+ export { assertGuardrailsAllowed, compileGuardrailPacks, describeGuardrailPacks, GuardrailError, GuardrailPackError, MAX_GUARDRAIL_CONCURRENCY, MAX_GUARDRAIL_PACK_RULES, MAX_GUARDRAIL_PACKS, runGuardrails, } from "./guardrails.js";
31
33
  export { assertIdentityActive, assertIdentityMatchesOwnership, assertIdentityPropagation, DEFAULT_IDENTITY_LIMITS, HARD_IDENTITY_LIMITS, IdentityError, identityTelemetryAttributes, narrowIdentity, ownershipFromIdentity, resolveIdentityLimits, resolveRunIdentity, } from "./identity.js";
32
34
  export { assembleProviderInput, createDefaultInputBuilder, createDefaultPromptBuilder, EMPTY_TOOL_RESULT_TEXT, renderPromptTemplate, resolveContextProviders, } from "./input.js";
33
35
  export { resolveInstructionInjectors, runInstructionInjectors } from "./instruction-injection.js";
34
36
  export { createMemoryLeaseStore, LEASE_CONFLICT_CODE, LeaseConflictError } from "./leases.js";
35
37
  export { definePrismManifest, parsePrismManifest } from "./manifests.js";
36
- export { createMiddlewareRegistry } from "./middleware.js";
38
+ export { createMiddlewareRegistry, DeterministicTurnError } from "./middleware.js";
37
39
  export { createMockProvider } from "./mock-provider.js";
38
40
  export { createModelRegistry } from "./models.js";
39
41
  export { abortableSleep, pollDeviceCodeToken, redactOAuthError, throwIfAborted, } from "./oauth-device-code.js";
40
42
  export { createProviderTurnMetadata, readProviderHttpStatus } from "./observability.js";
41
43
  export { createMemoryPersistenceLifecycle, DEFAULT_LIFECYCLE_PAGE_SIZE, DEFAULT_MAX_HOLD_REASON_BYTES, HARD_LIFECYCLE_PAGE_SIZE, HARD_MAX_HOLD_REASON_BYTES, isResourceHeld, PersistenceLifecycleError, } from "./persistence-lifecycle.js";
42
44
  export { boundResponse, defaultResolver, isLoopbackAddress, isLoopbackHostname, normalizeHostname, pinnedFetch, raceAbort, requestPinned, resolvePinnedAddress, } from "./pinned-fetch.js";
43
- export { providerContentDelta, providerContinuationRequired, providerDone, providerError, providerTextDelta, providerThinkingDelta, providerToolCall, providerToolCallDelta, providerUsage, toolCallContent, toolCallFromArgumentsText, } from "./provider-events.js";
45
+ export { mapProviderStopReason, providerContentDelta, providerContinuationRequired, providerDone, providerError, providerTextDelta, providerThinkingDelta, providerToolCall, providerToolCallDelta, providerUsage, toolCallContent, toolCallFromArgumentsText, } from "./provider-events.js";
44
46
  export { authMethodKey, defineProviderPackage, systemPromptContributionKey } from "./provider-packages.js";
45
47
  export { applyDefaultProviderRequestOptions, createProviderRequestPolicyChain, createSessionCachePolicy, mergeProviderRequestOptions, ProviderRequirementError, } from "./provider-request-policy.js";
46
48
  export { canonicalizeJsonSchema } from "./providers/schema.js";
@@ -67,8 +69,9 @@ export { DEFAULT_TOOL_RESULT_FOLD_MAX_SUMMARY_BYTES, DEFAULT_TOOL_RESULT_FOLD_MI
67
69
  export { createActiveToolSet, createSearchToolsTool, createToolSearchIndex, createToolSearchState, DEFAULT_MAX_TOOLS_SEARCH_QUERY_BYTES, DEFAULT_TOOLS_SEARCH_TOP_K, HARD_MAX_TOOLS_INDEX, HARD_MAX_TOOLS_SEARCH_QUERY_BYTES, HARD_MAX_TOOLS_SEARCH_TOP_K, isToolDisclosureError, resolveToolsDisclosure, SEARCH_TOOLS_TOOL_NAME, scoreTools, selectDisclosedTools, TOOL_DISCLOSURE_ERROR_CODE, ToolDisclosureError, } from "./tool-search.js";
68
70
  export { createToolParameterValidator, createToolRegistry, dispatchToolCall, filterTools } from "./tools.js";
69
71
  export { trimTrailingSlashes } from "./trim-trailing-slashes.js";
72
+ export { MODEL_FAMILY_TOKENS, resolveModelFamily } from "./usage-estimation.js";
70
73
  export { resolveUseCaseModel, resolveUseCaseModelBinding, useCaseCredentialProviderId, } from "./use-case-model.js";
71
74
  export const name = "prism";
72
- export const version = "0.8.0";
75
+ export const version = "0.10.0";
73
76
  export const description = "Agent harness for AI providers, agents, sessions, and tools.";
74
77
  //# sourceMappingURL=index.js.map
package/dist/input.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type AttentionStickyFrontier } from "./attention-compiler.js";
1
+ import { type AttentionFoldLedger, type AttentionStickyFrontier } from "./attention-compiler.js";
2
2
  import { type ContextBudget } from "./context-budget.js";
3
3
  import type { AttentionCompiler, AttentionCompilerOptions, AttentionReport, ContentBlock, ContextBlock, ContextProvider, ContextResolutionContext, InputBuildContext, InputBuilder, InstructionInjector, JsonObject, Message, ModelConfig, PromptBuilder, PromptBuildRequest, ProviderRequest, ProviderRequestOptions, ResourceLoader, Skill, ToolDefinition, ToolResult } from "./contracts.js";
4
4
  import type { MiddlewareRegistry } from "./middleware.js";
@@ -65,6 +65,8 @@ export interface AssembleProviderInputOptions extends DefaultInputBuildContext {
65
65
  readonly skills?: readonly Skill[];
66
66
  readonly skillsDisclosure?: SkillsDisclosure;
67
67
  readonly loadedSkills?: LoadedSkillSet;
68
+ /** Run-owned append-only segments. Omit outside a session to retain existing assembly exactly. */
69
+ readonly tailSegments?: Map<string, Message>;
68
70
  readonly tools?: readonly ToolDefinition[];
69
71
  /** Tools disclosure: "search" narrows the disclosed tool list (activated ∪ top-k); default "all" is unchanged. */
70
72
  readonly toolsDisclosure?: ToolsDisclosure;
@@ -86,9 +88,14 @@ export interface AssembleProviderInputOptions extends DefaultInputBuildContext {
86
88
  readonly attentionCompiler?: AttentionCompilerOptions | AttentionCompiler;
87
89
  /** Per-session-leaf sticky frontier; omit for one-shot assemblies (no cross-turn stickiness). */
88
90
  readonly attentionSticky?: AttentionStickyFrontier;
91
+ /** Per-session folded bodies; omit to re-summarize every folded row on every turn. */
92
+ readonly attentionFold?: AttentionFoldLedger;
89
93
  /** Called once per *mutated* turn with the report, so a host can emit telemetry: under-ratio
90
94
  * turns never call it, and it runs before `input_assembly` middleware. */
91
95
  readonly onAttentionReport?: (report: AttentionReport) => void;
96
+ /** Run input tokens already charged this run; feeds the `run_input_ratio` axis projection
97
+ * (default 0). The run budget itself rides the resolved `AttentionCompiler` handle. */
98
+ readonly runInputTokens?: number;
92
99
  }
93
100
  export declare function createDefaultInputBuilder(): DefaultInputBuilder;
94
101
  export declare function resolveContextProviders(options: ResolveContextOptions): Promise<readonly ContextBlock[]>;