@arnilo/prism 0.6.0 → 0.7.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 (129) hide show
  1. package/CHANGELOG.md +44 -5
  2. package/README.md +10 -10
  3. package/dist/agent-definitions.js +1 -0
  4. package/dist/agent-run-lifecycle.js +11 -0
  5. package/dist/agent-run-state.d.ts +6 -0
  6. package/dist/agent-run-state.js +29 -9
  7. package/dist/agent-session/session/assemble.js +33 -2
  8. package/dist/agent-session/session/persist.js +6 -2
  9. package/dist/agent-session/session/tool-round.js +1 -0
  10. package/dist/agent-session/session/types.d.ts +10 -0
  11. package/dist/agent-session/session.d.ts +14 -0
  12. package/dist/agent-session/session.js +40 -3
  13. package/dist/artifacts.d.ts +39 -1
  14. package/dist/artifacts.js +73 -0
  15. package/dist/attention-compiler.d.ts +121 -0
  16. package/dist/attention-compiler.js +479 -0
  17. package/dist/cli-init.js +20 -6
  18. package/dist/context-budget.d.ts +20 -1
  19. package/dist/context-budget.js +10 -1
  20. package/dist/contracts-core/agent.d.ts +7 -0
  21. package/dist/contracts-core/attention.d.ts +66 -0
  22. package/dist/contracts-core/attention.js +2 -0
  23. package/dist/contracts-core/compaction.d.ts +59 -0
  24. package/dist/contracts-core/compaction.js +77 -1
  25. package/dist/contracts-core/provider.d.ts +4 -0
  26. package/dist/contracts-core.d.ts +1 -0
  27. package/dist/contracts-core.js +1 -0
  28. package/dist/contracts-protocol.d.ts +29 -0
  29. package/dist/contracts-run-state.d.ts +6 -0
  30. package/dist/host-composition.d.ts +78 -0
  31. package/dist/host-composition.js +248 -0
  32. package/dist/index.d.ts +9 -6
  33. package/dist/index.js +5 -4
  34. package/dist/input.d.ts +13 -1
  35. package/dist/input.js +40 -1
  36. package/dist/secure-agent.d.ts +2 -0
  37. package/dist/secure-agent.js +6 -1
  38. package/dist/tool-result-fold.d.ts +12 -0
  39. package/dist/tool-result-fold.js +13 -6
  40. package/dist/tools.d.ts +10 -0
  41. package/dist/tools.js +41 -0
  42. package/docs/acp-agent.md +42 -11
  43. package/docs/acp.md +2 -1
  44. package/docs/ag-ui.md +5 -3
  45. package/docs/agent-definitions.md +9 -1
  46. package/docs/agent-events.md +4 -1
  47. package/docs/agent-session-runtime.md +6 -6
  48. package/docs/attention-compiler.md +272 -0
  49. package/docs/cli-rpc.md +4 -2
  50. package/docs/coding-agent-tools.md +1 -1
  51. package/docs/coding-security.md +5 -3
  52. package/docs/coding-tools.md +1 -1
  53. package/docs/coding-workspaces.md +22 -0
  54. package/docs/compaction-and-retry.md +36 -4
  55. package/docs/compaction-observational-memory.md +62 -9
  56. package/docs/context-and-skills.md +4 -2
  57. package/docs/conversations.md +1 -1
  58. package/docs/dev-inspector.md +4 -0
  59. package/docs/device-adapters.md +1 -0
  60. package/docs/document-reader.md +11 -3
  61. package/docs/documents.md +10 -2
  62. package/docs/enterprise-postgres-state.md +2 -2
  63. package/docs/evaluations.md +168 -4
  64. package/docs/execution-timeline.md +180 -0
  65. package/docs/history/0.7.0-primitive-review.md +254 -0
  66. package/docs/history/migration-0.0.md +2 -2
  67. package/docs/history/release-handoffs.md +37 -1
  68. package/docs/host-compositions.md +147 -0
  69. package/docs/hosted-sandboxes.md +94 -0
  70. package/docs/index.md +58 -39
  71. package/docs/input-and-prompt-assembly.md +1 -0
  72. package/docs/knowledge-sync.md +84 -0
  73. package/docs/language-intelligence.md +1 -1
  74. package/docs/live-testing.md +4 -1
  75. package/docs/mcp-tools.md +2 -1
  76. package/docs/memory-fabric.md +416 -0
  77. package/docs/migrate-to-0.5.md +1 -1
  78. package/docs/migrate-to-0.6.md +1 -0
  79. package/docs/migrate-to-0.7.md +345 -0
  80. package/docs/migration.md +13 -1
  81. package/docs/model-routing.md +79 -4
  82. package/docs/multi-agent-patterns.md +20 -6
  83. package/docs/observability.md +52 -1
  84. package/docs/operations.md +13 -1
  85. package/docs/options-index.md +13 -1
  86. package/docs/peer-dependencies.md +6 -4
  87. package/docs/process-sessions.md +3 -1
  88. package/docs/prompt-registry.md +1 -1
  89. package/docs/provider-caching.md +4 -2
  90. package/docs/provider-conformance.md +1 -1
  91. package/docs/provider-packages.md +22 -22
  92. package/docs/providers/bedrock.md +71 -7
  93. package/docs/providers/openai.md +1 -1
  94. package/docs/rag.md +24 -8
  95. package/docs/realtime-voice.md +87 -0
  96. package/docs/release-and-install.md +36 -34
  97. package/docs/runs-and-usage.md +3 -2
  98. package/docs/server.md +5 -3
  99. package/docs/speech.md +2 -0
  100. package/docs/supervisors.md +33 -5
  101. package/docs/testing.md +1 -1
  102. package/docs/thinking-and-reasoning.md +3 -1
  103. package/docs/tools.md +6 -5
  104. package/docs/web-tools.md +2 -1
  105. package/docs/work-artifacts-and-review.md +14 -4
  106. package/docs/work-connectors.md +3 -1
  107. package/docs/work-tools.md +14 -4
  108. package/docs/workflows.md +69 -1
  109. package/docs/working-and-semantic-memory.md +25 -14
  110. package/package.json +1 -1
  111. package/templates/README.md +2 -0
  112. package/templates/business-worker/README.md.tmpl +19 -0
  113. package/templates/business-worker/env.example.tmpl +1 -0
  114. package/templates/business-worker/gitignore.tmpl +11 -0
  115. package/templates/business-worker/manifest.json +11 -0
  116. package/templates/business-worker/package.json.tmpl +23 -0
  117. package/templates/business-worker/src/agent.ts.tmpl +92 -0
  118. package/templates/business-worker/src/index.ts.tmpl +13 -0
  119. package/templates/business-worker/src/tests/agent.test.ts.tmpl +77 -0
  120. package/templates/business-worker/tsconfig.json.tmpl +15 -0
  121. package/templates/personal-assistant/README.md.tmpl +18 -0
  122. package/templates/personal-assistant/env.example.tmpl +1 -0
  123. package/templates/personal-assistant/gitignore.tmpl +11 -0
  124. package/templates/personal-assistant/manifest.json +11 -0
  125. package/templates/personal-assistant/package.json.tmpl +23 -0
  126. package/templates/personal-assistant/src/agent.ts.tmpl +65 -0
  127. package/templates/personal-assistant/src/index.ts.tmpl +13 -0
  128. package/templates/personal-assistant/src/tests/agent.test.ts.tmpl +28 -0
  129. package/templates/personal-assistant/tsconfig.json.tmpl +15 -0
