@arnilo/prism 0.0.11 → 0.0.13

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 +24 -0
  2. package/dist/agent-run-lifecycle.d.ts +5 -1
  3. package/dist/agent-run-lifecycle.js +17 -1
  4. package/dist/agents.d.ts +3 -1
  5. package/dist/agents.js +98 -20
  6. package/dist/contracts.d.ts +29 -1
  7. package/dist/extensions.d.ts +11 -0
  8. package/dist/extensions.js +15 -0
  9. package/dist/identity.d.ts +92 -0
  10. package/dist/identity.js +257 -0
  11. package/dist/index.d.ts +8 -4
  12. package/dist/index.js +4 -2
  13. package/dist/persistence-lifecycle.d.ts +103 -0
  14. package/dist/persistence-lifecycle.js +204 -0
  15. package/dist/providers/openai-compatible.d.ts +5 -1
  16. package/dist/providers/openai-compatible.js +15 -6
  17. package/dist/secure-agent.js +7 -1
  18. package/dist/testing/persistence-schema.d.ts +2 -2
  19. package/dist/testing/persistence-schema.js +35 -2
  20. package/dist/tools.d.ts +2 -0
  21. package/dist/tools.js +6 -0
  22. package/docs/a2a.md +3 -0
  23. package/docs/ag-ui.md +123 -0
  24. package/docs/agent-events.md +2 -1
  25. package/docs/agent-identity.md +111 -0
  26. package/docs/agent-session-runtime.md +5 -1
  27. package/docs/coding-agent-tools.md +2 -0
  28. package/docs/compaction-and-retry.md +2 -1
  29. package/docs/compaction-llm.md +20 -1
  30. package/docs/credential-storage.md +5 -1
  31. package/docs/credentials-and-redaction.md +8 -0
  32. package/docs/database-persistence.md +18 -7
  33. package/docs/extensions.md +1 -0
  34. package/docs/guardrails.md +3 -0
  35. package/docs/host-security.md +7 -1
  36. package/docs/index.md +25 -14
  37. package/docs/mcp-tools.md +2 -0
  38. package/docs/migration.md +43 -0
  39. package/docs/model-routing.md +102 -0
  40. package/docs/observability.md +2 -0
  41. package/docs/performance.md +38 -0
  42. package/docs/policy-and-audit.md +127 -0
  43. package/docs/postgres-persistence.md +1 -1
  44. package/docs/provider-packages.md +17 -0
  45. package/docs/provider-request-policies.md +2 -0
  46. package/docs/providers/anthropic.md +3 -2
  47. package/docs/providers/azure.md +74 -0
  48. package/docs/providers/bedrock.md +72 -0
  49. package/docs/providers/google.md +4 -2
  50. package/docs/providers/openai-compatible.md +3 -1
  51. package/docs/providers/openai.md +2 -2
  52. package/docs/providers/openrouter.md +2 -0
  53. package/docs/providers/vertex.md +71 -0
  54. package/docs/public-contracts.md +5 -1
  55. package/docs/release-and-install.md +167 -17
  56. package/docs/review-coverage-2026-07-22-phase-7.md +173 -0
  57. package/docs/review-coverage-2026-07-23-phase-8.md +245 -0
  58. package/docs/runs-and-usage.md +3 -0
  59. package/docs/server.md +34 -4
  60. package/docs/sqlite-persistence.md +1 -1
  61. package/docs/supervisors.md +2 -0
  62. package/docs/work-connectors.md +28 -0
  63. package/docs/work-tools.md +114 -0
  64. package/package.json +5 -1
@@ -102,6 +102,14 @@ console.log(error.message);
102
102
  - Keep resolved credential values local to the request path. Do not put them in registries, model configs, messages, provider events, agent events, session entries, compaction summaries, or logs.
103
103
  - Future settings/config loaders may provide credential resolver instances, but core helpers remain storage-free.
104
104
 
105
+ ### Subscription OAuth eligibility
106
+
107
+ In 0.0.12, OpenAI Codex is Prism's only first-party subscription OAuth flow. It is explicit and host-invoked through `createOpenAICodexOAuthProvider()`; hosts own login UI and may use `createOAuthCredentialStoreAdapter()` for deliberately selected durable storage.
108
+
109
+ Anthropic and Google provider packages are API-key-only. Do not scrape or import Claude Code/Gemini CLI credential files, setup tokens, environment values, or browser sessions, and do not route a user's Claude.ai/Gemini subscription through Prism. Anthropic states that developers building products must use Claude Console API keys or a supported cloud provider and may not offer Claude.ai login or route Free/Pro/Max credentials ([legal and compliance](https://docs.anthropic.com/en/docs/claude-code/legal-and-compliance)). Gemini CLI states that third-party software using its OAuth to access backend services violates applicable terms; its FAQ names Vertex AI or Google AI Studio API keys as the supported third-party path ([terms](https://github.com/google-gemini/gemini-cli/blob/main/docs/resources/tos-privacy.md), [FAQ](https://github.com/google-gemini/gemini-cli/blob/main/docs/resources/faq.md)).
110
+
111
+ A future provider-local OAuth adapter needs published permission for third-party products, documented authorize/token/refresh endpoints and scopes, PKCE/state where required, abort/expiry/bounded-response/redaction/store-round-trip fixtures, and legal review before registration. Until then, absence is intentional.
112
+
105
113
  ## Security and performance notes
106
114
 
107
115
  - Redaction only removes exact known secret values passed to the helper. It is not a general-purpose secret detector.
@@ -334,19 +334,30 @@ Use `cursor`/`limit` when an adapter pages very long branches. Do not implement
334
334
 
335
335
  ## Retention policies
336
336
 
337
- A retention policy is a host-managed rule attached to sessions via `retention_policy_id`. Enforcement is host-owned and typically runs as a background job:
337
+ A retention policy is a host-managed rule attached to sessions via `retention_policy_id`. Phase 8 adds optional `ProductionPersistenceStore.lifecycle` (`createMemoryPersistenceLifecycle`, SQLite/Postgres `persistence.lifecycle`) for bounded apply/hold/export/quota:
338
+
339
+ ```ts
340
+ await store.lifecycle.putLegalHold({ tenantId, userId, resourceKind: "session", resourceId, reason });
341
+ await store.lifecycle.applyRetention({ tenantId, userId, policy, candidates }); // hold wins over delete
342
+ await store.lifecycle.exportUnderHold({ tenantId, userId, cursor, limit }); // redacted
343
+ await store.lifecycle.setTenantQuota({ tenantId, userId, resourceKind: "run", limit: 100 });
344
+ await store.lifecycle.consumeTenantQuota({ tenantId, userId, resourceKind: "run" }); // fails closed when exhausted
345
+ ```
346
+
347
+ Schema **v5** migration `005_lifecycle_hold_quota` adds `prism_legal_holds` and `prism_tenant_quotas`. Legal hold always blocks delete for the held resource id. Export pages are redacted refs only (no prompts/bodies/secrets).
348
+
349
+ Host background jobs may still:
338
350
 
339
351
  1. Select policies whose `max_age_days`, `max_entries_per_session`, or `max_total_bytes` thresholds are exceeded.
340
- 2. For each affected session, delete or archive entries older than the policy age, beyond the entry count, or over the byte budget.
341
- 3. Respect `applied_kinds` — only delete kinds listed in the policy (null means all kinds).
342
- 4. Compact or soft-delete sessions whose `expires_at` has passed.
343
- 5. Write audit metadata to the migration or host audit log; do not delete the policy row unless explicitly requested.
352
+ 2. Pass candidate session ids into `applyRetention` (or let SQL adapters discover expired sessions).
353
+ 3. Respect `applied_kinds` when selecting candidates.
354
+ 4. Never silently purge under hold.
344
355
 
345
- Retention jobs should not run inside the agent/session runtime. They are a host concern.
356
+ Retention jobs should not run inside the agent/session runtime.
346
357
 
347
358
  ## Migrations
348
359
 
