@arnilo/prism-hosts 0.0.0-stage → 0.13.1
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.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AgentEvent,
|
|
3
|
+
type AgentEventRecord,
|
|
4
|
+
createAgent,
|
|
5
|
+
createSecretRedactor,
|
|
6
|
+
type ModelConfig,
|
|
7
|
+
type PersistencePage,
|
|
8
|
+
type ProductionPersistenceStore,
|
|
9
|
+
providerDone,
|
|
10
|
+
registerContextSources,
|
|
11
|
+
providerTextDelta,
|
|
12
|
+
providerToolCall,
|
|
13
|
+
providerUsage,
|
|
14
|
+
type RunLedger,
|
|
15
|
+
type RunRecord,
|
|
16
|
+
SessionAppendConflictError,
|
|
17
|
+
type SessionAppendOptions,
|
|
18
|
+
type SessionBranchRead,
|
|
19
|
+
type SessionEntry,
|
|
20
|
+
type SessionStore,
|
|
21
|
+
type Skill,
|
|
22
|
+
type ToolCallRecord,
|
|
23
|
+
type ToolDefinition,
|
|
24
|
+
type ToolResult,
|
|
25
|
+
type UsageRecord,
|
|
26
|
+
} from "@arnilo/prism";
|
|
27
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
28
|
+
import { createMockProvider, storeConformance } from "@arnilo/prism/testing";
|
|
29
|
+
|
|
30
|
+
// Phase 41 — End-to-end external-app example with a DB-backed adapter
|
|
31
|
+
// reference mock.
|
|
32
|
+
//
|
|
33
|
+
// An external host implements the persistence/runtime contracts straight from
|
|
34
|
+
// the docs: a `SessionStore` (atomic append + `readBranchPath`), a `RunLedger`
|
|
35
|
+
// (durable run/event/tool/usage rows), and the `ProductionPersistenceStore`
|
|
36
|
+
// read queries used to resume a prior run timeline. No real database, no
|
|
37
|
+
// network — everything runs against the mock provider. This is boilerplate a
|
|
38
|
+
// host can lift into its own SQL/NoSQL adapter.
|
|
39
|
+
//
|
|
40
|
+
// Demonstrates: explicit tools + skills, mock provider, branch-handle checkout,
|
|
41
|
+
// fork, and timeline resume via the ledger reads — without reading Prism source.
|
|
42
|
+
|
|
43
|
+
const FAKE_SECRET = "FAKE_SECRET_PHASE41TOKEN";
|
|
44
|
+
const FAKE_API_KEY = "FAKE_KEY_phase41caller"; // caller-supplied credential resolver value
|
|
45
|
+
|
|
46
|
+
// --- Host-owned tool + skill (explicit capability activation, Phase 38) -----
|
|
47
|
+
|
|
48
|
+
const saveNoteTool: ToolDefinition = {
|
|
49
|
+
name: "notes/save",
|
|
50
|
+
description: "Persist a short note string.",
|
|
51
|
+
parameters: {
|
|
52
|
+
type: "object",
|
|
53
|
+
properties: { text: { type: "string" } },
|
|
54
|
+
required: ["text"],
|
|
55
|
+
},
|
|
56
|
+
execute(args, ctx): ToolResult {
|
|
57
|
+
return { toolCallId: ctx.toolCallId, name: "notes/save", value: (args as { text: string }).text };
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Host context as a `context.build` source (roadmap §2.4). A skill's context is no longer a
|
|
62
|
+
// registry lookup: the host composes the sources it wants for the skills it activates.
|
|
63
|
+
const summarizeContext = {
|
|
64
|
+
name: "notes/summary-context",
|
|
65
|
+
contextBlocks: [{ id: "sum-ctx", title: "Summary style", content: "Summaries are one sentence." }],
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const summarizeSkill: Skill = {
|
|
69
|
+
name: "summarize-skill",
|
|
70
|
+
description: "Activates summary context and the notes/save tool.",
|
|
71
|
+
instructions: "Summarize the request, then save the summary.",
|
|
72
|
+
toolNames: ["notes/save"], // enforced fail-closed before the first provider turn
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// --- DB-backed adapter reference mock ---------------------------------------
|
|
76
|
+
// Implements `SessionStore` + `RunLedger` + `ProductionPersistenceStore`
|
|
77
|
+
// against in-memory tables. A real host swaps these bodies for SQL/NoSQL; the
|
|
78
|
+
// contract shapes and redaction expectations are identical.
|
|
79
|
+
|
|
80
|
+
interface IdempotencyRow {
|
|
81
|
+
readonly key: string;
|
|
82
|
+
readonly parentId: string;
|
|
83
|
+
readonly entryId: string;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function createDbBackedReferenceStore(): SessionStore & RunLedger & ProductionPersistenceStore {
|
|
87
|
+
const entries = new Map<string, SessionEntry>();
|
|
88
|
+
const idempotency = new Map<string, IdempotencyRow>();
|
|
89
|
+
const runs: RunRecord[] = [];
|
|
90
|
+
const events: AgentEventRecord[] = [];
|
|
91
|
+
const toolCalls: ToolCallRecord[] = [];
|
|
92
|
+
const usage: UsageRecord[] = [];
|
|
93
|
+
|
|
94
|
+
const bySession = (sid: string) =>
|
|
95
|
+
[...entries.values()].filter((e) => e.sessionId === sid).sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
96
|
+
|
|
97
|
+
const readBranchPath = async (query: SessionBranchRead): Promise<PersistencePage<SessionEntry>> => {
|
|
98
|
+
const scoped = bySession(query.sessionId);
|
|
99
|
+
let leafId = query.leafId;
|
|
100
|
+
if (!leafId) {
|
|
101
|
+
// Latest leaf = the most recently appended entry that no other entry points at as parent.
|
|
102
|
+
const childTargets = new Set(scoped.map((e) => e.parentId).filter((p): p is string => Boolean(p)));
|
|
103
|
+
leafId = scoped.filter((e) => !childTargets.has(e.id)).at(-1)?.id;
|
|
104
|
+
}
|
|
105
|
+
const chain: SessionEntry[] = [];
|
|
106
|
+
let cursor = scoped.find((e) => e.id === leafId);
|
|
107
|
+
while (cursor) {
|
|
108
|
+
chain.unshift(cursor);
|
|
109
|
+
cursor = cursor.parentId ? scoped.find((e) => e.id === cursor!.parentId) : undefined;
|
|
110
|
+
}
|
|
111
|
+
return { items: chain };
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
name: "db-backed-reference-mock",
|
|
116
|
+
metadata: { kind: "reference", multiProcess: false },
|
|
117
|
+
|
|
118
|
+
// --- SessionStore: atomic append + DB-friendly branch read ---
|
|
119
|
+
async append(entry: SessionEntry, options?: SessionAppendOptions): Promise<void> {
|
|
120
|
+
// 1. expectedParentId existence check (mirrors the conditional-append transaction pattern).
|
|
121
|
+
if (options?.expectedParentId && !entries.has(options.expectedParentId)) {
|
|
122
|
+
throw new SessionAppendConflictError({ code: "session_append_conflict", expectedParentId: options.expectedParentId });
|
|
123
|
+
}
|
|
124
|
+
// 2. idempotency dedup: exact retry for the same parent + key is rejected as a duplicate.
|
|
125
|
+
if (options?.idempotencyKey) {
|
|
126
|
+
const rowKey = `${options.expectedParentId ?? ""}:${options.idempotencyKey}`;
|
|
127
|
+
const existing = idempotency.get(rowKey);
|
|
128
|
+
if (existing) {
|
|
129
|
+
throw new SessionAppendConflictError({ code: "session_append_conflict", idempotencyDuplicate: true });
|
|
130
|
+
}
|
|
131
|
+
idempotency.set(rowKey, { key: rowKey, parentId: options.expectedParentId ?? "", entryId: entry.id });
|
|
132
|
+
}
|
|
133
|
+
// 3. duplicate entry id fails closed.
|
|
134
|
+
if (entries.has(entry.id)) {
|
|
135
|
+
throw new Error(`Duplicate session entry id: ${entry.id}`);
|
|
136
|
+
}
|
|
137
|
+
entries.set(entry.id, entry);
|
|
138
|
+
},
|
|
139
|
+
async list(sessionId: string): Promise<readonly SessionEntry[]> {
|
|
140
|
+
return bySession(sessionId);
|
|
141
|
+
},
|
|
142
|
+
async get(id: string): Promise<SessionEntry | undefined> {
|
|
143
|
+
return entries.get(id);
|
|
144
|
+
},
|
|
145
|
+
readBranchPath,
|
|
146
|
+
|
|
147
|
+
// --- RunLedger: durable run/event/tool/usage rows (runtime already redacted them) ---
|
|
148
|
+
appendRun(record: RunRecord): void {
|
|
149
|
+
runs.push(record);
|
|
150
|
+
},
|
|
151
|
+
appendEvent(record: AgentEventRecord): void {
|
|
152
|
+
events.push(record);
|
|
153
|
+
},
|
|
154
|
+
appendToolCall(record: ToolCallRecord): void {
|
|
155
|
+
toolCalls.push(record);
|
|
156
|
+
},
|
|
157
|
+
appendUsage(record: UsageRecord): void {
|
|
158
|
+
usage.push(record);
|
|
159
|
+
},
|
|
160
|
+
|
|
161
|
+
// --- ProductionPersistenceStore reads (host fills sessions/branches/
|
|
162
|
+
// definitions/retention/migrations record tables separately) ---
|
|
163
|
+
async querySessions(): Promise<PersistencePage<never>> {
|
|
164
|
+
return { items: [] };
|
|
165
|
+
},
|
|
166
|
+
async queryBranches(): Promise<PersistencePage<never>> {
|
|
167
|
+
return { items: [] };
|
|
168
|
+
},
|
|
169
|
+
async queryEntries(query): Promise<PersistencePage<SessionEntry>> {
|
|
170
|
+
let rows = [...entries.values()];
|
|
171
|
+
if (query.sessionId) rows = rows.filter((e) => e.sessionId === query.sessionId);
|
|
172
|
+
if (query.runId) rows = rows.filter((e) => e.runId === query.runId);
|
|
173
|
+
rows.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
174
|
+
return { items: rows.slice(0, query.limit ?? rows.length) };
|
|
175
|
+
},
|
|
176
|
+
async queryRuns(query): Promise<PersistencePage<RunRecord>> {
|
|
177
|
+
// RunQuery has no runId field (runs are addressable by sessionId/branchId/status);
|
|
178
|
+
// narrow to one run by filtering the page by record id afterwards.
|
|
179
|
+
let rows = runs;
|
|
180
|
+
if (query.sessionId) rows = rows.filter((r) => r.sessionId === query.sessionId);
|
|
181
|
+
return { items: rows };
|
|
182
|
+
},
|
|
183
|
+
async queryEvents(query): Promise<PersistencePage<AgentEventRecord>> {
|
|
184
|
+
let rows = events;
|
|
185
|
+
if (query.sessionId) rows = rows.filter((e) => e.sessionId === query.sessionId);
|
|
186
|
+
if (query.runId) rows = rows.filter((e) => e.runId === query.runId);
|
|
187
|
+
return { items: rows };
|
|
188
|
+
},
|
|
189
|
+
async queryToolCalls(query): Promise<PersistencePage<ToolCallRecord>> {
|
|
190
|
+
let rows = toolCalls;
|
|
191
|
+
if (query.sessionId) rows = rows.filter((c) => c.sessionId === query.sessionId);
|
|
192
|
+
if (query.runId) rows = rows.filter((c) => c.runId === query.runId);
|
|
193
|
+
if (query.name) rows = rows.filter((c) => c.name === query.name);
|
|
194
|
+
return { items: rows };
|
|
195
|
+
},
|
|
196
|
+
async queryUsage(query): Promise<PersistencePage<UsageRecord>> {
|
|
197
|
+
let rows = usage;
|
|
198
|
+
if (query.sessionId) rows = rows.filter((u) => u.sessionId === query.sessionId);
|
|
199
|
+
if (query.runId) rows = rows.filter((u) => u.runId === query.runId);
|
|
200
|
+
return { items: rows };
|
|
201
|
+
},
|
|
202
|
+
async queryAgentDefinitions(): Promise<PersistencePage<never>> {
|
|
203
|
+
return { items: [] };
|
|
204
|
+
},
|
|
205
|
+
async queryRetentionPolicies(): Promise<PersistencePage<never>> {
|
|
206
|
+
return { items: [] };
|
|
207
|
+
},
|
|
208
|
+
async queryMigrations(): Promise<PersistencePage<never>> {
|
|
209
|
+
return { items: [] };
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// --- Demo driver -----------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
async function collectEvents(subscription: AsyncIterable<AgentEvent>): Promise<AgentEvent[]> {
|
|
217
|
+
const out: AgentEvent[] = [];
|
|
218
|
+
for await (const event of subscription) out.push(event);
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Known fake secrets are registered with the redactor so ledger/timeline/log
|
|
223
|
+
// paths cannot persist them even if a prompt or tool result echoes them.
|
|
224
|
+
|
|
225
|
+
export async function demo(): Promise<{
|
|
226
|
+
liveEventCount: number;
|
|
227
|
+
toolCallNames: string[];
|
|
228
|
+
branchHandleCheckout: boolean;
|
|
229
|
+
forkDiverged: boolean;
|
|
230
|
+
resumedRunCount: number;
|
|
231
|
+
resumedEventTypes: string[];
|
|
232
|
+
resumedUsageRuns: string[];
|
|
233
|
+
secretRedactedFromLedger: boolean;
|
|
234
|
+
credentialNeverLogged: boolean;
|
|
235
|
+
conformancePassed: boolean;
|
|
236
|
+
}> {
|
|
237
|
+
await storeConformance(createDbBackedReferenceStore);
|
|
238
|
+
const conformancePassed = true;
|
|
239
|
+
const store = createDbBackedReferenceStore();
|
|
240
|
+
|
|
241
|
+
const model: ModelConfig = { provider: "mock", model: "demo" };
|
|
242
|
+
const provider = createMockProvider(
|
|
243
|
+
[
|
|
244
|
+
providerToolCall({ type: "tool_call", id: "tc_save", name: "notes/save", arguments: { text: "saved summary" } }),
|
|
245
|
+
providerTextDelta("Summary saved."),
|
|
246
|
+
providerUsage({ inputTokens: 12, outputTokens: 8, totalTokens: 20 }),
|
|
247
|
+
providerDone(),
|
|
248
|
+
],
|
|
249
|
+
{ id: "mock" },
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
const agent = await createAgent({
|
|
253
|
+
model,
|
|
254
|
+
packages: [providerPackage("example-provider", [provider])],
|
|
255
|
+
instructions: "You are a concise assistant.",
|
|
256
|
+
tools: { add: [saveNoteTool] },
|
|
257
|
+
skills: { add: [summarizeSkill] },
|
|
258
|
+
// A skill no longer carries context providers; the host composes the `context.build`
|
|
259
|
+
// sources it wants for the skills it activates.
|
|
260
|
+
hooks: (hooks) => registerContextSources(hooks, [summarizeContext]),
|
|
261
|
+
slots: { store },
|
|
262
|
+
runLedger: store,
|
|
263
|
+
ownership: { tenantId: "tenant-1", accountId: "acct-1", userId: "user-1" },
|
|
264
|
+
redactor: createSecretRedactor([FAKE_SECRET, FAKE_API_KEY]),
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// Initial session through `agent.session()`, sharing the DB-backed store.
|
|
268
|
+
const session = await agent.session();
|
|
269
|
+
|
|
270
|
+
// Run 1 — the prompt carries a fake secret that must be redacted before storage.
|
|
271
|
+
const reader1 = collectEvents(session.subscribe());
|
|
272
|
+
await session.run(`Summarize this. Do not reveal ${FAKE_SECRET}.`);
|
|
273
|
+
const events1 = await reader1;
|
|
274
|
+
const run1Id = events1.find((e) => e.type === "run.started")?.runId ?? "";
|
|
275
|
+
const branchHandleLeaf = session.leafId; // durable (sessionId, leafId) handle
|
|
276
|
+
|
|
277
|
+
// Run 2 advances the main branch past run 1.
|
|
278
|
+
await session.run("Add a one-word follow-up.");
|
|
279
|
+
|
|
280
|
+
// Branch-handle checkout: rewind to the run-1 leaf, then fork a divergent branch.
|
|
281
|
+
await session.checkout(branchHandleLeaf);
|
|
282
|
+
const forked = await session.fork({ at: branchHandleLeaf });
|
|
283
|
+
const readerFork = collectEvents(forked.subscribe());
|
|
284
|
+
await forked.run("Divergent turn on the forked branch.");
|
|
285
|
+
const forkEvents = await readerFork;
|
|
286
|
+
const forkLeaf = forked.leafId;
|
|
287
|
+
|
|
288
|
+
// Resume run 1's timeline from the ledger via ProductionPersistenceStore reads
|
|
289
|
+
// — no Prism source, no in-memory capture. This is the audit/replay path.
|
|
290
|
+
const resumedRuns = await store.queryRuns({ sessionId: session.id });
|
|
291
|
+
const resumedRunOneEvents = await store.queryEvents({ runId: run1Id });
|
|
292
|
+
const resumedToolCalls = await store.queryToolCalls({ sessionId: session.id, name: "notes/save" });
|
|
293
|
+
const resumedUsage = await store.queryUsage({ runId: run1Id });
|
|
294
|
+
|
|
295
|
+
// Did the fork actually diverge from the main line at the shared leaf?
|
|
296
|
+
// readBranchPath is optional on the contract; this reference store always implements it.
|
|
297
|
+
const forkBranch = await store.readBranchPath!({ sessionId: forked.id, leafId: forkLeaf });
|
|
298
|
+
const forkDiverged = Boolean(forked.id !== session.id && forkLeaf && forkLeaf !== branchHandleLeaf && forkBranch.items.length > 0);
|
|
299
|
+
|
|
300
|
+
// Scan every persisted ledger/entry payload for the raw secrets.
|
|
301
|
+
const allLedgerText = JSON.stringify({
|
|
302
|
+
events: (await store.queryEvents({ sessionId: session.id })).items,
|
|
303
|
+
toolCalls: resumedToolCalls.items,
|
|
304
|
+
usage: resumedUsage.items,
|
|
305
|
+
entries: (await store.queryEntries({ sessionId: session.id })).items,
|
|
306
|
+
forkEntries: (await store.queryEntries({ sessionId: forked.id })).items,
|
|
307
|
+
});
|
|
308
|
+
const secretRedactedFromLedger = !allLedgerText.includes(FAKE_SECRET) && !allLedgerText.includes(FAKE_API_KEY);
|
|
309
|
+
// Credential resolver value must never appear in live events either.
|
|
310
|
+
const credentialNeverLogged = !JSON.stringify([...events1, ...forkEvents]).includes(FAKE_API_KEY);
|
|
311
|
+
|
|
312
|
+
return {
|
|
313
|
+
liveEventCount: events1.length,
|
|
314
|
+
toolCallNames: resumedToolCalls.items.map((c) => c.name),
|
|
315
|
+
branchHandleCheckout: Boolean(branchHandleLeaf) && session.leafId === branchHandleLeaf,
|
|
316
|
+
forkDiverged,
|
|
317
|
+
resumedRunCount: resumedRuns.items.filter((r) => r.sessionId === session.id).length,
|
|
318
|
+
resumedEventTypes: resumedRunOneEvents.items.map((e) => e.type),
|
|
319
|
+
resumedUsageRuns: resumedUsage.items.map((u) => u.runId).filter((r): r is string => Boolean(r)),
|
|
320
|
+
secretRedactedFromLedger,
|
|
321
|
+
credentialNeverLogged,
|
|
322
|
+
conformancePassed,
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export async function main(): Promise<void> {
|
|
327
|
+
const result = await demo();
|
|
328
|
+
console.log(JSON.stringify(result));
|
|
329
|
+
|
|
330
|
+
// Fail fast if the demo does not behave as expected.
|
|
331
|
+
if (!result.branchHandleCheckout) throw new Error("expected checkout to re-point the branch leaf");
|
|
332
|
+
if (!result.forkDiverged) throw new Error("expected the forked branch to diverge from the shared leaf");
|
|
333
|
+
if (!result.toolCallNames.includes("notes/save")) throw new Error("expected notes/save tool call persisted in ledger");
|
|
334
|
+
if (result.resumedRunCount < 1) throw new Error("expected at least one run resumable from the ledger");
|
|
335
|
+
if (result.resumedEventTypes.length === 0) throw new Error("expected run-1 events resumable from the ledger");
|
|
336
|
+
if (result.resumedUsageRuns.length === 0) throw new Error("expected run-1 usage resumable from the ledger");
|
|
337
|
+
if (!result.secretRedactedFromLedger) throw new Error("expected raw secrets redacted from the persisted ledger/entries");
|
|
338
|
+
if (!result.credentialNeverLogged) throw new Error("expected caller credential value to never enter the event stream");
|
|
339
|
+
if (!result.conformancePassed) throw new Error("expected DB-backed reference store to pass SessionStore conformance");
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
343
|
+
await main();
|
|
344
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Governance deny-by-default (plan 159 Task 6; Done criterion 2) — network-free: mock provider,
|
|
3
|
+
* in-memory audit store.
|
|
4
|
+
*
|
|
5
|
+
* One `tool.call` gate over `@arnilo/prism-extensions/governance`: the allow-listed `read_file` runs, the
|
|
6
|
+
* unlisted `write_file` is blocked with a `hook_denied` result naming the policy, and the run still
|
|
7
|
+
* completes. Every decision is appended to the configured `PolicyDecisionStore`, so the audit holds
|
|
8
|
+
* both the allow and the deny.
|
|
9
|
+
*
|
|
10
|
+
* Run: npm run build:core && node examples/governance-deny.ts
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
type ContentBlock,
|
|
14
|
+
createAgent,
|
|
15
|
+
createMemorySessionStore,
|
|
16
|
+
definePackage,
|
|
17
|
+
type ModelProvider,
|
|
18
|
+
type ProviderEvent,
|
|
19
|
+
providerDone,
|
|
20
|
+
providerTextDelta,
|
|
21
|
+
providerToolCall,
|
|
22
|
+
type ToolCapabilityKind,
|
|
23
|
+
type ToolDefinition,
|
|
24
|
+
toolCallContent,
|
|
25
|
+
} from "@arnilo/prism";
|
|
26
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
27
|
+
import governance, { type PolicyDecisionStore } from "@arnilo/prism-extensions/governance";
|
|
28
|
+
|
|
29
|
+
const MODEL = { provider: "mock", model: "governance-deny-demo" } as const;
|
|
30
|
+
const FINISH: readonly ProviderEvent[] = [providerTextDelta("done"), providerDone()];
|
|
31
|
+
|
|
32
|
+
function scriptedProvider(script: readonly (readonly ProviderEvent[])[]): ModelProvider {
|
|
33
|
+
let index = 0;
|
|
34
|
+
return {
|
|
35
|
+
id: "mock",
|
|
36
|
+
async *generate() {
|
|
37
|
+
const events = script[Math.min(index, script.length - 1)] ?? FINISH;
|
|
38
|
+
index += 1;
|
|
39
|
+
for (const event of events) yield event;
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function recordingTool(name: string, executed: string[], effects: readonly ToolCapabilityKind[]): ToolDefinition {
|
|
45
|
+
return {
|
|
46
|
+
name,
|
|
47
|
+
effects,
|
|
48
|
+
parameters: { type: "object" },
|
|
49
|
+
execute: (args, context) => {
|
|
50
|
+
executed.push(name);
|
|
51
|
+
return { toolCallId: context.toolCallId, name, value: { args } };
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Loads after governance and captures the `governance.audit` service so the demo can read the ledger. */
|
|
57
|
+
let audit: { store: PolicyDecisionStore } | undefined;
|
|
58
|
+
const auditCapture = definePackage({
|
|
59
|
+
name: "@prism-example/governance-audit-capture",
|
|
60
|
+
version: "0.0.0",
|
|
61
|
+
requires: { api: 1 },
|
|
62
|
+
setup(prism) {
|
|
63
|
+
audit = prism.services.consume<{ store: PolicyDecisionStore }>("governance.audit");
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
type MemorySessionStore = ReturnType<typeof createMemorySessionStore>;
|
|
68
|
+
|
|
69
|
+
/** Refusals the loop appended for blocked calls, read from the session store (tool results are not events). */
|
|
70
|
+
async function refusalsOf(
|
|
71
|
+
store: MemorySessionStore,
|
|
72
|
+
sessionId: string,
|
|
73
|
+
): Promise<readonly { tool: string; message: string; code?: string | number }[]> {
|
|
74
|
+
const refusals: { tool: string; message: string; code?: string | number }[] = [];
|
|
75
|
+
for (const entry of await store.list(sessionId)) {
|
|
76
|
+
for (const part of entry.message?.content ?? []) {
|
|
77
|
+
const block = (part as ContentBlock).type === "tool_result" ? (part as Extract<ContentBlock, { type: "tool_result" }>) : undefined;
|
|
78
|
+
if (block?.error?.message) refusals.push({ tool: block.name, message: block.error.message, code: block.error.code });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return refusals;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
85
|
+
const store = createMemorySessionStore();
|
|
86
|
+
const executed: string[] = [];
|
|
87
|
+
const agent = await createAgent({
|
|
88
|
+
id: "governance-deny",
|
|
89
|
+
model: MODEL,
|
|
90
|
+
slots: { store },
|
|
91
|
+
packages: [
|
|
92
|
+
providerPackage("governance-deny-provider", [
|
|
93
|
+
scriptedProvider([
|
|
94
|
+
[providerToolCall(toolCallContent("r1", "read_file", { path: "notes.txt" })), providerDone()],
|
|
95
|
+
[providerToolCall(toolCallContent("w1", "write_file", { path: "notes.txt" })), providerDone()],
|
|
96
|
+
FINISH,
|
|
97
|
+
]),
|
|
98
|
+
]),
|
|
99
|
+
governance({ default: "deny", rules: [{ tools: ["read_file"], outcome: "allow" }], audit: { store: "memory" } }),
|
|
100
|
+
auditCapture,
|
|
101
|
+
],
|
|
102
|
+
tools: { add: [recordingTool("read_file", executed, ["read"]), recordingTool("write_file", executed, ["write"])] },
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const result = await (await agent.session({ id: "governance-deny", create: true })).run("read then write notes.txt");
|
|
106
|
+
const refusals = await refusalsOf(store, result.sessionId);
|
|
107
|
+
const records = await audit?.store.query({ tenantId: "local", userId: "governance-deny" });
|
|
108
|
+
await agent.dispose();
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
runStatus: result.status,
|
|
112
|
+
executed,
|
|
113
|
+
blockedTool: refusals[0]?.tool,
|
|
114
|
+
blockedCode: refusals[0]?.code,
|
|
115
|
+
blockedReason: refusals[0]?.message,
|
|
116
|
+
auditOutcomes: (records?.items ?? []).map((record) => record.outcome).sort(),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
121
|
+
console.log(JSON.stringify(await demo()));
|
|
122
|
+
}
|