package/docs/web-tools.md CHANGED
@@ -67,7 +67,7 @@ Default/hard limits: query 4/16 KiB; results 10/20; URLs 5/20; request 256 KiB/1
67
67
 
68
68
  ## Security and performance notes
69
69
 
70
- Provider credentials never enter tool schemas/results, prompts, telemetry, URLs, or errors. Error text excludes remote bodies. Search snippets, Markdown, and extracted JSON are prompt-injection-capable data: never concatenate them into system instructions or use them to modify tools, permissions, credentials, trust, routing, or schemas. Firecrawl fetches target URLs remotely; Prism cannot claim target DNS pinning after handoff. Use controlled host fetch when that guarantee is required.
70
+ Provider credentials never enter tool schemas/results, prompts, telemetry, URLs, or errors. Error text excludes remote bodies. Search snippets, Markdown, and extracted JSON are prompt-injection-capable data: never concatenate them into system instructions or use them to modify tools, permissions, credentials, trust, routing, or schemas. `snapshotWebEvidence({ url, body, provider })` hashes an already-fetched body into the shared `ArtifactCitation` evidence shape; it does not refetch and does not store credentials. Firecrawl fetches target URLs remotely; Prism cannot claim target DNS pinning after handoff. Use controlled host fetch when that guarantee is required.
71
71
 
72
72
  Default tests use injected fake fetch and make no public request. Restricted smoke: `PRISM_LIVE_WEB=1 npm run test:live -w @arnilo/prism-web-tools` plus least-privilege provider environment credential. Prefer the [`browser`](browser-automation.md) subpath over ordinary public retrieval; use browser automation only for interactive/authenticated/JavaScript-heavy work behind a host egress proxy. Arbitrary HTML execution, model-selected providers, automatic OAuth forwarding, and generic web/MCP passthrough are unsupported.
73
73
 
@@ -77,4 +77,5 @@ Default tests use injected fake fetch and make no public request. Restricted smo
77
77
  - [Credential storage](credential-storage.md): explicit resolver composition and environment mapping.
78
78
  - [Host security](host-security.md): SSRF, untrusted-content, and secret boundaries.
79
79
  - [MCP tools](mcp-tools.md): hardened prototype path for official vendor MCP servers.
80
+ - [Work artifacts and review](work-artifacts-and-review.md): `snapshotWebEvidence` produces shared citation evidence from an already-fetched body.
80
81
  - [Performance and resource limits](performance.md): operational ceilings and benchmark evidence.
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## What it does
4
4
 
5
- `@arnilo/prism-core/runtime/server` ships a durable artifact co-work review service (Phase 9 / 0.0.14): authorized attach of source/output references with MIME/hash/version, producer-run attribution, citations/data sources, and preview metadata; revision comparison; reviewer approve/reject (request-changes) with last-validated recovery; and authorized, expiring delivery links. Core (`@arnilo/prism`) exports artifact **types only** (`ArtifactRecord`, `ArtifactRevision`, `ArtifactApproval`, `ArtifactDeliveryToken`, approval state `pending | approved | rejected`). Prism persists bounded metadata, revisions, approvals, and delivery references over the existing versioned checkpoint store — **never file bodies**; hosts own blob storage and rendering.
5
+ `@arnilo/prism-core/runtime/server` ships a durable artifact co-work review service: authorized attach of source/output references with MIME/hash/version, producer-run attribution, citations/data sources, and preview metadata; revision comparison; reviewer approve/reject (request-changes) with last-validated recovery; and authorized, expiring delivery links. Citations may carry shared evidence fields (`sourceId`, `revision`, `contentHash`, `retrievedAt`, `excerpt`, `span`, `tenantId`, `support`). Approve stamps `evidenceDigest` over those identity tuples. Core (`@arnilo/prism`) exports artifact types plus `checkCitationIntegrity` / `citationBindingDigest` / `approvalEvidenceIntact`. Prism persists bounded metadata, revisions, approvals, and delivery references over the existing versioned checkpoint store — **never file bodies**; hosts own blob storage and rendering. Integrity is existence/hash/span/ACL only; `support` is an optional host verdict, not proof.
6
6
 
7
7
  ## When to use it
8
8
 