349
- Hosts own schema migrations. Prism publishes only the TypeScript contracts; no DDL is generated or executed by the core library. First-party SQLite/PostgreSQL adapters automatically verify their checked-in schema-v3 history and catalog at open, before runtime writes. Their catalog reads are bounded metadata queries/PRAGMAs, not table-data scans.
360
+ Hosts own schema migrations. Prism publishes only the TypeScript contracts; no DDL is generated or executed by the core library. First-party SQLite/PostgreSQL adapters automatically verify their checked-in schema-v5 history and catalog at open, before runtime writes. Their catalog reads are bounded metadata queries/PRAGMAs, not table-data scans.
350
361
 
351
362
  Each new adapter-owned migration row records the contract SHA-256 checksum. A complete known v0.0.5 history whose checksum values are all `NULL` is a one-time compatibility case: under the SQLite transaction or PostgreSQL advisory transaction lock, the adapter verifies the full current shape, backfills all checksums, and continues. Unknown/duplicate/out-of-order/name-version/checksum mismatch, mixed/partial legacy values, or any missing/renamed/wrong-type/null/default/key/index artifact fails closed. Restore or apply a reviewed host migration; never edit checksums to silence drift.
352
363
 
@@ -122,6 +122,7 @@ await kernel.middleware.run("provider_request", { metadata: {} });
122
122
  - Do not put resolved credential values in extension events, registry metadata, docs, logs, prompts, or session stores.
123
123
  - Event and middleware dispatch are ordered and dependency-free. They use no timers, background workers, filesystem discovery, network calls, provider calls, or tool execution.
124
124
  - Extension middleware cannot bypass host tool permissions: tool dispatch re-checks active registry lookup, filters, and object arguments after `tool_call` middleware. Skills that reference `toolNames` are checked against host-active tools by `resolveActiveSkills()`.
125
+ - Optional `loadPolicy: { allowList?, verifySignature? }` on `createExtensionKernel` runs before `setup`. Unallowlisted or unsigned (when `verifySignature` is set) extensions fail closed. Put host-attested digests on `Extension.signature`.
125
126
 
126
127
  ## Related APIs
127
128
 
@@ -65,10 +65,13 @@ Guardrails are callbacks supplied by the host. Prism does not discover, load, re
65
65
 
66
66
  ## Security and performance notes
67
67
 
68
+ Optional `@arnilo/prism-policy` can record guardrail outcomes via `recordGuardrailDecision` (evidence refs only; see [Policy and audit](policy-and-audit.md)).
69
+
68
70
  Output buffering prevents blocked provider content from reaching subscribers, session entries, ledgers, parsers, delegation, or tools. Tool-output checks receive raw results but Prism discards blocked raw output before event, ledger, transcript, or MCP exposure. Redaction replaces exact known values only; it is not general secret detection. Parallel checks receive an abort signal, but callback code must honor it to stop in-flight work. Browser snapshots and page text from `@arnilo/prism-browser` are untrusted external content: never allow them to modify tools, permissions, credentials, or policy. Browser mutations still require host `ExecutionPolicy`/approval; prompt-injection text in a page cannot grant upload/download release.
69
71
 
70
72
  ## Related APIs
71
73
 
74
+ - [Policy and audit](policy-and-audit.md): optional attributable decision ledger for guardrail outcomes.
72
75
  - [Agent/session runtime](agent-session-runtime.md)
73
76
  - [Tools](tools.md)
74
77
  - [Browser automation](browser-automation.md)
@@ -34,6 +34,8 @@ Start from explicit host inputs. Do not let runtime code discover security state
34
34
  | Durable interruption | host checkpoint + session stores, exact ownership | `RunOptions.runState`, `resumeAgentRun()`, `createAgentRunLifecycle()`, `createSecureAgent()` |
35
35
  | Extensions | explicit package imports only | `createExtensionKernel`, `ExtensionAPI` |
36
36
  | Remote agent/workflow API | host authentication + ownership mapping | `@arnilo/prism-server`, `createPrismHandler()` |
37
+ | Authenticated identity | host `IdentityVerifier` → verified `AgentIdentity` | [Agent identity](agent-identity.md), `assertIdentityActive`, `narrowIdentity` |
38
+ | Policy decision audit | optional redacted ledger + host WORM sink | [Policy and audit](policy-and-audit.md), `@arnilo/prism-policy` |
37
39
  | MCP server exposure | host MCP auth + selected capability list | `createPrismMcpServer()`, `createPrismMcpWebHandler()` |
38
40
 
39
41
  ## Outputs / response / events
@@ -117,6 +119,7 @@ Wire those values where they matter: provider adapters receive the resolved cred
117
119
  - Resolve credentials at the provider/request edge, as late as possible. Do not put resolved credentials in configs, manifests, registries, prompts, messages, events, session entries, run ledgers, idempotency keys, cache keys, or logs.
118
120
  - Use `createExplicitCredentialResolver()` to document source order such as runtime override → stored credential → caller-supplied env object → fallback.
119
121
  - Use `createEnvCredentialResolver()` only with an object the host passes in. Prism does not read `process.env` for credentials.
