@arnilo/prism-hosts 0.0.0-stage → 0.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6197 -0
- package/host-builder/data/errors.json +558 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +255 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +318 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +68 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { type Agent, type AgentEvent, createAgent, definePackage, providerDone, providerTextDelta } from "@arnilo/prism";
|
|
6
|
+
import { createProfiles } from "@arnilo/prism/driver-kit";
|
|
7
|
+
import { createScriptedCli, createScriptedHostUi, mockProvider, type ScriptStep } from "@arnilo/prism/testing";
|
|
8
|
+
import { adapterDriver, processDriver } from "@arnilo/prism-hosts/driver-process";
|
|
9
|
+
import { sqliteStore } from "@arnilo/prism-extensions/store-sqlite";
|
|
10
|
+
import workflows, {
|
|
11
|
+
agentNode,
|
|
12
|
+
defineWorkflow,
|
|
13
|
+
fanOut,
|
|
14
|
+
gateNode,
|
|
15
|
+
humanGate,
|
|
16
|
+
type WorkflowRun,
|
|
17
|
+
type WorkflowStreamEvent,
|
|
18
|
+
workflowCommand,
|
|
19
|
+
} from "@arnilo/prism-extensions/workflows";
|
|
20
|
+
import { createWorkspaceService } from "@arnilo/prism-tools/coding";
|
|
21
|
+
import { rpcServerDialect, rpcServerFixtures } from "./adapters/rpc-server.dialect.js";
|
|
22
|
+
import { rpcServer } from "./adapters/rpc-server.js";
|
|
23
|
+
import { streamCliDialect, streamCliFixtures } from "./adapters/stream-cli.dialect.js";
|
|
24
|
+
import { streamCli } from "./adapters/stream-cli.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The §2.11 orchestration, offline (roadmap Phase 16 Done): `/build` runs research, plan, a plan gate that fails once
|
|
28
|
+
* and routes back, a `humanGate`, a `fanOut` of six tasks in git worktrees (three to a UI engineer under a profile cap
|
|
29
|
+
* of two), a merge gate over `workspace.merge`, a validator, and a tests gate.
|
|
30
|
+
*
|
|
31
|
+
* - host agent: the mock provider.
|
|
32
|
+
* - planner and UI engineer: the `stream-cli` reference adapter. Validator: the `rpc-server` reference adapter.
|
|
33
|
+
* Each runs over `createScriptedCli`, so no vendor binary and no network.
|
|
34
|
+
* - one SQLite file holds sessions, vendor state, checkpoints, and leases; a temp git repository backs `workspace`.
|
|
35
|
+
*
|
|
36
|
+
* The demo asserts the Done criteria it can reach in one process and throws on any miss. The rest are proven by tests:
|
|
37
|
+
* kill-and-resume by `kill_and_resume_skips_completed_nodes`, `workflowLoop` under approval by
|
|
38
|
+
* `workflow_loop_gates_tools_under_approval` (and `examples/workflow-loop.ts`), and no kernel checkpoints or leases by
|
|
39
|
+
* `kernel_contains_no_checkpoints_or_leases`.
|
|
40
|
+
* Run: npm run build:core && bun examples/build-workflow.ts
|
|
41
|
+
*/
|
|
42
|
+
|
|
43
|
+
const PROFILE_CAP = 2;
|
|
44
|
+
const TASKS = [
|
|
45
|
+
{ id: 1, ui: false },
|
|
46
|
+
{ id: 2, ui: true },
|
|
47
|
+
{ id: 3, ui: false },
|
|
48
|
+
{ id: 4, ui: false },
|
|
49
|
+
{ id: 5, ui: true },
|
|
50
|
+
{ id: 6, ui: true },
|
|
51
|
+
].map((task) => ({ ...task, prompt: `Build task ${task.id}` }));
|
|
52
|
+
|
|
53
|
+
const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
|
|
54
|
+
function assert(condition: boolean, message: string): asserts condition {
|
|
55
|
+
if (!condition) throw new Error(`build-workflow: ${message}`);
|
|
56
|
+
}
|
|
57
|
+
const delta = (value: string): ScriptStep => ({ out: { kind: "message.delta", content: { type: "text", text: value } } });
|
|
58
|
+
/** The final assistant message is what `result.text` reads; deltas alone only stream. */
|
|
59
|
+
const final = (value: string): ScriptStep => ({
|
|
60
|
+
out: { kind: "message", message: { role: "assistant", content: [{ type: "text", text: value }] } },
|
|
61
|
+
});
|
|
62
|
+
const text = (value: string): readonly ScriptStep[] => [delta(value), final(value)];
|
|
63
|
+
|
|
64
|
+
function repository(root: string): string {
|
|
65
|
+
const repo = join(root, "repo");
|
|
66
|
+
execFileSync("git", ["init", "-q", "-b", "main", repo]);
|
|
67
|
+
git(repo, "config", "user.name", "Build Example");
|
|
68
|
+
git(repo, "config", "user.email", "build@example.invalid");
|
|
69
|
+
writeFileSync(join(repo, "README.md"), "# build example\n");
|
|
70
|
+
git(repo, "add", "-A");
|
|
71
|
+
git(repo, "commit", "-q", "-m", "init");
|
|
72
|
+
return repo;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function demo(): Promise<Record<string, unknown>> {
|
|
76
|
+
const root = mkdtempSync(join(tmpdir(), "bw-"));
|
|
77
|
+
const clis: { dispose(): void }[] = [];
|
|
78
|
+
try {
|
|
79
|
+
const repo = repository(root);
|
|
80
|
+
const dbPath = join(root, "state.db");
|
|
81
|
+
const workspace = await createWorkspaceService({ root: repo, worktreeRoot: join(root, "trees"), maxWorktrees: 8 });
|
|
82
|
+
const ui = createScriptedHostUi({ confirm: true });
|
|
83
|
+
// Every agent gets the one workspace service, so a worktree the workflow creates is the one a driver resolves.
|
|
84
|
+
const shared = definePackage({
|
|
85
|
+
name: "@example/build-shared",
|
|
86
|
+
version: "1.0.0",
|
|
87
|
+
requires: { api: 1 },
|
|
88
|
+
setup: (prism) => prism.services.provide("workspace", workspace),
|
|
89
|
+
});
|
|
90
|
+
const store = () => sqliteStore({ path: dbPath });
|
|
91
|
+
|
|
92
|
+
// Drivers: one profile each, so the UI engineer's `maxConcurrentRuns` is the cap fanOut has to respect.
|
|
93
|
+
const driverAgent = async (
|
|
94
|
+
adapter: typeof streamCli | typeof rpcServer,
|
|
95
|
+
dialect: typeof streamCliDialect,
|
|
96
|
+
fixtures: typeof streamCliFixtures,
|
|
97
|
+
options: { name: string; script: readonly ScriptStep[]; cap?: number },
|
|
98
|
+
): Promise<Agent> => {
|
|
99
|
+
const cli = createScriptedCli({ dialect, script: options.script });
|
|
100
|
+
clis.push(cli);
|
|
101
|
+
await createProfiles({ root, driver: adapterDriver(adapter) }).create(options.name, {
|
|
102
|
+
mode: "key",
|
|
103
|
+
principal: "build",
|
|
104
|
+
...(options.cap === undefined ? {} : { maxConcurrentRuns: options.cap }),
|
|
105
|
+
});
|
|
106
|
+
return createAgent({
|
|
107
|
+
id: options.name,
|
|
108
|
+
packages: [store(), shared, processDriver(adapter)],
|
|
109
|
+
packageConfig: {
|
|
110
|
+
[adapter.name]: { ...fixtures.config(cli), name: options.name, profile: options.name, profilesRoot: root, principal: "build" },
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const plan = JSON.stringify({ tasks: TASKS });
|
|
116
|
+
const planner = await driverAgent(streamCli, streamCliDialect, streamCliFixtures, {
|
|
117
|
+
name: "planner",
|
|
118
|
+
script: [{ out: { kind: "message.delta", content: { type: "thinking", text: "Split the goal into six tasks." } } }, ...text(plan)],
|
|
119
|
+
});
|
|
120
|
+
const uiEngineer = await driverAgent(streamCli, streamCliDialect, streamCliFixtures, {
|
|
121
|
+
name: "ui-engineer",
|
|
122
|
+
cap: PROFILE_CAP,
|
|
123
|
+
script: [
|
|
124
|
+
{ out: { kind: "message.delta", content: { type: "thinking", text: "Reuse the Button component." } } },
|
|
125
|
+
{ out: { kind: "subagent", phase: "started", id: "sub-1", name: "reviewer", parentToolCallId: "t-1" } },
|
|
126
|
+
{ wait: 300 },
|
|
127
|
+
{ out: { kind: "subagent", phase: "completed", id: "sub-1", result: "ok" } },
|
|
128
|
+
...text("UI task done."),
|
|
129
|
+
],
|
|
130
|
+
});
|
|
131
|
+
// The validator's frames use the same dialect-agnostic shape; the rpc-server dialect encodes them.
|
|
132
|
+
const validator = await driverAgent(
|
|
133
|
+
rpcServer,
|
|
134
|
+
rpcServerDialect as typeof streamCliDialect,
|
|
135
|
+
rpcServerFixtures as typeof streamCliFixtures,
|
|
136
|
+
{
|
|
137
|
+
name: "validator",
|
|
138
|
+
script: text("Validated: all merged files present."),
|
|
139
|
+
},
|
|
140
|
+
);
|
|
141
|
+
let onRun: (started: WorkflowRun) => void = () => undefined;
|
|
142
|
+
const started = new Promise<WorkflowRun>((resolve) => {
|
|
143
|
+
onRun = resolve;
|
|
144
|
+
});
|
|
145
|
+
const host = await createAgent({
|
|
146
|
+
id: "host",
|
|
147
|
+
model: { provider: "mock", model: "m" },
|
|
148
|
+
packages: [
|
|
149
|
+
store(),
|
|
150
|
+
shared,
|
|
151
|
+
workflows,
|
|
152
|
+
mockProvider([[providerTextDelta("Research: prefer small, mergeable tasks."), providerDone()]]),
|
|
153
|
+
definePackage({
|
|
154
|
+
name: "@example/build-command",
|
|
155
|
+
version: "1.0.0",
|
|
156
|
+
requires: { api: 1 },
|
|
157
|
+
setup: (prism) =>
|
|
158
|
+
prism.commands.register(
|
|
159
|
+
workflowCommand(prism, "build", () => build, {
|
|
160
|
+
description: "Run the build workflow",
|
|
161
|
+
args: {
|
|
162
|
+
type: "object",
|
|
163
|
+
properties: { goal: { type: "string", minLength: 1 } },
|
|
164
|
+
required: ["goal"],
|
|
165
|
+
additionalProperties: false,
|
|
166
|
+
},
|
|
167
|
+
onRun: (started) => onRun(started),
|
|
168
|
+
}),
|
|
169
|
+
),
|
|
170
|
+
}),
|
|
171
|
+
],
|
|
172
|
+
host: { ui: ui.ui },
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
let planAttempts = 0;
|
|
176
|
+
let planned: typeof TASKS = [];
|
|
177
|
+
const merged: string[] = [];
|
|
178
|
+
const build = defineWorkflow({
|
|
179
|
+
id: "build",
|
|
180
|
+
revision: "1",
|
|
181
|
+
limits: { maxSupersteps: 24, maxConcurrency: 4 },
|
|
182
|
+
nodes: {
|
|
183
|
+
research: agentNode({ agent: host, input: (ctx) => `Research: ${String(ctx.workflowInput)}` }),
|
|
184
|
+
plan: agentNode({
|
|
185
|
+
agent: planner,
|
|
186
|
+
activation: "any",
|
|
187
|
+
input: (ctx) => `Plan: ${String(ctx.upstream.research ?? ctx.workflowInput)}`,
|
|
188
|
+
}),
|
|
189
|
+
planOk: gateNode({
|
|
190
|
+
check: (ctx) => {
|
|
191
|
+
planAttempts += 1;
|
|
192
|
+
// The first draft is rejected as unreviewed; the revision passes.
|
|
193
|
+
if (planAttempts < 2) return { pass: false, reason: "plan_unreviewed" };
|
|
194
|
+
planned = (JSON.parse(String(ctx.upstream.plan)) as { tasks: typeof TASKS }).tasks;
|
|
195
|
+
return { pass: true };
|
|
196
|
+
},
|
|
197
|
+
}),
|
|
198
|
+
approve: humanGate({ request: { kind: "confirm", title: "Execute this plan?" }, onFail: "plan" }),
|
|
199
|
+
// A node a failed gate routes back to needs `activation: "any"`: its back edge is not an upstream it waits for.
|
|
200
|
+
execute: fanOut({
|
|
201
|
+
activation: "any",
|
|
202
|
+
items: () => planned,
|
|
203
|
+
maxConcurrency: 4,
|
|
204
|
+
route: (item) => {
|
|
205
|
+
const task = item as (typeof TASKS)[number];
|
|
206
|
+
return agentNode({
|
|
207
|
+
agent: task.ui ? uiEngineer : host,
|
|
208
|
+
worktree: true,
|
|
209
|
+
input: () => task.prompt,
|
|
210
|
+
// The scripted binaries edit nothing, so the node writes this task's file into its own worktree.
|
|
211
|
+
output: (result) => {
|
|
212
|
+
const tree = workspace.worktree.bound(result.sessionId);
|
|
213
|
+
assert(tree !== undefined, `task ${task.id} has no bound worktree`);
|
|
214
|
+
writeFileSync(join(tree.path, `task-${task.id}.txt`), `${result.text}\n`);
|
|
215
|
+
return { task: task.id };
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
},
|
|
219
|
+
}),
|
|
220
|
+
merge: gateNode({
|
|
221
|
+
check: async (ctx) => {
|
|
222
|
+
const results = ctx.upstream.execute as { worktree: { path: string; branch: string } }[];
|
|
223
|
+
for (const [index, item] of results.entries()) {
|
|
224
|
+
const outcome = await workspace.merge(item.worktree.path, { into: "main", commit: { message: `task ${index + 1}` } });
|
|
225
|
+
if (outcome.status !== "merged") return { pass: false, reason: "merge_conflict" };
|
|
226
|
+
merged.push(item.worktree.branch);
|
|
227
|
+
}
|
|
228
|
+
return { pass: true };
|
|
229
|
+
},
|
|
230
|
+
}),
|
|
231
|
+
validate: agentNode({ activation: "any", agent: validator, input: () => "Validate the merged tree." }),
|
|
232
|
+
tests: gateNode({
|
|
233
|
+
check: () => {
|
|
234
|
+
const present = TASKS.every((task) => existsSync(join(repo, `task-${task.id}.txt`)));
|
|
235
|
+
return present ? { pass: true } : { pass: false, reason: "missing_task_files" };
|
|
236
|
+
},
|
|
237
|
+
}),
|
|
238
|
+
},
|
|
239
|
+
edges: [
|
|
240
|
+
["research", "plan"],
|
|
241
|
+
["plan", "planOk"],
|
|
242
|
+
["planOk", "plan"],
|
|
243
|
+
["planOk", "approve"],
|
|
244
|
+
["approve", "plan"],
|
|
245
|
+
["approve", "execute"],
|
|
246
|
+
["execute", "merge"],
|
|
247
|
+
// A failed merge gate re-runs the fan-out; a failed tests gate re-runs the validator.
|
|
248
|
+
["merge", "execute"],
|
|
249
|
+
["merge", "validate"],
|
|
250
|
+
["validate", "tests"],
|
|
251
|
+
["tests", "validate"],
|
|
252
|
+
],
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const parent = await host.session();
|
|
256
|
+
// The command resolves when the run ends, so render the stream from the run `onRun` hands over.
|
|
257
|
+
const command = host.commands.run("build", { goal: "add six tasks" }, { session: parent });
|
|
258
|
+
const run = await Promise.race([started, command.then(() => Promise.reject(new Error("build ended before it started")))]);
|
|
259
|
+
const events: WorkflowStreamEvent[] = [];
|
|
260
|
+
for await (const event of run.stream()) {
|
|
261
|
+
events.push(event);
|
|
262
|
+
}
|
|
263
|
+
const result = await run.result();
|
|
264
|
+
await command;
|
|
265
|
+
assert(result.status === "succeeded", `workflow ended ${result.status}`);
|
|
266
|
+
|
|
267
|
+
// Done: the gate routed back once, inside maxSupersteps.
|
|
268
|
+
const gates = events.filter((e) => e.type === "package.event" && e.name === "workflow.gate") as {
|
|
269
|
+
data?: { nodeId?: string; pass?: boolean };
|
|
270
|
+
}[];
|
|
271
|
+
const planGate = gates.filter((g) => g.data?.nodeId === "planOk");
|
|
272
|
+
assert(planGate.length === 2 && planGate[0]?.data?.pass === false, "the plan gate should fail once, then pass");
|
|
273
|
+
|
|
274
|
+
// Done: the merged stream carries each agent's events with origin, including a sub-agent and thinking.
|
|
275
|
+
// An external origin names the adapter it ran under; native children carry none.
|
|
276
|
+
const agentEvents = events.filter((e): e is AgentEvent => e.type !== "package.event");
|
|
277
|
+
const external = agentEvents.filter((e) => e.origin?.kind === "external");
|
|
278
|
+
const adapters = new Set(external.map((e) => e.origin?.agent));
|
|
279
|
+
assert(adapters.has(streamCli.name) && adapters.has(rpcServer.name), `origins seen: ${[...adapters].join(",")}`);
|
|
280
|
+
assert(
|
|
281
|
+
external.some((e) => e.type === "message.delta" && e.content.type === "thinking"),
|
|
282
|
+
"no thinking delta in the stream",
|
|
283
|
+
);
|
|
284
|
+
assert(
|
|
285
|
+
external.some((e) => e.origin?.subagentId !== undefined && (e.origin?.depth ?? 0) > 0),
|
|
286
|
+
"no sub-agent origin in the stream",
|
|
287
|
+
);
|
|
288
|
+
assert(
|
|
289
|
+
agentEvents.some((e) => e.origin === undefined),
|
|
290
|
+
"the host's own events should carry no origin",
|
|
291
|
+
);
|
|
292
|
+
|
|
293
|
+
// Done: fanOut never ran more UI-engineer runs at once than the profile allows.
|
|
294
|
+
const children = await host.sessions.list({ workflowRunId: run.id });
|
|
295
|
+
const uiSessions = new Set(children.items.filter((item) => item.agentId === "ui-engineer").map((item) => item.sessionId));
|
|
296
|
+
// An item refused by the profile is re-queued and opens a new session when it starts, so there can be more than three.
|
|
297
|
+
assert(uiSessions.size >= TASKS.filter((task) => task.ui).length, `only ${uiSessions.size} UI sessions`);
|
|
298
|
+
// A run refused with `profile_busy` starts and fails at once and is retried later, so only completed runs count.
|
|
299
|
+
const uiEvents = agentEvents.filter((e) => e.sessionId !== undefined && uiSessions.has(e.sessionId));
|
|
300
|
+
const admitted = new Set(uiEvents.filter((e) => e.type === "run.completed").map((e) => e.runId));
|
|
301
|
+
let active = 0;
|
|
302
|
+
let peak = 0;
|
|
303
|
+
for (const event of uiEvents.filter((e) => e.runId !== undefined && admitted.has(e.runId))) {
|
|
304
|
+
if (event.type === "run.started") peak = Math.max(peak, ++active);
|
|
305
|
+
if (event.type === "run.completed") active -= 1;
|
|
306
|
+
}
|
|
307
|
+
assert(peak === PROFILE_CAP, `UI engineer peak concurrency ${peak}, expected the cap ${PROFILE_CAP} reached and not exceeded`);
|
|
308
|
+
|
|
309
|
+
// Done: one search finds both an external agent's message and the host's, across the run's sessions.
|
|
310
|
+
const externalHits = await host.sessions.search({ query: "UI task done", workflowRunId: run.id });
|
|
311
|
+
const hosted = await host.sessions.search({ query: "Research", workflowRunId: run.id });
|
|
312
|
+
assert(externalHits.items.length > 0 && hosted.items.length > 0, "build_workflow_session_search_spans_agents");
|
|
313
|
+
|
|
314
|
+
assert(merged.length === TASKS.length, `merged ${merged.length} of ${TASKS.length} worktrees`);
|
|
315
|
+
assert(readFileSync(join(repo, "task-6.txt"), "utf8").includes("UI task done"), "task 6 is not in the main tree");
|
|
316
|
+
await parent.close();
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
status: result.status,
|
|
320
|
+
planGateRuns: planGate.length,
|
|
321
|
+
humanGateAsked: ui.requestsOf("confirm").length,
|
|
322
|
+
originAdapters: [...adapters].sort(),
|
|
323
|
+
uiEngineerPeak: peak,
|
|
324
|
+
profileCap: PROFILE_CAP,
|
|
325
|
+
mergedWorktrees: merged.length,
|
|
326
|
+
searchSpansAgents: true,
|
|
327
|
+
};
|
|
328
|
+
} finally {
|
|
329
|
+
for (const cli of clis) cli.dispose();
|
|
330
|
+
rmSync(root, { recursive: true, force: true });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (import.meta.url === `file://${process.argv[1]}`) console.log(JSON.stringify(await demo()));
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { type ModelProvider, assembleProviderInput, type ModelConfig, type ProviderRequest, type Usage } from "@arnilo/prism";
|
|
2
|
+
import { cacheHitRate, cacheSavings, cacheUsageReport } from "@arnilo/prism/provider-kit";
|
|
3
|
+
import { createHyperProvider, defineHyperModel } from "@arnilo/prism-ai/hyper";
|
|
4
|
+
import { createOpenCodeGoProvider, defineOpenCodeGoModel } from "@arnilo/prism-ai/opencode-go";
|
|
5
|
+
|
|
6
|
+
const explicitCacheModel = defineHyperModel({
|
|
7
|
+
model: "claude-sonnet-4",
|
|
8
|
+
compat: { route: "openai" },
|
|
9
|
+
cache: { kind: "cache_control", maxBreakpoints: 4, longRetention: true },
|
|
10
|
+
cost: { input: 3, output: 15, cacheRead: 0.3, currency: "USD", unit: "1m_tokens" },
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const implicitCacheModel = defineOpenCodeGoModel({
|
|
14
|
+
model: "gpt-5.1-go",
|
|
15
|
+
compat: { route: "openai" },
|
|
16
|
+
cache: { kind: "implicit" },
|
|
17
|
+
cost: { input: 1, output: 3, cacheRead: 0.25, currency: "USD", unit: "1m_tokens" },
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
async function assemble(model: ModelConfig): Promise<ProviderRequest> {
|
|
21
|
+
return assembleProviderInput({
|
|
22
|
+
model,
|
|
23
|
+
inputLayout: "cache_aware",
|
|
24
|
+
// Host context is a `context.build` handler now, so this assembler call sees only what the
|
|
25
|
+
// kernel assembles: instructions, skills, attachments, summaries, and the transcript.
|
|
26
|
+
systemInstructions: "Answer from the pinned workspace context.",
|
|
27
|
+
skills: [{ name: "concise", description: "Keep answers short.", instructions: "Use concise answers." }],
|
|
28
|
+
skillsDisclosure: "progressive",
|
|
29
|
+
attachments: [{ name: "schema.md", text: "Stable response schema." }],
|
|
30
|
+
summaries: ["Stable project summary reused across turns."],
|
|
31
|
+
history: [
|
|
32
|
+
{ role: "user", content: [{ type: "text", text: "Summarize the cache plan." }] },
|
|
33
|
+
{ role: "assistant", content: [{ type: "text", text: "Keep stable context before new turns." }] },
|
|
34
|
+
],
|
|
35
|
+
input: "What changed since the last turn?",
|
|
36
|
+
// Agent sessions stamp sessionId from session.id; this custom assemble site still passes it.
|
|
37
|
+
providerOptions: {
|
|
38
|
+
sessionId: "workspace-cache-demo",
|
|
39
|
+
cache: {
|
|
40
|
+
mode: "on",
|
|
41
|
+
key: "workspace-cache-demo",
|
|
42
|
+
retention: "long",
|
|
43
|
+
breakpoints: [{ location: "system_prompt" }, { location: "last_stable_message" }],
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function run(provider: ModelProvider, request: ProviderRequest): Promise<Usage | undefined> {
|
|
50
|
+
let usage: Usage | undefined;
|
|
51
|
+
for await (const event of provider.generate(request)) {
|
|
52
|
+
if (event.type === "usage") usage = event.usage;
|
|
53
|
+
if (event.type === "done") usage = event.usage ?? usage;
|
|
54
|
+
if (event.type === "error") throw new Error(event.error.message);
|
|
55
|
+
}
|
|
56
|
+
return usage;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function summarize(model: ModelConfig, usage: Usage | undefined) {
|
|
60
|
+
const report = cacheUsageReport(usage, model);
|
|
61
|
+
const hitRate = cacheHitRate(usage);
|
|
62
|
+
const savings = cacheSavings(usage, model);
|
|
63
|
+
return {
|
|
64
|
+
provider: model.provider,
|
|
65
|
+
cacheKind: model.cache?.kind,
|
|
66
|
+
cacheReadTokens: report?.cacheReadTokens,
|
|
67
|
+
cacheWriteTokens: report?.cacheWriteTokens,
|
|
68
|
+
cacheHitRate: hitRate,
|
|
69
|
+
cacheHitRatePercent: hitRate === undefined ? undefined : Math.round(hitRate * 100),
|
|
70
|
+
cacheSavings: savings,
|
|
71
|
+
currency: report?.currency,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function sse(chunks: readonly unknown[]) {
|
|
76
|
+
const encoder = new TextEncoder();
|
|
77
|
+
return new ReadableStream<Uint8Array>({
|
|
78
|
+
start(controller) {
|
|
79
|
+
for (const chunk of chunks) controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
|
|
80
|
+
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
81
|
+
controller.close();
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function ok(body: ReadableStream<Uint8Array>) {
|
|
87
|
+
return Promise.resolve(new Response(body, { status: 200 }));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function demo() {
|
|
91
|
+
const hyperProvider = createHyperProvider({
|
|
92
|
+
apiKey: async () => "fake-hyper-key",
|
|
93
|
+
fetch: () =>
|
|
94
|
+
ok(
|
|
95
|
+
sse([
|
|
96
|
+
{ choices: [{ delta: { content: "Hyper" } }] },
|
|
97
|
+
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
|
98
|
+
{
|
|
99
|
+
usage: {
|
|
100
|
+
prompt_tokens: 2000,
|
|
101
|
+
completion_tokens: 20,
|
|
102
|
+
total_tokens: 2020,
|
|
103
|
+
prompt_tokens_details: { cached_tokens: 1500, cache_write_tokens: 400 },
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
]),
|
|
107
|
+
),
|
|
108
|
+
});
|
|
109
|
+
const opencodeGoProvider = createOpenCodeGoProvider({
|
|
110
|
+
apiKey: async () => "fake-opencode-go-key",
|
|
111
|
+
fetch: () =>
|
|
112
|
+
ok(
|
|
113
|
+
sse([
|
|
114
|
+
{ choices: [{ delta: { content: "OpenCodeGo" } }] },
|
|
115
|
+
{ choices: [{ delta: {}, finish_reason: "stop" }] },
|
|
116
|
+
{ usage: { prompt_tokens: 2000, completion_tokens: 20, total_tokens: 2020, prompt_tokens_details: { cached_tokens: 1600 } } },
|
|
117
|
+
]),
|
|
118
|
+
),
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const hyper = await assemble(explicitCacheModel);
|
|
122
|
+
const opencodeGo = await assemble(implicitCacheModel);
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
hyper: summarize(explicitCacheModel, await run(hyperProvider, hyper)),
|
|
126
|
+
opencodeGo: {
|
|
127
|
+
...summarize(implicitCacheModel, await run(opencodeGoProvider, opencodeGo)),
|
|
128
|
+
note: "OpenCode Go receives stable-prefix input; its provider sends no explicit cache payload.",
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function main() {
|
|
134
|
+
console.log(JSON.stringify(await demo()));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
138
|
+
await main();
|
|
139
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import {
|
|
4
|
+
assembleProviderInput,
|
|
5
|
+
createAgent,
|
|
6
|
+
createLoadedSkillSet,
|
|
7
|
+
createLoadSkillTool,
|
|
8
|
+
createMemorySessionStore,
|
|
9
|
+
createSessionEntry,
|
|
10
|
+
createSkillRegistry,
|
|
11
|
+
createToolRegistry,
|
|
12
|
+
definePackage,
|
|
13
|
+
dispatchToolCall,
|
|
14
|
+
type ProviderRequest,
|
|
15
|
+
providerDone,
|
|
16
|
+
resolveActiveSkills,
|
|
17
|
+
type Skill,
|
|
18
|
+
toolCallContent,
|
|
19
|
+
} from "@arnilo/prism";
|
|
20
|
+
import { loadSkillDirectory } from "@arnilo/prism/node/contribution-discovery";
|
|
21
|
+
import { mockProvider } from "@arnilo/prism/testing";
|
|
22
|
+
|
|
23
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
const skillsDir = join(here, "fixtures/behavior-skills/skills");
|
|
25
|
+
const sessionId = "behavior-demo";
|
|
26
|
+
|
|
27
|
+
const _PONYTAIL_BODY_MARKER = "seen every over-engineered codebase";
|
|
28
|
+
const AUDIT_BODY_MARKER = "ponytail-review, repo-wide";
|
|
29
|
+
|
|
30
|
+
type HostStore = ReturnType<typeof createMemorySessionStore>;
|
|
31
|
+
|
|
32
|
+
function messageText(request: Awaited<ReturnType<typeof assembleProviderInput>>): string {
|
|
33
|
+
return request.messages
|
|
34
|
+
.flatMap((message) => message.content)
|
|
35
|
+
.map((block) => (block.type === "text" ? block.text : ""))
|
|
36
|
+
.join("\n");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface PersonaOptions {
|
|
40
|
+
/** Command name, mode header prefix, and the SKILL.md whose body becomes the slice. */
|
|
41
|
+
readonly name: "caveman" | "ponytail";
|
|
42
|
+
readonly skills: readonly Skill[];
|
|
43
|
+
readonly store: HostStore;
|
|
44
|
+
/** Session-entry `data.type` used to persist/restore the mode: `caveman-level` / `ponytail-mode`. */
|
|
45
|
+
readonly stateType: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Host-owned persona: no package subpath needed. One extension loads upstream
|
|
50
|
+
* skills from disk, registers a `/mode` command, persists the active mode into
|
|
51
|
+
* session entries, and injects the upstream SKILL.md body every turn while the
|
|
52
|
+
* mode is not `off`.
|
|
53
|
+
*/
|
|
54
|
+
function personaPackage(options: PersonaOptions) {
|
|
55
|
+
const bodies = new Map(options.skills.map((skill) => [skill.name, skill.instructions ?? ""] as const));
|
|
56
|
+
let mode = "off";
|
|
57
|
+
return definePackage({
|
|
58
|
+
name: `@example/${options.name}`,
|
|
59
|
+
version: "1.0.0",
|
|
60
|
+
requires: { api: 1 },
|
|
61
|
+
async setup(prism) {
|
|
62
|
+
const entries = await options.store.list(sessionId);
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
const data = entry.kind === "custom" ? (entry.data as { type?: unknown; mode?: unknown }) : undefined;
|
|
65
|
+
if (data?.type === options.stateType && typeof data.mode === "string") mode = data.mode;
|
|
66
|
+
}
|
|
67
|
+
for (const skill of options.skills) prism.skills.register(skill);
|
|
68
|
+
prism.commands.register({
|
|
69
|
+
name: options.name,
|
|
70
|
+
description: `Set the ${options.name} persona mode`,
|
|
71
|
+
args: { type: "object", properties: { mode: { type: "string" } }, additionalProperties: false },
|
|
72
|
+
async run(args) {
|
|
73
|
+
mode = typeof args.mode === "string" ? args.mode : "full";
|
|
74
|
+
const listed = await options.store.list(sessionId);
|
|
75
|
+
const parentId = listed.at(-1)?.id;
|
|
76
|
+
await options.store.append(
|
|
77
|
+
createSessionEntry({
|
|
78
|
+
sessionId,
|
|
79
|
+
parentId,
|
|
80
|
+
kind: "custom",
|
|
81
|
+
data: { type: options.stateType, mode },
|
|
82
|
+
}),
|
|
83
|
+
{ expectedParentId: parentId },
|
|
84
|
+
);
|
|
85
|
+
return { mode };
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
prism.hooks.on(
|
|
89
|
+
"context.build",
|
|
90
|
+
(draft) => {
|
|
91
|
+
if (mode === "off") return undefined;
|
|
92
|
+
const body = bodies.get(options.name) ?? "";
|
|
93
|
+
const text = `${options.name.toUpperCase()} MODE ACTIVE (${mode})\n\n${body}`;
|
|
94
|
+
const boundary = draft.messages.findIndex((message) => message.role !== "system");
|
|
95
|
+
const at = boundary === -1 ? draft.messages.length : boundary;
|
|
96
|
+
return {
|
|
97
|
+
...draft,
|
|
98
|
+
messages: [
|
|
99
|
+
...draft.messages.slice(0, at),
|
|
100
|
+
{ id: `${options.name}-mode:${at}`, role: "system", content: [{ type: "text", text }] },
|
|
101
|
+
...draft.messages.slice(at),
|
|
102
|
+
],
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
{ id: `${options.name}-mode` },
|
|
106
|
+
);
|
|
107
|
+
},
|
|
108
|
+
})();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Host-owned persona packages: upstream skills loaded from disk, progressive catalog,
|
|
112
|
+
// load_skill, mode injector + session-entry persistence (network-free).
|
|
113
|
+
export async function demo() {
|
|
114
|
+
const store = createMemorySessionStore();
|
|
115
|
+
const skills = await loadSkillDirectory(skillsDir);
|
|
116
|
+
const [cavemanSkill, ponytailSkill, auditSkill] = ["caveman", "ponytail", "ponytail-audit"].map((name) => {
|
|
117
|
+
const skill = skills.find((candidate) => candidate.name === name);
|
|
118
|
+
if (!skill) throw new Error(`missing fixture skill: ${name}`);
|
|
119
|
+
return skill;
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const registry = createSkillRegistry([ponytailSkill, cavemanSkill, auditSkill]);
|
|
123
|
+
const loaded = createLoadedSkillSet();
|
|
124
|
+
const loadSkill = createLoadSkillTool({ registry, loaded });
|
|
125
|
+
const toolRegistry = createToolRegistry([loadSkill]);
|
|
126
|
+
const activeNames = ["ponytail", "caveman", "ponytail-audit"];
|
|
127
|
+
const activeSkills = resolveActiveSkills({ registry, names: activeNames });
|
|
128
|
+
|
|
129
|
+
const captured: ProviderRequest[] = [];
|
|
130
|
+
const agent = await createAgent({
|
|
131
|
+
model: { provider: "mock", model: "demo" },
|
|
132
|
+
packages: [
|
|
133
|
+
personaPackage({ name: "caveman", skills: [cavemanSkill], store, stateType: "caveman-level" }),
|
|
134
|
+
personaPackage({ name: "ponytail", skills: [ponytailSkill, auditSkill], store, stateType: "ponytail-mode" }),
|
|
135
|
+
mockProvider([[providerDone()]], { onRequest: (request) => captured.push(request) }),
|
|
136
|
+
],
|
|
137
|
+
});
|
|
138
|
+
await agent.commands.run("ponytail", { mode: "lite" });
|
|
139
|
+
await agent.commands.run("caveman", { mode: "full" });
|
|
140
|
+
const session = await agent.session({ id: sessionId, create: true });
|
|
141
|
+
|
|
142
|
+
await session.run("Pick skills");
|
|
143
|
+
const catalogText = messageText(captured[0]!);
|
|
144
|
+
// Progressive disclosure: every active skill appears as a one-line catalog entry, and the
|
|
145
|
+
// bodies only reach the transcript once the skill is loaded (or as the persona mode slice).
|
|
146
|
+
const catalogLines = catalogText.split("\n").filter((line) => /^- /.test(line));
|
|
147
|
+
const catalogOnly =
|
|
148
|
+
catalogLines.length === 3 &&
|
|
149
|
+
["ponytail", "caveman", "ponytail-audit"].every((name) => catalogLines.some((line) => line.startsWith(`- ${name}:`)));
|
|
150
|
+
|
|
151
|
+
const injectorText = catalogText;
|
|
152
|
+
const injectorSliceWithoutBody = injectorText.includes("PONYTAIL MODE ACTIVE") && !injectorText.includes(AUDIT_BODY_MARKER);
|
|
153
|
+
|
|
154
|
+
await dispatchToolCall({
|
|
155
|
+
call: toolCallContent("call_1", "load_skill", { name: "ponytail-audit" }),
|
|
156
|
+
registry: toolRegistry,
|
|
157
|
+
context: {
|
|
158
|
+
sessionId,
|
|
159
|
+
runId: "r1",
|
|
160
|
+
toolCallId: "call_1",
|
|
161
|
+
metadata: {
|
|
162
|
+
loadedSkills: loaded,
|
|
163
|
+
activeSkillNames: activeNames,
|
|
164
|
+
activeTools: toolRegistry.list(),
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// The skill body lands once `load_skill` has marked it loaded in the shared set.
|
|
170
|
+
const loadedText = messageText(
|
|
171
|
+
await assembleProviderInput({
|
|
172
|
+
model: { provider: "mock", model: "demo" },
|
|
173
|
+
input: "Audit",
|
|
174
|
+
skills: activeSkills,
|
|
175
|
+
skillsDisclosure: "progressive",
|
|
176
|
+
loadedSkills: loaded,
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
const auditBodyLoaded = loadedText.includes(AUDIT_BODY_MARKER);
|
|
180
|
+
|
|
181
|
+
const entries = await store.list(sessionId);
|
|
182
|
+
const modeEntries = entries.filter((entry) => entry.kind === "custom" && (entry.data as { type?: string }).type === "ponytail-mode");
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
skillCount: skills.length,
|
|
186
|
+
extensionsLoaded: agent.inspect().skills.length > 0,
|
|
187
|
+
catalogOnly,
|
|
188
|
+
injectorSliceWithoutBody,
|
|
189
|
+
auditBodyLoaded,
|
|
190
|
+
loadedCount: loaded.list().length,
|
|
191
|
+
persistedModeEntries: modeEntries.length,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
196
|
+
console.log(JSON.stringify(await demo()));
|
|
197
|
+
}
|