@arnilo/prism-hosts 0.0.0-stage → 0.13.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.
- 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 +6167 -0
- package/host-builder/data/errors.json +546 -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 +252 -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 +317 -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 +64 -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,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Prism agent as the builder of a host: it works on a host project the way a coding agent does, using the
|
|
3
|
+
* `prism-host-builder` kit (plan 215 Task 19).
|
|
4
|
+
*
|
|
5
|
+
* 1. `prism-host-builder install --target prism` copies the skill into the project's `.agents/skills`.
|
|
6
|
+
* 2. `contextFiles` discovers that skill, `tools-coding` is rooted in the project, and `@arnilo/prism-extensions/mcp`
|
|
7
|
+
* connects `prism-host-builder mcp` over stdio. The host starts the server; no model output chooses its
|
|
8
|
+
* command, root or check targets.
|
|
9
|
+
* 3. A scripted turn loads the skill, looks up `createAgent` with `prism_api`, and runs the host's
|
|
10
|
+
* factory with `prism_inspect_host`.
|
|
11
|
+
*
|
|
12
|
+
* Mock provider, no credential, no network. Spawns one MCP server and, for the inspection, one check child.
|
|
13
|
+
* Run: timeout 180 bun examples/host-builder-agent.ts
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import assert from "node:assert/strict";
|
|
17
|
+
import { spawnSync } from "node:child_process";
|
|
18
|
+
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
|
19
|
+
import { createRequire } from "node:module";
|
|
20
|
+
import { tmpdir } from "node:os";
|
|
21
|
+
import { dirname, join, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
23
|
+
import { type AgentEvent, createAgent } from "@arnilo/prism";
|
|
24
|
+
import { mockProvider, providerDone, providerTextDelta, providerToolCall, toolCallContent } from "@arnilo/prism/testing";
|
|
25
|
+
import { contextFiles } from "@arnilo/prism-extensions/context-files";
|
|
26
|
+
import { mcp } from "@arnilo/prism-extensions/mcp";
|
|
27
|
+
import { toolsCoding } from "@arnilo/prism-tools/coding";
|
|
28
|
+
|
|
29
|
+
const SKILL = "prism-host-builder";
|
|
30
|
+
const SERVER_ID = "host-builder";
|
|
31
|
+
const FACTORY = `import { createAgent } from "@arnilo/prism";
|
|
32
|
+
import { mockProvider } from "@arnilo/prism/testing";
|
|
33
|
+
|
|
34
|
+
export async function createInspectionAgent() {
|
|
35
|
+
return createAgent({ model: { provider: "mock", model: "demo" }, packages: [mockProvider()] });
|
|
36
|
+
}
|
|
37
|
+
`;
|
|
38
|
+
|
|
39
|
+
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
40
|
+
// `bin/prism-host-builder.ts` is what `bunx prism-host-builder` runs; the example calls it through the package.
|
|
41
|
+
const binEntry = fileURLToPath(
|
|
42
|
+
new URL("../bin/prism-host-builder.ts", pathToFileURL(createRequire(import.meta.url).resolve("@arnilo/prism-hosts/host-builder"))),
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
/** The text a finished tool call returned (a blocked call returns its reason). */
|
|
46
|
+
function textOf(event: AgentEvent): string {
|
|
47
|
+
if (event.type !== "tool.completed") return "";
|
|
48
|
+
const content = (event.result as { content?: Array<{ type: string; text?: string }> } | undefined)?.content;
|
|
49
|
+
return content?.map((block) => block.text ?? "").join("") ?? event.reason ?? "";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
53
|
+
const root = await mkdtemp(join(tmpdir(), "prism-host-builder-agent-"));
|
|
54
|
+
try {
|
|
55
|
+
// The host project the builder works on: a factory to inspect, and the kernel installed under node_modules
|
|
56
|
+
// (a symlink to this repository, where a real project has `bun add @arnilo/prism`).
|
|
57
|
+
await mkdir(join(root, "src"), { recursive: true });
|
|
58
|
+
await mkdir(join(root, "node_modules", "@arnilo"), { recursive: true });
|
|
59
|
+
await symlink(repo, join(root, "node_modules", "@arnilo", "prism"), "dir");
|
|
60
|
+
await writeFile(join(root, "package.json"), JSON.stringify({ name: "demo-host", private: true, type: "module" }));
|
|
61
|
+
await writeFile(join(root, "src", "agent.ts"), FACTORY);
|
|
62
|
+
|
|
63
|
+
// 1. Install the skill the way a user would. `--target prism` copies it into `.agents/skills`.
|
|
64
|
+
const install = spawnSync(process.execPath, [binEntry, "install", "--target", "prism", "--root", root], { encoding: "utf8" });
|
|
65
|
+
assert.equal(install.status, 0, `install exited ${install.status}\n${install.stderr}`);
|
|
66
|
+
|
|
67
|
+
// 2. The builder: coding tools in the project, skill discovery, and the MCP server over stdio.
|
|
68
|
+
const agent = await createAgent({
|
|
69
|
+
id: "host-builder-agent",
|
|
70
|
+
model: { provider: "mock", model: "demo" },
|
|
71
|
+
ownership: { tenantId: "local" },
|
|
72
|
+
principal: { kind: "user", id: "local" },
|
|
73
|
+
packages: [
|
|
74
|
+
mockProvider([
|
|
75
|
+
[providerToolCall(toolCallContent("call-1", "load_skill", { name: SKILL })), providerDone()],
|
|
76
|
+
[providerToolCall(toolCallContent("call-2", `mcp:${SERVER_ID}:prism_api`, { symbol: "createAgent" })), providerDone()],
|
|
77
|
+
[
|
|
78
|
+
providerToolCall(
|
|
79
|
+
toolCallContent("call-3", `mcp:${SERVER_ID}:prism_inspect_host`, { entry: "src/agent.ts#createInspectionAgent" }),
|
|
80
|
+
),
|
|
81
|
+
providerDone(),
|
|
82
|
+
],
|
|
83
|
+
[providerTextDelta("Looked up createAgent and inspected the host: it lists the mock provider only."), providerDone()],
|
|
84
|
+
]),
|
|
85
|
+
toolsCoding({ root }),
|
|
86
|
+
contextFiles({ root }),
|
|
87
|
+
mcp({
|
|
88
|
+
servers: [
|
|
89
|
+
{
|
|
90
|
+
id: SERVER_ID,
|
|
91
|
+
transport: "stdio",
|
|
92
|
+
command: process.execPath,
|
|
93
|
+
args: [binEntry, "mcp", "--root", root, "--entry", "src/agent.ts#createInspectionAgent"],
|
|
94
|
+
allow: "stdio",
|
|
95
|
+
connectTimeoutMs: 30_000,
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
}),
|
|
99
|
+
],
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
try {
|
|
103
|
+
const skillFound = agent.skills.some((skill) => skill.name === SKILL);
|
|
104
|
+
const toolNames = agent.tools.map((tool) => tool.name);
|
|
105
|
+
const session = await agent.session();
|
|
106
|
+
const events: AgentEvent[] = [];
|
|
107
|
+
for await (const event of session.stream("Look up createAgent, then inspect this host.")) events.push(event);
|
|
108
|
+
await session.close();
|
|
109
|
+
|
|
110
|
+
const results = new Map<string, string>();
|
|
111
|
+
for (const event of events) {
|
|
112
|
+
if (event.type === "tool.completed") results.set(event.result?.name ?? "", textOf(event));
|
|
113
|
+
}
|
|
114
|
+
const loaded = results.get("load_skill") ?? "";
|
|
115
|
+
const api = results.get(`mcp:${SERVER_ID}:prism_api`) ?? "";
|
|
116
|
+
const inspected = results.get(`mcp:${SERVER_ID}:prism_inspect_host`) ?? "";
|
|
117
|
+
|
|
118
|
+
assert.ok(skillFound, "contextFiles did not discover the installed skill");
|
|
119
|
+
assert.ok(
|
|
120
|
+
toolNames.includes("read") && toolNames.includes(`mcp:${SERVER_ID}:prism_api`),
|
|
121
|
+
"tools-coding or the MCP tools are missing",
|
|
122
|
+
);
|
|
123
|
+
assert.ok(loaded.includes("Building a Prism host"), `load_skill did not return the skill: ${loaded.slice(0, 200)}`);
|
|
124
|
+
const apiResult = JSON.parse(api) as { found: boolean; matches: Array<{ package: string; name: string; signature?: string }> };
|
|
125
|
+
const inspection = JSON.parse(inspected) as { ok: boolean; result?: { packages: Array<{ name: string }> } };
|
|
126
|
+
assert.ok(apiResult.found && apiResult.matches.some((match) => match.name === "createAgent"), `prism_api did not find createAgent`);
|
|
127
|
+
assert.ok(inspection.ok, `prism_inspect_host failed: ${inspected.slice(0, 200)}`);
|
|
128
|
+
|
|
129
|
+
return {
|
|
130
|
+
skillDiscovered: skillFound,
|
|
131
|
+
mcpTools: toolNames.filter((name) => name.startsWith(`mcp:${SERVER_ID}:`)).sort(),
|
|
132
|
+
skillLoaded: true,
|
|
133
|
+
createAgent: apiResult.matches.map((match) => `${match.package}: ${match.signature ?? match.name}`.slice(0, 120)),
|
|
134
|
+
inspectedPackages: inspection.result?.packages.map((entry) => entry.name),
|
|
135
|
+
};
|
|
136
|
+
} finally {
|
|
137
|
+
await agent.dispose();
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
await rm(root, { recursive: true, force: true });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function main(): Promise<void> {
|
|
145
|
+
console.log(JSON.stringify(await demo(), null, 2));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
149
|
+
await main();
|
|
150
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createAgent } from "@arnilo/prism";
|
|
2
|
+
import { mockProvider, providerDone, providerTextDelta, providerToolCall, toolCallContent } from "@arnilo/prism/testing";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Host hooks (roadmap §2.11): the host is an inline package, so `AgentConfig.hooks` registers on the same
|
|
6
|
+
* bus as any package. Three of them: a `tool.call` deny on `network` effects, a `turn.before` budget stop,
|
|
7
|
+
* and a `disable` of one tool. `agent.inspect().hooks` lists every registration in execution order.
|
|
8
|
+
* Imports only `@arnilo/prism` and `@arnilo/prism/testing`. Network-free.
|
|
9
|
+
* Run: npm run build:core && node examples/host-hooks.ts
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const allowNetwork = false;
|
|
13
|
+
|
|
14
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
15
|
+
const executed: string[] = [];
|
|
16
|
+
const tool = (name: string, effects: readonly ("read" | "write" | "execute" | "network" | "external")[]) => ({
|
|
17
|
+
name,
|
|
18
|
+
description: `${name} tool`,
|
|
19
|
+
parameters: {},
|
|
20
|
+
effects,
|
|
21
|
+
execute: (_args: unknown, context: { readonly toolCallId: string }) => {
|
|
22
|
+
executed.push(name);
|
|
23
|
+
return { toolCallId: context.toolCallId, name, value: "ran" };
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// Turn 1: the model calls the network tool and a local read. Turn 2 would answer, but the budget stops the run first.
|
|
28
|
+
const agent = await createAgent({
|
|
29
|
+
id: "host-hooks",
|
|
30
|
+
model: { provider: "mock", model: "demo" },
|
|
31
|
+
packages: [
|
|
32
|
+
mockProvider([
|
|
33
|
+
[
|
|
34
|
+
providerToolCall(toolCallContent("net-1", "fetch_url", { url: "https://example.com" })),
|
|
35
|
+
providerToolCall(toolCallContent("read-1", "read_file", { path: "README.md" })),
|
|
36
|
+
providerDone(),
|
|
37
|
+
],
|
|
38
|
+
[providerTextDelta("never reached"), providerDone()],
|
|
39
|
+
]),
|
|
40
|
+
],
|
|
41
|
+
tools: { add: [tool("fetch_url", ["network"]), tool("read_file", ["read"]), tool("shell", ["execute"])] },
|
|
42
|
+
// One tool switched off by id, whoever registered it.
|
|
43
|
+
disable: { tools: ["shell"] },
|
|
44
|
+
hooks: (hooks) => {
|
|
45
|
+
hooks.on("tool.call", (call) => (call.effects.includes("network") && !allowNetwork ? { deny: "network disabled" } : undefined), {
|
|
46
|
+
id: "no-network",
|
|
47
|
+
});
|
|
48
|
+
hooks.on("turn.before", (turn) => (turn.turn > 1 ? { stop: "turn budget spent" } : undefined), { id: "turn-budget" });
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const result = await (await agent.session()).run("fetch and read");
|
|
53
|
+
// Every registration in execution order, per hook name (the host's and the kernel's own).
|
|
54
|
+
const hooks = Object.fromEntries(Object.entries(agent.inspect().hooks).map(([name, list]) => [name, list.map((entry) => entry.id)]));
|
|
55
|
+
const tools = agent.tools.map((entry) => entry.name);
|
|
56
|
+
await agent.dispose();
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
status: result.status,
|
|
60
|
+
stopReason: result.stopReason,
|
|
61
|
+
stopDetail: result.stopDetail,
|
|
62
|
+
executed,
|
|
63
|
+
denied: result.messages
|
|
64
|
+
.flatMap((message) => message.content)
|
|
65
|
+
.filter((block) => block.type === "tool_result" && block.error !== undefined).length,
|
|
66
|
+
tools,
|
|
67
|
+
hooks,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host step-loop timeline correlation composition (plan 122 Task 5).
|
|
3
|
+
*
|
|
4
|
+
* A host that owns an eight-step plan maps each of its own business identities
|
|
5
|
+
* (`stepId` / `actionId` / `attemptId`) onto the Prism `sessionId` / `runId` of the
|
|
6
|
+
* `session.run()` that performed it, and persists a metadata-only `ExecutionTimeline`
|
|
7
|
+
* per step into a newline-delimited JSON ledger file.
|
|
8
|
+
*
|
|
9
|
+
* The projection is incremental: one `createTimelineFolder` per step receives the live
|
|
10
|
+
* events as they stream (`folder.push`), and a single `snapshot()` at run end yields that
|
|
11
|
+
* step's frozen timeline — no re-folding of a stored event list.
|
|
12
|
+
*
|
|
13
|
+
* The host's legacy 480-character prose trace is carried beside the structural timeline
|
|
14
|
+
* as display-only data (`legacyTrace480`). Nothing reads it back: budgets, turns and stop
|
|
15
|
+
* reasons come from the typed projection, never from parsing prose.
|
|
16
|
+
*
|
|
17
|
+
* External commit/verification evidence is host authority, not a Prism effect, so it is
|
|
18
|
+
* attached at the ledger envelopes's top level (`externalEvidence`, `inPrismEffects: false`)
|
|
19
|
+
* and never injected as a fake timeline step.
|
|
20
|
+
*
|
|
21
|
+
* `content: "metadata"` is the default: kinds, names, statuses, timings, usage and error
|
|
22
|
+
* codes only. Tool arguments never reach the timeline; the ledger records a host-computed
|
|
23
|
+
* `sha256:` hash for correlation instead of the raw arguments.
|
|
24
|
+
*
|
|
25
|
+
* Correlation uses existing identities only: Prism events already carry `sessionId` and
|
|
26
|
+
* `runId`, so no core correlation field was added. Host ids have no Prism-side identity and
|
|
27
|
+
* live in the ledger envelope.
|
|
28
|
+
*
|
|
29
|
+
* Run: npm run build:core && node examples/host-step-loop-timeline.ts
|
|
30
|
+
*/
|
|
31
|
+
import { createHash } from "node:crypto";
|
|
32
|
+
import { appendFileSync, mkdtempSync, readFileSync } from "node:fs";
|
|
33
|
+
import { tmpdir } from "node:os";
|
|
34
|
+
import { join } from "node:path";
|
|
35
|
+
import {
|
|
36
|
+
type ModelProvider,
|
|
37
|
+
createAgent,
|
|
38
|
+
type JsonObject,
|
|
39
|
+
type ProviderEvent,
|
|
40
|
+
providerDone,
|
|
41
|
+
providerTextDelta,
|
|
42
|
+
providerToolCall,
|
|
43
|
+
providerUsage,
|
|
44
|
+
type ToolDefinition,
|
|
45
|
+
} from "@arnilo/prism";
|
|
46
|
+
import { createTimelineFolder } from "@arnilo/prism-extensions/observability";
|
|
47
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
48
|
+
|
|
49
|
+
const STEP_COUNT = 8;
|
|
50
|
+
const LEGACY_TRACE_BYTES = 480;
|
|
51
|
+
|
|
52
|
+
const lookupTool: ToolDefinition = {
|
|
53
|
+
name: "host_lookup",
|
|
54
|
+
description: "Look up a host record for the current step",
|
|
55
|
+
execute: async (args, context) => ({
|
|
56
|
+
toolCallId: context.toolCallId,
|
|
57
|
+
name: "host_lookup",
|
|
58
|
+
value: { found: true, recordId: String(args.recordId ?? "unknown") },
|
|
59
|
+
}),
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function textTurn(step: number): ProviderEvent[] {
|
|
63
|
+
return [providerTextDelta(`step ${step} complete`), providerUsage({ inputTokens: 10, outputTokens: 5, totalTokens: 15 }), providerDone()];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function toolTurn(step: number): ProviderEvent[] {
|
|
67
|
+
return [
|
|
68
|
+
providerToolCall({
|
|
69
|
+
type: "tool_call",
|
|
70
|
+
id: `call_step_${step}`,
|
|
71
|
+
name: "host_lookup",
|
|
72
|
+
arguments: { recordId: `rec-${step}`, amount: 1_250, apiKey: "sk-live-never-persist-this" },
|
|
73
|
+
}),
|
|
74
|
+
providerDone(),
|
|
75
|
+
];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function hashArguments(args: JsonObject): string {
|
|
79
|
+
return `sha256:${createHash("sha256").update(JSON.stringify(args)).digest("hex")}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function stepId(step: number): string {
|
|
83
|
+
return `step-${String(step).padStart(2, "0")}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Host-side prose trace in the legacy shape: truncated, lossy, display-only. */
|
|
87
|
+
function legacyTrace(step: number): string {
|
|
88
|
+
const prose = `host decision trace for ${stepId(step)}: ${"the host selected the next action and executed it; ".repeat(24)}`;
|
|
89
|
+
return prose.slice(0, LEGACY_TRACE_BYTES);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
93
|
+
const ledgerDir = mkdtempSync(join(tmpdir(), "prism-host-step-loop-"));
|
|
94
|
+
const ledgerPath = join(ledgerDir, "host-ledger.ndjson");
|
|
95
|
+
|
|
96
|
+
const turns: ProviderEvent[][] = [];
|
|
97
|
+
const provider: ModelProvider = {
|
|
98
|
+
id: "mock",
|
|
99
|
+
async *generate(): AsyncIterable<ProviderEvent> {
|
|
100
|
+
const events = turns.shift() ?? [providerTextDelta("fallback"), providerDone()];
|
|
101
|
+
for (const event of events) yield event;
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const agent = await createAgent({
|
|
106
|
+
id: "host-step-loop-agent",
|
|
107
|
+
model: { provider: "mock", model: "demo" },
|
|
108
|
+
packages: [providerPackage("test-provider", [provider])],
|
|
109
|
+
tools: { add: [lookupTool] },
|
|
110
|
+
});
|
|
111
|
+
const session = await agent.session({ id: "host-step-loop-session", create: true });
|
|
112
|
+
|
|
113
|
+
const records: Record<string, unknown>[] = [];
|
|
114
|
+
const stepSummaries: Record<string, unknown>[] = [];
|
|
115
|
+
|
|
116
|
+
for (let step = 1; step <= STEP_COUNT; step += 1) {
|
|
117
|
+
const usesTool = step === 4;
|
|
118
|
+
turns.length = 0;
|
|
119
|
+
turns.push(...(usesTool ? [toolTurn(step), textTurn(step)] : [textTurn(step)]));
|
|
120
|
+
|
|
121
|
+
const folder = createTimelineFolder({ content: "metadata" });
|
|
122
|
+
const toolCalls: { readonly id: string; readonly name: string; readonly argHash: string }[] = [];
|
|
123
|
+
let eventsPushed = 0;
|
|
124
|
+
|
|
125
|
+
// Subscribe *before* starting the run so the folder receives `run.started` too — the
|
|
126
|
+
// subscriber is registered synchronously, while `session.run` emits its first event before
|
|
127
|
+
// returning. Consume concurrently and drain after the run closes the subscriber.
|
|
128
|
+
const subscription = session.subscribe();
|
|
129
|
+
const consume = (async () => {
|
|
130
|
+
for await (const event of subscription) {
|
|
131
|
+
eventsPushed += 1;
|
|
132
|
+
folder.push(event);
|
|
133
|
+
if (event.type === "tool.started") {
|
|
134
|
+
toolCalls.push({ id: event.call.id, name: event.call.name, argHash: hashArguments(event.call.arguments) });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
})();
|
|
138
|
+
const result = await session.run(`Execute ${stepId(step)}`);
|
|
139
|
+
await consume;
|
|
140
|
+
|
|
141
|
+
const timeline = folder.snapshot();
|
|
142
|
+
const host = {
|
|
143
|
+
planId: "host-plan-157-demo",
|
|
144
|
+
step,
|
|
145
|
+
stepId: stepId(step),
|
|
146
|
+
actionId: `act-${stepId(step)}`,
|
|
147
|
+
attemptId: `att-${stepId(step)}-1`,
|
|
148
|
+
};
|
|
149
|
+
const legacyTrace480 = legacyTrace(step);
|
|
150
|
+
const record: Record<string, unknown> = {
|
|
151
|
+
ledgerVersion: 1,
|
|
152
|
+
recordedAt: new Date().toISOString(),
|
|
153
|
+
host,
|
|
154
|
+
prism: { sessionId: session.id, runId: result.runId, status: result.status },
|
|
155
|
+
projection: { mode: "incremental_folder", content: timeline.content, eventsPushed },
|
|
156
|
+
timeline,
|
|
157
|
+
toolCalls,
|
|
158
|
+
legacyTrace480,
|
|
159
|
+
...(step === STEP_COUNT
|
|
160
|
+
? {
|
|
161
|
+
externalEvidence: {
|
|
162
|
+
authority: "host",
|
|
163
|
+
kind: "commit_and_verification",
|
|
164
|
+
commitId: `commit_${stepId(step)}`,
|
|
165
|
+
verification: { status: "verified", method: "host-ledger-audit", verifiedAt: new Date().toISOString() },
|
|
166
|
+
inPrismEffects: false,
|
|
167
|
+
},
|
|
168
|
+
}
|
|
169
|
+
: {}),
|
|
170
|
+
};
|
|
171
|
+
records.push(record);
|
|
172
|
+
appendFileSync(ledgerPath, `${JSON.stringify(record)}\n`);
|
|
173
|
+
|
|
174
|
+
stepSummaries.push({
|
|
175
|
+
step,
|
|
176
|
+
stepId: host.stepId,
|
|
177
|
+
actionId: host.actionId,
|
|
178
|
+
attemptId: host.attemptId,
|
|
179
|
+
runId: result.runId,
|
|
180
|
+
sessionId: session.id,
|
|
181
|
+
status: result.status,
|
|
182
|
+
turnCount: timeline.turns?.length ?? 0,
|
|
183
|
+
stopReasons: timeline.turns?.map((turn) => turn.stopReason),
|
|
184
|
+
budgetRunInputUsed: timeline.turns?.map((turn) => turn.budgets?.runInputUsed),
|
|
185
|
+
toolSteps: timeline.steps.filter((entry) => entry.kind === "tool").length,
|
|
186
|
+
legacyTraceChars: legacyTrace480.length,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const ledgerLines = readFileSync(ledgerPath, "utf8").trim().split("\n").length;
|
|
191
|
+
return {
|
|
192
|
+
ledgerPath,
|
|
193
|
+
ledgerLines,
|
|
194
|
+
stepCount: STEP_COUNT,
|
|
195
|
+
projectionMode: "incremental_folder",
|
|
196
|
+
contentPolicy: "metadata",
|
|
197
|
+
prosePolicy: "legacyTrace480 is display-only; structural fields are the source of truth",
|
|
198
|
+
correlation: "host ids in ledger envelope; prism sessionId/runId come from the events themselves",
|
|
199
|
+
externalEvidenceStep: STEP_COUNT,
|
|
200
|
+
steps: stepSummaries,
|
|
201
|
+
recordCount: records.length,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export async function main(): Promise<void> {
|
|
206
|
+
const result = await demo();
|
|
207
|
+
console.log(JSON.stringify(result));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
211
|
+
await main();
|
|
212
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { connectE2BSandbox, createE2BSandbox, type E2BClient, type E2BSandboxInstance } from "@arnilo/prism-tools/coding";
|
|
2
|
+
|
|
3
|
+
const instance = (): E2BSandboxInstance => ({
|
|
4
|
+
sandboxId: "sbx_demo",
|
|
5
|
+
commands: {
|
|
6
|
+
async run(_cmd, opts) {
|
|
7
|
+
if (opts?.background) return { pid: 3, wait: async () => ({ exitCode: 0 }) };
|
|
8
|
+
return { exitCode: 0, stdout: "ok\n", stderr: "" };
|
|
9
|
+
},
|
|
10
|
+
async kill() {
|
|
11
|
+
return true;
|
|
12
|
+
},
|
|
13
|
+
},
|
|
14
|
+
async pause() {
|
|
15
|
+
return true;
|
|
16
|
+
},
|
|
17
|
+
async kill() {
|
|
18
|
+
return true;
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const client: E2BClient = {
|
|
23
|
+
Sandbox: {
|
|
24
|
+
create: async () => instance(),
|
|
25
|
+
connect: async () => instance(),
|
|
26
|
+
getInfo: async () => ({ sandboxId: "sbx_demo", state: "paused", metadata: { "app.owner": "demo" } }),
|
|
27
|
+
kill: async () => true,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const sandbox = await createE2BSandbox({ client, labels: { "app.owner": "demo" } });
|
|
32
|
+
await sandbox.execFile({ file: "/bin/echo", args: ["hello"], cwd: "/workspace" });
|
|
33
|
+
const paused = await sandbox.pause!({ keepMemory: false });
|
|
34
|
+
const reconnected = await connectE2BSandbox({
|
|
35
|
+
client,
|
|
36
|
+
sandboxId: sandbox.id,
|
|
37
|
+
expectedLabels: { "app.owner": "demo" },
|
|
38
|
+
});
|
|
39
|
+
await reconnected.kill();
|
|
40
|
+
|
|
41
|
+
console.log(
|
|
42
|
+
JSON.stringify({
|
|
43
|
+
id: sandbox.id,
|
|
44
|
+
pauseKind: paused.kind,
|
|
45
|
+
reconnectState: (await reconnected.status()).state,
|
|
46
|
+
autoResume: false,
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import type { ContextSource, ProviderRequest } from "@arnilo/prism";
|
|
4
|
+
import {
|
|
5
|
+
createAgent,
|
|
6
|
+
createPathTrustPolicy,
|
|
7
|
+
createSecretRedactor,
|
|
8
|
+
providerDone,
|
|
9
|
+
registerContextSources,
|
|
10
|
+
withContextBlocks,
|
|
11
|
+
} from "@arnilo/prism";
|
|
12
|
+
import { discoverContributions } from "@arnilo/prism/node/contribution-discovery";
|
|
13
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
14
|
+
import { createMockProvider } from "@arnilo/prism/testing";
|
|
15
|
+
import { resolveInstructionSources } from "@arnilo/prism-extensions/context-files";
|
|
16
|
+
|
|
17
|
+
// Instruction injection, end-to-end with the mock provider.
|
|
18
|
+
//
|
|
19
|
+
// Instruction injectors and context providers are both `context.build` handlers now
|
|
20
|
+
// (roadmap §2.4), so this shows the whole shape: a discovered
|
|
21
|
+
// `.agents/instructions/<name>/` bundle loaded as a static source, an always-on
|
|
22
|
+
// source, a source that reacts to the user's input, and a source that accidentally
|
|
23
|
+
// emits a secret — which the runtime redactor strips before the provider sees it.
|
|
24
|
+
// Network-free; no real credentials.
|
|
25
|
+
|
|
26
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
const workspaceRoot = join(here, "instruction-injection-workspace");
|
|
28
|
+
|
|
29
|
+
// Always-on project context.
|
|
30
|
+
const projectContext: ContextSource = {
|
|
31
|
+
name: "project-context",
|
|
32
|
+
contextBlocks: [{ title: "Repo", content: "Prism monorepo — see docs/." }],
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
// A redaction demo source that accidentally emits a secret in its text.
|
|
36
|
+
// The runtime's redactor strips it from the ProviderRequest (backstop, not
|
|
37
|
+
// an invitation — never author secrets into context-source text).
|
|
38
|
+
const SECRET = "phase30-example-token-xyz";
|
|
39
|
+
const leakySource: ContextSource = { name: "leaky", instructions: `auth token=${SECRET}` };
|
|
40
|
+
|
|
41
|
+
export async function demo(): Promise<{
|
|
42
|
+
discoveredSource: string | undefined;
|
|
43
|
+
everyTurnInstructionInInput: boolean;
|
|
44
|
+
firstTurnContextBlockInInput: boolean;
|
|
45
|
+
onInputInjectorApplied: boolean;
|
|
46
|
+
injectedSecretRedacted: boolean;
|
|
47
|
+
}> {
|
|
48
|
+
// 1. Discover: scan <workspace>/.agents/instructions/<name>/manifest.json.
|
|
49
|
+
const trust = createPathTrustPolicy({ trustedRoots: [workspaceRoot] });
|
|
50
|
+
const discovered = await discoverContributions({
|
|
51
|
+
kinds: ["instructions"],
|
|
52
|
+
workspaceRoot,
|
|
53
|
+
trust,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// 2. Load: markdown-only (no `module` field) becomes a static source reading the
|
|
57
|
+
// resource text, trust-gated by the same policy. Core never `import()`s.
|
|
58
|
+
const discoveredSources = await resolveInstructionSources(discovered, { resourceTrust: trust });
|
|
59
|
+
const selected = discoveredSources.filter((source) => source.name === "json-always");
|
|
60
|
+
const discoveredSource = selected[0];
|
|
61
|
+
|
|
62
|
+
// 3. Run: mock provider captures the assembled request so we can prove the
|
|
63
|
+
// context-source instructions/blocks reached the model request. The runtime
|
|
64
|
+
// redactor (configured on the agent) strips the leaky source's secret
|
|
65
|
+
// before the provider is called.
|
|
66
|
+
const captured: ProviderRequest[] = [];
|
|
67
|
+
const provider = createMockProvider([providerDone()], {
|
|
68
|
+
onRequest: (request) => {
|
|
69
|
+
captured.push(request);
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
const session = await (
|
|
73
|
+
await createAgent({
|
|
74
|
+
model: { provider: "mock", model: "demo" },
|
|
75
|
+
packages: [providerPackage("test-provider", [provider])],
|
|
76
|
+
instructions: "You are helpful.",
|
|
77
|
+
// ponytail: runtime redacts ProviderRequest before the provider is called;
|
|
78
|
+
// this is the backstop that strips the leaked secret from source text.
|
|
79
|
+
redactor: createSecretRedactor([SECRET]),
|
|
80
|
+
hooks: (hooks) => {
|
|
81
|
+
registerContextSources(hooks, [...selected, projectContext, leakySource]);
|
|
82
|
+
// A handler can branch on the turn's transcript, which is what the retired
|
|
83
|
+
// `on_input` predicate did.
|
|
84
|
+
hooks.on(
|
|
85
|
+
"context.build",
|
|
86
|
+
(draft) => {
|
|
87
|
+
const asked = draft.messages.some((message) => /json/i.test(JSON.stringify(message.content)));
|
|
88
|
+
return asked
|
|
89
|
+
? withContextBlocks(draft, [{ title: "Format", content: "Reply with JSON because the user asked for JSON." }])
|
|
90
|
+
: undefined;
|
|
91
|
+
},
|
|
92
|
+
{ id: "json-on-json-input" },
|
|
93
|
+
);
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
).session();
|
|
97
|
+
|
|
98
|
+
// Fire run() (resolves into closeSubscribers) and drain the event stream.
|
|
99
|
+
const done = session.run("List primes. Respond in JSON.");
|
|
100
|
+
for await (const _event of session.subscribe()) {
|
|
101
|
+
void _event;
|
|
102
|
+
}
|
|
103
|
+
await done;
|
|
104
|
+
|
|
105
|
+
// captured[0] is already redacted by the runtime — the provider never sees SECRET.
|
|
106
|
+
const inputJson = JSON.stringify(captured[0]);
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
discoveredSource: discoveredSource?.name,
|
|
110
|
+
everyTurnInstructionInInput: /Always structure the final answer as a single JSON object/.test(inputJson),
|
|
111
|
+
firstTurnContextBlockInInput: /Prism monorepo — see docs\//.test(inputJson),
|
|
112
|
+
// The transcript branch matched because the user said "JSON".
|
|
113
|
+
onInputInjectorApplied: /Reply with JSON because the user asked for JSON/.test(inputJson),
|
|
114
|
+
// Runtime redacted the leaky source's secret before the provider call.
|
|
115
|
+
injectedSecretRedacted: !inputJson.includes(SECRET),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Runnable smoke test: `node examples/instruction-injection.ts`. Network-free.
|
|
120
|
+
export async function main(): Promise<void> {
|
|
121
|
+
const result = await demo();
|
|
122
|
+
console.log(JSON.stringify(result));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
126
|
+
await main();
|
|
127
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
createMemorySessionStore,
|
|
5
|
+
createSessionEntry,
|
|
6
|
+
getSessionBranchEntries,
|
|
7
|
+
listSessionBranches,
|
|
8
|
+
rebuildSessionContext,
|
|
9
|
+
} from "@arnilo/prism";
|
|
10
|
+
import { createJsonlSessionStore } from "@arnilo/prism-extensions/store-jsonl";
|
|
11
|
+
|
|
12
|
+
// In-memory store + branching; JSONL persistence via the Node subpath.
|
|
13
|
+
// Stores receive no provider credentials. Branching preserves old paths.
|
|
14
|
+
export async function demo() {
|
|
15
|
+
const store = createMemorySessionStore();
|
|
16
|
+
const sessionId = "s1";
|
|
17
|
+
|
|
18
|
+
const root = createSessionEntry({
|
|
19
|
+
sessionId,
|
|
20
|
+
kind: "message",
|
|
21
|
+
parentId: undefined,
|
|
22
|
+
message: { role: "user", content: [{ type: "text", text: "Hi" }] },
|
|
23
|
+
});
|
|
24
|
+
const leaf = createSessionEntry({
|
|
25
|
+
sessionId,
|
|
26
|
+
kind: "message",
|
|
27
|
+
parentId: root.id,
|
|
28
|
+
message: { role: "assistant", content: [{ type: "text", text: "Hello" }] },
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
await store.append(root);
|
|
32
|
+
await store.append(leaf);
|
|
33
|
+
|
|
34
|
+
const entries = await store.list(sessionId);
|
|
35
|
+
const branches = listSessionBranches(entries);
|
|
36
|
+
const snapshot = rebuildSessionContext(entries);
|
|
37
|
+
|
|
38
|
+
// JSONL persistence (caller-named file, host-controlled).
|
|
39
|
+
const dir = join(tmpdir(), `prism-demo-${Date.now()}`);
|
|
40
|
+
const jsonl = createJsonlSessionStore({ dir });
|
|
41
|
+
await jsonl.append(root);
|
|
42
|
+
|
|
43
|
+
return {
|
|
44
|
+
branchCount: branches.length,
|
|
45
|
+
leafId: snapshot.leafId,
|
|
46
|
+
branchEntryCount: getSessionBranchEntries(entries).length,
|
|
47
|
+
jsonlRootId: (await jsonl.list(sessionId))[0]?.id,
|
|
48
|
+
};
|
|
49
|
+
}
|