@@ -34,8 +34,8 @@ Every operation input carries `ownership` (from host `authorize`, never request
34
34
  | `list` | Ownership/thread-scoped `PersistencePage<ArtifactRecord>` |
35
35
  | `get` | `ArtifactRecord` |
36
36
  | `revise` | `ArtifactRecord` with an appended revision (new revision resets state to pending) |
37
- | `compare` | `{ artifactId, from, to, changed: { hash, mime, uri, citations } }` — hash+metadata only |
38
- | `approve` / `reject` | `ArtifactRecord`; approve advances `lastValidatedVersion`, reject never clears it |
37
+ | `compare` | `{ artifactId, from, to, changed: { hash, mime, uri, citations } }` — hash+metadata only; structural Office diffs use `diffDocument` |
38
+ | `approve` / `reject` | `ArtifactRecord`; approve advances `lastValidatedVersion` and stamps `evidenceDigest`; reject never clears last-validated |
39
39
  | `lastValidated` | The last approved `ArtifactRevision` (fails closed before any approval) |
40
40
  | `deliveryLink` | `{ link, token }` — signed expiring `ArtifactDeliveryToken` |
41
41
 
@@ -87,7 +87,7 @@ export const handler = createArtifactHandler({ service: artifacts, authorize: ho
87
87
 
88
88
  - Every operation requires authenticated identity + thread ownership derived from host `authorize`; cross-ownership access fails closed as `not_found` (never leaks existence).
89
89
  - Concurrent reviewer conflicts resolve via checkpoint CAS (`expectedVersion`); the loser gets a retryable `conflict` and no approval is lost or duplicated. A throw before commit persists nothing, so failed updates roll back.
90
- - Local filesystem paths are rejected in `uri`/citations (`file:`, absolute, or drive paths); records are redacted before persist and on response, so paths/secrets/document-private data never enter records, events, or exports.
90
+ - Local filesystem paths are rejected in `uri`/citations (`file:`, absolute, or drive paths); records are redacted before persist and on response, so paths/secrets/document-private data never enter records, events, or exports. Citation evidence is untrusted/inert: hosts pass already-retrieved snapshots into `checkCitationIntegrity` (no URL refetch, no persisted presigned credentials). A live source hash/revision/ACL change fails integrity even when a semantic judge scores the prose 1.0.
91
91
  - Frozen caps (default / hard): artifacts per thread 64/256; revisions per artifact 32/128; record 8/64 KiB; preview 16/64 KiB; citations 32/128 and 2/8 KiB each; MIME 128/512 B; hash 256/1 KiB; compare exactly 2 revisions; delivery TTL 5 min/24 h; delivery token 4/16 KiB. Raising the revision cap may require raising `recordBytes` (aggregate backstop).
92
92
  - Compare is hash+metadata-bounded (hosts render content); no file bodies are persisted or transferred. With a wired body store, bodies live in the host's object store and are streamed through the adapter (bounded by `maxBodyBytes` 64 MiB/512 MiB, concurrent transfers 4/16, presign TTL 10 min/24 h); object-store outages surface typed `ERR_PRISM_S3_*` / `ERR_PRISM_ARTIFACT_BODY_*` errors, never silent success.
93
93
 
@@ -95,6 +95,14 @@ export const handler = createArtifactHandler({ service: artifacts, authorize: ho
95
95
 
96
96
  `@arnilo/prism-coding-tools/agent` composes over this service for the coding patch review workflow: `createCodingPatchReviewManifest` builds a bounded manifest (repository/worktree identity, base/head, patch digest, changed paths, diffstat, check and diagnostic summaries) and returns a structural `ArtifactAttachInput` whose `preview.review` embeds the manifest and whose `hash` is the patch SHA-256; `assertCodingPatchAccepted` derives `pending|accepted|rejected|superseded` from the returned `ArtifactRecord` by binding to the exact artifact revision, digest, and identity — any patch/repository/worktree/base/head change supersedes a prior acceptance (a newer revision attached after approval makes the old acceptance stale and refused). Decisions never apply/commit/push/merge; the manifest never embeds a raw patch body. Full contract: [Coding review and diagnostics](coding-review-and-diagnostics.md).
97
97
 
98
+ ## Business action drafts and editable approvals (0.7.0)
99
+
100
+ Business tools (e.g. mail, calendar, documents in `@arnilo/prism-core/integrations/work`) record mutations through durable `WorkDraftStore` drafts before execution. Human reviewers can approve, deny, or edit draft payloads directly:
101
+ - AG-UI clients advertise and send `approveWithEdits` with revised arguments (`editedArgs`/`modifiedArguments`).
102
+ - The server resume endpoint accepts `{ decision: "approve", modifiedArguments: { ... } }` under CAS `expectedVersion`.
103
+ - If arguments are modified, a new draft revision is created with bumped revision number and payload digest. The previous revision's approval is invalidated and the mutation requires approval for the revised content.
104
+ - Untyped/malformed edits, recipient escalation, schema violations, or stale CAS versions fail closed.
105
+
98
106
  ## Live probe (plans/064 Task 9)
99
107
 
100
108
  The S3 artifact-body store has an operator-gated live probe against a real S3-compatible endpoint (use a throwaway bucket):
@@ -115,3 +123,5 @@ Probes: put → get (hash + size verified), presigned delivery URL with `X-Amz-S
115
123
  - [Policy and audit](policy-and-audit.md): `onDecision` events bridge here for an auditable review ledger.
116
124
  - [Host security](host-security.md): identity/ownership, redaction, and expiring-link boundaries.
117
125
  - [Frontend interoperability (AG-UI and ACP)](ag-ui.md): projects artifact progress/approval/download-link as redacted co-work events over the durable-resume stream.
126
+ - [Documents, spreadsheets, and presentations](documents.md): `diffDocument` for structural paragraph/table/cell/slide review.
127
+ - [Evaluations](evaluations.md): `createCitationIntegrityScorer` invariant over `environment.citations`.
@@ -6,7 +6,7 @@ Least-privilege Microsoft 365 and Google Workspace connectors live in `@arnilo/p
6
6
 
7
7
  1. **Host-pinned binary** — Prism never downloads or shells an untrusted CLI path.
8
8
  2. **Hard-coded argv templates** — models choose typed tool args; they never supply command strings.
9
- 3. **Draft-then-approve** — mutations create a draft; side effects run only after host approval.
9
+ 3. **Draft-then-approve & durable resumption** — mutations create a draft with tracked revisions and payload digests; side effects run only after host approval binds to that exact revision; durable checkpoint persistence survives process restart.
10
10
  4. **Idempotent retries** — `IdempotencyStore` keyed by identity + operation key.
11
11
  5. **Isolated config** — per-identity `configDir` (CLI `HOME`); no credential argv.
12
12
  6. **Shared result shapes** — mail/calendar/file/task list/get tools normalize onto `WorkMailMessage` / `WorkCalendarEvent` / `WorkFileItem` / `WorkTaskItem` without hiding provider-specific ops.
@@ -23,6 +23,8 @@ See [Work tools](work-tools.md). Adapter: `createGoogleWorkspaceCliAdapter` / su
23
23
 
24
24
  Uses [`@googleworkspace/cli` (`gws`)](https://github.com/googleworkspace/cli): `gmail users messages list|get`, `gmail +send`, `calendar events list|insert`, `drive files list|create`, `drive permissions create`, `tasks tasks *`. Docs/Sheets/Slides create remain capability-gated. Discovery `schema` and `auth`/`login`/`setup` are forbidden from Prism argv.
25
25
 
26
+ Drive **knowledge synchronization** (RAG import of file text + host-mapped ACL via `changes.list`) is not this CLI adapter. Use `createGoogleDriveConnector` / `syncKnowledge` from `@arnilo/prism-memory/rag` — see [Knowledge synchronization](knowledge-sync.md).
27
+
26
28
  ## Scoped OAuth establishment (0.0.14)
27
29
 
28
30
  Hosts establish, refresh, and revoke scoped OAuth credentials for these workloads through the existing `OAuthProvider` / credential-store seams (`@arnilo/prism-core/credentials/node`): `createMicrosoft365OAuthProvider` / `createGoogleWorkspaceOAuthProvider` (PKCE + device code), least-privilege scope bundles per capability (`resolveMicrosoft365Scopes` / `resolveGoogleWorkspaceScopes`, read vs mutation). Connectors consume a per-identity token via a late-bound `tokenProvider` injected as an env var — never argv, never model context; revocation fails closed. See [Credential storage](credential-storage.md) and [Work tools](work-tools.md).
@@ -1,6 +1,6 @@
1
1
  # Work tools
2
2
 
3
- Optional `@arnilo/prism-core/integrations/work` package: identity-scoped Microsoft 365 and Google Workspace connectors. Host-pinned CLI binaries only; hard-coded `execFile` argv templates; draft-then-approve mutations; side-effect idempotency; shared mail/calendar/file/task result shapes.
3
+ Optional `@arnilo/prism-core/integrations/work` subpath: identity-scoped Microsoft 365 and Google Workspace connectors. Host-pinned CLI binaries only; hard-coded `execFile` argv templates; draft-then-approve mutations; side-effect idempotency; shared mail/calendar/file/task result shapes.
4
4
 
5
5
  ## When to use
6
6
 
@@ -9,7 +9,7 @@ Use when agents must read or mutate tenant mail/calendar/files/tasks through the
9
9
  ## Install
10
10
 
11
11
  ```bash
12
- npm install @arnilo/prism-core/integrations/work
12
+ npm install @arnilo/prism-core
13
13
  # host separately:
14
14
  # npm i -g @pnp/cli-microsoft365
15
15
  # npm i -g @googleworkspace/cli
@@ -87,9 +87,19 @@ Verified against [`@googleworkspace/cli` / `gws`](https://github.com/googleworks
87
87
 
88
88
  Startup: M365 `version --output json`; GWS `--version`. Forbidden: `login`, `setup`, `auth`, `schema`, `doctor`, `--debug`, `--verbose`, credentials in argv, anonymous share, model-supplied command strings / free-form Discovery.
89
89
 
90
- ### Draft → approve → execute
90
+ ### Draft → approve → execute (0.7.0, R02)
91
91
 
92
- Mutation tools (`*_mail_draft_send`, `*_draft_*`) create an in-adapter draft and return `{ status: "pending_approval", draftId }` until `approval.isApproved` is true.
92
+ Mutation tools (`*_mail_draft_send`, `*_draft_*`) create an in-adapter draft and return `{ status: "pending_approval", draftId, revision, payloadDigest }` until the host approval gate grants permission.
93
+
94
+ In Prism 0.7.0, draft lifecycles are durably managed:
95
+
96
+ - **Exact revision binding**: Every draft carries an integer `revision` (starts at 1) and a deterministic canonical `payloadDigest` (`sha256:<hex>`). Approvals bind strictly to `{ draftId, revision, payloadDigest, identityKey, approvedAt, expiresAt, policyRevision }`.
97
+ - **Durable persistence across restarts**: When adapters are configured with `checkpoints: CheckpointStore` (e.g. `createPostgresEnterpriseState({ pool }).checkpoints` or `createMemoryCheckpointStore()`), drafts are stored under namespace `prism.work.draft`. Drafts survive process restarts; a worker process can resume an exact draft revision approved in a prior process or via a delayed human-in-the-loop review.
98
+ - **Edits invalidate approval**: Any mutation or update to a draft increments `revision`, recalculates `payloadDigest`, clears any previous `approval`, and resets `status` to `pending_approval`. Prior approvals cannot execute a modified draft.
99
+ - **Resuming approved drafts**: Mutation tools accept `{ draftId, revision }` without requiring callers to re-supply the full payload. The tool loads the stored draft, validates approval status and digest, reauthorizes immediately before execution, and executes the effect.
100
+ - **Idempotent duplicate approvals**: Re-approving an approved draft with the same approval object is idempotent. Submitting an approval with a mismatched revision or payload digest is rejected with `ERR_PRISM_WORK_DRAFT_STALE` or `ERR_PRISM_WORK_DRAFT_DIGEST`.
101
+ - **Ambiguous failure handling**: If a connector call fails ambiguously after dispatch, both the idempotency record and the draft are marked `unknown`. Re-running with that draft ID or idempotency key fails closed (`ERR_PRISM_WORK_IDEMPOTENCY_UNKNOWN`) and never auto-replays without explicit operator reconciliation.
102
+ - **Optional body offloading**: Supplying `bodies: ArtifactBodyStore` automatically stores large draft message/file bodies in the object store with an `ArtifactBodyRef` recorded on the draft metadata.
93
103
 
94
104
  ### Durable idempotency (0.0.23)
95
105
 
package/docs/workflows.md CHANGED
@@ -20,6 +20,9 @@ Primary exports:
20
20
  | `defineSaga` / `runSaga` / `resumeSaga` | Bounded linear durable forward steps, reverse compensation, unknown-outcome reconciliation, lease fencing, and manual resolution over existing checkpoint/lease stores |
21
21
  | `createWorkflowSchedules` | Explicit ownership-scoped one-time/interval/host-calculated schedules over existing checkpoint/lease stores |
22
22
  | `createProactiveScheduleCapabilities` | Scoped, expiring, revocable capability tokens that enable proactive schedules; revocation stops firing fail-closed |
23
+ | `serializeWorkflowGraph` / `collectWorkflowGraphs` | Pure JSON serialization of workflow DAGs (`WorkflowGraphView`) without functions/closures; collect nested graphs |
24
+ | `workflowGraphToMermaid` / `workflowGraphToDot` | Deterministic Mermaid flowchart and Graphviz DOT exporters with node shapes by kind and label escaping |
25
+ | `projectWorkflowGraphRun` / `createWorkflowGraphRunFolder` | Run overlay view (`WorkflowGraphRunView`) from checkpoints, timelines, or live event stream |
23
26
 
24
27
  Included through the `@arnilo/prism` / `@arnilo/prism-core` family packages; installing them does not start workflows. Interactive TUI is out of scope (C-012 deferred).
25
28
 
@@ -106,7 +109,7 @@ Every node receives bounded `ctx.state`, `ctx.stateVersion`, and async `ctx.upda
106
109
 
107
110
  `replayWorkflow(workflow, { sourceRunId, fromNodeId, runId? }, options)` requires a succeeded source/node, creates a new checkpoint, copies terminal evidence outside the selected node's downstream closure, restores selected-node pre-state, and records `{ sourceRunId, fromNodeId, rootRunId, depth }`. Source evidence is untouched. Copying any prior nested/tool approval is rejected; replay from that approval node or earlier so Phase 8 approval executes again.
108
111
 
109
- `createWorkflowCoordinator({ coordinatorId, workflows, checkpoints, leases, ... })` polls queued/running checkpoints with bounded pages, atomically claims each run, renews its lease, and aborts/fences work after lease loss. Key controls: `leaseTtlMs` (default 30s), `renewalIntervalMs` (default TTL/3), `pollIntervalMs` (default 1s), `maxConcurrentRuns` (default 4), and `pageSize` (default 100, maximum 500).
112
+ `createWorkflowCoordinator({ coordinatorId, workflows, checkpoints, leases, ... })` polls queued/running checkpoints with bounded pages, atomically claims each run, renews its lease, and aborts/fences work after lease loss. Key controls: `leaseTtlMs` (default 30s), `renewalIntervalMs` (default TTL/3), `pollIntervalMs` (default 1s), `maxConcurrentRuns` (default 4), and `pageSize` (default 100, maximum 500). Optional `admission` wraps claims: cursor wrap across pages (default 4 pages/poll, hard 16) so a noisy first page cannot starve later tenants; `perTenant` / `perClass` cap concurrent claims on that worker; `deadlineMs` skips stale `createdAt`; `drain` stops new claims while draining and aborts in-flight after `snapshot().expired`. Workload class is `metadata.workloadClass` (`^[a-z][a-z0-9_-]{0,31}$`, else `default`). `onMetric` labels are `outcome` + `class` only — never tenant or run ids. This is not a second scheduler.
110
113
 
111
114
  `defineSaga({ id, revision, steps })` validates a bounded linear definition. Each step supplies `run`, `compensate`, and `reconcile`; handlers receive a stable tenant-scoped `operationId`, redacted bounded input/output, prior outputs, and an abort signal. `runSaga(definition, { checkpoints, leases, ownerId, tenantId, runId?, input?, maxAttempts?, leaseTtlMs?, redactor?, onEvent? })` stores a surrogate workflow checkpoint through `WorkflowCheckpointAdapter`, acquires a fenced `LeaseStore` lease, and advances one cursor at a time. `resumeSaga` takes over an expired run; it never replays durably succeeded steps. Forward or compensation handlers mark ambiguous failures with `unknown: true` (or `ERR_PRISM_SAGA_UNKNOWN`), and `reconcile` must return `succeeded`, `failed`, or `unknown` before retry.
112
115
 
@@ -404,6 +407,70 @@ For a single bounded refinement, prefer `loopNode`. Keep this host-loop pattern
404
407
  - Agent exclusivity is per session: one active `run()` at a time, same as core.
405
408
  - Saga definitions remain host code and only their revision, ordered step IDs, bounded JSON snapshots, cursors, attempt counters, and redacted error/provenance metadata are persisted. The surrogate workflow checkpoint namespace is private to the package.
406
409
 
410
+ ## Graph serialization, Mermaid, DOT, and run overlay
411
+
412
+ Workflows can be converted to JSON view-models and visualization formats without executing them or shipping JS functions:
413
+
414
+ ```ts
415
+ import {
416
+ collectWorkflowGraphs,
417
+ createWorkflowGraphRunFolder,
418
+ projectWorkflowGraphRun,
419
+ serializeWorkflowGraph,
420
+ workflowGraphToDot,
421
+ workflowGraphToMermaid,
422
+ } from "@arnilo/prism-core/runtime/workflows";
423
+
424
+ // 1. Pure static graph view (JSON-serializable)
425
+ const view = serializeWorkflowGraph(workflow);
426
+ // view.nodes: [{ id: "stepA", kind: "function", label: "stepA" }, ...]
427
+ // view.edges: [{ from: "stepA", to: "stepB", kind: "always" }, ...]
428
+
429
+ // 2. Export to Mermaid flowchart
430
+ const mermaid = workflowGraphToMermaid(view);
431
+ // flowchart TD
432
+ // stepA["stepA"]
433
+ // stepB["stepB"]
434
+ // stepA --> stepB
435
+
436
+ // 3. Export to Graphviz DOT
437
+ const dot = workflowGraphToDot(view);
438
+
439
+ // 4. Project run state overlay from checkpoint or timeline
440
+ const overlay = projectWorkflowGraphRun(view, checkpoint);
441
+ // overlay.nodes[0].run?.status -> "succeeded" | "failed" | "running" | ...
442
+
443
+ // 5. Incremental live folder for WebSocket/SSE cockpits
444
+ const folder = createWorkflowGraphRunFolder(view);
445
+ for await (const event of eventBus.subscribe()) {
446
+ folder.push(event);
447
+ const live = folder.snapshot();
448
+ }
449
+
450
+ // 6. Collect nested workflow graphs by ID
451
+ const graphs = collectWorkflowGraphs(hierarchicalWorkflow);
452
+ // Map with parent and child workflow views
453
+ ```
454
+
455
+ ### Graph view-model (`WorkflowGraphView`)
456
+
457
+ - `schemaVersion`: 1
458
+ - `workflowId`, `revision`, `definitionHash`: matches definition
459
+ - `nodes`: deterministically sorted array of `WorkflowGraphNode` with `id`, `kind`, `label`, `metadata`, `nestedWorkflowId`, `loop`
460
+ - `edges`: deterministically sorted array of `WorkflowGraphEdge` with `from`, `to`, `kind` (`"always" | "then" | "else"`)
461
+ - Closures and functions (`when`, `execute`, `map`, `reduce`) are **omitted** by design so the view is safe for JSON wire transfer and audit logging.
462
+
463
+ ### Visualization & escaping
464
+
465
+ - `workflowGraphToMermaid()` assigns distinct shapes by node kind: diamond for `conditional`, hexagon for `loop`, stadium for `agent`, subroutine for `workflow`, rounded for `tool`, box for `function`.
466
+ - Mermaid and DOT exporters automatically escape double quotes, HTML characters (`<`, `>`), and literal arrows (`-->`) to prevent script injection (XSS) and parser corruption.
467
+ - Output is byte-identical across runs regardless of dictionary key insertion order.
468
+
469
+ ### Run overlay (`WorkflowGraphRunView`)
470
+
471
+ - Paints per-node runtime status (`status`, `durationMs`, `attempt`, `errorCode`, `skippedReason`) onto the static DAG structure.
472
+ - Does **not** include node outputs — outputs remain on the execution timeline under content-capture policy to protect credentials and manage payload size.
473
+
407
474
  ## Security and performance notes
408
475
 
409
476
  - Definitions require a non-empty host-authored `revision` and fail closed on cycles, unknown edges, self-edges, invalid limits, and `maxNodes` overflow. Revision and every nested revision enter the deterministic definition hash; hosts must bump revision when function/tool behavior changes. Loop `maxIterations` is required and capped at 64.
@@ -440,6 +507,7 @@ Use workflows for known, durable, replayable graphs. Use optional supervisor del
440
507
  - [A2A interoperability](a2a.md): hosts may adapt existing exact-owner workflow status/list/cancel/checkpoint/event surfaces to `A2ATaskLifecycle`; A2A package adds no workflow worker, queue, or schema.
441
508
  - [Agent events](agent-events.md): core `AgentEvent` wrapped by `agent_event`
442
509
  - [Session stores and branching](session-stores-and-branching.md): session `leafId` reuse on resume
510
+ - [Observational memory compaction](compaction-observational-memory.md): hosts may pass `ctx.nodeId` to `withWorkScope`; the workflow runner stays scope-unaware.
443
511
  - [CLI/RPC](cli-rpc.md): host control seam; wire `createWorkflowCommands()` into `runRpcServer`
444
512
  - [Database persistence](database-persistence.md): generic `CheckpointStore` and `LeaseStore` capabilities
445
513
  - [SQLite persistence](sqlite-persistence.md): durable `persistence.checkpoints`
@@ -4,6 +4,8 @@
4
4
 
5
5
  `@arnilo/prism-memory` is an optional package for schema/template-backed working memory and embedding-based semantic recall. It owns narrow `Embedder` and `VectorStore` contracts reused by the `@arnilo/prism-memory/rag` subpath, plus an in-memory reference path and one PostgreSQL/pgvector production adapter.
6
6
 
7
+ The [memory fabric](memory-fabric.md) subpath is a typed-notes layer on top of these same stores: notes are ordinary rows here, so this page's consent, redaction, lineage, and scope rules are the whole rulebook. [Observational memory](compaction-observational-memory.md) is a separate, **episodic** layer — a source-backed ledger for the current session — and is not a store this package owns or replaces.
8
+
7
9
  ## When to use it
8
10
 
9
11
  Use it when a host needs durable per-tenant profile/state (working memory) or top-K semantic retrieval over prior thread entries. Do not use it as a replacement for observational memory compaction: observational memory compresses source-backed observations; semantic memory retrieves embeddings; working memory stores the current structured profile.
@@ -27,6 +29,7 @@ Ordinary Prism sessions do not require this package or any vector backend.
27
29
  | `redactor` / `secrets` | no | Redact text/metadata before persist/inject |
28
30
  | `requireConsent` | no | Strict mode: recall/injection excludes entries lacking explicit consent |
29
31
  | `importanceFrom` | no | Host-owned hook deriving importance from a redacted reflection payload (write time only; no default, no LLM) |
32
+ | `onInvalidate` | no | After lineage rows land, before body delete (observational drop / RAG delete wiring) |
30
33
 
31
34
  Semantic indexing (entries carry `MemoryConsent` source/visibility; unset defaults to `{ source: "user", scope: "thread", visible: true }`):
32
35
 
@@ -38,13 +41,13 @@ Semantic indexing (entries carry `MemoryConsent` source/visibility; unset defaul
38
41
  | `grantedAt` / `revokedAt` | Optional host/audit timestamps; a revocation excludes the record. |
39
42
 
40
43
  ```ts
41
- await memory.remember({ entries: [{ id, text, metadata?, consent?, sequence?, importance?, reflection? }] }, { wait?: boolean })
44
+ await memory.remember({ entries: [{ id, text, metadata?, consent?, sequence?, importance?, reflection?, lineage?: { sourceIds, reason? } }] }, { wait?: boolean })
42
45
  ```
43
46
 
44
47
  Semantic recall (honors consent/visibility at assembly time):
45
48
 
46
49
  ```ts
47
- await memory.recall(query, { topK?, messageRange?, requireConsent?, scoring?, signal? })
50
+ await memory.recall(query, { topK?, messageRange?, requireConsent?, scoring?, explain?, shareFromParentThreadId?, signal? })
48
51
  ```
49
52
 
50
53
  #### Composite recall scoring (opt-in)
@@ -99,8 +102,10 @@ Consent + lifecycle (real grant/correct/delete/retention on stored entries):
99
102
  ```ts
100
103
  await memory.setConsent(entryId, { visible?: boolean, source?, scope? }) // grant/revoke; no re-embed
101
104
  await memory.correct(entryId, text) // re-embeds, preserves consent
102
- await memory.forget({ ids? }) // real delete (whole thread if no ids)
103
- await memory.applyRetention({ maxAgeDays?, maxEntries?, batchSize? }) // bounded real-delete sweep
105
+ await memory.forget({ ids?, hold? }) // real delete; hold:true = legal_hold, no body delete
106
+ await memory.shareWith(childThreadId, sourceIds, { expiresAt? }) // parent→child allow-list; empty ids revoke
107
+ await memory.revokeShare(childThreadId)
108
+ await memory.applyRetention({ maxAgeDays?, maxEntries?, batchSize? }) // bounded real-delete sweep; skips legal_hold
104
109
 
105
110
  const page = await memory.exportMemory({
106
111
  identity: { tenantId, resourceId, threadId }, // exact host-verified owner
@@ -117,9 +122,10 @@ const rebuilt = await memory.rebuildIndex({ cursor?, batchSize?, maxMs?, signal?
117
122
  | --- | --- |
118
123
  | `updateWorking` / `getWorking` | Versioned `WorkingMemoryRecord` |
119
124
  | `remember` | `{ accepted, pending, done }` — default `wait: false` indexes asynchronously |
120
- | `recall` | `{ hits, adjacent }` tenant/thread scoped; invisible/revoked entries excluded |
121
- | `setConsent` / `correct` | Updated `MemoryVectorRecord` with stamped grant/revoke times |
122
- | `forget` | Removed count (real delete) |
125
+ | `recall` | `{ hits, adjacent, explanations? }` tenant/thread scoped; invisible/revoked/invalidated entries excluded |
126
+ | `setConsent` / `correct` | Updated `MemoryVectorRecord`; revoke/correct marks lineage before dependents can inject |
127
+ | `forget` | Removed count (real delete); `0` when `hold: true` |
128
+ | `shareWith` / `revokeShare` | Parent-child grant; sibling threads cannot use it |
123
129
  | `applyRetention` | `{ deleted, scanned }` bounded real-delete sweep |
124
130
  | `exportMemory` | `{ entries, bytes, nextCursor? }` redacted, explicitly consented, identity-bound page |
125
131
  | `rebuildIndex` | `{ rebuilt, nextCursor? }` re-embedded bounded page; caller owns resume scheduling |
@@ -215,8 +221,10 @@ const store = await createPostgresVectorStore({
215
221
  dimension: 32, // optional; pins the embedding column width (HNSW + drift guard)
216
222
  }); // PostgresVectorStoreOptions; dimension must match the embedder's dimensions
217
223
  // store implements rag's VectorStore/TransactionalVectorStore contract: upsert,
218
- // query, getBySource, transaction, lexicalQuery (fts, when available), and
219
- // getCurrentGeneration/setCurrentGeneration. close() ends adapter-owned pools.
224
+ // query, getBySource, transaction, lexicalQuery (fts, when available),
225
+ // getCurrentGeneration/setCurrentGeneration, and document ACL
226
+ // (`authorization: "acl"`, setSourceAccess, checkSourceAccess).
227
+ // close() ends adapter-owned pools.
220
228
  ```
221
229
 
222
230
  `createPostgresVectorStore()` is the production counterpart to `createMemoryVectorStore()` used by the `rag` subpath; `createPostgresMemoryStores()` reuses the same vector implementation internally.
@@ -226,9 +234,9 @@ const store = await createPostgresVectorStore({
226
234
  - Hosts wire the context provider into `AgentConfig.context` or `resolveContextProviders()`.
227
235
  - The working-memory processor is opt-in and host-invoked; middleware is not required.
228
236
  - `createHashEmbedder()` is for tests/demos only; production hosts supply a real `Embedder`.
229
- - Observational memory (`/compaction/observational-memory`) remains unchanged and composable.
230
- - Consent is enforced at the single `recall()` gate, so both direct recall and `createContextProvider()` injection honor it; `visible: false` (or a revoked grant) keeps an entry out of prompts, events, exports, and telemetry. `setConsent`/`correct` re-upsert in place (consent change does not re-embed); `forget`/`applyRetention` are real deletes, not tombstones. Retention uses indexed oldest-first pages plus a scoped count, deleting one default-500/hard-5000 batch without reading a corpus into memory. The PostgreSQL adapter persists consent in a `consent JSONB` column added by `buildMemoryDdl`.
231
- - The PostgreSQL vector path owns its DDL in Prism (`buildMemoryDdl`/`buildVectorSearchDdl` exported): the `<table>_rag_scope_generations` per-scope generation pointer table, `text_tsv` tsvector column + GIN index for the lexical RAG leg, and an HNSW index when the embedding dimension is pinned. DDL runs against the host's **knowledge database** — the host names `schema`/`table` (defaults `prism_memory`/`semantic_memory`), owns backup/retention of that database, and can run migrations manually with `skipMigrations: true`. Identifiers are validated/quoted; values stay parameterized.
237
+ - Observational memory (`/compaction/observational-memory`) is composable. Stamp `lineage.sourceIds` on semantic writes; pass the same ids as `invalidatedIds` into observational projection/recall, or append `om.observations.dropped` from `onInvalidate`. Multi-source facts stay injectable only if none of their sources are invalidated (regenerate from remaining evidence).
238
+ - Consent is enforced at the single `recall()` gate, so both direct recall and `createContextProvider()` injection honor it; `visible: false` (or a revoked grant) keeps an entry out of prompts, events, exports, and telemetry. `setConsent`/`correct` re-upsert in place (consent change does not re-embed) and write invalidation rows first. `forget`/`applyRetention` are real deletes after those rows land; `forget({ hold: true })` keeps the body for legal hold but still excludes injection/export. A revoked grant is not a legal hold: it blocks injection/export but `forget` still purges the body. Legacy records without `_lineage` are self-only: only their own id is excluded. Caps: walk depth 8, 256 edges, 32 source ids, 64-row delete batches — over-cap throws rather than leak. No claim to retract prior disclosures.
239
+ - The PostgreSQL vector path owns its DDL in Prism (`buildMemoryDdl`/`buildVectorSearchDdl` exported): the `<table>_rag_scope_generations` per-scope generation pointer table, `<table>_rag_source_acl` principal/group grants (query-time EXISTS, indexed by principal and group), `<table>_invalidation` tombstones (query-time NOT EXISTS; `corrected` keeps the source), `<table>_share_grant` parent-child allow-lists, GIN on `metadata._lineage.sourceIds`, `text_tsv` tsvector column + GIN index for the lexical RAG leg, and an HNSW index when the embedding dimension is pinned. DDL runs against the host's **knowledge database** — the host names `schema`/`table` (defaults `prism_memory`/`semantic_memory`), owns backup/retention of that database, and can run migrations manually with `skipMigrations: true`. Identifiers are validated/quoted; values stay parameterized.
232
240
  - `createPostgresVectorStore({ dimension })` pins the embedding column width before building indexes: pgvector can only build HNSW over `vector(N)` columns, and dimension mismatch fails closed instead of drifting.
233
241
  - `exportMemory()` requires an exact `{ tenantId, resourceId, threadId }` identity equal to its `createMemory()` scope. It excludes legacy consent-less, invisible, and revoked records even when normal recall allows legacy entries. It returns a stable sequence cursor page, redacted before response, with defaults/hard caps of 100/200 entries, 4/32 MiB, and 10/60 seconds. `rebuildIndex()` uses the same stable cursor shape to re-embed one 32/128-record page under a 10/60-second cap; save the cursor durably to resume. Both APIs require a store implementing bounded `listByThread()`; retention also requires `countByThread()`. PostgreSQL/pgvector and the in-memory reference adapter conform; SQLite persistence stores sessions, not semantic vectors.
234
242
  - Profile bundles do not include this package yet.
@@ -249,7 +257,9 @@ await runMemoryConformance(() => ({
249
257
 
250
258
  - Every write/query/delete requires `tenantId` + `resourceId`; semantic paths also require `threadId`.
251
259
  - Cross-tenant and cross-thread access is denied.
252
- - Revoked/invisible/non-consented memories never enter prompts, events, exports, or telemetry; `requireConsent: true` additionally drops consent-less (legacy) entries. Consent checks are O(hits) at recall, within the existing injected-token cap.
260
+ - RAG document ACL (`RagAccessConstraint`) is host-verified and applied inside `query`/`lexicalQuery` before ranking when `authorization` is passed. Missing grants and unresolved access versions deny. `filter` is not ACL.
261
+ - Revoked/invisible/non-consented/invalidated memories never enter prompts, events, exports, or telemetry; `requireConsent: true` additionally drops consent-less (legacy) entries. Query-time invalidation is an indexed NOT EXISTS (no full-corpus scan on recall). Parent-child shares are explicit, tenant-bound, expiring, and fail closed when missing. Cross-tenant lineage/grants reject.
262
+ - `revokedIdsAbsent(environment, deniedIds)` is the 072 invariant body (`metadata.invariant: true`, score 0 cannot be averaged away). Hosts wrap it with `defineScorer`.
253
263
  - Configure `secrets` / `redactor` so memory text and metadata cannot persist or inject raw canaries.
254
264
  - Injected context is inert text — it cannot grant tools or permissions.
255
265
  - Hard caps: top-K ≤ 32, messageRange ≤ 4, embed batch ≤ 128, injected tokens ≤ 8000, payload/working-memory byte limits enforced.
@@ -266,6 +276,7 @@ Supervisor child factories receive unique derived `resourceId` and `threadId` va
266
276
  - [Supervisor delegation](supervisors.md): package-derived child resource/thread scope.
267
277
  - [Retrieval-augmented generation](rag.md): bounded document chunks reuse this package's embed/vector contracts.
268
278
  - [Context and skills](context-and-skills.md): `ContextProvider` injection seam.
269
- - [Observational memory compaction package](compaction-observational-memory.md): source-backed observation/reflection memory distinction.
279
+ - [Observational memory compaction package](compaction-observational-memory.md): source-backed observation/reflection memory distinction; still episodic, owned by that subpath, not by these stores.
270
280
  - [PostgreSQL persistence](postgres-persistence.md): session/run persistence; memory vectors live in this optional package instead.
271
281
  - [Middleware hooks](middleware-hooks.md): reuse existing `context` hook if hosts transform injected blocks.
282
+ - [Memory fabric](memory-fabric.md): typed notes over these stores, with recall explanations and conversation search.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arnilo/prism",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Agent harness for AI providers, agents, sessions, and tools.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -8,6 +8,8 @@ Ready-to-run project templates for `prism init --template <name>`.
8
8
  | --- | --- | --- |
9
9
  | `init` | Minimal starter Prism agent with one selected provider and offline mock test | `@arnilo/prism` |
10
10
  | `deep-research` | Flagship deep research agent: plan -> search -> extract -> refine loop -> citations -> HITL clarify | `@arnilo/prism`, `@arnilo/prism-web-tools`, `@arnilo/prism-memory`, `@arnilo/prism-workflows` |
11
+ | `personal-assistant` | Personal workstation assistant: single-user ownership, local tools, credential references, and dev inspection | `@arnilo/prism`, `@arnilo/prism-core`, `@arnilo/prism-providers` |
12
+ | `business-worker` | Multi-tenant business worker: durable storage, tenant isolation, verified identity, and governed boundaries | `@arnilo/prism`, `@arnilo/prism-core`, `@arnilo/prism-providers` |
11
13
 
12
14
  ## Usage
13
15
 
@@ -0,0 +1,19 @@
1
+ # __PROJECT_NAME__
2
+
3
+ Multi-tenant business worker built with Prism. Features strict tenant isolation, verified identities, durable persistence, and governed invocation boundaries.
4
+
5
+ ## Quickstart
6
+
7
+ ```bash
8
+ npm install
9
+ npm test
10
+ npm start
11
+ ```
12
+
13
+ ## Production Readiness Requirements
14
+
15
+ - **Tenant Isolation**: Non-empty `tenantId` in ownership; tenant-scoped stores and workspaces.
16
+ - **Verified Identity**: Host-verified principal matching tenant ownership; no fabricated identities.
17
+ - **Durable Persistence**: Production readiness strictly rejects in-memory stores; PostgreSQL or SQLite durable stores required.
18
+ - **Workspace Containment**: Execution confined to authorized tenant sandbox directories.
19
+ - **Governed Invocation**: Permission policies, trust verification, parameter validation, and secret redaction enforced.
@@ -0,0 +1 @@
1
+ BUSINESS_API_KEY=
@@ -0,0 +1,11 @@
1
+ node_modules/
2
+ dist/
3
+ .env
4
+ .env.local
5
+ *.db
6
+ *.sqlite
7
+ *.sqlite3
8
+ .prism/
9
+ coverage/
10
+ .DS_Store
11
+ *.log
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "business-worker",
3
+ "description": "Multi-tenant business worker: durable storage, tenant isolation, verified identity, and governed invocation boundaries",
4
+ "version": "0.1.0",
5
+ "tags": ["business", "worker", "multi-tenant", "enterprise", "secure"],
6
+ "packages": [
7
+ "@arnilo/prism",
8
+ "@arnilo/prism-core",
9
+ "@arnilo/prism-providers"
10
+ ]
11
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "__PROJECT_NAME__",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "build": "tsc -p tsconfig.json",
8
+ "typecheck": "tsc -p tsconfig.json --noEmit",
9
+ "test": "npm run build && node --test dist/__tests__/agent.test.js",
10
+ "start": "npm run build && node dist/index.js",
11
+ "dev": "prism dev"
12
+ },
13
+ "dependencies": {
14
+ __DEPENDENCIES__
15
+ },
16
+ "devDependencies": {
17
+ "@types/node": "^22.0.0",
18
+ "typescript": "^5.7.0"
19
+ },
20
+ "engines": {
21
+ "node": ">=20"
22
+ }
23
+ }
@@ -0,0 +1,92 @@
1
+ import {
2
+ type Agent,
3
+ createMemoryCheckpointStore,
4
+ createMockProvider,
5
+ createSecretRedactor,
6
+ createSecureAgent,
7
+ createStaticPermissionPolicy,
8
+ createStaticTrustPolicy,
9
+ providerDone,
10
+ providerTextDelta,
11
+ } from "@arnilo/prism";
12
+ import { createJsonSchemaArgumentValidator } from "@arnilo/prism-core/validation/json-schema";
13
+ import { createMemoryWorkDraftStore, type SyncWorkDraftStore } from "@arnilo/prism-core/integrations/work";
14
+ import type { AgentIdentity } from "@arnilo/prism";
15
+
16
+ export interface CreateBusinessWorkerOptions {
17
+ readonly tenantId?: string;
18
+ readonly userId?: string;
19
+ readonly identity?: AgentIdentity;
20
+ readonly store?: import("@arnilo/prism").CheckpointStore;
21
+ readonly provider?: import("@arnilo/prism").AIProvider;
22
+ readonly model?: { readonly provider: string; readonly model: string };
23
+ readonly workspaceRoot?: string;
24
+ }
25
+
26
+ export function createAppAgent(options: CreateBusinessWorkerOptions = {}): Agent {
27
+ const tenantId = options.tenantId ?? "tenant-corp";
28
+ const userId = options.userId ?? "worker-1";
29
+
30
+ const identity: AgentIdentity = options.identity ?? {
31
+ tenantId,
32
+ userId,
33
+ principal: { kind: "user", id: userId },
34
+ scopes: ["worker:execute"],
35
+ verified: true,
36
+ issuedAt: new Date().toISOString(),
37
+ };
38
+
39
+ const redactor = createSecretRedactor(
40
+ [process.env.BUSINESS_API_KEY].filter((v): v is string => typeof v === "string" && v.length > 0),
41
+ );
42
+
43
+ const provider =
44
+ options.provider ??
45
+ createMockProvider([
46
+ providerTextDelta("Business worker ready for tenant tasks."),
47
+ providerDone(),
48
+ ]);
49
+
50
+ return createSecureAgent({
51
+ id: "business-worker",
52
+ definitionRevision: "1",
53
+ ownership: { tenantId, userId },
54
+ identity,
55
+ redactor,
56
+ permission: createStaticPermissionPolicy(true),
57
+ trust: createStaticTrustPolicy(true),
58
+ toolArgumentValidator: createJsonSchemaArgumentValidator(),
59
+ limits: { maxToolRounds: 15 },
60
+ runState: { checkpoints: options.store ?? createMemoryCheckpointStore() },
61
+ tools: [
62
+ {
63
+ name: "process_tenant_record",
64
+ description: "Processes a verified tenant batch item",
65
+ parameters: {
66
+ type: "object",
67
+ properties: {
68
+ recordId: { type: "string" },
69
+ action: { type: "string" },
70
+ },
71
+ required: ["recordId", "action"],
72
+ additionalProperties: false,
73
+ },
74
+ execute: async (args, ctx) => ({
75
+ toolCallId: ctx.toolCallId,
76
+ name: "process_tenant_record",
77
+ value: {
78
+ processed: true,
79
+ tenantId,
80
+ recordId: (args as { recordId: string }).recordId,
81
+ },
82
+ }),
83
+ },
84
+ ],
85
+ provider,
86
+ model: options.model ?? { provider: "mock", model: "corp-worker-model" },
87
+ });
88
+ }
89
+
90
+ export function createWorkerDraftStore(): SyncWorkDraftStore {
91
+ return createMemoryWorkDraftStore();
92
+ }
@@ -0,0 +1,13 @@
1
+ import { createAppAgent } from "./agent.js";
2
+
3
+ async function main() {
4
+ const agent = createAppAgent({ tenantId: "tenant-acme", userId: "worker-prod-1" });
5
+ const session = agent.createSession({ id: "biz-session-1" });
6
+ const result = await session.run("Process batch queue item");
7
+ console.log(result.text);
8
+ }
9
+
10
+ main().catch((error) => {
11
+ console.error("Business worker failed:", error);
12
+ process.exit(1);
13
+ });
@@ -0,0 +1,77 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { assertHostCompositionReadiness, inspectHostComposition, HostCompositionError } from "@arnilo/prism";
4
+ import { validateApproval } from "@arnilo/prism-core/integrations/work";
5
+ import type { AgentIdentity } from "@arnilo/prism";
6
+ import { createAppAgent, createWorkerDraftStore } from "../agent.js";
7
+
8
+ describe("business worker template", () => {
9
+ it("creates agent and processes task with tenant context", async () => {
10
+ const agent = createAppAgent({ tenantId: "tenant-enterprise", userId: "worker-test" });
11
+ const session = agent.createSession({ id: "test-biz-session" });
12
+ const result = await session.run("Run tenant task");
13
+ assert.ok(result.text.includes("Business worker ready"));
14
+ });
15
+
16
+ it("fails business readiness if memory-only store is configured", () => {
17
+ const agent = createAppAgent({ tenantId: "tenant-enterprise", userId: "worker-test" });
18
+ assert.throws(
19
+ () => {
20
+ assertHostCompositionReadiness({
21
+ profile: "business",
22
+ agent,
23
+ store: { kind: "memory", durable: false },
24
+ });
25
+ },
26
+ (error) => error instanceof HostCompositionError && error.message.includes("durable storage"),
27
+ );
28
+ });
29
+
30
+ it("passes business readiness with durable store and isolated workspace", () => {
31
+ const agent = createAppAgent({ tenantId: "tenant-enterprise", userId: "worker-test" });
32
+ const report = inspectHostComposition({
33
+ profile: "business",
34
+ agent,
35
+ store: { kind: "postgres", durable: true },
36
+ workspaceRoot: "/var/tenant-enterprise",
37
+ sandboxRoots: ["/var/tenant-enterprise/tasks"],
38
+ credentialRefs: ["BUSINESS_API_KEY"],
39
+ });
40
+
41
+ assert.equal(report.profile, "business");
42
+ assert.equal(report.ownership.tenantId, "tenant-enterprise");
43
+ assert.equal(report.storage.durable, true);
44
+ assert.equal(report.sandbox.isolated, true);
45
+ assert.equal(report.readiness.ok, true);
46
+ });
47
+
48
+ it("rejects a stale draft revision after edit", () => {
49
+ const store = createWorkerDraftStore();
50
+ const identity: AgentIdentity = {
51
+ tenantId: "tenant-enterprise",
52
+ userId: "worker-test",
53
+ principal: { kind: "user", id: "worker-test" },
54
+ scopes: ["Mail.Send"],
55
+ issuedAt: new Date().toISOString(),
56
+ verified: true,
57
+ };
58
+ const draft = store.createDraft({
59
+ provider: "microsoft365",
60
+ op: "mail.send",
61
+ identity,
62
+ payload: { to: "a@contoso.com", subject: "v1" },
63
+ });
64
+ const approval = {
65
+ draftId: draft.draftId,
66
+ revision: draft.revision,
67
+ payloadDigest: draft.payloadDigest,
68
+ };
69
+ const updated = store.updateDraft({
70
+ draftId: draft.draftId,
71
+ identity,
72
+ payload: { to: "a@contoso.com", subject: "v2" },
73
+ expectedRevision: 1,
74
+ });
75
+ assert.throws(() => validateApproval(updated, approval), /does not match draft revision/);
76
+ });
77
+ });