@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,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guardrail packs end to end (plan 104 Task 7; moved onto `@arnilo/prism-extensions/guardrail-packs` in plan 159 Task 5) —
|
|
3
|
+
* network-free: mock provider, in-memory stores.
|
|
4
|
+
*
|
|
5
|
+
* One file, four demonstrations, one printed line each:
|
|
6
|
+
* 1. two built-in packs refuse a `shell` and a `write` call, and the refusal names the rule;
|
|
7
|
+
* 2. the same trajectory graded by `createGuardrailPackScorer()` fails naming that rule;
|
|
8
|
+
* 3. an inline `ask` rule suspends a durable run before dispatch and the approval dispatches it;
|
|
9
|
+
* 4. a secret-shaped argument is refused without the refusal echoing the token.
|
|
10
|
+
*
|
|
11
|
+
* Pack rules are restrictive-only: `deny`, `tripwire`, and `ask` narrow what the agent may do on
|
|
12
|
+
* seams it already has. A pack never grants a capability, never widens a tool allow-list, and never
|
|
13
|
+
* approves its own `ask` gate — an approval applies to the suspension, not to the ruleset, so a
|
|
14
|
+
* sibling `deny` rule matching the same call still blocks it at dispatch.
|
|
15
|
+
*
|
|
16
|
+
* The packs are package config (`guardrailPacks({ packs })`), not a session option. Their state
|
|
17
|
+
* rides package session state, which is what keeps an `ask` rule enforced after the suspend/resume
|
|
18
|
+
* in step 3.
|
|
19
|
+
*
|
|
20
|
+
* Run: npm run build:core && node examples/guardrail-packs.ts
|
|
21
|
+
*/
|
|
22
|
+
import assert from "node:assert/strict";
|
|
23
|
+
import {
|
|
24
|
+
type ContentBlock,
|
|
25
|
+
createAgent,
|
|
26
|
+
createMemorySessionStore,
|
|
27
|
+
type JsonObject,
|
|
28
|
+
type ModelProvider,
|
|
29
|
+
type ProviderEvent,
|
|
30
|
+
providerDone,
|
|
31
|
+
providerTextDelta,
|
|
32
|
+
providerToolCall,
|
|
33
|
+
type ToolDefinition,
|
|
34
|
+
toolCallContent,
|
|
35
|
+
} from "@arnilo/prism";
|
|
36
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
37
|
+
import { createGuardrailPackScorer, runScenario } from "@arnilo/prism-hosts/evals";
|
|
38
|
+
import guardrailPacks from "@arnilo/prism-extensions/guardrail-packs";
|
|
39
|
+
|
|
40
|
+
const MODEL = { provider: "mock", model: "guardrail-packs-demo" } as const;
|
|
41
|
+
const FINISH: readonly ProviderEvent[] = [providerTextDelta("done"), providerDone()];
|
|
42
|
+
|
|
43
|
+
const call = (id: string, name: string, args: JsonObject): ProviderEvent => providerToolCall(toolCallContent(id, name, args));
|
|
44
|
+
|
|
45
|
+
/** One provider turn per `generate()`; the last script entry repeats, so every run terminates. */
|
|
46
|
+
function scriptedProvider(script: readonly (readonly ProviderEvent[])[]): ModelProvider {
|
|
47
|
+
let index = 0;
|
|
48
|
+
return {
|
|
49
|
+
id: "mock",
|
|
50
|
+
async *generate() {
|
|
51
|
+
// Advance before yielding: a consumer stops pulling at `providerDone()`, so anything after the loop may never run.
|
|
52
|
+
const events = script[Math.min(index, script.length - 1)] ?? FINISH;
|
|
53
|
+
index += 1;
|
|
54
|
+
for (const event of events) yield event;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function recordingTool(name: string, executed: string[]): ToolDefinition {
|
|
60
|
+
return {
|
|
61
|
+
name,
|
|
62
|
+
parameters: { type: "object" },
|
|
63
|
+
execute: (args, context) => {
|
|
64
|
+
executed.push(name);
|
|
65
|
+
return { toolCallId: context.toolCallId, name, value: { args } };
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type MemorySessionStore = ReturnType<typeof createMemorySessionStore>;
|
|
71
|
+
|
|
72
|
+
/** The `pack:<pack>/<rule>` identity out of any refusal line. */
|
|
73
|
+
const ruleIdOf = (text: string): string | undefined => /pack:[^\s:]+/.exec(text)?.[0];
|
|
74
|
+
|
|
75
|
+
/** Refusals the loop appended for blocked calls, read from the session store (tool results are not events). */
|
|
76
|
+
async function refusalsOf(store: MemorySessionStore, sessionId: string): Promise<readonly { tool: string; message: string }[]> {
|
|
77
|
+
const refusals: { tool: string; message: string }[] = [];
|
|
78
|
+
for (const entry of await store.list(sessionId)) {
|
|
79
|
+
for (const part of entry.message?.content ?? []) {
|
|
80
|
+
const block: Extract<ContentBlock, { type: "tool_result" }> | undefined = part.type === "tool_result" ? part : undefined;
|
|
81
|
+
if (block?.error?.message) refusals.push({ tool: block.name, message: block.error.message });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return refusals;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Step 1: two built-in packs on one agent; the blocked calls name the rule that refused them. */
|
|
88
|
+
async function blockedCalls(executed: string[]): Promise<readonly { tool: string; message: string }[]> {
|
|
89
|
+
const store = createMemorySessionStore();
|
|
90
|
+
const agent = await createAgent({
|
|
91
|
+
id: "pack-demo-block",
|
|
92
|
+
model: { ...MODEL },
|
|
93
|
+
slots: { store },
|
|
94
|
+
packages: [
|
|
95
|
+
providerPackage("test-provider", [
|
|
96
|
+
scriptedProvider([
|
|
97
|
+
[
|
|
98
|
+
call("c1", "shell", { command: "git push origin main --force" }),
|
|
99
|
+
call("c2", "write", { path: "/repo/src/app.test.ts", content: "// tidy" }),
|
|
100
|
+
providerDone(),
|
|
101
|
+
],
|
|
102
|
+
FINISH,
|
|
103
|
+
]),
|
|
104
|
+
]),
|
|
105
|
+
guardrailPacks({ packs: ["destructive-commands", { id: "coding-standard", options: { cwd: "/repo", roots: ["/repo"] } }] }),
|
|
106
|
+
],
|
|
107
|
+
tools: { add: [recordingTool("shell", executed), recordingTool("write", executed)] },
|
|
108
|
+
});
|
|
109
|
+
const result = await (await agent.session()).run("redeploy and tidy the tests");
|
|
110
|
+
const refusals = await refusalsOf(store, result.sessionId);
|
|
111
|
+
for (const refusal of refusals) console.log(`step 1 built-in packs: ${refusal.tool} refused — ${refusal.message}`);
|
|
112
|
+
assert.equal(result.status, "completed", "a blocked tool call does not fail the run");
|
|
113
|
+
assert.deepEqual(executed, [], "neither refused call reached its tool");
|
|
114
|
+
assert.equal(refusals.length, 2, "both calls were refused");
|
|
115
|
+
assert.match(refusals[0]?.message ?? "", /pack:destructive-commands\/no-force-push/);
|
|
116
|
+
assert.match(refusals[1]?.message ?? "", /pack:coding-standard\/no-test-rewrites/);
|
|
117
|
+
return refusals;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Step 2: the same denial graded on the execution timeline, which is what release evidence reads. */
|
|
121
|
+
async function scoredScenario(executed: string[]): Promise<string> {
|
|
122
|
+
const agent = await createAgent({
|
|
123
|
+
id: "pack-demo-eval",
|
|
124
|
+
model: { ...MODEL },
|
|
125
|
+
slots: { store: createMemorySessionStore() },
|
|
126
|
+
packages: [
|
|
127
|
+
providerPackage("test-provider", [scriptedProvider([[call("c1", "shell", { command: "rm -rf ./build" }), providerDone()], FINISH])]),
|
|
128
|
+
guardrailPacks({ packs: ["destructive-commands"] }),
|
|
129
|
+
],
|
|
130
|
+
tools: { add: [recordingTool("shell", executed)] },
|
|
131
|
+
});
|
|
132
|
+
const scenario = await runScenario({
|
|
133
|
+
agent,
|
|
134
|
+
turns: ["clean the build directory"],
|
|
135
|
+
timeline: "metadata",
|
|
136
|
+
scorers: [createGuardrailPackScorer({ forbidTools: ["shell"] })],
|
|
137
|
+
});
|
|
138
|
+
const graded = scenario.evaluations.at(-1);
|
|
139
|
+
console.log(`step 2 eval scenario: ${graded?.scorerId} scored ${graded?.score} — ${graded?.reason}`);
|
|
140
|
+
assert.equal(scenario.status, "succeeded", "the scenario itself ran to completion");
|
|
141
|
+
assert.equal(graded?.score, 0, "a pack denial is a scored violation, not a silent pass");
|
|
142
|
+
assert.match(graded?.reason ?? "", /pack:destructive-commands\/no-recursive-force-delete/);
|
|
143
|
+
assert.match(graded?.reason ?? "", /forbidden tool|denied the trajectory/);
|
|
144
|
+
assert.deepEqual(executed, [], "the graded run executed no forbidden tool");
|
|
145
|
+
return String(graded?.reason);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Step 3: an `ask` rule suspends selectively (no all-tools gate) and the approval dispatches once. */
|
|
149
|
+
async function durableAsk(executed: string[]): Promise<{ rule?: string; dispatched: readonly string[] }> {
|
|
150
|
+
const askPack = {
|
|
151
|
+
id: "deploy-guard",
|
|
152
|
+
rules: [
|
|
153
|
+
{
|
|
154
|
+
id: "prod-version-approval",
|
|
155
|
+
tool: "deploy",
|
|
156
|
+
argPath: "version",
|
|
157
|
+
pattern: "^prod-",
|
|
158
|
+
action: "ask" as const,
|
|
159
|
+
reason: "Production tags need approval",
|
|
160
|
+
},
|
|
161
|
+
],
|
|
162
|
+
};
|
|
163
|
+
const agent = await createAgent({
|
|
164
|
+
id: "pack-demo-ask",
|
|
165
|
+
model: { ...MODEL },
|
|
166
|
+
slots: { store: createMemorySessionStore() },
|
|
167
|
+
packages: [
|
|
168
|
+
providerPackage("test-provider", [
|
|
169
|
+
scriptedProvider([
|
|
170
|
+
[call("d1", "deploy", { version: "prod-7" }), providerDone()],
|
|
171
|
+
[providerTextDelta("shipped"), providerDone()],
|
|
172
|
+
]),
|
|
173
|
+
]),
|
|
174
|
+
guardrailPacks({ packs: [askPack] }),
|
|
175
|
+
],
|
|
176
|
+
tools: { add: [recordingTool("deploy", executed)] },
|
|
177
|
+
});
|
|
178
|
+
const session = await agent.session();
|
|
179
|
+
// The pack's own state rides the store slot's `suspended_run` entry into the resumed session.
|
|
180
|
+
const result = await session.run("ship prod-7");
|
|
181
|
+
const pending = result.pending?.[0];
|
|
182
|
+
if (pending === undefined) throw new Error(`expected a durable ask suspension, got ${result.status}`);
|
|
183
|
+
const rule = ruleIdOf(pending.reason);
|
|
184
|
+
console.log(`step 3 ask gate: suspended on ${rule} — ${pending.reason}`);
|
|
185
|
+
assert.deepEqual(executed, [], "the gated call did not dispatch before the decision");
|
|
186
|
+
|
|
187
|
+
let lastEvent: string | undefined;
|
|
188
|
+
for await (const event of session.resume([{ approvalId: pending.approvalId, outcome: "allow_once" as const }])) {
|
|
189
|
+
lastEvent = event.type; // the resumed leg restores the pack state and dispatches the approved call once
|
|
190
|
+
}
|
|
191
|
+
console.log(`step 3 ask gate: approved → run resumed, dispatched ${executed.join(", ")}`);
|
|
192
|
+
assert.equal(lastEvent, "run.completed");
|
|
193
|
+
assert.deepEqual(executed, ["deploy"], "the approved call dispatched exactly once");
|
|
194
|
+
return { rule, dispatched: executed };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Step 4: a secret-shaped argument is refused, and the refusal never echoes the token. */
|
|
198
|
+
async function secretRefusal(executed: string[]): Promise<string> {
|
|
199
|
+
// Obviously fake and deliberately short of a real key shape: no credential is ever a literal here.
|
|
200
|
+
const fakeToken = "sk-TESTONLYFAKEKEY1";
|
|
201
|
+
const store = createMemorySessionStore();
|
|
202
|
+
const agent = await createAgent({
|
|
203
|
+
id: "pack-demo-secret",
|
|
204
|
+
model: { ...MODEL },
|
|
205
|
+
slots: { store },
|
|
206
|
+
packages: [
|
|
207
|
+
providerPackage("test-provider", [
|
|
208
|
+
scriptedProvider([[call("s1", "write", { path: "/repo/.env.example", content: `TOKEN=${fakeToken}` }), providerDone()], FINISH]),
|
|
209
|
+
]),
|
|
210
|
+
guardrailPacks({ packs: ["secrets-hygiene"] }),
|
|
211
|
+
],
|
|
212
|
+
tools: { add: [recordingTool("write", executed)] },
|
|
213
|
+
});
|
|
214
|
+
const result = await (await agent.session()).run("write the example env file");
|
|
215
|
+
const refusal = (await refusalsOf(store, result.sessionId))[0];
|
|
216
|
+
console.log(`step 4 secrets hygiene: ${refusal?.tool} refused — ${refusal?.message}`);
|
|
217
|
+
assert.match(refusal?.message ?? "", /pack:secrets-hygiene\/no-secret-material-in-arguments/);
|
|
218
|
+
assert.equal(refusal?.message.includes(fakeToken), false, "the refusal never echoes the token");
|
|
219
|
+
assert.deepEqual(executed, [], "the call carrying the token never executed");
|
|
220
|
+
return String(refusal?.message);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
224
|
+
const blocked: string[] = [];
|
|
225
|
+
const refusals = await blockedCalls(blocked);
|
|
226
|
+
const scenarioReason = await scoredScenario([]);
|
|
227
|
+
const ask = await durableAsk([]);
|
|
228
|
+
const secretReason = await secretRefusal([]);
|
|
229
|
+
return {
|
|
230
|
+
blockedRules: refusals.map((refusal) => ruleIdOf(refusal.message)),
|
|
231
|
+
scenarioReason,
|
|
232
|
+
askRule: ask.rule,
|
|
233
|
+
askDispatched: ask.dispatched,
|
|
234
|
+
secretRule: ruleIdOf(secretReason),
|
|
235
|
+
// Step 1 refused both calls, so its tool list stayed empty — enforcement, not agent goodwill.
|
|
236
|
+
toolsExecutedInStep1: blocked.length,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { type Agent, createAgent, definePackage, type HostUi } from "@arnilo/prism";
|
|
5
|
+
import { mockProvider, providerDone, providerTextDelta, providerToolCall, toolCallContent } from "@arnilo/prism/testing";
|
|
6
|
+
import approval from "@arnilo/prism-extensions/approval";
|
|
7
|
+
import { type ChannelConnectionHandle, channelHostUi, connectTelegram, createChannelPairingStore } from "@arnilo/prism-hosts/channels";
|
|
8
|
+
import { createResumeAuthority, createScheduler, policyDefault, routeHostUi, type SchedulerClock } from "@arnilo/prism-hosts/headless";
|
|
9
|
+
import { createSqlitePersistence } from "@arnilo/prism-extensions/store-sqlite";
|
|
10
|
+
import workflows, { agentNode, defineWorkflow, workflowCommand } from "@arnilo/prism-extensions/workflows";
|
|
11
|
+
|
|
12
|
+
// Keep Bun transport declarations out of the examples compiler, as in remote-agent.ts.
|
|
13
|
+
const remoteModule = "@arnilo/prism-hosts/remote";
|
|
14
|
+
const remoteHostUi: () => HostUi = (await import(remoteModule)).remoteHostUi;
|
|
15
|
+
|
|
16
|
+
function assert(condition: unknown, message: string): asserts condition {
|
|
17
|
+
if (!condition) throw new Error(`headless_host_example_output: ${message}`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function until(check: () => boolean | Promise<boolean>) {
|
|
21
|
+
const deadline = Date.now() + 2000;
|
|
22
|
+
while (!(await check())) {
|
|
23
|
+
assert(Date.now() < deadline, "scripted host did not settle");
|
|
24
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Offline: bun examples/headless-host.ts. All channel traffic stays in the scripted fetch.
|
|
29
|
+
export async function demo() {
|
|
30
|
+
const root = mkdtempSync(join(tmpdir(), "prism-headless-"));
|
|
31
|
+
const store = createSqlitePersistence({ filename: join(root, "host.db") });
|
|
32
|
+
const agents: Agent[] = [];
|
|
33
|
+
let connection: ChannelConnectionHandle | undefined;
|
|
34
|
+
let scheduler: ReturnType<typeof createScheduler> | undefined;
|
|
35
|
+
const previousToken = process.env.HEADLESS_DEMO_TOKEN;
|
|
36
|
+
process.env.HEADLESS_DEMO_TOKEN = "123456:headless-demo-dummy";
|
|
37
|
+
try {
|
|
38
|
+
const ownership = { tenantId: "demo", userId: "operator" };
|
|
39
|
+
const model = { provider: "mock", model: "demo" };
|
|
40
|
+
const channelAgent = await createAgent({ model, ownership, slots: { store }, packages: [mockProvider([])] });
|
|
41
|
+
agents.push(channelAgent);
|
|
42
|
+
const pairing = createChannelPairingStore({ checkpoints: store.checkpoints });
|
|
43
|
+
const grant = await pairing.create({
|
|
44
|
+
...ownership,
|
|
45
|
+
connectionId: "telegram-default",
|
|
46
|
+
externalConversationId: "101",
|
|
47
|
+
externalActorId: "202",
|
|
48
|
+
grantRevision: "demo-1",
|
|
49
|
+
});
|
|
50
|
+
assert(
|
|
51
|
+
(await pairing.consume({ ...ownership, connectionId: "telegram-default", token: grant.token })).status === "consumed",
|
|
52
|
+
"pairing",
|
|
53
|
+
);
|
|
54
|
+
const sent: { reply_markup?: { inline_keyboard: { callback_data: string }[][] } }[] = [];
|
|
55
|
+
connection = await connectTelegram(channelAgent, {
|
|
56
|
+
token: "env:HEADLESS_DEMO_TOKEN",
|
|
57
|
+
checkpoints: store.checkpoints,
|
|
58
|
+
authorize: (event) =>
|
|
59
|
+
event.externalActorId === "202" && event.externalConversationId === "101"
|
|
60
|
+
? {
|
|
61
|
+
identity: {
|
|
62
|
+
...ownership,
|
|
63
|
+
principal: { kind: "user", id: "operator" },
|
|
64
|
+
verified: true,
|
|
65
|
+
scopes: ["chat"],
|
|
66
|
+
issuedAt: new Date(0).toISOString(),
|
|
67
|
+
},
|
|
68
|
+
grantRevision: "demo-1",
|
|
69
|
+
}
|
|
70
|
+
: false,
|
|
71
|
+
fetch: async (_url, init) => {
|
|
72
|
+
sent.push(JSON.parse(String(init?.body)));
|
|
73
|
+
return Response.json({ ok: true, result: { message_id: sent.length } });
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
const routes = [
|
|
77
|
+
{ name: "client", ui: remoteHostUi() },
|
|
78
|
+
{
|
|
79
|
+
name: "channel",
|
|
80
|
+
ui: channelHostUi({ connection, chat: `pair:${grant.token}`, ownership }),
|
|
81
|
+
kinds: ["confirm"] as const,
|
|
82
|
+
timeoutMs: 50,
|
|
83
|
+
},
|
|
84
|
+
policyDefault(),
|
|
85
|
+
];
|
|
86
|
+
let writes = 0;
|
|
87
|
+
const agent = await createAgent({
|
|
88
|
+
id: "headless-worker",
|
|
89
|
+
model,
|
|
90
|
+
ownership,
|
|
91
|
+
slots: { store },
|
|
92
|
+
host: { ui: routeHostUi(routes, { answerLog: store.checkpoints, ownership }) },
|
|
93
|
+
packages: [
|
|
94
|
+
approval({ mode: "ask" }),
|
|
95
|
+
mockProvider([
|
|
96
|
+
[providerToolCall(toolCallContent("write-1", "write", {})), providerDone()],
|
|
97
|
+
[providerTextDelta("Approved"), providerDone()],
|
|
98
|
+
[providerTextDelta("Scheduled report"), providerDone()],
|
|
99
|
+
]),
|
|
100
|
+
],
|
|
101
|
+
tools: {
|
|
102
|
+
add: [
|
|
103
|
+
{
|
|
104
|
+
name: "write",
|
|
105
|
+
parameters: { type: "object", properties: {} },
|
|
106
|
+
effects: ["write"],
|
|
107
|
+
execute: (_args, ctx) => ({ toolCallId: ctx.toolCallId, name: "write", value: ++writes }),
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
agents.push(agent);
|
|
113
|
+
const router = routeHostUi(routes, { resumeAuthority: createResumeAuthority(agent), answerLog: store.checkpoints, ownership });
|
|
114
|
+
|
|
115
|
+
// 1. No client or timely channel reply: persist the suspension, then offer it again.
|
|
116
|
+
const session = await agent.session();
|
|
117
|
+
const suspended = await session.run("Write the report");
|
|
118
|
+
assert(suspended.status === "suspended" && writes === 0, "tool must wait for approval");
|
|
119
|
+
const inline = await router.answers();
|
|
120
|
+
// Durable log timestamps can tie; their read order does not distinguish same-ms attempts.
|
|
121
|
+
for (const sessionId of [undefined, session.id]) {
|
|
122
|
+
const attempts = inline.filter((row) => row.sessionId === sessionId);
|
|
123
|
+
assert(
|
|
124
|
+
attempts
|
|
125
|
+
.map((row) => row.route)
|
|
126
|
+
.sort()
|
|
127
|
+
.join(",") === "channel,client,policy",
|
|
128
|
+
"all routes attempted",
|
|
129
|
+
);
|
|
130
|
+
const at = (route: string) => attempts.find((row) => row.route === route)!.at;
|
|
131
|
+
assert(at("client") <= at("channel") && at("channel") <= at("policy"), "route order");
|
|
132
|
+
}
|
|
133
|
+
assert(
|
|
134
|
+
inline.every((row) => row.status === "unavailable"),
|
|
135
|
+
"inline timeout",
|
|
136
|
+
);
|
|
137
|
+
const resuming = router.resumeWhenAnswered(session, undefined, { signal: AbortSignal.timeout(2000) });
|
|
138
|
+
await until(() => sent.length === 3);
|
|
139
|
+
const callbackData = sent[2].reply_markup?.inline_keyboard[0][0].callback_data;
|
|
140
|
+
assert(callbackData, "fresh channel prompt");
|
|
141
|
+
const reply = await connection.handle({
|
|
142
|
+
update_id: 1,
|
|
143
|
+
callback_query: {
|
|
144
|
+
id: "reply-1",
|
|
145
|
+
from: { id: 202, is_bot: false },
|
|
146
|
+
message: { message_id: 3, chat: { id: 101, type: "private" } },
|
|
147
|
+
data: callbackData,
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
assert(reply && typeof reply === "object" && "status" in reply && reply.status === "accepted", "paired channel reply");
|
|
151
|
+
const resumed = await resuming;
|
|
152
|
+
assert(resumed.status === "resumed", "resume status");
|
|
153
|
+
let completed = false;
|
|
154
|
+
for await (const event of resumed.events) if (event.type === "run.completed") completed = true;
|
|
155
|
+
assert(completed && Number(writes) === 1, "resume must execute the tool once");
|
|
156
|
+
console.log(JSON.stringify({ half: "routing", status: resumed.status }));
|
|
157
|
+
|
|
158
|
+
// 2. One cron occurrence runs a registered workflow, with an indexed agent child.
|
|
159
|
+
let now = Date.parse("2026-10-13T00:00:00Z");
|
|
160
|
+
let wake = () => {};
|
|
161
|
+
const clock: SchedulerClock = {
|
|
162
|
+
now: () => now,
|
|
163
|
+
sleep: (_ms, signal) =>
|
|
164
|
+
new Promise<void>((resolve) => {
|
|
165
|
+
const done = () => {
|
|
166
|
+
signal.removeEventListener("abort", done);
|
|
167
|
+
resolve();
|
|
168
|
+
};
|
|
169
|
+
wake = done;
|
|
170
|
+
signal.addEventListener("abort", done, { once: true });
|
|
171
|
+
if (signal.aborted) done();
|
|
172
|
+
}),
|
|
173
|
+
};
|
|
174
|
+
const flow = defineWorkflow({
|
|
175
|
+
id: "report",
|
|
176
|
+
revision: "1",
|
|
177
|
+
nodes: { report: agentNode({ agent, input: () => "Summarize the report" }) },
|
|
178
|
+
});
|
|
179
|
+
const host = await createAgent({
|
|
180
|
+
model,
|
|
181
|
+
ownership,
|
|
182
|
+
slots: { store },
|
|
183
|
+
packages: [
|
|
184
|
+
mockProvider([]),
|
|
185
|
+
workflows,
|
|
186
|
+
definePackage({
|
|
187
|
+
name: "@example/headless",
|
|
188
|
+
version: "1.0.0",
|
|
189
|
+
requires: { api: 1 },
|
|
190
|
+
capabilities: ["session-state"],
|
|
191
|
+
setup(prism) {
|
|
192
|
+
prism.commands.register(workflowCommand(prism, "report", flow, { args: { type: "object", properties: {} } }));
|
|
193
|
+
},
|
|
194
|
+
}),
|
|
195
|
+
],
|
|
196
|
+
});
|
|
197
|
+
agents.push(host);
|
|
198
|
+
scheduler = createScheduler({
|
|
199
|
+
checkpoints: store.checkpoints,
|
|
200
|
+
ownership,
|
|
201
|
+
clock,
|
|
202
|
+
targets: { report: { kind: "workflow", agent: host, command: "report", input: {} } },
|
|
203
|
+
});
|
|
204
|
+
const schedule = await scheduler.schedule({ id: "minute-report", target: "report", cron: "* * * * *" });
|
|
205
|
+
scheduler.start();
|
|
206
|
+
now += 60000;
|
|
207
|
+
wake();
|
|
208
|
+
await until(async () => (await scheduler!.list())[0].lastFiring?.status === "succeeded");
|
|
209
|
+
await scheduler.stop();
|
|
210
|
+
const state = (await scheduler.list())[0];
|
|
211
|
+
const children = await host.sessions.list({ parentSessionId: schedule.scheduleSessionId });
|
|
212
|
+
assert(children.items.length === 1, "one scheduled workflow child");
|
|
213
|
+
assert(
|
|
214
|
+
state.nextRunAt === "2026-10-13T00:02:00.000Z" && state.lastFiring?.workflowRunId,
|
|
215
|
+
"one cron firing and persisted next deadline",
|
|
216
|
+
);
|
|
217
|
+
const answers = await router.answers();
|
|
218
|
+
assert(
|
|
219
|
+
answers.some((row) => row.route === "channel" && row.status === "answered" && row.approvalId),
|
|
220
|
+
"route: channel answer metadata",
|
|
221
|
+
);
|
|
222
|
+
console.log(JSON.stringify({ half: "scheduling", scheduledFirings: 1, children: children.items.length }));
|
|
223
|
+
await session.close();
|
|
224
|
+
return { status: "resumed", scheduledFirings: 1, answers };
|
|
225
|
+
} finally {
|
|
226
|
+
try {
|
|
227
|
+
await scheduler?.stop();
|
|
228
|
+
} finally {
|
|
229
|
+
try {
|
|
230
|
+
await connection?.close();
|
|
231
|
+
} finally {
|
|
232
|
+
try {
|
|
233
|
+
for (const agent of agents.reverse()) await agent.dispose();
|
|
234
|
+
} finally {
|
|
235
|
+
store.close();
|
|
236
|
+
rmSync(root, { recursive: true, force: true });
|
|
237
|
+
if (previousToken === undefined) delete process.env.HEADLESS_DEMO_TOKEN;
|
|
238
|
+
else process.env.HEADLESS_DEMO_TOKEN = previousToken;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Fixture for examples/hooks-json.ts — a stand-in for a host audit command.
|
|
2
|
+
// Reads the hook payload on stdin, decides from it, answers as JSON on stdout.
|
|
3
|
+
let raw = "";
|
|
4
|
+
process.stdin.setEncoding("utf8");
|
|
5
|
+
process.stdin.on("data", (chunk) => {
|
|
6
|
+
raw += chunk;
|
|
7
|
+
});
|
|
8
|
+
process.stdin.on("end", () => {
|
|
9
|
+
const payload = JSON.parse(raw);
|
|
10
|
+
if (payload.hook_event_name === "PreToolUse" && payload.tool_input?.path?.endsWith(".env")) {
|
|
11
|
+
process.stdout.write(
|
|
12
|
+
JSON.stringify({
|
|
13
|
+
hookSpecificOutput: {
|
|
14
|
+
hookEventName: "PreToolUse",
|
|
15
|
+
permissionDecision: "deny",
|
|
16
|
+
permissionDecisionReason: "secrets stay out of the audit trail",
|
|
17
|
+
},
|
|
18
|
+
}),
|
|
19
|
+
);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (payload.hook_event_name === "SessionStart") {
|
|
23
|
+
process.stdout.write(
|
|
24
|
+
JSON.stringify({
|
|
25
|
+
hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: "Audit trail: every write is logged." },
|
|
26
|
+
}),
|
|
27
|
+
);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
process.stdout.write(JSON.stringify({ continue: true }));
|
|
31
|
+
});
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
type ModelProvider,
|
|
6
|
+
createAgent,
|
|
7
|
+
providerDone,
|
|
8
|
+
providerTextDelta,
|
|
9
|
+
providerToolCallDelta,
|
|
10
|
+
type ToolDefinition,
|
|
11
|
+
} from "@arnilo/prism";
|
|
12
|
+
import { hookCommandHash, hooksJson } from "@arnilo/prism-extensions/hooks-json";
|
|
13
|
+
import { providerPackage } from "@arnilo/prism/provider-kit";
|
|
14
|
+
|
|
15
|
+
// hooks.json package: config is the file. SessionStart is session.opened. PreToolUse is tool.call.
|
|
16
|
+
// The handler is a local fixture spawned with an argv array. The allow-list is a hash pin.
|
|
17
|
+
|
|
18
|
+
const fixture = fileURLToPath(new URL("./hooks-audit-command.mjs", import.meta.url));
|
|
19
|
+
const handler = { type: "command" as const, command: `node ${fixture}`, timeout: 10 };
|
|
20
|
+
const config = {
|
|
21
|
+
SessionStart: [{ hooks: [handler] }],
|
|
22
|
+
PreToolUse: [{ matcher: "write", hooks: [handler] }],
|
|
23
|
+
Stop: [{ hooks: [handler] }],
|
|
24
|
+
allowCommands: { [handler.command]: hookCommandHash(handler) },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const written: string[] = [];
|
|
28
|
+
const write: ToolDefinition = {
|
|
29
|
+
name: "write",
|
|
30
|
+
parameters: {
|
|
31
|
+
type: "object",
|
|
32
|
+
properties: { path: { type: "string" }, text: { type: "string" } },
|
|
33
|
+
required: ["path"],
|
|
34
|
+
},
|
|
35
|
+
execute(args, context) {
|
|
36
|
+
written.push(String(args.path));
|
|
37
|
+
return { toolCallId: context.toolCallId, name: "write", value: `wrote ${String(args.path)}` };
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
let turn = 0;
|
|
42
|
+
const requests: unknown[] = [];
|
|
43
|
+
const provider: ModelProvider = {
|
|
44
|
+
id: "mock",
|
|
45
|
+
async *generate(request) {
|
|
46
|
+
requests.push(request);
|
|
47
|
+
turn += 1;
|
|
48
|
+
if (turn === 1) {
|
|
49
|
+
yield providerToolCallDelta({ index: 0, id: "call_notes", name: "write", argumentsText: '{"path":"notes.md","text":"hi"}' });
|
|
50
|
+
} else if (turn === 2) {
|
|
51
|
+
yield providerToolCallDelta({ index: 0, id: "call_env", name: "write", argumentsText: '{"path":".env","text":"secret"}' });
|
|
52
|
+
} else {
|
|
53
|
+
yield providerTextDelta("audit complete");
|
|
54
|
+
}
|
|
55
|
+
yield providerDone();
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const agent = await createAgent({
|
|
60
|
+
model: { provider: "mock", model: "demo" },
|
|
61
|
+
tools: { add: [write] },
|
|
62
|
+
packages: [
|
|
63
|
+
hooksJson({ config, onWarning: (warning) => console.log(`warning: ${warning.code} ${warning.message}`) }),
|
|
64
|
+
providerPackage("test-provider", [provider]),
|
|
65
|
+
],
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const session = await agent.session({ id: "hooks-json-example", create: true });
|
|
69
|
+
const result = await session.run("Record the notes, then the environment file.");
|
|
70
|
+
|
|
71
|
+
console.log(
|
|
72
|
+
JSON.stringify(
|
|
73
|
+
{
|
|
74
|
+
status: result.status,
|
|
75
|
+
written,
|
|
76
|
+
envBlocked: written.includes(".env") === false,
|
|
77
|
+
sessionStartContextInjected: JSON.stringify(requests).includes("Audit trail: every write is logged."),
|
|
78
|
+
seams: {
|
|
79
|
+
// Every hooks.json event now arrives as one hook registration on the agent's bus.
|
|
80
|
+
hooks: Object.keys(agent.inspect().hooks),
|
|
81
|
+
fixtureReadable: readFileSync(fixture, "utf8").length > 0,
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
null,
|
|
85
|
+
0,
|
|
86
|
+
),
|
|
87
|
+
);
|