@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,318 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
type Agent,
|
|
8
|
+
type AgentEvent,
|
|
9
|
+
createAgent,
|
|
10
|
+
definePackage,
|
|
11
|
+
type ModelProvider,
|
|
12
|
+
type PackageInstance,
|
|
13
|
+
type ProviderRequest,
|
|
14
|
+
providerDone,
|
|
15
|
+
providerTextDelta,
|
|
16
|
+
providerToolCall,
|
|
17
|
+
type Session,
|
|
18
|
+
SlotConflictError,
|
|
19
|
+
toolCallContent,
|
|
20
|
+
} from "@arnilo/prism";
|
|
21
|
+
import memoryCompaction from "@arnilo/prism-extensions/compaction";
|
|
22
|
+
import { sqliteStore } from "@arnilo/prism-extensions/store-sqlite";
|
|
23
|
+
import memorySystem from "@arnilo/prism-memory-system";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Session memory (`@arnilo/prism-memory-system`'s session tiers), proved end to end over a durable
|
|
27
|
+
* SQLite store and a two-process resume:
|
|
28
|
+
*
|
|
29
|
+
* 1. **The STM worker runs on its own model.** The agent runs on `mock/main`; the package config names
|
|
30
|
+
* `mock/observer`, and the demo asserts both models saw requests.
|
|
31
|
+
* 2. **Compaction uses observations.** `session.compact()` writes a summary carrying the observation
|
|
32
|
+
* the observer recorded, from the ledger rather than the raw transcript.
|
|
33
|
+
* 3. **A session is toggled by command.** `agent.commands.run("memory:session", …)` turns memory on for one
|
|
34
|
+
* session; a second session of the same agent stays off.
|
|
35
|
+
* 4. **State survives resume.** Process A spawns `bun <file> --phase=b <dir> <sessionId> <leafId>`;
|
|
36
|
+
* B reopens the session on the same database and reports the toggle, the worker model, the ledger
|
|
37
|
+
* counts, the rendered ledger, and whether `recall` was offered to the model.
|
|
38
|
+
* 5. **The host holds no memory logic.** This file lists packages, runs commands, reads the session's
|
|
39
|
+
* entries, and reads `memory.session.status` events. Nothing here touches a ledger, a worker, or a prompt.
|
|
40
|
+
* 6. **The slot conflict fails closed.** Listing both memory packages without an assignment rejects
|
|
41
|
+
* with `SlotConflictError`; assigning `slots.compaction` resolves it and `inspect()` names the owner.
|
|
42
|
+
*
|
|
43
|
+
* Imports only `@arnilo/prism`, the two memory packages, and `@arnilo/prism-extensions/store-sqlite`; the mock
|
|
44
|
+
* provider is inline, so there is no credential and no network. The first turn carries a sentinel
|
|
45
|
+
* secret and the demo asserts the ledger and the events never render it. Run: `bun examples/session-memory.ts`
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
const MAIN_MODEL = { provider: "mock", model: "main", limits: { contextWindow: 64_000, maxOutputTokens: 0 } } as const;
|
|
49
|
+
const OBSERVER_MODEL = "mock/observer";
|
|
50
|
+
const OBSERVATION = "OBSERVED-FACT: the retry budget is capped at three attempts.";
|
|
51
|
+
/** A secret-shaped sentinel: the ledger and the events must never render it. */
|
|
52
|
+
const SENTINEL_SECRET = "sk-observational-memory-demo-sentinel";
|
|
53
|
+
const OM_PACKAGE = "@arnilo/prism-memory-system";
|
|
54
|
+
const COMPACTION_PACKAGE = "@arnilo/prism-extensions/compaction";
|
|
55
|
+
|
|
56
|
+
interface Recorder {
|
|
57
|
+
readonly requests: ProviderRequest[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* One provider for both models: the observer answers the package's worker prompt with one
|
|
62
|
+
* `record_event` call sourced from the entries the prompt lists as `[id]`, the main model
|
|
63
|
+
* answers a turn. Every request is recorded, which is how the demo proves which model was asked.
|
|
64
|
+
*/
|
|
65
|
+
function demoProvider(recorder: Recorder): ModelProvider {
|
|
66
|
+
return {
|
|
67
|
+
id: "mock",
|
|
68
|
+
async *generate(request) {
|
|
69
|
+
recorder.requests.push(request);
|
|
70
|
+
if (request.model.model !== "observer") {
|
|
71
|
+
yield providerTextDelta("ack");
|
|
72
|
+
yield providerDone();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
const answered = request.messages.some((message) => message.role === "tool");
|
|
76
|
+
const prompt = request.messages.find((message) => message.role === "user")?.content[0];
|
|
77
|
+
const sourceId =
|
|
78
|
+
prompt?.type === "text" ? /\[[^\]]+\] \[([^\]]+)\] (?:user|assistant|tool|system):/.exec(prompt.text)?.[1] : undefined;
|
|
79
|
+
if (!answered && sourceId) {
|
|
80
|
+
yield providerToolCall(
|
|
81
|
+
toolCallContent("observe-1", "record_event", {
|
|
82
|
+
kind: "statement",
|
|
83
|
+
// Names its source entry, so each turn's pass records its own event (an identical one would habituate).
|
|
84
|
+
description: `${OBSERVATION} (entry ${sourceId})`,
|
|
85
|
+
relevance: "high",
|
|
86
|
+
sourceEntryIds: [sourceId],
|
|
87
|
+
}),
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
yield providerDone();
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Registers {@link demoProvider} as provider id `mock`, so `"mock/main"` and `"mock/observer"` resolve. */
|
|
96
|
+
function mockProviderPackage(recorder: Recorder): PackageInstance {
|
|
97
|
+
return definePackage({
|
|
98
|
+
name: "@acme/observational-memory-demo-provider",
|
|
99
|
+
version: "1.0.0",
|
|
100
|
+
description: "The demo's scripted provider for the main and observer models.",
|
|
101
|
+
requires: { api: 1 },
|
|
102
|
+
setup(prism) {
|
|
103
|
+
prism.providers.register(demoProvider(recorder));
|
|
104
|
+
},
|
|
105
|
+
})();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface DemoAgent {
|
|
109
|
+
readonly agent: Agent;
|
|
110
|
+
readonly events: AgentEvent[];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The whole host wiring: one store package, one provider package, one memory package. */
|
|
114
|
+
async function buildAgent(dir: string, recorder: Recorder): Promise<DemoAgent> {
|
|
115
|
+
const events: AgentEvent[] = [];
|
|
116
|
+
const agent = await createAgent({
|
|
117
|
+
id: "observational-memory-demo",
|
|
118
|
+
model: MAIN_MODEL,
|
|
119
|
+
packages: [
|
|
120
|
+
sqliteStore({ path: join(dir, "sessions.db") }),
|
|
121
|
+
mockProviderPackage(recorder),
|
|
122
|
+
// The package is inert until a session's `memory:session` toggle turns it on. `triggerTokens: 1` makes the
|
|
123
|
+
// first eligible turn cross the observation threshold, so one pass runs in one turn.
|
|
124
|
+
memorySystem({ stm: { model: OBSERVER_MODEL, triggerTokens: 1 }, context: { recentMessages: 2 } }),
|
|
125
|
+
],
|
|
126
|
+
hooks: (hooks: { on: (name: "package.event", handler: (payload: unknown) => void) => void }) => {
|
|
127
|
+
hooks.on("package.event", (payload) => events.push(payload as AgentEvent));
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
return { agent, events };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type OmStatus = {
|
|
134
|
+
readonly enabled: boolean;
|
|
135
|
+
readonly contextMode: "none" | "own-compaction" | "pinned";
|
|
136
|
+
readonly stm: unknown;
|
|
137
|
+
readonly observations: { readonly recorded: number; readonly active: number };
|
|
138
|
+
readonly wmItems: { readonly recorded: number };
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** Reads the package's own status command — the host's only view of memory state. */
|
|
142
|
+
const statusOf = async (agent: Agent, session: Session): Promise<OmStatus> =>
|
|
143
|
+
(await agent.commands.run("memory:session:status", {}, { session })) as OmStatus;
|
|
144
|
+
|
|
145
|
+
/** Waits for the background observation pass a turn started; the pass is not awaited by `run()`. */
|
|
146
|
+
async function waitForObservations(agent: Agent, session: Session, atLeast: number): Promise<OmStatus> {
|
|
147
|
+
const deadline = Date.now() + 10_000;
|
|
148
|
+
for (;;) {
|
|
149
|
+
const status = await statusOf(agent, session);
|
|
150
|
+
if (status.observations.recorded >= atLeast) return status;
|
|
151
|
+
if (Date.now() > deadline) throw new Error("timed out waiting for the observation pass");
|
|
152
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Criterion 6: the slot conflict fails closed, and naming an owner resolves it. */
|
|
157
|
+
async function slotAssignment(): Promise<{ conflict: string; owner: string }> {
|
|
158
|
+
const recorder: Recorder = { requests: [] };
|
|
159
|
+
const both = () => [mockProviderPackage(recorder), memorySystem({}), memoryCompaction({})];
|
|
160
|
+
let conflict = "";
|
|
161
|
+
try {
|
|
162
|
+
await createAgent({ model: MAIN_MODEL, packages: both() });
|
|
163
|
+
} catch (error) {
|
|
164
|
+
assert.ok(error instanceof SlotConflictError, `expected SlotConflictError, got ${String(error)}`);
|
|
165
|
+
assert.equal(error.code, "ERR_PRISM_SLOT_CONFLICT");
|
|
166
|
+
assert.deepEqual(error.owners, [OM_PACKAGE, COMPACTION_PACKAGE]);
|
|
167
|
+
conflict = error.code;
|
|
168
|
+
}
|
|
169
|
+
assert.equal(conflict, "ERR_PRISM_SLOT_CONFLICT", "two providers and no assignment must fail closed");
|
|
170
|
+
|
|
171
|
+
const resolved = await createAgent({
|
|
172
|
+
model: MAIN_MODEL,
|
|
173
|
+
packages: both(),
|
|
174
|
+
slots: { compaction: OM_PACKAGE },
|
|
175
|
+
});
|
|
176
|
+
const owner = (await resolved.inspect()).slots.compaction;
|
|
177
|
+
assert.equal(owner, OM_PACKAGE, "the assignment names the owner");
|
|
178
|
+
await resolved.dispose();
|
|
179
|
+
return { conflict, owner };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
type PhaseB = {
|
|
183
|
+
readonly phase: "b";
|
|
184
|
+
readonly pid: number;
|
|
185
|
+
readonly sessionId: string;
|
|
186
|
+
readonly enabled: boolean;
|
|
187
|
+
readonly observer: string;
|
|
188
|
+
readonly observations: number;
|
|
189
|
+
readonly wmItems: number;
|
|
190
|
+
readonly messageCount: number;
|
|
191
|
+
readonly ledgerHasObservation: boolean;
|
|
192
|
+
readonly recallVisible: boolean;
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
/** Process A: toggle one session, observe, compact, then assert what a fresh process reads back. */
|
|
196
|
+
async function phaseA(script: string): Promise<Record<string, unknown>> {
|
|
197
|
+
const dir = mkdtempSync(join(tmpdir(), "prism-observational-memory-"));
|
|
198
|
+
try {
|
|
199
|
+
const recorder: Recorder = { requests: [] };
|
|
200
|
+
const { agent, events } = await buildAgent(dir, recorder);
|
|
201
|
+
const session = await agent.session({ id: "observed", create: true });
|
|
202
|
+
const untouched = await agent.session({ id: "untouched", create: true });
|
|
203
|
+
|
|
204
|
+
// Criterion 3: the command turns memory on for one session only.
|
|
205
|
+
const toggled = (await agent.commands.run("memory:session", {}, { session })) as { enabled: boolean };
|
|
206
|
+
assert.equal(toggled.enabled, true, "memory:session turns memory on");
|
|
207
|
+
const off = await statusOf(agent, untouched);
|
|
208
|
+
assert.equal(off.enabled, false, "the other session stays off");
|
|
209
|
+
|
|
210
|
+
// Criterion 1: two main turns, and the observer pass they trigger.
|
|
211
|
+
await session.run(`Plan the migration and keep the retry budget small (demo sentinel ${SENTINEL_SECRET}).`);
|
|
212
|
+
await waitForObservations(agent, session, 1);
|
|
213
|
+
await session.run("Write the plan down.");
|
|
214
|
+
await waitForObservations(agent, session, 2);
|
|
215
|
+
const models = recorder.requests.map((request) => request.model.model);
|
|
216
|
+
assert.equal(models.filter((model) => model === "main").length >= 2, true, "the turns ran on mock/main");
|
|
217
|
+
assert.equal(models.filter((model) => model === "observer").length >= 1, true, "the observer ran on mock/observer");
|
|
218
|
+
|
|
219
|
+
// Criterion 2: compaction summarizes from the ledger, not the raw transcript.
|
|
220
|
+
assert.equal((await statusOf(agent, session)).contextMode, "none");
|
|
221
|
+
await session.compact();
|
|
222
|
+
assert.equal((await statusOf(agent, session)).contextMode, "own-compaction");
|
|
223
|
+
const compaction = (await session.entries()).filter((entry) => entry.kind === "compaction").at(-1);
|
|
224
|
+
assert.ok(compaction, "compaction appended an entry");
|
|
225
|
+
assert.match(compaction.summary ?? "", /OBSERVED-FACT/, "the summary carries the recorded observation");
|
|
226
|
+
assert.equal((compaction.data as { strategy?: string }).strategy, "session-memory");
|
|
227
|
+
|
|
228
|
+
// Criterion 5: the host sees the pass only as a package event and through `memory:session:status`.
|
|
229
|
+
assert.equal(
|
|
230
|
+
events.some((event) => event.type === "package.event" && event.name === "memory.session.status"),
|
|
231
|
+
true,
|
|
232
|
+
"the package reports its status as an event",
|
|
233
|
+
);
|
|
234
|
+
const view = (await agent.commands.run("memory:session:view", {}, { session })) as { text: string };
|
|
235
|
+
assert.equal(view.text.includes(SENTINEL_SECRET), false, "the ledger never renders the raw turn");
|
|
236
|
+
assert.equal(JSON.stringify(events).includes(SENTINEL_SECRET), false, "no secret in the events");
|
|
237
|
+
|
|
238
|
+
const messageCount = (await session.messages()).length;
|
|
239
|
+
const leafId = session.leafId;
|
|
240
|
+
assert.ok(leafId, "the session has a leaf to resume from");
|
|
241
|
+
|
|
242
|
+
// Criterion 4: a second process over the same database.
|
|
243
|
+
const child = spawnSync("bun", [script, "--phase=b", dir, session.id, leafId], { encoding: "utf8", timeout: 30_000 });
|
|
244
|
+
assert.equal(child.status, 0, `phase B exited ${child.status}\n${child.stderr}`);
|
|
245
|
+
const b = JSON.parse(child.stdout.trim().split("\n").at(-1) ?? "{}") as PhaseB;
|
|
246
|
+
assert.equal(b.phase, "b");
|
|
247
|
+
assert.notEqual(b.pid, process.pid, "phase B is another process");
|
|
248
|
+
assert.equal(b.sessionId, session.id, "phase B reopened the same session");
|
|
249
|
+
assert.equal(b.enabled, true, "the toggle survived the restart");
|
|
250
|
+
assert.equal(b.observer, OBSERVER_MODEL, "the observer model is unchanged");
|
|
251
|
+
assert.equal(b.observations >= 2, true, "the ledger still holds A's observations");
|
|
252
|
+
assert.equal(b.wmItems, 0, "the WM trigger was never crossed");
|
|
253
|
+
assert.equal(b.ledgerHasObservation, true, "the rendered ledger carries the observation");
|
|
254
|
+
assert.equal(b.recallVisible, true, "the toggled session is offered recall");
|
|
255
|
+
assert.equal(b.messageCount, messageCount, "phase B sees the same messages");
|
|
256
|
+
|
|
257
|
+
const slots = await slotAssignment();
|
|
258
|
+
await agent.dispose();
|
|
259
|
+
return {
|
|
260
|
+
phase: "a",
|
|
261
|
+
mainRequests: models.filter((model) => model === "main").length,
|
|
262
|
+
observerRequests: models.filter((model) => model === "observer").length,
|
|
263
|
+
untouchedSessionEnabled: off.enabled,
|
|
264
|
+
compactionStrategy: (compaction.data as { strategy?: string }).strategy,
|
|
265
|
+
summaryHasObservation: true,
|
|
266
|
+
sentinelSecretInLedgerOrEvents: false,
|
|
267
|
+
slotConflict: slots.conflict,
|
|
268
|
+
slotOwner: slots.owner,
|
|
269
|
+
child: b,
|
|
270
|
+
};
|
|
271
|
+
} finally {
|
|
272
|
+
rmSync(dir, { recursive: true, force: true });
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Process B: a new agent over the same database, resuming the session A left behind. */
|
|
277
|
+
async function phaseB(dir: string, sessionId: string, leafId: string): Promise<PhaseB> {
|
|
278
|
+
const recorder: Recorder = { requests: [] };
|
|
279
|
+
const { agent } = await buildAgent(dir, recorder);
|
|
280
|
+
const session = await agent.session({ id: sessionId, leafId });
|
|
281
|
+
const status = await statusOf(agent, session);
|
|
282
|
+
const view = (await agent.commands.run("memory:session:view", {}, { session })) as { text: string };
|
|
283
|
+
const messageCount = (await session.messages()).length;
|
|
284
|
+
|
|
285
|
+
// One more turn: the toggle survived, so `recall` is offered to the model for this session.
|
|
286
|
+
await session.run("Continue the plan.");
|
|
287
|
+
const mainRequest = recorder.requests.filter((request) => request.model.model === "main").at(-1);
|
|
288
|
+
const recallVisible = (mainRequest?.tools ?? []).some((tool) => tool.name === "recall");
|
|
289
|
+
|
|
290
|
+
await agent.dispose();
|
|
291
|
+
return {
|
|
292
|
+
phase: "b",
|
|
293
|
+
pid: process.pid,
|
|
294
|
+
sessionId: session.id,
|
|
295
|
+
enabled: status.enabled,
|
|
296
|
+
observer: String(status.stm),
|
|
297
|
+
observations: status.observations.recorded,
|
|
298
|
+
wmItems: status.wmItems.recorded,
|
|
299
|
+
messageCount,
|
|
300
|
+
ledgerHasObservation: view.text.includes("OBSERVED-FACT"),
|
|
301
|
+
recallVisible,
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
306
|
+
const args = process.argv.slice(2);
|
|
307
|
+
const phase = args.find((arg) => arg.startsWith("--phase="))?.slice("--phase=".length) ?? "a";
|
|
308
|
+
if (phase === "b") {
|
|
309
|
+
const [dir, sessionId, leafId] = args.filter((arg) => !arg.startsWith("--phase="));
|
|
310
|
+
if (!dir || !sessionId || !leafId) throw new Error("phase B needs a database directory, a session id, and a leaf id");
|
|
311
|
+
return phaseB(dir, sessionId, leafId);
|
|
312
|
+
}
|
|
313
|
+
const script = process.argv[1];
|
|
314
|
+
if (!script) throw new Error("phase A needs its own script path to spawn process B");
|
|
315
|
+
return phaseA(script);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { createSessionEntry, type SessionSearchHit } from "@arnilo/prism";
|
|
6
|
+
import { createJsonlSessionStore } from "@arnilo/prism-extensions/store-jsonl";
|
|
7
|
+
import { createSqlitePersistence } from "@arnilo/prism-extensions/store-sqlite";
|
|
8
|
+
|
|
9
|
+
// Workspace session search over stored sessions (plan 095). One query API covers the indexed
|
|
10
|
+
// stores (SQLite FTS5 / Postgres tsvector) and the linear-scan fallbacks (memory, JSONL): hits
|
|
11
|
+
// carry the matched entry id, run id, 1-based turn, store score, and a bounded snippet.
|
|
12
|
+
// Network-free: an in-memory SQLite database plus a temp JSONL file.
|
|
13
|
+
|
|
14
|
+
const WORKSPACES: Record<string, string> = { "session-auth": "/repo/app", "session-docs": "/repo/docs" };
|
|
15
|
+
|
|
16
|
+
function corpus(): ReturnType<typeof createSessionEntry>[] {
|
|
17
|
+
return [
|
|
18
|
+
createSessionEntry({
|
|
19
|
+
id: "auth-root",
|
|
20
|
+
sessionId: "session-auth",
|
|
21
|
+
timestamp: "2026-01-01T00:00:02.000Z",
|
|
22
|
+
kind: "message",
|
|
23
|
+
runId: "run-auth",
|
|
24
|
+
label: "auth-flake",
|
|
25
|
+
message: { role: "user", content: [{ type: "text", text: "fix the flaky auth test timeout" }] },
|
|
26
|
+
metadata: { workspaceRoot: WORKSPACES["session-auth"] },
|
|
27
|
+
}),
|
|
28
|
+
createSessionEntry({
|
|
29
|
+
id: "auth-summary",
|
|
30
|
+
sessionId: "session-auth",
|
|
31
|
+
parentId: "auth-root",
|
|
32
|
+
timestamp: "2026-01-01T00:00:03.000Z",
|
|
33
|
+
kind: "summary",
|
|
34
|
+
runId: "run-auth",
|
|
35
|
+
summary: "Auth test stabilized by seeding the clock.",
|
|
36
|
+
}),
|
|
37
|
+
createSessionEntry({
|
|
38
|
+
id: "docs-root",
|
|
39
|
+
sessionId: "session-docs",
|
|
40
|
+
timestamp: "2026-01-01T00:00:01.000Z",
|
|
41
|
+
kind: "message",
|
|
42
|
+
message: { role: "user", content: [{ type: "text", text: "fix the flaky auth docs build" }] },
|
|
43
|
+
metadata: { workspaceRoot: WORKSPACES["session-docs"] },
|
|
44
|
+
}),
|
|
45
|
+
createSessionEntry({
|
|
46
|
+
id: "deps-root",
|
|
47
|
+
sessionId: "session-deps",
|
|
48
|
+
timestamp: "2026-01-01T00:00:00.500Z",
|
|
49
|
+
kind: "message",
|
|
50
|
+
message: { role: "user", content: [{ type: "text", text: "bump the linter and fix warnings" }] },
|
|
51
|
+
metadata: { workspaceRoot: "/repo/docs" },
|
|
52
|
+
}),
|
|
53
|
+
createSessionEntry({
|
|
54
|
+
id: "web-root",
|
|
55
|
+
sessionId: "session-web",
|
|
56
|
+
timestamp: "2026-01-01T00:00:00.500Z",
|
|
57
|
+
kind: "message",
|
|
58
|
+
message: { role: "user", content: [{ type: "text", text: "add a health endpoint" }] },
|
|
59
|
+
metadata: { workspaceRoot: "/repo/web" },
|
|
60
|
+
}),
|
|
61
|
+
];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Hit shape a host render: pointers to the matched entry plus the store's relevance. */
|
|
65
|
+
function hit(hit: SessionSearchHit): Record<string, unknown> {
|
|
66
|
+
return {
|
|
67
|
+
sessionId: hit.sessionId,
|
|
68
|
+
entryId: hit.entryId,
|
|
69
|
+
runId: hit.runId,
|
|
70
|
+
turn: hit.turn,
|
|
71
|
+
score: hit.score === undefined ? undefined : Number(hit.score.toFixed(4)),
|
|
72
|
+
snippet: hit.snippet,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function demo(): Promise<Record<string, unknown>> {
|
|
77
|
+
const entries = corpus();
|
|
78
|
+
const stem = `prism-session-search-${process.pid}`;
|
|
79
|
+
const dbPath = join(tmpdir(), `${stem}.db`);
|
|
80
|
+
const jsonlDir = join(tmpdir(), `${stem}-jsonl`);
|
|
81
|
+
const persistence = createSqlitePersistence({ filename: dbPath });
|
|
82
|
+
try {
|
|
83
|
+
// SQLite: the FTS5 index is maintained at append time, so the query is an indexed lookup.
|
|
84
|
+
for (const sessionId of new Set(entries.map((entry) => entry.sessionId))) {
|
|
85
|
+
const first = entries.find((entry) => entry.sessionId === sessionId);
|
|
86
|
+
await persistence.appendSession!({
|
|
87
|
+
id: sessionId,
|
|
88
|
+
createdAt: first?.timestamp ?? "2026-01-01T00:00:00.000Z",
|
|
89
|
+
updatedAt: first?.timestamp ?? "2026-01-01T00:00:00.000Z",
|
|
90
|
+
metadata: { workspaceRoot: WORKSPACES[sessionId] },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
for (const entry of entries) await persistence.append(entry);
|
|
94
|
+
|
|
95
|
+
const indexed = await persistence.searchSessions!({ workspaceRoot: "/repo/app", query: "flaky auth", limit: 10 });
|
|
96
|
+
// Annotation search: the same API restricted to annotation entry kinds finds the summary.
|
|
97
|
+
const annotations = await persistence.searchSessions!({ query: "clock", kind: ["summary"], limit: 10 });
|
|
98
|
+
|
|
99
|
+
// JSONL: no index - the same query scans the file (O(corpus) per query) with the same hit shape.
|
|
100
|
+
const writer = createJsonlSessionStore({ dir: jsonlDir });
|
|
101
|
+
for (const entry of entries) await writer.append(entry);
|
|
102
|
+
const linear = await createJsonlSessionStore({ dir: jsonlDir }).searchSessions!({
|
|
103
|
+
workspaceRoot: "/repo/app",
|
|
104
|
+
query: "flaky auth",
|
|
105
|
+
limit: 10,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
assert.equal(indexed.items[0]?.entryId, "auth-root");
|
|
109
|
+
assert.equal(indexed.items[0]?.runId, "run-auth");
|
|
110
|
+
assert.equal(indexed.items[0]?.turn, 1);
|
|
111
|
+
assert.match(indexed.items[0]?.snippet ?? "", /flaky auth/i);
|
|
112
|
+
assert.equal(annotations.items[0]?.entryId, "auth-summary");
|
|
113
|
+
assert.equal(annotations.items[0]?.turn, 2);
|
|
114
|
+
assert.deepEqual(
|
|
115
|
+
linear.items.map((hit) => [hit.sessionId, hit.entryId, hit.turn]),
|
|
116
|
+
indexed.items.map((hit) => [hit.sessionId, hit.entryId, hit.turn]),
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
indexSearch: indexed.items.map(hit),
|
|
121
|
+
annotationSearch: annotations.items.map(hit),
|
|
122
|
+
linearFallback: linear.items.map(hit),
|
|
123
|
+
};
|
|
124
|
+
} finally {
|
|
125
|
+
persistence.close();
|
|
126
|
+
for (const file of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) rmSync(file, { force: true });
|
|
127
|
+
rmSync(jsonlDir, { recursive: true, force: true });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo(), null, 2));
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createAgent } from "@arnilo/prism";
|
|
2
|
+
import { mockProvider, providerDone, providerTextDelta } from "@arnilo/prism/testing";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Open a session, stream one run, and read the RunResult (roadmap Phase 3). `agent.session()` opens a new
|
|
6
|
+
* session; `agent.session({ id })` reopens it through the `store` slot; `run` resolves to a `RunResult`
|
|
7
|
+
* whose `status` is completed | stopped | suspended | failed | aborted, and a failed run returns instead
|
|
8
|
+
* of throwing. Imports only `@arnilo/prism` and `@arnilo/prism/testing`. Network-free.
|
|
9
|
+
* Run: npm run build:core && node examples/session.ts
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
13
|
+
const agent = await createAgent({
|
|
14
|
+
id: "session-demo",
|
|
15
|
+
model: { provider: "mock", model: "demo" },
|
|
16
|
+
packages: [
|
|
17
|
+
mockProvider([
|
|
18
|
+
[providerTextDelta("Hello"), providerTextDelta(", world."), providerDone()],
|
|
19
|
+
[providerTextDelta("Second answer."), providerDone()],
|
|
20
|
+
]),
|
|
21
|
+
],
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const session = await agent.session();
|
|
25
|
+
let streamed = "";
|
|
26
|
+
for await (const event of session.stream("Say hello")) {
|
|
27
|
+
if (event.type === "message.delta" && event.content.type === "text") streamed += event.content.text;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A second turn through `run` returns the RunResult.
|
|
31
|
+
const result = await session.run("And once more");
|
|
32
|
+
|
|
33
|
+
// The same session, reopened by id: the branch comes back from the store slot.
|
|
34
|
+
const reopened = await agent.session({ id: session.id });
|
|
35
|
+
const messages = await reopened.messages();
|
|
36
|
+
const listed = await agent.sessions.list();
|
|
37
|
+
await agent.dispose();
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
streamed,
|
|
41
|
+
status: result.status,
|
|
42
|
+
text: result.text,
|
|
43
|
+
appended: result.messages.map((message) => message.role),
|
|
44
|
+
reopenedMessages: messages.length,
|
|
45
|
+
sessions: listed.items.map((item) => ({
|
|
46
|
+
id: item.sessionId === session.id ? "this-session" : item.sessionId,
|
|
47
|
+
messageCount: item.messageCount,
|
|
48
|
+
})),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createAgent, definePackage, providerDone, providerTextDelta, toolCallContent } from "@arnilo/prism";
|
|
2
|
+
import { mockProvider } from "@arnilo/prism/testing";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A package calling a second model mid-turn (roadmap Phase 5).
|
|
6
|
+
*
|
|
7
|
+
* The agent runs on two `mockProvider` packages: `main` answers the run and `side` is reached only through
|
|
8
|
+
* `PackageAPI.models.client("side/side")` from inside the `ask_side` tool. The package declares the `models`
|
|
9
|
+
* capability; the main provider emits the tool call, the tool streams the side model's text, and the side
|
|
10
|
+
* provider is called exactly once. The tool passes its `context.session` so the side call is charged to the run. Imports only `@arnilo/prism` and `@arnilo/prism/testing`. Network-free.
|
|
11
|
+
* Run: npm run build:core && node examples/side-call.ts
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
15
|
+
let sideCalls = 0;
|
|
16
|
+
let sideText = "";
|
|
17
|
+
|
|
18
|
+
const sideCall = definePackage({
|
|
19
|
+
name: "@acme/side-call",
|
|
20
|
+
version: "1.0.0",
|
|
21
|
+
requires: { api: 1 },
|
|
22
|
+
capabilities: ["models"],
|
|
23
|
+
setup(prism) {
|
|
24
|
+
prism.tools.register({
|
|
25
|
+
name: "ask_side",
|
|
26
|
+
description: "Asks the side model a question and returns its text.",
|
|
27
|
+
parameters: { type: "object", properties: { question: { type: "string" } }, required: ["question"] },
|
|
28
|
+
execute: async (args, context) => {
|
|
29
|
+
// Passing the tool's session runs the call on the hook plane and charges it to this run's limits.
|
|
30
|
+
for await (const event of prism.models
|
|
31
|
+
.client("side/side")
|
|
32
|
+
.generate(
|
|
33
|
+
{ messages: [{ role: "user", content: [{ type: "text", text: String(args.question ?? "") }] }] },
|
|
34
|
+
{ session: context.session },
|
|
35
|
+
)) {
|
|
36
|
+
if (event.type === "content_delta" && event.content.type === "text") sideText += event.content.text;
|
|
37
|
+
}
|
|
38
|
+
return { toolCallId: context.toolCallId, name: "ask_side", value: sideText };
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const agent = await createAgent({
|
|
45
|
+
id: "side-call-demo",
|
|
46
|
+
model: { provider: "main", model: "main" },
|
|
47
|
+
packages: [
|
|
48
|
+
mockProvider(
|
|
49
|
+
[
|
|
50
|
+
[{ type: "tool_call", call: toolCallContent("c1", "ask_side", { question: "What is the side answer?" }) }, providerDone()],
|
|
51
|
+
[providerTextDelta("main done"), providerDone()],
|
|
52
|
+
],
|
|
53
|
+
{ id: "main" },
|
|
54
|
+
),
|
|
55
|
+
mockProvider([[providerTextDelta("side answer"), providerDone()]], { id: "side", onRequest: () => void (sideCalls += 1) }),
|
|
56
|
+
sideCall,
|
|
57
|
+
],
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const session = await agent.session();
|
|
61
|
+
const result = await session.run("Ask the side model, then finish.");
|
|
62
|
+
await agent.dispose();
|
|
63
|
+
|
|
64
|
+
if (sideCalls !== 1) throw new Error(`the side provider was called ${sideCalls} times`);
|
|
65
|
+
return { status: result.status, mainText: result.text, sideText, sideCalls };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Explicit, externally supervised signal-cli composition.
|
|
2
|
+
import type { Agent } from "@arnilo/prism";
|
|
3
|
+
import { connectSignal, type ChannelConnectionHandle, type SignalConnectOptions } from "@arnilo/prism-hosts/channels/signal";
|
|
4
|
+
|
|
5
|
+
export async function startSignalChannel(agent: Agent, options: SignalConnectOptions): Promise<ChannelConnectionHandle> {
|
|
6
|
+
const handle = await connectSignal(agent, options);
|
|
7
|
+
await handle.start();
|
|
8
|
+
return handle;
|
|
9
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {
|
|
2
|
+
assembleProviderInput,
|
|
3
|
+
createLoadedSkillSet,
|
|
4
|
+
createLoadSkillTool,
|
|
5
|
+
createSkillRegistry,
|
|
6
|
+
createToolRegistry,
|
|
7
|
+
dispatchToolCall,
|
|
8
|
+
type Skill,
|
|
9
|
+
toolCallContent,
|
|
10
|
+
} from "@arnilo/prism";
|
|
11
|
+
|
|
12
|
+
function catalogSkills(count: number): Skill[] {
|
|
13
|
+
return Array.from({ length: count }, (_, i) => ({
|
|
14
|
+
name: `skill-${i}`,
|
|
15
|
+
description: `Catalog entry ${i}.`,
|
|
16
|
+
instructions: `Full instructions for skill ${i}. `.repeat(24),
|
|
17
|
+
}));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Many-skill catalog under budget, then load one body on demand (no live provider).
|
|
21
|
+
export async function demo() {
|
|
22
|
+
const skills = catalogSkills(8);
|
|
23
|
+
const registry = createSkillRegistry(skills);
|
|
24
|
+
const loaded = createLoadedSkillSet();
|
|
25
|
+
const loadSkill = createLoadSkillTool({ registry, loaded });
|
|
26
|
+
const toolRegistry = createToolRegistry([loadSkill]);
|
|
27
|
+
|
|
28
|
+
const catalogRequest = await assembleProviderInput({
|
|
29
|
+
model: { provider: "mock", model: "demo" },
|
|
30
|
+
input: "Pick a skill",
|
|
31
|
+
skills,
|
|
32
|
+
skillsDisclosure: "progressive",
|
|
33
|
+
});
|
|
34
|
+
const catalogText = catalogRequest.messages
|
|
35
|
+
.flatMap((message) => message.content)
|
|
36
|
+
.map((block) => (block.type === "text" ? block.text : ""))
|
|
37
|
+
.join("\n");
|
|
38
|
+
|
|
39
|
+
const catalogOnly = skills.every(
|
|
40
|
+
(skill) =>
|
|
41
|
+
catalogText.includes(`- ${skill.name}: ${skill.description}`) && !catalogText.includes((skill.instructions ?? "").slice(0, 40)),
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
const loadResult = await dispatchToolCall({
|
|
45
|
+
call: toolCallContent("call_1", "load_skill", { name: "skill-3" }),
|
|
46
|
+
registry: toolRegistry,
|
|
47
|
+
context: {
|
|
48
|
+
sessionId: "s1",
|
|
49
|
+
runId: "r1",
|
|
50
|
+
toolCallId: "call_1",
|
|
51
|
+
metadata: {
|
|
52
|
+
loadedSkills: loaded,
|
|
53
|
+
activeSkillNames: skills.map((skill) => skill.name),
|
|
54
|
+
activeTools: toolRegistry.list(),
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const loadedRequest = await assembleProviderInput({
|
|
60
|
+
model: { provider: "mock", model: "demo" },
|
|
61
|
+
input: "Use loaded skill",
|
|
62
|
+
history: [
|
|
63
|
+
{
|
|
64
|
+
role: "tool",
|
|
65
|
+
content: [{ type: "tool_result", toolCallId: "call_1", name: "load_skill", result: loadResult.value }],
|
|
66
|
+
metadata: loadResult.metadata,
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
skills,
|
|
70
|
+
skillsDisclosure: "progressive",
|
|
71
|
+
loadedSkills: loaded,
|
|
72
|
+
runId: "r1",
|
|
73
|
+
tailSegments: new Map(),
|
|
74
|
+
});
|
|
75
|
+
const bodyLoaded = JSON.stringify(loadedRequest.messages).includes("Full instructions for skill 3.");
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
skillCount: skills.length,
|
|
79
|
+
catalogOnly,
|
|
80
|
+
loadedSkill: "skill-3",
|
|
81
|
+
bodyLoaded,
|
|
82
|
+
loadedCount: loaded.list().length,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
87
|
+
console.log(JSON.stringify(await demo()));
|
|
88
|
+
}
|