@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,55 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createAgent,
|
|
3
|
+
createSecretRedactor,
|
|
4
|
+
createStaticTrustPolicy,
|
|
5
|
+
createToolParameterValidator,
|
|
6
|
+
type JsonSchema,
|
|
7
|
+
providerDone,
|
|
8
|
+
providerTextDelta,
|
|
9
|
+
validateJsonSchema,
|
|
10
|
+
} from "@arnilo/prism";
|
|
11
|
+
import { mockProvider } from "@arnilo/prism/testing";
|
|
12
|
+
import governance from "@arnilo/prism-extensions/governance";
|
|
13
|
+
|
|
14
|
+
// Network-free secure baseline (plan 159 Task 7). `createSecureAgent` is gone; the same guarantees
|
|
15
|
+
// are explicit `AgentConfig` fields plus `governance({ require: { principal, ownership } })`, which
|
|
16
|
+
// fails a run closed when the session has no principal. A deny-by-default policy admits only the
|
|
17
|
+
// listed tool, so a tool call suspends/denies before any side effect.
|
|
18
|
+
export async function demo() {
|
|
19
|
+
const agent = await createAgent({
|
|
20
|
+
id: "secure-demo",
|
|
21
|
+
model: { provider: "mock", model: "demo" },
|
|
22
|
+
principal: { kind: "user", id: "operator" },
|
|
23
|
+
ownership: { tenantId: "demo", userId: "operator" },
|
|
24
|
+
redactor: createSecretRedactor(["fake-secret"]),
|
|
25
|
+
trust: createStaticTrustPolicy(true),
|
|
26
|
+
validator: createToolParameterValidator(
|
|
27
|
+
{
|
|
28
|
+
validate(schema: JsonSchema, value: unknown) {
|
|
29
|
+
const result = validateJsonSchema(schema, value);
|
|
30
|
+
return result.ok ? { ok: true } : { ok: false, errors: result.errors };
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
{ missingSchema: "reject" },
|
|
34
|
+
),
|
|
35
|
+
limits: { maxTurns: 2, maxToolCalls: 1 },
|
|
36
|
+
tools: {
|
|
37
|
+
add: [
|
|
38
|
+
{
|
|
39
|
+
name: "notes/read",
|
|
40
|
+
parameters: { type: "object" },
|
|
41
|
+
execute: (_args, context) => ({ toolCallId: context.toolCallId, name: "notes/read", value: "ok" }),
|
|
42
|
+
},
|
|
43
|
+
],
|
|
44
|
+
},
|
|
45
|
+
packages: [
|
|
46
|
+
mockProvider([[providerTextDelta("safe"), providerDone()]]),
|
|
47
|
+
governance({
|
|
48
|
+
default: "deny",
|
|
49
|
+
rules: [{ tools: ["notes/read"], outcome: "allow" }],
|
|
50
|
+
require: { principal: true, ownership: true },
|
|
51
|
+
}),
|
|
52
|
+
],
|
|
53
|
+
});
|
|
54
|
+
return (await agent.session()).run("hello");
|
|
55
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Semantic memory with a hash embedder: remember, recall with adjacent entries, and context injection.
|
|
2
|
+
// Long-term working memory was retired in 0.13.0 (plan 216 Task 7); the memory system's WM component replaces it.
|
|
3
|
+
import { createAgent, providerDone, providerTextDelta } from "@arnilo/prism";
|
|
4
|
+
import { createHashEmbedder } from "@arnilo/prism-memory-system/core";
|
|
5
|
+
import { createMemory } from "@arnilo/prism-memory-system";
|
|
6
|
+
import { mockProvider } from "@arnilo/prism/testing";
|
|
7
|
+
|
|
8
|
+
const memory = createMemory({
|
|
9
|
+
tenantId: "demo",
|
|
10
|
+
resourceId: "user-ada",
|
|
11
|
+
threadId: "thread-1",
|
|
12
|
+
embedder: createHashEmbedder({ dimensions: 32 }),
|
|
13
|
+
secrets: ["DEMO_SECRET_VALUE"],
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
await memory.remember(
|
|
17
|
+
{
|
|
18
|
+
entries: [
|
|
19
|
+
{ id: "m1", text: "Prefers concise answers", sequence: 1 },
|
|
20
|
+
{ id: "m2", text: "Lives in Lisbon", sequence: 2 },
|
|
21
|
+
],
|
|
22
|
+
},
|
|
23
|
+
{ wait: true },
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const recalled = await memory.recall("concise answers", { topK: 2, messageRange: 1 });
|
|
27
|
+
console.log(
|
|
28
|
+
"recall",
|
|
29
|
+
recalled.hits.map((hit) => hit.id),
|
|
30
|
+
"adjacent",
|
|
31
|
+
recalled.adjacent.map((item) => item.id),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
// The same projection the agent's `context.build` handler runs, called directly here.
|
|
35
|
+
const draft = await memory.contextBlocks(
|
|
36
|
+
{ messages: [{ role: "user", content: [{ type: "text", text: "Do I prefer concise answers?" }] }] },
|
|
37
|
+
{ sessionId: "s", runId: "r", emit: () => undefined, reject: () => ({ __prismHookRejection: "x" }) },
|
|
38
|
+
{ includeSemantic: true },
|
|
39
|
+
);
|
|
40
|
+
console.log(
|
|
41
|
+
"context blocks",
|
|
42
|
+
(draft?.messages.at(-1)?.metadata?.contextBlocks as { title?: string }[] | undefined)?.map((block) => block.title) ?? [],
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
const agent = await createAgent({
|
|
46
|
+
model: { provider: "mock", model: "demo" },
|
|
47
|
+
packages: [mockProvider([[providerTextDelta("Understood."), providerDone()]])],
|
|
48
|
+
hooks: (hooks) => memory.registerContextBuild(hooks, { includeSemantic: true }),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const result = await (await agent.session()).run("Remind me how to format answers");
|
|
52
|
+
console.log("agent", result.text);
|
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 14 end to end, offline: serving a run's tools to an external agent's own loop.
|
|
3
|
+
*
|
|
4
|
+
* The driver below is the template an adapter author copies for Phase 15. It names no vendor. It runs inside one
|
|
5
|
+
* `session.run` and, for that run's session, it:
|
|
6
|
+
* - binds a git worktree through the `workspace` service, and materializes the vendor's MCP configuration into
|
|
7
|
+
* that worktree with `excludeOverlay`, so the file is git-excluded and never reaches a diff or a commit
|
|
8
|
+
* - serves `read` and `edit` from `@arnilo/prism-tools/coding`, plus the permission tool, with `serveTools`,
|
|
9
|
+
* and lends the one skill those two tools satisfy (a small host skill the example writes, `edit-notes`) as an MCP resource with `skillResources`
|
|
10
|
+
* - runs the vendor binary (the scripted CLI from `@arnilo/prism/testing`, `jsonl-stream` dialect) over
|
|
11
|
+
* `loopback-http` first and `stdio-relay` second, handing it the endpoint as `--mcp-endpoint`
|
|
12
|
+
* - closes the served handle and runs the vendor again, to show a call after `close()` is refused
|
|
13
|
+
* The run shows, in order:
|
|
14
|
+
* - an allowed `edit`, which changes the file in the worktree because the session is bound to it (Task 7)
|
|
15
|
+
* - a declined `edit` under `@arnilo/prism-extensions/approval` in `ask` mode, whose deny text reaches the vendor
|
|
16
|
+
* - the permission tool's deny and allow, each one `run.ask` that never executes anything
|
|
17
|
+
* - a tool outside the allow list, which the vendor cannot see
|
|
18
|
+
* - the worktree diff, which lists the edit and not the overlay, and a conflicting merge, reported unresolved
|
|
19
|
+
* Imports only `@arnilo/prism`, `@arnilo/prism/driver-kit`, `@arnilo/prism/testing`, `@arnilo/prism-hosts/mcp-server`,
|
|
20
|
+
* `@arnilo/prism-tools/coding`, `@arnilo/prism-extensions/approval`, and Node built-ins.
|
|
21
|
+
* Run: npm run build:core && bun examples/serve-tools.ts
|
|
22
|
+
*/
|
|
23
|
+
import { type ChildProcessWithoutNullStreams, spawn, spawnSync } from "node:child_process";
|
|
24
|
+
import { randomUUID } from "node:crypto";
|
|
25
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { tmpdir } from "node:os";
|
|
27
|
+
import { join, resolve } from "node:path";
|
|
28
|
+
import { createInterface } from "node:readline";
|
|
29
|
+
import { pathToFileURL } from "node:url";
|
|
30
|
+
import {
|
|
31
|
+
type AgentEvent,
|
|
32
|
+
createAgent,
|
|
33
|
+
createMemorySessionStore,
|
|
34
|
+
definePackage,
|
|
35
|
+
type EventOrigin,
|
|
36
|
+
type JsonValue,
|
|
37
|
+
type PackageInstance,
|
|
38
|
+
type RunController,
|
|
39
|
+
} from "@arnilo/prism";
|
|
40
|
+
import {
|
|
41
|
+
buildChildEnv,
|
|
42
|
+
createCallbackBroker,
|
|
43
|
+
createProfiles,
|
|
44
|
+
createRunDirectory,
|
|
45
|
+
type DriverBinary,
|
|
46
|
+
type DriverRunContext,
|
|
47
|
+
defineDriver,
|
|
48
|
+
driverPackage,
|
|
49
|
+
type HookCodec,
|
|
50
|
+
type McpEndpoint,
|
|
51
|
+
relayCommand,
|
|
52
|
+
signalLadder,
|
|
53
|
+
} from "@arnilo/prism/driver-kit";
|
|
54
|
+
import {
|
|
55
|
+
createScriptedCli,
|
|
56
|
+
createScriptedHostUi,
|
|
57
|
+
jsonlStreamDialect,
|
|
58
|
+
type ScriptedCli,
|
|
59
|
+
type ScriptedRecordEntry,
|
|
60
|
+
type ScriptStep,
|
|
61
|
+
} from "@arnilo/prism/testing";
|
|
62
|
+
import approval from "@arnilo/prism-extensions/approval";
|
|
63
|
+
import { type ServeToolsTransport, serveTools, skillResources } from "@arnilo/prism-hosts/mcp-server";
|
|
64
|
+
import toolsCoding, { type WorkspaceService } from "@arnilo/prism-tools/coding";
|
|
65
|
+
|
|
66
|
+
/** The vendor's MCP configuration, written into the worktree and excluded from git. */
|
|
67
|
+
const MCP_CONFIG = ".mcp.json";
|
|
68
|
+
/** The tracked file the vendor edits. The driver re-seeds it per leg, so both legs start from the same worktree. */
|
|
69
|
+
const EDITED_FILE = "a.txt";
|
|
70
|
+
/** The tools lent to the vendor. A skill is lent with them only when everything it `requiresTools` is in this list. */
|
|
71
|
+
const SERVED_TOOLS = ["read", "edit"];
|
|
72
|
+
/** The origin every served call is attributed to; it rides each `tool.*` event the call emits. */
|
|
73
|
+
const ORIGIN: EventOrigin = { kind: "external", agent: "vendor-loop", agentId: "vendor-loop", vendor: "example", depth: 0 };
|
|
74
|
+
/** The broker's answer when a relay frame arrives and the route cannot: the vendor must not proceed. */
|
|
75
|
+
const FAIL_CLOSED = { exitCode: 2, stdout: '{"allow":false,"message":"prism relay is unavailable"}' };
|
|
76
|
+
/** This vendor gates through the served permission tool, not the relay, so no hook frame is expected. */
|
|
77
|
+
const NO_HOOKS: HookCodec = { decode: () => ({ kind: "stop" }), encode: () => FAIL_CLOSED };
|
|
78
|
+
/** A stable identity for git in the fixture, so no user-level configuration is read. */
|
|
79
|
+
const GIT_ENV = { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
|
|
80
|
+
|
|
81
|
+
type Agent = Awaited<ReturnType<typeof createAgent>>;
|
|
82
|
+
|
|
83
|
+
interface DriverConfig {
|
|
84
|
+
/** The driver's own config keys. The spec never carries them. */
|
|
85
|
+
readonly binary: string;
|
|
86
|
+
readonly args?: readonly string[];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** What the vendor's own loop asks the served tools to do, in order. */
|
|
90
|
+
const VENDOR_SCRIPT: readonly ScriptStep[] = [
|
|
91
|
+
// What the vendor can see: the allow list in order, then the permission tool.
|
|
92
|
+
{ mcp: { method: "tools/list" } },
|
|
93
|
+
// An allowed edit. `@arnilo/prism-extensions/approval` asks the host; the host approves once, and the file changes.
|
|
94
|
+
{ mcp: { method: "tools/call", params: { name: "edit", arguments: { path: "a.txt", edits: [{ oldText: "one", newText: "served" }] } } } },
|
|
95
|
+
// A read is allowed without a prompt, so it costs no host request.
|
|
96
|
+
{ mcp: { method: "tools/call", params: { name: "read", arguments: { path: "a.txt" } } } },
|
|
97
|
+
// A declined edit: the host says no, and the deny text reaches the vendor as the tool result.
|
|
98
|
+
{
|
|
99
|
+
mcp: { method: "tools/call", params: { name: "edit", arguments: { path: "a.txt", edits: [{ oldText: "served", newText: "again" }] } } },
|
|
100
|
+
},
|
|
101
|
+
// The permission tool: the vendor asks, Prism decides through the same gate, and nothing is executed.
|
|
102
|
+
{ mcp: { method: "tools/call", params: { name: "permission", arguments: { toolName: "shell", input: { command: "cat secrets" } } } } },
|
|
103
|
+
{ mcp: { method: "tools/call", params: { name: "permission", arguments: { toolName: "shell", input: { command: "ls" } } } } },
|
|
104
|
+
// A tool outside the allow list is not served at all, so the call is a JSON-RPC error.
|
|
105
|
+
{ mcp: { method: "tools/call", params: { name: "delete", arguments: { path: "a.txt" } } } },
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
/** The driver's descriptor: what the vendor can enforce and capture. The kit checks `requires` against it. */
|
|
109
|
+
const descriptor = {
|
|
110
|
+
vendor: "example",
|
|
111
|
+
usesModel: false as const,
|
|
112
|
+
models: "passthrough" as const,
|
|
113
|
+
controls: {
|
|
114
|
+
systemPrompt: [] as readonly ("replace" | "append")[],
|
|
115
|
+
builtinTools: "none" as const,
|
|
116
|
+
clientTools: "mcp" as const,
|
|
117
|
+
skills: false,
|
|
118
|
+
subagents: false,
|
|
119
|
+
permissionCallback: true,
|
|
120
|
+
rewrite: false,
|
|
121
|
+
continueOnStop: false,
|
|
122
|
+
steer: "none" as const,
|
|
123
|
+
resume: "none" as const,
|
|
124
|
+
isolation: "none" as const,
|
|
125
|
+
},
|
|
126
|
+
capture: {
|
|
127
|
+
textDeltas: false,
|
|
128
|
+
thinking: "none" as const,
|
|
129
|
+
skillActivation: "none" as const,
|
|
130
|
+
toolCalls: true,
|
|
131
|
+
fileDiffs: false,
|
|
132
|
+
subagents: "none" as const,
|
|
133
|
+
usage: "none" as const,
|
|
134
|
+
},
|
|
135
|
+
auth: {
|
|
136
|
+
// A key mode needs no sign-in, so the example runs offline with no account and no terminal request.
|
|
137
|
+
modes: [{ name: "key", kind: "api-key" as const, deployments: ["local" as const], protected: { paths: [], env: [] } }],
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** One served leg, as the example reports it. `env` holds the bearer token's *name*, never its value. */
|
|
142
|
+
interface ServedLeg {
|
|
143
|
+
readonly transport: ServeToolsTransport;
|
|
144
|
+
readonly tools: readonly string[];
|
|
145
|
+
readonly env: Readonly<Record<string, string>>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** What the driver learned about the worktree, the diff, and the merge, for the example's output. */
|
|
149
|
+
interface Evidence {
|
|
150
|
+
readonly served: ServedLeg[];
|
|
151
|
+
worktree?: { readonly path: string; readonly branch: string; readonly base: string };
|
|
152
|
+
overlay?: { readonly path: string; readonly excluded: boolean };
|
|
153
|
+
diff?: { readonly changes: readonly string[]; readonly truncated: boolean };
|
|
154
|
+
merge?: { readonly status: string; readonly files: readonly string[]; readonly worktreeUnchanged: boolean };
|
|
155
|
+
worktreeFile?: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** What the driver needs from the example: the package's service, the repository, and where to report. */
|
|
159
|
+
interface DriverDeps {
|
|
160
|
+
readonly workspace: () => WorkspaceService | undefined;
|
|
161
|
+
readonly repo: string;
|
|
162
|
+
readonly evidence: Evidence;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The driver: a config schema, a status parser, and `start`, which probes the binary and serves it tools. */
|
|
166
|
+
export function exampleDriver(deps: DriverDeps) {
|
|
167
|
+
return defineDriver<DriverConfig>({
|
|
168
|
+
name: "serve-tools-example",
|
|
169
|
+
vendor: "example",
|
|
170
|
+
revision: "1",
|
|
171
|
+
descriptor,
|
|
172
|
+
config: {
|
|
173
|
+
type: "object",
|
|
174
|
+
properties: { binary: { type: "string", minLength: 1 }, args: { type: "array", items: { type: "string" } } },
|
|
175
|
+
required: ["binary"],
|
|
176
|
+
},
|
|
177
|
+
parseStatus: () => ({ signedIn: true }),
|
|
178
|
+
start: {
|
|
179
|
+
probe: async (config) => ({ path: config.binary, version: "1.0.0" }),
|
|
180
|
+
run: (context) => runAdapter(context, deps),
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** One run: a run directory, a callback broker, one bound worktree, and two served legs, closed in `finally`. */
|
|
186
|
+
async function runAdapter(context: DriverRunContext<DriverConfig>, deps: DriverDeps): Promise<void> {
|
|
187
|
+
const { run, lease, binary, config } = context;
|
|
188
|
+
if (lease === undefined) throw new Error("the example driver needs a profile lease");
|
|
189
|
+
const workspace = deps.workspace();
|
|
190
|
+
if (workspace === undefined) throw new Error("no workspace service: the package root must be inside a git repository");
|
|
191
|
+
// The run directory holds the relay socket, so keep its name short (a Unix socket path must fit in 103 bytes).
|
|
192
|
+
const runDir = await createRunDirectory(lease.home, randomUUID().slice(0, 8));
|
|
193
|
+
try {
|
|
194
|
+
const broker = await createCallbackBroker(run, { runDir: runDir.path, hookCodec: NO_HOOKS, failClosed: FAIL_CLOSED, timeoutMs: 5000 });
|
|
195
|
+
try {
|
|
196
|
+
// One worktree for this run's session. Task 7's routing makes this session's coding tools run inside it.
|
|
197
|
+
const worktree = await workspace.worktree.create({ sessionId: run.session.id });
|
|
198
|
+
deps.evidence.worktree = { path: worktree.path, branch: worktree.branch, base: worktree.base };
|
|
199
|
+
try {
|
|
200
|
+
// Both legs must start from the same worktree, so each one re-seeds the file the vendor edits.
|
|
201
|
+
const seed = readFileSync(join(worktree.path, EDITED_FILE), "utf8");
|
|
202
|
+
for (const transport of ["loopback-http", "stdio-relay"] as const) {
|
|
203
|
+
writeFileSync(join(worktree.path, EDITED_FILE), seed);
|
|
204
|
+
const served = await serveTools(run, {
|
|
205
|
+
broker,
|
|
206
|
+
// The definitions are the agent's own registered tools; only the allow list is exposed.
|
|
207
|
+
tools: context.tools,
|
|
208
|
+
allow: SERVED_TOOLS,
|
|
209
|
+
transport,
|
|
210
|
+
origin: ORIGIN,
|
|
211
|
+
permissionTool: { name: "permission" },
|
|
212
|
+
// `edit-notes` requires `read edit`, so the vendor can read it as `prism-skill://edit-notes`.
|
|
213
|
+
resources: skillResources(context.skills.list(), SERVED_TOOLS).resources,
|
|
214
|
+
...(transport === "stdio-relay" ? { relay: { command: relayCommand() } } : {}),
|
|
215
|
+
});
|
|
216
|
+
// The vendor reads its MCP configuration from the worktree. Prism writes it there and excludes it from git.
|
|
217
|
+
await workspace.excludeOverlay(worktree.path, [
|
|
218
|
+
{ path: MCP_CONFIG, content: JSON.stringify({ mcpServers: { prism: served.endpoint } }, null, 2) },
|
|
219
|
+
]);
|
|
220
|
+
deps.evidence.served.push({ transport, tools: served.tools, env: redact(served.env) });
|
|
221
|
+
try {
|
|
222
|
+
await driveVendor(run, binary, config, served.endpoint, served.env);
|
|
223
|
+
await served.close();
|
|
224
|
+
// The route is gone, but the vendor still knows the endpoint: the next call is refused.
|
|
225
|
+
await driveVendor(run, binary, config, served.endpoint, served.env);
|
|
226
|
+
} finally {
|
|
227
|
+
await served.close();
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
deps.evidence.worktreeFile = readFileSync(join(worktree.path, EDITED_FILE), "utf8").trim();
|
|
232
|
+
const { changes, truncated } = await workspace.diff(worktree.path);
|
|
233
|
+
deps.evidence.diff = { changes: changes.map((change) => `${change.change} ${change.path}`), truncated };
|
|
234
|
+
deps.evidence.overlay = {
|
|
235
|
+
path: MCP_CONFIG,
|
|
236
|
+
// The file is on disk in the worktree, and no diff line names it.
|
|
237
|
+
excluded: existsSync(join(worktree.path, MCP_CONFIG)) && !changes.some((change) => change.path === MCP_CONFIG),
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// A conflicting change on the target branch, so the merge has something to report and nothing to resolve.
|
|
241
|
+
writeFileSync(join(deps.repo, EDITED_FILE), "a conflicting change on main\n");
|
|
242
|
+
git(deps.repo, ["commit", "-am", "conflicting change"]);
|
|
243
|
+
const merged = await workspace.merge(worktree.path, { into: "main", commit: { message: "serve-tools example merge" } });
|
|
244
|
+
deps.evidence.merge =
|
|
245
|
+
merged.status === "conflict"
|
|
246
|
+
? {
|
|
247
|
+
status: merged.status,
|
|
248
|
+
files: merged.files,
|
|
249
|
+
worktreeUnchanged: readFileSync(join(worktree.path, EDITED_FILE), "utf8").trim() === deps.evidence.worktreeFile,
|
|
250
|
+
}
|
|
251
|
+
: { status: merged.status, files: [], worktreeUnchanged: false };
|
|
252
|
+
} finally {
|
|
253
|
+
// The worktree is dirty after a reported conflict, and the branch was never merged.
|
|
254
|
+
await worktree.dispose({ force: true });
|
|
255
|
+
}
|
|
256
|
+
} finally {
|
|
257
|
+
await broker.close();
|
|
258
|
+
}
|
|
259
|
+
} finally {
|
|
260
|
+
await runDir.dispose();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Spawns the vendor binary against one served endpoint and waits for its turn to end. */
|
|
265
|
+
async function driveVendor(
|
|
266
|
+
run: RunController,
|
|
267
|
+
binary: DriverBinary,
|
|
268
|
+
config: DriverConfig,
|
|
269
|
+
endpoint: McpEndpoint,
|
|
270
|
+
env: Readonly<Record<string, string>>,
|
|
271
|
+
): Promise<void> {
|
|
272
|
+
const child = spawn(binary.path, [...(config.args ?? []), "--mcp-endpoint", JSON.stringify(endpoint)], {
|
|
273
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
274
|
+
env: { ...buildChildEnv({ base: process.env, modes: descriptor.auth.modes }), ...env },
|
|
275
|
+
}) as ChildProcessWithoutNullStreams;
|
|
276
|
+
child.stdin.on("error", () => undefined);
|
|
277
|
+
|
|
278
|
+
let turnDone!: () => void;
|
|
279
|
+
const turn = new Promise<"turn">((resolve) => (turnDone = () => resolve("turn")));
|
|
280
|
+
const exited = new Promise<"exit">((resolve) => child.once("close", () => resolve("exit")));
|
|
281
|
+
const aborted = new Promise<"abort">((resolve) => run.signal.addEventListener("abort", () => resolve("abort"), { once: true }));
|
|
282
|
+
|
|
283
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
284
|
+
const output = jsonlStreamDialect.parseFrame(line);
|
|
285
|
+
if (output === undefined) return;
|
|
286
|
+
// A client-gated hook call is not this example's path; a real adapter would answer it through `run.ask`.
|
|
287
|
+
if (output.kind === "hook") return;
|
|
288
|
+
// `turn.done` is the only frame without a `kind`. A real adapter also maps activity frames through `run.observe`.
|
|
289
|
+
if (!("kind" in output.frame)) turnDone();
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
child.stdin.write(`${jsonlStreamDialect.encodeInput({ kind: "user", text: "Serve the tools to the vendor." })}\n`);
|
|
293
|
+
const outcome = await Promise.race([turn, exited, aborted]);
|
|
294
|
+
if (outcome === "exit" && !run.signal.aborted) throw new Error("the vendor process exited before turn.done");
|
|
295
|
+
child.stdin.end();
|
|
296
|
+
await Promise.race([exited, sleep(2000)]);
|
|
297
|
+
if (child.exitCode === null && child.signalCode === null) await signalLadder(child, { graceMs: 200 });
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Reads the package's `workspace` service once the packages are set up, so the driver can bind a worktree. */
|
|
301
|
+
function workspaceProbe(): { readonly package: PackageInstance; readonly service: () => WorkspaceService | undefined } {
|
|
302
|
+
let service: WorkspaceService | undefined;
|
|
303
|
+
const instance = definePackage({
|
|
304
|
+
name: "example-workspace-probe",
|
|
305
|
+
version: "1.0.0",
|
|
306
|
+
requires: { api: 1 },
|
|
307
|
+
setup: ({ services }) => {
|
|
308
|
+
service = services.consume<WorkspaceService>("workspace");
|
|
309
|
+
},
|
|
310
|
+
})();
|
|
311
|
+
return { package: instance, service: () => service };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The served environment with every value masked: a token is never printed, only the variable that carries it. */
|
|
315
|
+
function redact(env: Readonly<Record<string, string>>): Readonly<Record<string, string>> {
|
|
316
|
+
return Object.fromEntries(Object.keys(env).map((name) => [name, "[redacted]"]));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** One process run of the scripted CLI: every run starts with an `argv` entry, so a record splits into runs. */
|
|
320
|
+
function runs(cli: ScriptedCli): readonly (readonly ScriptedRecordEntry[])[] {
|
|
321
|
+
const groups: ScriptedRecordEntry[][] = [];
|
|
322
|
+
for (const entry of cli.record()) {
|
|
323
|
+
if (entry.event === "argv") groups.push([]);
|
|
324
|
+
groups.at(-1)?.push(entry);
|
|
325
|
+
}
|
|
326
|
+
return groups;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const callsOf = (run: readonly ScriptedRecordEntry[]) => run.filter((entry) => entry.event === "mcp");
|
|
330
|
+
const resultOf = (entry: ScriptedRecordEntry | undefined): JsonValue | undefined =>
|
|
331
|
+
entry !== undefined && "result" in entry ? entry.result : undefined;
|
|
332
|
+
const refused = (entry: ScriptedRecordEntry | undefined): boolean => entry !== undefined && "error" in entry;
|
|
333
|
+
/** The MCP result's own error flag: a denied or failed tool call is a result, not a JSON-RPC error. */
|
|
334
|
+
const isErrorOf = (entry: ScriptedRecordEntry | undefined): boolean =>
|
|
335
|
+
(resultOf(entry) as { readonly isError?: boolean } | undefined)?.isError === true;
|
|
336
|
+
|
|
337
|
+
/** The text of an MCP `tools/call` result, joined across its text blocks. */
|
|
338
|
+
function resultText(result: JsonValue | undefined): string {
|
|
339
|
+
const blocks = (result as { readonly content?: readonly { readonly text?: string }[] } | undefined)?.content ?? [];
|
|
340
|
+
return blocks.map((block) => block.text ?? "").join("");
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The tool names in a `tools/list` result. */
|
|
344
|
+
function listedNames(result: JsonValue | undefined): readonly string[] {
|
|
345
|
+
const tools = (result as { readonly tools?: readonly { readonly name?: string }[] } | undefined)?.tools ?? [];
|
|
346
|
+
return tools.map((tool) => tool.name ?? "");
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The neutral permission decision a permission-tool result carries as JSON text. */
|
|
350
|
+
function decisionOf(entry: ScriptedRecordEntry | undefined): string {
|
|
351
|
+
return (JSON.parse(resultText(resultOf(entry)) || "{}") as { readonly behavior?: string }).behavior ?? "none";
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
interface LegEvidence {
|
|
355
|
+
readonly transport: string;
|
|
356
|
+
readonly tools: readonly string[];
|
|
357
|
+
readonly env: Readonly<Record<string, string>>;
|
|
358
|
+
readonly listed: readonly string[];
|
|
359
|
+
readonly allowedEdit: { readonly isError: boolean; readonly replaced: boolean };
|
|
360
|
+
readonly read: { readonly isError: boolean; readonly text: string };
|
|
361
|
+
readonly declinedEdit: { readonly isError: boolean; readonly denied: boolean };
|
|
362
|
+
readonly permission: { readonly denied: string; readonly allowed: string };
|
|
363
|
+
readonly outsideAllowList: { readonly refused: boolean };
|
|
364
|
+
readonly afterClose: { readonly refused: boolean };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** One leg's evidence, read from the two runs the driver made: while served, then after `close()`. */
|
|
368
|
+
function legEvidence(served: ServedLeg, main: readonly ScriptedRecordEntry[], late: readonly ScriptedRecordEntry[]): LegEvidence {
|
|
369
|
+
const calls = callsOf(main);
|
|
370
|
+
// The vendor's script fixes this order: list, edit, read, declined edit, denied permission, allowed permission, unserved name.
|
|
371
|
+
const [, list, edit, read, declined, denied, allowed, outside] = calls;
|
|
372
|
+
return {
|
|
373
|
+
transport: served.transport,
|
|
374
|
+
tools: served.tools,
|
|
375
|
+
env: served.env,
|
|
376
|
+
listed: listedNames(resultOf(list)),
|
|
377
|
+
allowedEdit: { isError: isErrorOf(edit), replaced: /Edited .*: 1 block\(s\)/.test(resultText(resultOf(edit))) },
|
|
378
|
+
read: { isError: isErrorOf(read), text: resultText(resultOf(read)).trim() },
|
|
379
|
+
declinedEdit: { isError: isErrorOf(declined), denied: /denied/.test(resultText(resultOf(declined))) },
|
|
380
|
+
permission: { denied: decisionOf(denied), allowed: decisionOf(allowed) },
|
|
381
|
+
// The unserved name never reaches the run: the call is a JSON-RPC error, not a tool result.
|
|
382
|
+
outsideAllowList: { refused: refused(outside) },
|
|
383
|
+
afterClose: { refused: refused(callsOf(late)[0]) },
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
388
|
+
|
|
389
|
+
/** Runs one git command in the fixture repository, failing loudly. */
|
|
390
|
+
function git(cwd: string, args: readonly string[]): void {
|
|
391
|
+
const result = spawnSync("git", [...args], { cwd, encoding: "utf8", env: GIT_ENV });
|
|
392
|
+
if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${result.stderr}`);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
396
|
+
const base = mkdtempSync(join(tmpdir(), "ex-serve-"));
|
|
397
|
+
const repo = join(base, "repo");
|
|
398
|
+
mkdirSync(repo, { recursive: true });
|
|
399
|
+
git(repo, ["init", "-q", "-b", "main", "."]);
|
|
400
|
+
git(repo, ["config", "user.name", "Prism Example"]);
|
|
401
|
+
git(repo, ["config", "user.email", "example@prism.local"]);
|
|
402
|
+
writeFileSync(join(repo, "a.txt"), "one\n");
|
|
403
|
+
git(repo, ["add", "-A"]);
|
|
404
|
+
git(repo, ["commit", "-qm", "seed"]);
|
|
405
|
+
|
|
406
|
+
const vendor = createScriptedCli({ dialect: "jsonl-stream", script: VENDOR_SCRIPT });
|
|
407
|
+
const probe = workspaceProbe();
|
|
408
|
+
const evidence: Evidence = { served: [] };
|
|
409
|
+
const driver = exampleDriver({ workspace: probe.service, repo, evidence });
|
|
410
|
+
|
|
411
|
+
// A scripted terminal answers the gate prompts. Every select is `once`; the vendor's second edit per run is
|
|
412
|
+
// declined, and so is the permission tool's read of a secret, so one run shows both an allow and a deny.
|
|
413
|
+
let edits = 0;
|
|
414
|
+
const scriptedUi = createScriptedHostUi((request) => {
|
|
415
|
+
if (request.kind === "select") return "once";
|
|
416
|
+
if (request.kind !== "confirm") return { status: "unavailable" };
|
|
417
|
+
const detail = request.detail ?? "";
|
|
418
|
+
if (detail.startsWith("shell ")) return !detail.includes("secrets");
|
|
419
|
+
edits += 1;
|
|
420
|
+
return edits % 2 === 1;
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
const profiles = createProfiles({ root: join(base, "profiles"), driver, host: { ui: scriptedUi.ui }, binary: process.execPath });
|
|
424
|
+
try {
|
|
425
|
+
await profiles.create("example", { mode: "key", principal: "u1" });
|
|
426
|
+
// A host skill that needs exactly the served tools; `skillResources` lends it only because both are in SERVED_TOOLS.
|
|
427
|
+
const skillsDir = join(base, "skills");
|
|
428
|
+
mkdirSync(join(skillsDir, "edit-notes"), { recursive: true });
|
|
429
|
+
writeFileSync(
|
|
430
|
+
join(skillsDir, "edit-notes", "SKILL.md"),
|
|
431
|
+
"---\nname: edit-notes\ndescription: Load before editing a tracked file. Read it first and keep the edit to the lines the task names.\nmetadata:\n prism-requires-tools: read edit\n---\n\n# Edit notes\n\n- Read the file before you edit it.\n- Change only the lines the task names.\n",
|
|
432
|
+
);
|
|
433
|
+
const agent: Agent = await createAgent({
|
|
434
|
+
id: "serve-tools-example",
|
|
435
|
+
skills: { dirs: [skillsDir] },
|
|
436
|
+
ownership: { tenantId: "example" },
|
|
437
|
+
principal: { kind: "user", id: "u1" },
|
|
438
|
+
packages: [
|
|
439
|
+
driverPackage(driver),
|
|
440
|
+
toolsCoding({ root: repo, workspace: { worktreeRoot: join(base, "worktrees") } }),
|
|
441
|
+
approval({ mode: "ask" }),
|
|
442
|
+
probe.package,
|
|
443
|
+
],
|
|
444
|
+
packageConfig: {
|
|
445
|
+
[driver.name]: {
|
|
446
|
+
binary: vendor.command[0] as string,
|
|
447
|
+
args: vendor.command.slice(1),
|
|
448
|
+
name: "vendor-loop",
|
|
449
|
+
profile: "example",
|
|
450
|
+
profilesRoot: join(base, "profiles"),
|
|
451
|
+
principal: "u1",
|
|
452
|
+
},
|
|
453
|
+
},
|
|
454
|
+
host: { ui: scriptedUi.ui },
|
|
455
|
+
slots: { store: createMemorySessionStore() },
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
const session = await agent.session();
|
|
459
|
+
const events: AgentEvent[] = [];
|
|
460
|
+
const pump = (async () => {
|
|
461
|
+
for await (const event of session.subscribe()) events.push(event);
|
|
462
|
+
})();
|
|
463
|
+
const result = await session.run("Serve the tools to the vendor.");
|
|
464
|
+
await session.close();
|
|
465
|
+
await pump.catch(() => undefined);
|
|
466
|
+
|
|
467
|
+
const groups = runs(vendor);
|
|
468
|
+
const legs = evidence.served.map((served, index) => legEvidence(served, groups[index * 2] ?? [], groups[index * 2 + 1] ?? []));
|
|
469
|
+
const origins = events.filter((event) => event.origin !== undefined);
|
|
470
|
+
return {
|
|
471
|
+
status: result.status,
|
|
472
|
+
worktree: { branch: evidence.worktree?.branch, base: evidence.worktree?.base },
|
|
473
|
+
worktreeFile: evidence.worktreeFile,
|
|
474
|
+
overlay: evidence.overlay,
|
|
475
|
+
diff: evidence.diff,
|
|
476
|
+
merge: evidence.merge,
|
|
477
|
+
http: legs[0],
|
|
478
|
+
stdio: legs[1],
|
|
479
|
+
origins: {
|
|
480
|
+
types: [...new Set(origins.map((event) => event.type))].sort(),
|
|
481
|
+
vendor: origins[0]?.origin?.vendor,
|
|
482
|
+
kind: origins[0]?.origin?.kind,
|
|
483
|
+
depth: origins[0]?.origin?.depth,
|
|
484
|
+
},
|
|
485
|
+
prompts: { confirm: scriptedUi.requestsOf("confirm").length, select: scriptedUi.requestsOf("select").length },
|
|
486
|
+
};
|
|
487
|
+
} finally {
|
|
488
|
+
vendor.dispose();
|
|
489
|
+
rmSync(base, { recursive: true, force: true });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
494
|
+
console.log(JSON.stringify(await demo()));
|
|
495
|
+
}
|