122
+ - Do not treat a local vendor CLI credential file, setup token, browser session, or consumer subscription as a Prism credential source. In 0.0.12 only OpenAI Codex has a first-party subscription OAuth flow; Anthropic and Google providers remain API-key-only under their published third-party restrictions. See [Credentials and redaction](credentials-and-redaction.md#subscription-oauth-eligibility).
120
123
  - Use `createPathTrustPolicy()` for workspace/resource roots and fail closed on symlink escapes.
121
124
  - Use `createContributionRegistries({ duplicate: "error" })` and prefixed names for third-party packages to prevent silent shadowing.
122
125
  - Extension contributions are inert until selected. Loading an extension package runs its `setup(api)` code, so hosts should load only trusted packages or isolate untrusted code outside Prism.
@@ -143,7 +146,8 @@ Wire those values where they matter: provider adapters receive the resolved cred
143
146
  - LLM compaction always sends finite summary `maxTokens`, retains bounded deltas/events, and bounds/redacts provider/factory/policy error detail. Observational-memory workers cap turns, calls, arguments, results, transcript, and surfaced errors; unknown tools fail before execution, while invalid results can only be rejected after a host tool returns and may therefore follow side effects. Pass all known provider/credential/tool secrets into compaction/runtime options; exact replacement is not secret discovery.
144
147
  - Default remote-media loading resolves every DNS answer, rejects the hostname if any address is non-public, and pins one validated address through the request. Explicit `allowedHostnames` can trust private destinations. A host-supplied `fetch` owns DNS/rebinding/proxy/redirect safety; a custom `requestUrl` must connect to its supplied validated address.
145
148
  - Permission checks happen before tool validation and before `tool.execute()`. Middleware cannot grant permission by renaming a tool.
146
- - Session stores and ledgers receive redacted values when a redactor is active, but durable storage remains host-owned. Enforce tenant/account/user ownership and retention in the database layer.
149
+ - Session stores and ledgers receive redacted values when a redactor is active, but durable storage remains host-owned. Enforce tenant/account/user ownership, retention, legal hold, and quotas via `ProductionPersistenceStore.lifecycle` (or host-equivalent DB controls). Hold always blocks delete.
150
+ - Prefer `createExtensionKernel({ loadPolicy })` allow-list/signature checks before loading third-party extension packages.
147
151
  - Provider-owned auth/content/session/cache/security headers win over caller headers in adapters that merge headers.
148
152
  - Security checks are bounded explicit calls on the active path. Prism adds no hidden global middleware, background workers, watchers, network calls, or filesystem scans.
149
153
 
@@ -171,6 +175,7 @@ PostgreSQL TLS/network policy, MCP endpoint trust/credentials and egress policy
171
175
  ## Web research boundaries
172
176
 
173
177
  - Construct `@arnilo/prism-web-tools` with one host-selected Brave or Exa adapter; never expose adapter/provider/credential/schema selection to model arguments.
178
+ - Construct `@arnilo/prism-work-tools` with host-pinned CLI binary + isolated `configDir` + verified `AgentIdentity` (M365 and/or GWS). Never pass model-built command strings, `login`/`setup`/`auth`/`schema`/`--debug`, or credentials in argv. Mutations require draft approval; external recipients and anonymous/`anyone` shares fail closed.
174
179
  - Provider API origins are fixed exact HTTPS origins and redirects fail. Credentials resolve immediately before I/O; remote bodies and secrets are excluded from errors/results/telemetry.
175
180
  - Firecrawl targets reject userinfo, non-HTTP(S), private literals, and policy-denied hosts. Supply `validateUrl` for host DNS/rebinding/egress checks. Firecrawl performs remote retrieval, so Prism cannot pin target DNS after handoff.
176
181
  - Treat every snippet, highlight, Markdown byte, metadata field, and extracted JSON value as prompt-injection-capable untrusted data. Never elevate it into system instructions or let it modify tools, permissions, trust, credentials, routing, or extraction schema.
@@ -190,6 +195,7 @@ PostgreSQL TLS/network policy, MCP endpoint trust/credentials and egress policy
190
195
  ## Related APIs
191
196
 
192
197
  - [Web-standard server handler](server.md): remote agent/workflow route, ownership, limits, abort, and deployment boundary.
198
+ - [Frontend interoperability (AG-UI and ACP)](ag-ui.md): authorize every protocol selector/operation; default-deny tool/state/path projection; exact interrupt/version resume; redacted, ownership-scoped replay.
193
199
  - [Supervisor delegation](supervisors.md): local child permission/memory/budget boundary.
194
200
  - [A2A interoperability](a2a.md): remote card/auth/origin/signature boundary.
195
201
  - [Settings, auth, trust, and security controls](settings-auth-trust-security.md): low-level helpers and boundary hardening table.
package/docs/index.md CHANGED
@@ -5,8 +5,13 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
5
5
  ## Public contracts
6
6
  - [Public contracts](public-contracts.md): type shapes for messages, agents, tools, stores, generic `CheckpointStore`, atomic `LeaseStore`, bounded `EventMultiplexer`, resources, credentials, and events.
7
7
 
8
+ ## Identity and governance
9
+ - [Agent identity](agent-identity.md): host-verified `Principal` / `AgentIdentity`, delegation narrowing, ownership projection, and redacted telemetry refs for enterprise runs/tools/MCP/A2A/workflows.
10
+ - [Policy and audit](policy-and-audit.md): optional `@arnilo/prism-policy` decision ledger (allow/deny/modify/approval), evidence refs only, and cursor-paginated WORM export.
11
+ - [Model routing](model-routing.md): optional `@arnilo/prism-model-router` allow-list/residency/budget/rate/circuit/fallback governance over `ProviderResolver` with redacted diagnostics.
12
+
8
13
  ## Agent/session runtime
9
- - [Agent/session runtime](agent-session-runtime.md): create explicit or opt-in secure agents/sessions, get direct `AgentRunResult` values from `run`/`prompt`, mid-run `steer` (turn-boundary or softInterrupt), use integrated `stream()`, subscribe to normalized events, and expose opted-in durable lifecycle capabilities.
14
+ - [Agent/session runtime](agent-session-runtime.md): create explicit or opt-in secure agents/sessions, get direct `AgentRunResult` values from `run`/`prompt`, mid-run `steer` (turn-boundary or softInterrupt), use integrated `stream()`/`resumeAgentRunStream()`, subscribe to normalized events, and expose opted-in durable lifecycle capabilities.
10
15
  - [Agent definitions](agent-definitions.md): resolve declarative `AgentDefinition` values via `resolveAgentDefinition`, and turn app-config `<configRoot>/agents/<name>/AGENT.md` bundles into runnable agents via `discoverAgentBundles` / `resolveAgentBundle` (explicit tool/skill activation by name, fail-closed omitted capabilities, migration-only `activateAllCapabilities`, strict duplicate scope checks, configurable prompt layers, no auto-discovery).
11
16
  - [Agent loops](agent-loops.md): replaceable per-run control loops — `singleShotLoop` default and opt-in bounded artifact-loop tool rounds with host-supplied `validator`/`parser`/`repairer` callbacks.
12
17
  - [Guardrails](guardrails.md): typed fail-closed input/output/tool checks with buffered provider output and redacted decision records.
@@ -14,20 +19,20 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
14
19
  - [Observability](observability.md): OTel GenAI agent/provider/tool hierarchy, host context parenting, bounded trace linkage, safe evaluation events, controlled metrics, and exporter isolation.
15
20
  - [Evaluations](evaluations.md): deterministic and bounded trace/model-judge/pairwise scoring, CI thresholds, OTel trace-reference linkage, coding/browser adversarial fixtures, and ID-only linkage to immutable owned run feedback.
16
21
  - [Runs and usage ledger](runs-and-usage.md): durable run/event/tool/usage persistence, optional bounded FIFO durability policies, session snapshot caching, and immutable run/trace feedback.
17
- - [Performance limits](performance.md): bounded evaluation traces/judges/reports, 0.0.11 search/budget, 0.0.10 workspace-mode, and 0.0.9 coding/browser benchmark evidence, security scan/live-canary backstops, live subscriber queues, branch-read pagination expectations, JSONL/dev-store limits, and production sizing assumptions.
22
+ - [Performance limits](performance.md): bounded evaluation traces/judges/reports, 0.0.12 frontend interoperability benchmark evidence/caps, 0.0.11 search/budget, 0.0.10 workspace-mode, and 0.0.9 coding/browser benchmark evidence, security scan/live-canary backstops, live subscriber queues, branch-read pagination expectations, JSONL/dev-store limits, and production sizing assumptions.
18
23
  - [Structured output](structured-output.md): the `Artifact*` seam plus provider-native `StructuredOutputOptions` / `structuredOutputMode` for capable models.
19
24
 
20
25
  ## Compaction/session memory
21
26
  - [Compaction and retry policies](compaction-and-retry.md): summarize branch history and retry transient provider failures with host-replaceable policies.
22
- - [LLM compaction package](compaction-llm.md): optional provider-backed strategy with finite summary/reserve/error caps, bounded redacted streaming retention, and mandatory finite post-policy `model.parameters.maxTokens`.
27
+ - [LLM compaction package](compaction-llm.md): optional provider-backed strategy with finite summary/reserve/error caps, bounded redacted streaming retention, mandatory finite post-policy `model.parameters.maxTokens`, and `createCodingCompactionStrategy()` for coding handoff focus.
23
28
  - [Observational memory compaction package](compaction-observational-memory.md): optional source-backed memory with owned append callback, finite turn/call/argument/result/transcript/error worker limits, redacted provider-valid transcripts, fast compaction, recall, and status/view commands; worker model falls back to host-supplied `sessionModel`.
24
29
  - [Working and semantic memory](working-and-semantic-memory.md): optional `@arnilo/prism-memory` working-memory store, semantic recall, finite Embedder/VectorStore contracts, in-memory adapters, and PostgreSQL/pgvector path.
25
30
  - [Session stores](session-stores.md): `SessionStore` contract, `SessionAppendOptions`, `SessionAppendConflictError`, branch handles, `readBranchPath`, optional bounded `searchSessions` / `SessionIndex` (memory linear|unsupported), and dev-vs-production branch reads — start here for session persistence.
26
31
  - [Session stores and branching](session-stores-and-branching.md): detailed branch semantics and helper reference (kept for compatibility; links back to the canonical atomic append / branch-handle sections).
27
- - [Database persistence](database-persistence.md): production persistence contracts, shared checksummed migration/full-shape catalog primitives (`@arnilo/prism/testing/persistence-schema`), conditional append, indexes, `readBranchPath`, reference relational schema, retention, and NoSQL mapping.
32
+ - [Database persistence](database-persistence.md): production persistence contracts, shared checksummed migration/full-shape catalog primitives (`@arnilo/prism/testing/persistence-schema`), conditional append, indexes, `readBranchPath`, reference relational schema, retention/legal-hold/quota lifecycle (`lifecycle`), and NoSQL mapping.
28
33
  - [SQLite persistence](sqlite-persistence.md): optional `better-sqlite3` adapter with session/run storage, checkpoints/leases, feedback, FTS `searchSessions` (migration-v4), and transactionally verified/backfilled migration metadata.
29
34
  - [PostgreSQL persistence](postgres-persistence.md): optional pooled `pg` adapter with session/run/checkpoint/lease/feedback storage, FTS `searchSessions` (migration-v4), advisory-locked checksummed/full-shape migrations, and opt-in live conformance.
30
- - [Migration guide](migration.md): 0.0.3 compatibility through **0.0.11** coding-harness fundamentals (SessionIndex, contextBudget, Anthropic/Google providers, steer, ask_user_decision, goal→verify), 0.0.10 workspace modes, and 0.0.9 coding/browser surfaces.
35
+ - [Migration guide](migration.md): **0.0.13** enterprise identity/policy/router/work connectors, cloud providers, server deployment seams, persistence schema v5, and explicit **0.0.14+** deferrals; plus 0.0.12 AG-UI/ACP, 0.0.11 coding-harness fundamentals, 0.0.10 workspace modes, and 0.0.9 coding/browser surfaces.
31
36
  - [Node JSONL session store](node-jsonl-session-store.md): development-only JSONL file adapter for single-process Node hosts; no cross-process safety; `searchSessions` throws `SessionSearchUnsupportedError`.
32
37
  - [Persistence, credentials, and multimodality primitives](persistence-credentials-multimodality-primitives.md): Plan 056 inventory — session/run-ledger/persistence contracts, credential/OAuth seams, content/resource/model capabilities, package dependency matrix, conformance matrix, and threat model for production adapters.
33
38
 
@@ -39,10 +44,11 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
39
44
  - [Thinking and reasoning](thinking-and-reasoning.md): portable `ThinkingLevel` helpers (`applyThinkingLevel` / `thinkingCompatFor`) map per-turn effort into provider `compat` fields; model defaults stay on `ModelConfig.compat`; no second options tree.
40
45
  - [Use-case model selection](use-case-model-selection.md): bind `{ model?, provider?, thinkingLevel? }` for observational memory, LLM compaction, and other non-session LLM jobs with explicit session-model fallback via `resolveUseCaseModel`.
41
46
  - [Provider request policies](provider-request-policies.md): chain `ProviderRequestPolicy` hooks, use `createSessionCachePolicy`, and merge legacy/structured cache options safely.
42
- - [Provider packages](provider-packages.md): define explicit provider packages, model metadata, auth descriptors, request/cache policies, and provider-owned header precedence without package discovery or provider-specific core behavior; includes a first-party cache behavior summary and the **caller-gated on-demand model discovery** contract (`list*Models`, setup zero-fetch).
43
- - Phase 12 package workspaces: [`@arnilo/prism-provider-openai`](providers/openai.md), [`@arnilo/prism-provider-anthropic`](providers/anthropic.md) (native Messages, `cache_control`, thinking, caller-gated `listAnthropicModels`), [`@arnilo/prism-provider-google`](providers/google.md) (native Gemini `generateContent` SSE, caller-gated `listGoogleModels`; Vertex deferred), [`@arnilo/prism-provider-opencode-go`](providers/opencode-go.md) (official Go open models, dual-route Anthropic/OpenAI, caller-gated `listOpenCodeGoModels`, `reasoning_content`/thinking preserve), [`@arnilo/prism-provider-openrouter`](providers/openrouter.md) (app-controlled catalog, caller-gated `listOpenRouterModels`, `reasoning` merge/preserve, `cache_control` + sticky `session_id`), [`@arnilo/prism-provider-zai`](providers/zai.md) (official `thinking`/`reasoning_effort`/`tool_stream`, implicit cache, caller-gated `listZaiModels`), [`@arnilo/prism-provider-kimi`](providers/kimi.md), and [`@arnilo/prism-provider-neuralwatt`](providers/neuralwatt.md) with implicit vLLM prefix caching, reasoning controls (`reasoning_effort`/`thinking_token_budget`/`enable_thinking`/`preserve_thinking`/`clear_thinking`), reasoning preservation, OpenAI-style tool-call loop, quota, telemetry, and retry classification helpers.
47
+ - [Provider packages](provider-packages.md): define explicit provider packages, model metadata, auth descriptors, request/cache policies, provider-owned header precedence, and the 0.0.12 provider-authorized OAuth matrix without package discovery or provider-specific core behavior; includes a first-party cache behavior summary and the **caller-gated on-demand model discovery** contract (`list*Models`, setup zero-fetch).
48
+ - Phase 12 package workspaces: [`@arnilo/prism-provider-openai`](providers/openai.md), [`@arnilo/prism-provider-anthropic`](providers/anthropic.md) (native Messages, `cache_control`, thinking, caller-gated `listAnthropicModels`), [`@arnilo/prism-provider-google`](providers/google.md) (native Gemini `generateContent` SSE, caller-gated `listGoogleModels`), [`@arnilo/prism-provider-opencode-go`](providers/opencode-go.md) (official Go open models, dual-route Anthropic/OpenAI, caller-gated `listOpenCodeGoModels`, `reasoning_content`/thinking preserve), [`@arnilo/prism-provider-openrouter`](providers/openrouter.md) (app-controlled catalog, caller-gated `listOpenRouterModels`, `reasoning` merge/preserve, `cache_control` + sticky `session_id`), [`@arnilo/prism-provider-zai`](providers/zai.md) (official `thinking`/`reasoning_effort`/`tool_stream`, implicit cache, caller-gated `listZaiModels`), [`@arnilo/prism-provider-kimi`](providers/kimi.md), and [`@arnilo/prism-provider-neuralwatt`](providers/neuralwatt.md) with implicit vLLM prefix caching, reasoning controls (`reasoning_effort`/`thinking_token_budget`/`enable_thinking`/`preserve_thinking`/`clear_thinking`), reasoning preservation, OpenAI-style tool-call loop, quota, telemetry, and retry classification helpers.
49
+ - Phase 8 enterprise cloud (workload identity; separate from consumer Anthropic/Google): [`@arnilo/prism-provider-azure`](providers/azure.md) (Entra / Foundry), [`@arnilo/prism-provider-bedrock`](providers/bedrock.md) (IAM/IRSA + region/PrivateLink), [`@arnilo/prism-provider-vertex`](providers/vertex.md) (ADC / Vertex OpenAPI).
44
50
  - Optional AI SDK adapter: [`@arnilo/prism-provider-ai-sdk`](providers/ai-sdk.md) maps host-owned `LanguageModelV4` models onto Prism `AIProvider` streams (specification v4; no Prism catalog; maps `finish.usage` cache read/write tokens; reasoning is host-model-owned).
45
- - [OpenAI-compatible provider](providers/openai-compatible.md): optional provider subpath using native or injected `fetch` for Chat Completions streaming.
51
+ - [OpenAI-compatible provider](providers/openai-compatible.md): optional provider subpath using native or injected `fetch` for Chat Completions streaming (`chatCompletionsUrl` / `authStyle` overrides for enterprise adapters).
46
52
 
47
53
  ## Input, prompt, and context assembly
48
54
  - [SDK customization guide](customization.md): map provider resolution, middleware, context, builders, injectors, loops, compaction, retry, stores, and skills to explicit host-wired APIs.
@@ -59,6 +65,8 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
59
65
  - [Tool validator JSON Schema package](../packages/tool-validator-json-schema/README.md): optional `@arnilo/prism-tool-validator-json-schema` adapter for `tool.parameters`.
60
66
  - [MCP client bridge and server exposure](mcp-tools.md): SDK-1.29.0 bounded tools/resources/prompts, host-owned roots/sampling/elicitation, exact-origin DNS-pinned client transport, and principal-bound opt-in Streamable HTTP sessions.
61
67
  - [Web search, fetch, and extraction](web-tools.md): optional host-selected Brave/Exa discovery and Firecrawl Markdown/schema tools with native fetch, stable citations, late credentials, finite limits, and explicit untrusted-content boundaries.
68
+ - [Work tools](work-tools.md): optional `@arnilo/prism-work-tools` identity-scoped M365 + GWS connectors (hard-coded CLI argv, draft-then-approve, idempotency, shared result shapes).
69
+ - [Work connectors](work-connectors.md): connector principles, capability gates, and out-of-scope boundaries for Microsoft 365 / Google Workspace.
62
70
  - [Browser automation](browser-automation.md): optional `@arnilo/prism-browser` with host-supplied Playwright contexts, AI-mode snapshots/refs, ordered `browser_open`/`browser_snapshot`/`browser_act`/`browser_close`, egress/side-effect/upload/download/screenshot policy, and finite page/action/snapshot/network/artifact caps.
63
71
  - [Coding agent tools](coding-agent-tools.md): optional `shell`, `read`, `write`, `edit`, `repo_list`, and `repo_search` definitions plus opt-in `createGitTools()` / `coding_check`, opt-in `createAskUserDecisionTool` (single/multi/free-text + durable suspend glue), and `runCodingGoalVerify`; durable plan/todo Markdown helpers with workflow `state.coding` checkpoint metadata; streamed text pages, bounded repository list/search, finite Git/check/plan/ask caps, bounded image/edit reads and write/edit payloads, finite shell wall/total-output limits, secure host-owned spill cleanup, pluggable bounded operation contracts, per-path mutation serialization, and optional `ExecutionPolicy`. Limits do not sandbox host access—gate with permission/trust policy and `@arnilo/prism-coding-security`.
64
72
  - [Coding execution approval and sandboxing](coding-security.md): path/command approval, identity-scoped caching, shell-turn exclusivity, required `workspaceMode` (`host`/`sandbox`) with fail-closed mixed wiring, `createSandboxCodingComposition()` containment metadata, and the disposable Docker/OCI sandbox reference with bounded workspace import/export.
@@ -76,11 +84,12 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
76
84
  - [Resource loading](resource-loading.md): decode text, JSON, binary, and manifest resources through caller-provided loaders with bounded byte limits.
77
85
 
78
86
  ## Server/API
79
- - [Web-standard server handler](server.md): optional framework-free authorized direct/SSE agent, explicitly selected durable agent lifecycle, and durable workflow routes with explicit bounds and zero default exposure.
87
+ - [Web-standard server handler](server.md): optional framework-free authorized direct/SSE agent, durable agent lifecycle, durable workflow routes, plus optional health/drain/rate-limit/replay/deployment-lease seams; explicit bounds and zero default exposure.
80
88
 
81
89
  ## Multi-agent and interoperability
82
90
  - [Supervisor delegation](supervisors.md): optional explicit child allow-list, derived memory scopes, narrowing-only permissions, lifecycle hooks, nested delegation, cancellation, finite budgets, host-projected delegation telemetry, and separate A2A durable adapter boundary.
83
91
  - [A2A interoperability](a2a.md): A2A 1.0 JSON-RPC/HTTPS cards plus host-owned durable task get/list/cancel/subscribe, bounded rich parts/replay, principal-scoped push configs, and exact-origin verified client.
92
+ - [Frontend interoperability (AG-UI and ACP)](ag-ui.md): optional `@arnilo/prism-ag-ui` AG-UI mapper/authorized Web handler/replay and stable ACP sibling over shared redacted event and durable-approval seams; no TUI, editor, filesystem, or A2A runtime.
84
93
 
85
94
  ## CLI/RPC
86
95
  - [CLI/RPC](cli-rpc.md): Run print/json modes and LF-delimited RPC over the public AgentSession runtime, including mid-run `steer`, branch-handle results, fixed `forkSession`, and `checkout`. `prism init` scaffolds a tiny TypeScript project with one selected provider and an offline mock test.
@@ -89,10 +98,10 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
89
98
  - [Workflow/TUI scope](workflow-tui-primitives.md): records why 0.0.5 ships workflow APIs/RPC control but no interactive terminal UI.
90
99
 
91
100
  ## Security and credentials
92
- - [Host security guide](host-security.md): fail-closed checklist for supply-chain/attestation/canary isolation, bounded credentials, JSON/schema/vector/crypto, MCP/A2A/web remote boundaries, untrusted external content, settings, redaction, trust roots, workflow ownership, coding I/O, permissions, persistence, extensions, and tool validation.
101
+ - [Host security guide](host-security.md): fail-closed checklist for supply-chain/attestation/canary isolation, bounded credentials, AG-UI/ACP/A2A/web remote boundaries, untrusted external content, settings, redaction, trust roots, workflow ownership, coding I/O, permissions, persistence, extensions, and tool validation.
93
102
  - [Security/auth/trust](settings-auth-trust-security.md): settings providers, credential helpers, trust/permission policies, redaction controls, host-owned settings/credentials wiring outside `AgentConfig`, and security-boundary hardening summary.
94
- - [Credentials and redaction](credentials-and-redaction.md): compose explicit credential resolver order, use caller-supplied env objects/OAuth refresh helpers, resolve credentials only at the provider edge, and redact known secret values.
95
- - [Credential storage](credential-storage.md): optional `@arnilo/prism-credentials-node` adapter with strict bounded AES-GCM envelopes, async finite scrypt, restrictive Unix files, and abort-aware bounded system-keychain calls.
103
+ - [Credentials and redaction](credentials-and-redaction.md): compose explicit credential resolver order, use caller-supplied env objects/OAuth refresh helpers, resolve credentials only at the provider edge, redact known secret values, and follow the provider-authorized subscription OAuth matrix.
104
+ - [Credential storage](credential-storage.md): optional `@arnilo/prism-credentials-node` adapter with strict bounded AES-GCM envelopes, async finite scrypt, restrictive Unix files, abort-aware bounded system-keychain calls, and optional host-KMS wrap (`encryptWithHostKms`).
96
105
 
97
106
  ## Testing and examples
98
107
  - Provider test doubles: `createMockProvider()` and provider event helpers are documented on the canonical Provider layer page above.
@@ -102,10 +111,12 @@ Prism is a TypeScript/Node.js agent harness. Host apps and extension packages ow
102
111
  - [Compaction conformance](compaction-conformance.md): assert any `CompactionStrategy` returns a non-empty redacted summary and observes abort from `@arnilo/prism/testing/compaction-conformance`.
103
112
  - [Tool conformance](tool-conformance.md): assert the tool-dispatch blocked-reason matrix (unknown/denied/invalid/permission/validator) and success path from `@arnilo/prism/testing/tool-conformance`.
104
113
  - [Extension conformance](extension-conformance.md): assert an `Extension` setup runs, contributions stay inert, and setup errors are redacted or rethrown from `@arnilo/prism/testing/extension-conformance`.
105
- - `examples/`: compile-checked typed examples and runnable mock demos (SDK basics, provider registration, auth, tools, cache-aware prompt assembly, NeuralWatt agent run, stores/branching, compaction, observational-memory recall, structured-output/artifact-loop, CLI, RPC, workflow orchestration).
114
+ - `examples/`: compile-checked typed examples and runnable mock demos (SDK basics, provider registration, auth, tools, [`examples/ag-ui-server.ts`](../examples/ag-ui-server.ts), [`examples/enterprise-identity.ts`](../examples/enterprise-identity.ts), [`examples/enterprise-policy-audit.ts`](../examples/enterprise-policy-audit.ts), [`examples/enterprise-work-connectors.ts`](../examples/enterprise-work-connectors.ts), [`examples/server-deployment-seams.ts`](../examples/server-deployment-seams.ts), cache-aware prompt assembly, NeuralWatt agent run ([`examples/neuralwatt-agent-run.ts`](../examples/neuralwatt-agent-run.ts)), [`examples/coding-compaction.ts`](../examples/coding-compaction.ts), stores/branching, structured-output/artifact-loop, CLI, RPC, workflow orchestration).
106
115
 
107
116
  ## Release and install
108
- - [Release and install](release-and-install.md): 32-package graph (including optional browser), install/tarball rules, pinned CodeQL/dependency/SBOM/license/secret/attestation gates, deterministic resumable publication, offline tests, protected live canaries, and sandbox-browser Docker/Playwright gates.
117
+ - [Release and install](release-and-install.md): current **41**-package graph (Phase 8 optional policy/router/enterprise providers/work-tools ship at 0.0.13; profile enrollment Task 10), install/tarball rules, pinned CodeQL/dependency/SBOM/license/secret/attestation gates, deterministic resumable publication, offline tests, protected live canaries, and sandbox-browser Docker/Playwright gates.
118
+ - [Review coverage (2026-07-23 Phase 8)](review-coverage-2026-07-23-phase-8.md): Plan 076 evidence freeze — enterprise identity/policy/router packages, Azure/Bedrock/Vertex adapters, server deployment seams, persistence lifecycle hooks, and M365/GWS work-connector bounds for 0.0.13.
119
+ - [Review coverage (2026-07-22 Phase 7)](review-coverage-2026-07-22-phase-7.md): Plan 075 evidence freeze — AG-UI/ACP package boundary, streamed durable resume, bounded replay/projection, coding compaction preset, and provider-authorized OAuth policy for 0.0.12.
109
120
  - [Review coverage (2026-07-22 Phase 6)](review-coverage-2026-07-22-phase-6.md): Plan 074 evidence freeze — SessionIndex/search, contextBudget, native Anthropic/Google packages, goal→verify, steer, ask_user_decision (multi/free-text/suspend), finite limits, threats, and 0.0.11 release gates.
110
121
  - [Review coverage (2026-07-21 Phase 5)](review-coverage-2026-07-21-phase-5.md): Plan 073 evidence freeze — unified workspace modes, primitive ownership, reused finite limits, threats, and 0.0.10 release gates.
111
122
  - [Review coverage (2026-07-20 Phase 4)](review-coverage-2026-07-20-phase-4.md): Plan 072 evidence freeze — revised coding/browser-only scope, external revisions, primitive ownership, finite limits, threats, and 0.0.9 release gates.
package/docs/mcp-tools.md CHANGED
@@ -198,6 +198,7 @@ Web handler defaults: 1 MiB request (8 MiB hard), 2 MiB response (16 MiB hard),
198
198
  | Oversized/deep/wide server output | One aggregate byte/depth/property walk covers content, structured content, compatibility `toolResult`, and bounded remote errors before `ToolResult` |
199
199
  | Unvalidated arguments | Register tools with `createJsonSchemaToolArgumentValidator()` at dispatch |
200
200
  | Missing permission gate | Client direction: `PermissionPolicy` on `tool:mcp:<serverId>:<name>:execute`; server direction: required MCP `authorize` plus optional core `PermissionPolicy` |
201
+ | Unverified / widened identity | Optional `PrismMcpAuthorization.identity` must be host-verified and match ownership; invalid identity is forbidden before tool dispatch |
201
202
  | Accidental server exposure | Empty default arrays/maps, duplicate-name rejection, explicit tools/commands/lifecycle only |
202
203
  | Agent lifecycle data leak or cross-tenant resume | `agentRuns` requires exact tenant plus account/user ownership; core lifecycle returns public redacted state only and CAS-resumes with current agent/revision |
203
204
  | Unbounded MCP HTTP | Bounded pre-parsed JSON, response bytes, concurrent requests, call timeout, SDK web-standard transport |
@@ -216,6 +217,7 @@ Official Exa/Firecrawl MCP servers may be tested only as explicit hardened proto
216
217
 
217
218
  ## Related APIs
218
219
 
220
+ - [Agent identity](agent-identity.md): optional verified identity on MCP authorize results
219
221
  - [Tools](tools.md): registry, dispatch, validation
220
222
  - [Web search, fetch, and extraction](web-tools.md): preferred direct bounded Brave/Exa/Firecrawl production path
221
223
  - [Tool execution primitives](tool-execution-primitives.md): Plan 055 design and conformance matrix
package/docs/migration.md CHANGED
@@ -7,6 +7,49 @@ Prism 0.0.6 preserves documented 0.0.3 agent construction except for two intenti
7
7
  1. **`session.run()` / `session.prompt()` return `AgentRunResult`** and `session.stream()` starts one owned run after subscribing. Callers that ignored the previous `Promise<void>` keep working; failed/aborted runs reject with `AgentRunError` (`.result` attached).
8
8
  2. **`AgentConfig.extensions` / `settings` / `credentials` are removed.** Wire extensions through `createExtensionKernel()`, read settings in the host, and pass credential resolvers to the provider edge.
9
9
 
10
+ ## 0.0.12 → 0.0.13 enterprise identity, policy, routing, and work connectors (additive, pre-release)
11
+
12
+ Release **0.0.13** adds host-verified `Principal` / `AgentIdentity` on runs, tools, server/MCP/A2A/workflow seams. Hosts must supply an `IdentityVerifier` (`verify()` → `AgentIdentity` with `verified: true`); caller-asserted identity without host verification fails closed. See [Agent identity](agent-identity.md).
13
+
14
+ Optional `@arnilo/prism-policy` records allow/deny/modify/approval decisions with evidence refs only (no prompt/body/secret keys). Optional `@arnilo/prism-model-router` wraps `ProviderResolver` with allow-list, residency, token/cost budgets, rate limits, circuit breaking, and bounded fallbacks (`allowOpenRouterRouting` default false). See [Policy and audit](policy-and-audit.md) and [Model routing](model-routing.md).
15
+
16
+ | Surface | Before (0.0.12) | After (0.0.13) |
17
+ | --- | --- | --- |
18
+ | Run/tool identity | Ownership strings only | Optional verified `AgentIdentity`; `narrowIdentity` / propagation guards on delegation |
19
+ | Policy audit | Host-only logs | Optional append-only ledger + cursor export via `@arnilo/prism-policy` |
20
+ | Model governance | Host wraps resolver ad hoc | Optional `@arnilo/prism-model-router` before provider I/O |
21
+ | Work connectors | n/a | Optional `@arnilo/prism-work-tools` M365 + GWS; draft-then-approve; hard-coded CLI argv |
22
+
23
+ **Deferred to 0.0.14+:** conversation storage/service, Studio/control plane, internal auth DB, Redis/SQS queue adapters, local Office binaries. See [Phase 8 evidence](review-coverage-2026-07-23-phase-8.md).
24
+
25
+ Benchmark placeholder: `node scripts/benchmark-0.0.13.mjs` (release Task 10). Caps documented in [Performance limits](performance.md).
26
+
27
+ ## 0.0.12 → 0.0.13 enterprise cloud providers (additive, pre-release)
28
+
29
+ Release **0.0.13** adds optional `@arnilo/prism-provider-azure`, `@arnilo/prism-provider-bedrock`, and `@arnilo/prism-provider-vertex` for workload-identity enterprise endpoints. Consumer `@arnilo/prism-provider-anthropic` / `@arnilo/prism-provider-google` stay unchanged (API-key). Install enterprise packages explicitly; pass host Entra/IAM/ADC credential callbacks; preserve region/private-endpoint URLs. No database migration.
30
+
31
+ Release **0.0.13** also extends `@arnilo/prism-server` with optional `createPrismHealthHandler`, `createPrismDrainController`, handler `rateLimit` / `drain` options, `createPrismEventReplay`, and `createPrismDeploymentLease`. Existing routes stay compatible. Queue adapters remain absent (Postgres coordinator polling stays default).
32
+
33
+ Persistence schema **v5** adds `005_lifecycle_hold_quota` (`prism_legal_holds`, `prism_tenant_quotas`) plus `ProductionPersistenceStore.lifecycle` / `createMemoryPersistenceLifecycle`. Extension kernels accept optional `loadPolicy` allow-list/signature checks. Credentials-node adds optional `encryptWithHostKms` / `decryptWithHostKms`.
34
+
35
+ Optional `@arnilo/prism-work-tools` (+ `./microsoft365`, `./google-workspace`) adds identity-scoped Outlook/Gmail/calendar/file/task tools over host-pinned `@pnp/cli-microsoft365` and `@googleworkspace/cli` with hard-coded argv templates, draft-then-approve mutations, package-local `IdempotencyStore`, and shared result normalizers.
36
+
37
+ ## 0.0.11 → 0.0.12 coding harness interoperability (additive, pre-release)
38
+
39
+ Release **0.0.12** adds optional `@arnilo/prism-ag-ui` (root AG-UI and stable `./acp` sibling), generic `resumeAgentRunStream()` / `AgentRunLifecycle.resumeStream()`, and `createCodingCompactionStrategy()` from `@arnilo/prism-compaction-llm`. It adds no core UI dependency, session/database migration, listener, tool, editor/filesystem bridge, conversation/artifact service, worker, or background reconnect loop.
40
+
41
+ | Surface | Before (0.0.11) | After (0.0.12) |
42
+ | --- | --- | --- |
43
+ | Durable approval stream | `resumeAgentRun()` returns final result | `resumeAgentRunStream()` and lifecycle `resumeStream()` subscribe before resume and emit selected redacted run events; existing direct resume remains compatible. |
44
+ | Browser/TUI protocol | Host maps events itself | Install optional `@arnilo/prism-ag-ui`; `createAgUiHandler()` is host-authorized Web Request → SSE, while `@arnilo/prism-ag-ui/acp` is stable ACP v1 text/tool/usage/permission glue. |
45
+ | Reconnect | Host-specific ledger query | `createPersistenceAgUiReplay()` adapts ownership-scoped redacted `queryEvents` pages. Replay is at-least-once; client de-duplicates stable event/message/tool IDs and terminal replay never reruns work. |
46
+ | Coding compaction | Generic LLM strategy | `createCodingCompactionStrategy()` keeps existing caps/history semantics while prioritizing paths, patch intent, checks, plan/todos, blockers, and next verification. |
47
+ | Subscription OAuth | Existing Codex OAuth | OpenAI Codex remains the only first-party subscription OAuth flow. Anthropic and Google packages stay API-key-only; do not import/reroute Claude Code or Gemini CLI credentials. |
48
+
49
+ **Host actions:** install the optional package only when a frontend protocol is needed; keep authorization, session/thread/run mapping, durable correlation, storage, redaction, and projection in the host. Reject frontend tools and state unless an explicit host policy accepts them. For a durable approval, persist protocol-run correlation before exposing the exact `${runId}:${version}` interrupt, then resume through the lifecycle with current ownership/version. Configure a redacted `ProductionPersistenceStore` before enabling replay. Use `createCodingCompactionStrategy()` only when the host already supplies a summary provider/model.
50
+
51
+ AG-UI defaults/hard caps: request 64 KiB/1 MiB; projected event 64 KiB/1 MiB; replay page 100/500; subscriber queue 128/4096; stream 10k/100k events and 10/64 MiB; wall time 120 seconds/30 minutes. Benchmark results remain a release-gate placeholder: `node scripts/benchmark-0.0.12.mjs` lands in Task 8. See [Frontend interoperability](ag-ui.md), [LLM compaction package](compaction-llm.md), and [Phase 7 evidence](review-coverage-2026-07-22-phase-7.md).
52
+
10
53
  ## 0.0.10 → 0.0.11 coding harness fundamentals (additive)
11
54
 
12
55
  Release **0.0.11** adds SessionIndex/search, assembler `contextBudget`, native Anthropic + Google provider packages, mid-run `steer`, coding-agent goal→verify + `ask_user_decision` (multi/free-text/suspend glue). Package count: **32 → 34** (adds `@arnilo/prism-provider-anthropic`, `@arnilo/prism-provider-google`). Version bump itself is Task 13 / release gate — treat this section as the behavioral migration map.
@@ -0,0 +1,102 @@
1
+ # Model routing
2
+
3
+ ## What it does
4
+
5
+ `@arnilo/prism-model-router` is an optional governance facade over an existing `ProviderResolver`. It enforces allow-lists, residency, token/cost budgets, rate limits, circuit breaking, and bounded fallbacks before provider selection, and emits redacted selection diagnostics. It does not implement a second provider runtime.
6
+
7
+ ## When to use it
8
+
9
+ Use it for enterprise hosts that must deny models/regions before any provider call and attribute selection for audit. Skip it when a plain `createProviderResolver` allow-list is enough.
10
+
11
+ Do not put secrets, prompts, or raw OpenRouter keys into diagnostics. Do not honor `compat.openRouterRouting` unless `allowOpenRouterRouting: true`.
12
+
13
+ ## Inputs / request
14
+
15
+ | API / field | Meaning |
16
+ | --- | --- |
17
+ | `createModelRouter({ resolver, ... })` | Wraps host `ProviderResolver` |
18
+ | `allowList.providers` / `allowList.models` | Exact provider id / model id or `provider/model` |
19
+ | `allowedResidencies` | Request residency must match when configured |
20
+ | `budgets` / per-call `maxTokens` / `maxCostUsd` | Finite non-negative ceilings; `recordUsage` charges |
21
+ | `rateLimit` | Per identity+model key window |
22
+ | `circuit` | Failure threshold + cooldown; keys capped |
23
+ | `fallbacks` | Ordered candidates after primary; total attempts capped |
24
+ | `allowOpenRouterRouting` | Default `false`; when false, routing metadata is stripped |
25
+ | `onDiagnostics` | Optional redacted hook (e.g. policy ledger evidence ref) |
26
+ | `router.resolve({ model, identity?, residency?, ... })` | Rich async selection |
27
+ | `router.providerSource` | Sync `ProviderResolver` facade for `AgentConfig` |
28
+
29
+ Frozen caps (default / hard): attempts `3 / 8`, circuit keys `1,024 / 16,384`, diagnostics `8 KiB / 64 KiB`.
30
+
31
+ ## Outputs / response / events
32
+
33
+ - `ModelRouterResolveResult` — selected `provider` + possibly stripped `model`, `diagnostics`, and `providerRequestPolicy`.
34
+ - Deny throws `ModelRouterError` with code + redacted `diagnostics` (allow-list/residency/budget fail closed without calling resolver).
35
+ - `recordOutcome({ success })` opens/closes circuits; `recordUsage` advances budgets.
36
+
37
+ ## Request/response example
38
+
39
+ ```json
40
+ {
41
+ "outcome": "allow",
42
+ "selectedProvider": "openrouter",
43
+ "selectedModel": "auto",
44
+ "attempts": [
45
+ { "provider": "openai", "model": "gpt-4o", "outcome": "circuit_open", "reason": "circuit_open" },
46
+ { "provider": "openrouter", "model": "auto", "outcome": "selected" }
47
+ ],
48
+ "identityRefs": { "tenantId": "t1", "principalId": "a1", "principalKind": "agent" },
49
+ "openRouterRoutingHonored": false,
50
+ "residency": "eu"
51
+ }
52
+ ```
53
+
54
+ ## Implementation example
55
+
56
+ ```ts
57
+ import { createAgent, createProviderResolver } from "@arnilo/prism";
58
+ import { createModelRouter } from "@arnilo/prism-model-router";
59
+
60
+ const router = createModelRouter({
61
+ resolver: createProviderResolver(providers),
62
+ allowList: { providers: ["openai", "openrouter"] },
63
+ allowedResidencies: ["eu"],
64
+ fallbacks: [{ provider: "openrouter", model: "auto" }],
65
+ allowOpenRouterRouting: false,
66
+ });
67
+
68
+ const { provider, model, providerRequestPolicy } = await router.resolve({
69
+ model: sessionModel,
70
+ identity,
71
+ residency: "eu",
72
+ maxCostUsd: 0.25,
73
+ });
74
+
75
+ const agent = createAgent({
76
+ model,
77
+ provider,
78
+ providerRequestPolicies: [providerRequestPolicy],
79
+ });
80
+ // or: providerSource: router.providerSource
81
+ ```
82
+
83
+ ## Extension and configuration notes
84
+
85
+ Router is optional. Chain returned `providerRequestPolicy` with other `ProviderRequestPolicy` values. Wire `onDiagnostics` to `@arnilo/prism-policy` when audit export is required. OpenRouter package behavior is unchanged; routing metadata participates only when this gate allows it.
86
+
87
+ ## Security and performance notes
88
+
89
+ - Allow-list and residency denies never call the underlying resolver.
90
+ - Budget/rate/circuit state is memory-capped; oldest keys evict.
91
+ - Diagnostics carry identity refs and attempt outcomes only — no prompts/secrets.
92
+ - Selection is O(attempts × map ops); no network I/O inside the router.
93
+ - Raising hard caps requires Phase 8 freeze + tests + docs updates.
94
+
95
+ ## Related APIs
96
+
97
+ - [Provider layer](provider-layer.md)
98
+ - [Provider request policies](provider-request-policies.md)
99
+ - [OpenRouter](providers/openrouter.md)
100
+ - [Policy and audit](policy-and-audit.md)
101
+ - [Agent identity](agent-identity.md)
102
+ - Package README: [`@arnilo/prism-model-router`](../packages/model-router/README.md)
@@ -167,12 +167,14 @@ console.log(traceId, memory.spans.map((span) => span.name));
167
167
  ## Security and performance notes
168
168
 
169
169
  - Default events are metadata-only — no prompts, streamed deltas, tool arguments, or credentials.
170
+ - Use `identityTelemetryAttributes(identity)` when attaching enterprise identity to run metadata or OTel attributes; it emits `prism.identity.*` refs only (tenant/principal/scope counts), never credential secrets or raw tokens.
170
171
  - Opt-in content in other event types (`message_delta`, tool `result`) is still subject to `redactAgentEvent`.
171
172
  - Metric labels stay low-cardinality (`gen_ai.operation.name`, `gen_ai.provider.name`, token type, controlled outcome/status, feedback rating bucket/link presence); never use session/run/request/call IDs, model output, comments, tag values, scorer/evaluation IDs, or arbitrary metadata as labels. Token usage is recorded once at provider operation scope.
172
173
  - Target overhead when enabled is under 5% excluding exporter I/O; disabled hooks allocate no spans.
173
174
  - Provider transport limits and redaction order are documented in [Provider primitives](provider-primitives.md).
174
175
 
175
176
  ## Related APIs
177
+ - [Agent identity](agent-identity.md): redacted identity attribute helper for telemetry.
176
178
  - [Evaluations](evaluations.md): optional scorers can link scores to run/session/trace IDs from agent events.
177
179
 
178
180
  - [Agent events](agent-events.md): full `AgentEvent` union and subscriber semantics.
@@ -6,6 +6,25 @@ Evaluation defaults are finite: 100 trace rows × 20 pages and 4 MiB aggregate t
6
6
 
7
7
  This page states Prism runtime limits that keep slow consumers and long sessions from becoming unbounded memory or latency problems.
8
8
 
9
+ ## Release 0.0.12 frontend interoperability caps and evidence
10
+
11
+ `@arnilo/prism-ag-ui` uses finite handler/projection limits, all defaults / hard: request 64 KiB / 1 MiB; input 128 / 1024 messages and 64 KiB / 1 MiB text; event 64 KiB / 1 MiB; error 8 KiB / 64 KiB; replay cursor 4 / 16 KiB; replay page 100 / 500; subscriber queue 128 / 4096; stream 10,000 / 100,000 events and 10 / 64 MiB; request wall time 120 seconds / 30 minutes. Tool arguments/results/progress, frontend tools, and mutable frontend state default to zero exposure; hosts may only add bounded safe projection.
12
+
13
+ Reconnect is one ownership-scoped redacted durable page plus an optional bounded live subscriber. It is at-least-once at a page boundary, never a polling loop or terminal-run rerun. ACP uses the same event/byte/queue caps. Coding compaction reuses LLM summary/reserve/error/file-operation bounds (16,384 / 131,072 summary and reserve tokens; 1 / 8 KiB summary errors) and makes no additional provider call.
14
+
15
+ Run `node scripts/benchmark-0.0.12.mjs`; `PRISM_BENCH_ITERATIONS` accepts 10–100,000 (default 100). Schema/bounds test: `node --test scripts/benchmark-0.0.12.test.mjs`. Default mode is network-free and reports mapper/handler/replay throughput and p50/p95, peak emitted queue rows, event bytes, heap, and coding-preparation overhead. Bounds and hostile-input fixtures—not these host-local timings—are release gates.
16
+
17
+ 2026-07-22 baseline: Node v24.18.0, Linux x64, 100 iterations/scenario, network=false, credentials=false.
18
+
19
+ | Scenario | mode | ops/s | p95 ms | heap bytes | peak queue events | event bytes | cost USD | backpressure | resource limits |
20
+ | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
21
+ | AG-UI mapper | in-process | 23,561 | 0.0398 | 12,029,512 | 2 | 166 | 0 | 0 | 0 |
22
+ | AG-UI handler | web-in-process | 1,401 | 2.2651 | 19,545,416 | 5 | 508 | 0 | 0 | 0 |
23
+ | AG-UI replay | memory-page | 6,094 | 0.3047 | 19,098,240 | 2 | 243 | 0 | 0 | 0 |
24
+ | Coding compaction preparation | in-process | 75,515 | 0.0291 | 20,585,408 | 1 | 208 | 0 | 0 | 0 |
25
+
26
+ No network, credentials, provider summary call, durable database, or live subscriber is involved. These values are dated local comparison evidence, not portable thresholds.
27
+
9
28
  ## Release 0.0.11 session search / context budget / steer caps
10
29
 
11
30
  Finite caps (defaults / hard) — full matrix in [Phase 6 evidence](review-coverage-2026-07-22-phase-6.md):
@@ -436,6 +455,25 @@ Timings are one local Node v24.18.0 run over mock agents and an in-process fetch
436
455
 
437
456
  No performance ceiling was raised. Core grew from Phase 0's 346.0 kB packed baseline to ~403.7 kB after documented APIs/templates, while the full package set remains ~690.6 kB packed. Follow-up review includes all six Phase 4-13 capability packages through `prism-all` and AI SDK interoperability through `prism-providers`; focused base/code/SDK profiles remain unchanged and no capability auto-activates. Manifest tarballs remain tiny: providers 1.4 kB and all 1.6 kB packed.
438
457
 
458
+ ### 0.0.13 Phase 8 server deployment seams (2026-07-23)
459
+
460
+ Optional health/drain/rate-limit/replay/deployment-lease helpers on `@arnilo/prism-server`. No listener, queue adapter, or concurrency hard-cap raise.
461
+
462
+ | Surface | Result |
463
+ | --- | --- |
464
+ | Focused server suite | existing handler tests + 4 deployment seam tests pass |
465
+ | Health body | default 4 KiB / hard 64 KiB; detail requires authorize |
466
+ | Drain admit cutoff | default 30 s / hard 5 min; admits reject immediately on `beginDrain` |
467
+ | Replay page / cursor | 100 / 4 KiB default; 500 / 16 KiB hard |
468
+ | Concurrent runs | unchanged 16 / 256 |
469
+ | Queues | absent; use `createWorkflowCoordinator` polling until measured need |
470
+
471
+ ### 0.0.13 Phase 8 identity, policy, router, and work connectors (2026-07-24)
472
+
473
+ Enterprise governance and connector caps (defaults / hard). Timings: `node scripts/benchmark-0.0.13.mjs`; `PRISM_BENCH_ITERATIONS` accepts 10–100,000 (default 100). Schema/bounds test: `node --test scripts/benchmark-0.0.13.test.mjs`. Default mode is network-free and reports identity/policy/router/work-connector/deployment throughput and p50/p95 with frozen budget refs in the report JSON. Bounds and hostile-input fixtures—not these host-local timings—are release gates.
474
+
475
+ Offline behavior tests (identity propagation, policy export, router deny paths, fake CLI argv) are release gates; live tenant canaries remain operator-gated.
476
+
439
477
  ## Related APIs
440
478
 
441
479
  - [Agent events](agent-events.md): `SubscribeOptions` and `event_subscriber_overflow` event details.