@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,272 @@
|
|
|
1
|
+
import type { Message as AgUiMessage } from "@ag-ui/core";
|
|
2
|
+
import type { AgentEvent } from "@arnilo/prism";
|
|
3
|
+
import type { AgUiProjection } from "./projection.js";
|
|
4
|
+
|
|
5
|
+
/** Default / hard caps for standard message projectors (Task 0 freeze). */
|
|
6
|
+
export const DEFAULT_MAX_PROJECTOR_MESSAGES = 128;
|
|
7
|
+
export const HARD_MAX_PROJECTOR_MESSAGES = 1024;
|
|
8
|
+
|
|
9
|
+
/** Host-owned run-state snapshot source. Prism starts no watcher. */
|
|
10
|
+
export interface AgUiStateStore {
|
|
11
|
+
get(): unknown;
|
|
12
|
+
subscribe?(onChange: () => void): () => void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface CreateMessagesFromSessionProjectionOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Host-owned authorized AG-UI transcript. May be async — e.g. `async () => (await session.entries()).map(entryToAgUiMessage)`.
|
|
18
|
+
* Prefer this for full session history. Absent → accumulate from `message.completed` events in the live stream.
|
|
19
|
+
*/
|
|
20
|
+
readonly getMessages?: () => readonly AgUiMessage[] | Promise<readonly AgUiMessage[]>;
|
|
21
|
+
readonly redact?: (message: AgUiMessage) => AgUiMessage | undefined;
|
|
22
|
+
readonly maxMessages?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CreateStateFromStoreProjectionOptions {
|
|
26
|
+
readonly maxStateBytes?: number;
|
|
27
|
+
readonly maxPatchOperations?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CreateActivityFromToolProgressProjectionOptions {
|
|
31
|
+
readonly activityType?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Opt-in `MESSAGES_SNAPSHOT` projector. Emits when the authorized transcript is available
|
|
36
|
+
* (host `getMessages`) or when the live stream finishes a message.
|
|
37
|
+
*/
|
|
38
|
+
export function createMessagesFromSessionProjection(options: CreateMessagesFromSessionProjectionOptions = {}): AgUiProjection {
|
|
39
|
+
const maxMessages = clamp(options.maxMessages, DEFAULT_MAX_PROJECTOR_MESSAGES, HARD_MAX_PROJECTOR_MESSAGES);
|
|
40
|
+
const accumulated: AgUiMessage[] = [];
|
|
41
|
+
let lastKey: string | undefined;
|
|
42
|
+
|
|
43
|
+
const project = (raw: readonly AgUiMessage[]): readonly AgUiMessage[] | undefined => {
|
|
44
|
+
const out: AgUiMessage[] = [];
|
|
45
|
+
for (const message of raw.slice(-maxMessages)) {
|
|
46
|
+
try {
|
|
47
|
+
const next = options.redact ? options.redact(message) : message;
|
|
48
|
+
if (next) out.push(next);
|
|
49
|
+
} catch {
|
|
50
|
+
// redactor throw → drop that message closed
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const key = stableKey(out);
|
|
54
|
+
if (key === lastKey) return undefined;
|
|
55
|
+
lastKey = key;
|
|
56
|
+
return out;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
async messages(event) {
|
|
61
|
+
if (options.getMessages) {
|
|
62
|
+
if (event.type !== "run.started" && event.type !== "message.completed" && event.type !== "run.completed") {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
return project(await options.getMessages());
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (event.type === "message.completed") {
|
|
72
|
+
const converted = prismMessageToAgUi(event.message);
|
|
73
|
+
if (converted) accumulated.push(converted);
|
|
74
|
+
return project(accumulated);
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Opt-in state projector. `STATE_SNAPSHOT` on `run.started`; RFC 6902 `STATE_DELTA`
|
|
83
|
+
* (add/replace/remove) when `store.get()` changes. Optional `subscribe` only marks dirty —
|
|
84
|
+
* Prism starts no background watcher.
|
|
85
|
+
*/
|
|
86
|
+
export function createStateFromStoreProjection(store: AgUiStateStore, options: CreateStateFromStoreProjectionOptions = {}): AgUiProjection {
|
|
87
|
+
const maxBytes = options.maxStateBytes ?? 64 * 1024;
|
|
88
|
+
const maxOps = options.maxPatchOperations ?? 128;
|
|
89
|
+
let last: unknown;
|
|
90
|
+
let snapped = false;
|
|
91
|
+
let dirty = true;
|
|
92
|
+
store.subscribe?.(() => {
|
|
93
|
+
dirty = true;
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
stateSnapshot(event) {
|
|
98
|
+
if (event.type !== "run.started" || snapped) return undefined;
|
|
99
|
+
try {
|
|
100
|
+
const value = store.get();
|
|
101
|
+
if (!withinBytes(value, maxBytes)) return undefined;
|
|
102
|
+
last = cloneJson(value);
|
|
103
|
+
snapped = true;
|
|
104
|
+
dirty = false;
|
|
105
|
+
return last;
|
|
106
|
+
} catch {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
},
|
|
110
|
+
stateDelta() {
|
|
111
|
+
if (!snapped) return undefined;
|
|
112
|
+
try {
|
|
113
|
+
const value = store.get();
|
|
114
|
+
if (!dirty && stableKey(value) === stableKey(last)) return undefined;
|
|
115
|
+
if (!withinBytes(value, maxBytes)) return undefined;
|
|
116
|
+
const patch = jsonDiff(last, value);
|
|
117
|
+
if (patch.length === 0 || patch.length > maxOps) return undefined;
|
|
118
|
+
last = cloneJson(value);
|
|
119
|
+
dirty = false;
|
|
120
|
+
return patch;
|
|
121
|
+
} catch {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Opt-in activity projector for `tool.progress`. First progress per tool call →
|
|
130
|
+
* snapshot; later updates → delta. Missing/malformed payloads drop closed.
|
|
131
|
+
*/
|
|
132
|
+
export function createActivityFromToolProgressProjection(options: CreateActivityFromToolProgressProjectionOptions = {}): AgUiProjection {
|
|
133
|
+
const activityType = options.activityType ?? "tool-progress";
|
|
134
|
+
const last = new Map<string, Record<string, unknown>>();
|
|
135
|
+
|
|
136
|
+
return {
|
|
137
|
+
activity(event: AgentEvent) {
|
|
138
|
+
if (event.type !== "tool.progress") return undefined;
|
|
139
|
+
if (event.progress === undefined && event.metadata === undefined) return undefined;
|
|
140
|
+
const messageId = `tool-progress-${event.toolCallId}`;
|
|
141
|
+
const content: Record<string, unknown> = {
|
|
142
|
+
toolCallId: event.toolCallId,
|
|
143
|
+
name: event.name,
|
|
144
|
+
...(event.progress !== undefined ? { progress: event.progress } : {}),
|
|
145
|
+
...(event.metadata !== undefined ? { metadata: event.metadata } : {}),
|
|
146
|
+
};
|
|
147
|
+
const previous = last.get(event.toolCallId);
|
|
148
|
+
if (!previous) {
|
|
149
|
+
last.set(event.toolCallId, content);
|
|
150
|
+
return { type: "snapshot" as const, messageId, activityType, content };
|
|
151
|
+
}
|
|
152
|
+
const patch = jsonDiff(previous, content);
|
|
153
|
+
last.set(event.toolCallId, content);
|
|
154
|
+
if (patch.length === 0) return undefined;
|
|
155
|
+
return { type: "delta" as const, messageId, activityType, patch };
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Merge projectors; **first defined callback wins** (left to right). Undefined fragments skipped. */
|
|
161
|
+
export function composeAgUiProjections(...projections: readonly (AgUiProjection | undefined)[]): AgUiProjection {
|
|
162
|
+
const list = projections.filter((item): item is AgUiProjection => item !== undefined);
|
|
163
|
+
const first = <K extends keyof AgUiProjection>(key: K): AgUiProjection[K] | undefined => {
|
|
164
|
+
for (const projection of list) {
|
|
165
|
+
const value = projection[key];
|
|
166
|
+
if (value !== undefined) return value;
|
|
167
|
+
}
|
|
168
|
+
return undefined;
|
|
169
|
+
};
|
|
170
|
+
return {
|
|
171
|
+
toolArguments: first("toolArguments"),
|
|
172
|
+
toolResult: first("toolResult"),
|
|
173
|
+
state: first("state"),
|
|
174
|
+
stateSnapshot: first("stateSnapshot"),
|
|
175
|
+
stateDelta: first("stateDelta"),
|
|
176
|
+
messages: first("messages"),
|
|
177
|
+
activity: first("activity"),
|
|
178
|
+
reasoning: first("reasoning"),
|
|
179
|
+
raw: first("raw"),
|
|
180
|
+
custom: first("custom"),
|
|
181
|
+
interrupt: first("interrupt"),
|
|
182
|
+
coWork: first("coWork"),
|
|
183
|
+
path: first("path"),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Minimal RFC 6902 add/replace/remove diff. Arrays replaced as a whole when unequal. */
|
|
188
|
+
export function jsonDiff(from: unknown, to: unknown, path = ""): unknown[] {
|
|
189
|
+
if (stableKey(from) === stableKey(to)) return [];
|
|
190
|
+
if (!isPlainObject(from) || !isPlainObject(to)) {
|
|
191
|
+
if (path === "") return [{ op: "replace", path: "", value: to }];
|
|
192
|
+
return [{ op: from === undefined ? "add" : "replace", path, value: to }];
|
|
193
|
+
}
|
|
194
|
+
const ops: unknown[] = [];
|
|
195
|
+
for (const key of Object.keys(to)) {
|
|
196
|
+
const child = `${path}/${escapePointer(key)}`;
|
|
197
|
+
if (!Object.hasOwn(from, key)) {
|
|
198
|
+
ops.push({ op: "add", path: child, value: to[key] });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const left = from[key];
|
|
202
|
+
const right = to[key];
|
|
203
|
+
if (stableKey(left) === stableKey(right)) continue;
|
|
204
|
+
if (isPlainObject(left) && isPlainObject(right)) ops.push(...jsonDiff(left, right, child));
|
|
205
|
+
else ops.push({ op: "replace", path: child, value: right });
|
|
206
|
+
}
|
|
207
|
+
for (const key of Object.keys(from)) {
|
|
208
|
+
if (!Object.hasOwn(to, key)) ops.push({ op: "remove", path: `${path}/${escapePointer(key)}` });
|
|
209
|
+
}
|
|
210
|
+
return ops;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function prismMessageToAgUi(message: {
|
|
214
|
+
readonly id?: string;
|
|
215
|
+
readonly role: string;
|
|
216
|
+
readonly content: readonly { readonly type: string; readonly text?: string }[];
|
|
217
|
+
}): AgUiMessage | undefined {
|
|
218
|
+
if (message.role !== "user" && message.role !== "assistant" && message.role !== "system" && message.role !== "developer") {
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
const text = message.content
|
|
222
|
+
.filter((block) => block.type === "text" && typeof block.text === "string")
|
|
223
|
+
.map((block) => block.text as string)
|
|
224
|
+
.join("");
|
|
225
|
+
const id = message.id ?? `msg-${message.role}-${text.length}`;
|
|
226
|
+
switch (message.role) {
|
|
227
|
+
case "user":
|
|
228
|
+
return { id, role: "user", content: text };
|
|
229
|
+
case "assistant":
|
|
230
|
+
return { id, role: "assistant", content: text };
|
|
231
|
+
case "system":
|
|
232
|
+
return { id, role: "system", content: text };
|
|
233
|
+
case "developer":
|
|
234
|
+
return { id, role: "developer", content: text };
|
|
235
|
+
default:
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function escapePointer(key: string): string {
|
|
241
|
+
return key.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
245
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function cloneJson(value: unknown): unknown {
|
|
249
|
+
return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function stableKey(value: unknown): string {
|
|
253
|
+
try {
|
|
254
|
+
return JSON.stringify(value) ?? "undefined";
|
|
255
|
+
} catch {
|
|
256
|
+
return "unserializable";
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function withinBytes(value: unknown, maxBytes: number): boolean {
|
|
261
|
+
try {
|
|
262
|
+
return Buffer.byteLength(JSON.stringify(value) ?? "null", "utf8") <= maxBytes;
|
|
263
|
+
} catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function clamp(value: number | undefined, fallback: number, hard: number): number {
|
|
269
|
+
if (value === undefined) return fallback;
|
|
270
|
+
if (!Number.isFinite(value) || value < 1) return fallback;
|
|
271
|
+
return Math.min(Math.floor(value), hard);
|
|
272
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task 14: thin DOM binding for the A2UI renderer model.
|
|
3
|
+
* Host-supplied catalog component renderers (framework-free functions) and a
|
|
4
|
+
* built-in default text/container set. Never executes remote HTML: only
|
|
5
|
+
* `createElement`/`createTextNode`/`appendChild`; no HTML-string assignment,
|
|
6
|
+
* no dynamic code evaluation.
|
|
7
|
+
*/
|
|
8
|
+
import type { AgUiA2UiAction } from "../a2ui.js";
|
|
9
|
+
import type { A2UiSurfaceModel } from "./core.js";
|
|
10
|
+
import { resolvePointer } from "./core.js";
|
|
11
|
+
|
|
12
|
+
/** Minimal DOM surface the binding needs; testable with a stub, no jsdom. */
|
|
13
|
+
export interface DomNode {
|
|
14
|
+
readonly nodeType: number;
|
|
15
|
+
readonly nodeName: string;
|
|
16
|
+
textContent: string | null;
|
|
17
|
+
readonly children: readonly DomNode[];
|
|
18
|
+
appendChild(child: DomNode): void;
|
|
19
|
+
replaceChildren(...children: DomNode[]): void;
|
|
20
|
+
removeChild(child: DomNode): void;
|
|
21
|
+
setAttribute(name: string, value: string): void;
|
|
22
|
+
addEventListener(type: string, listener: (event: unknown) => void): void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface Dom {
|
|
26
|
+
createElement(tag: string): DomNode;
|
|
27
|
+
createTextNode(text: string): DomNode;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface A2UiRenderContext {
|
|
31
|
+
readonly surfaceId: string;
|
|
32
|
+
readonly dataModel: unknown;
|
|
33
|
+
/** Resolve `{"path": "/pointer"}` bindings against the surface data model. */
|
|
34
|
+
readonly resolve: (value: unknown) => unknown;
|
|
35
|
+
/** Render a sibling component by id (children/child references). */
|
|
36
|
+
readonly renderComponent: (id: string) => DomNode;
|
|
37
|
+
readonly emitAction: (action: AgUiA2UiAction) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type A2UiComponentRenderer = (props: Readonly<Record<string, unknown>>, ctx: A2UiRenderContext, dom: Dom) => DomNode;
|
|
41
|
+
|
|
42
|
+
export type A2UiCatalog = Readonly<Record<string, A2UiComponentRenderer>>;
|
|
43
|
+
|
|
44
|
+
export interface RenderA2UiSurfaceOptions {
|
|
45
|
+
readonly onAction?: (action: AgUiA2UiAction) => void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const MAX_RENDER_DEPTH = 64; // mirrors HARD_MAX_A2UI_COMPONENT_DEPTH
|
|
49
|
+
|
|
50
|
+
/** Render one surface model into a detached DOM node. */
|
|
51
|
+
export function renderA2UiSurface(
|
|
52
|
+
surface: A2UiSurfaceModel,
|
|
53
|
+
catalog: A2UiCatalog,
|
|
54
|
+
dom: Dom,
|
|
55
|
+
options: RenderA2UiSurfaceOptions = {},
|
|
56
|
+
): DomNode {
|
|
57
|
+
const root = dom.createElement("div");
|
|
58
|
+
root.setAttribute("class", "a2ui-surface");
|
|
59
|
+
root.setAttribute("data-surface-id", surface.surfaceId);
|
|
60
|
+
|
|
61
|
+
const visited = new Set<string>();
|
|
62
|
+
const ctx: A2UiRenderContext = {
|
|
63
|
+
surfaceId: surface.surfaceId,
|
|
64
|
+
dataModel: surface.dataModel,
|
|
65
|
+
resolve: (value) => resolveBinding(value, surface.dataModel),
|
|
66
|
+
renderComponent: (id) => renderComponent(id, 0),
|
|
67
|
+
emitAction: (action) => options.onAction?.(action),
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const placeholder = (message: string): DomNode => {
|
|
71
|
+
const node = dom.createElement("div");
|
|
72
|
+
node.setAttribute("class", "a2ui-placeholder");
|
|
73
|
+
node.appendChild(dom.createTextNode(message));
|
|
74
|
+
return node;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function renderComponent(id: string, depth: number): DomNode {
|
|
78
|
+
if (depth > MAX_RENDER_DEPTH) return placeholder("component depth exceeded");
|
|
79
|
+
const component = surface.components.get(id);
|
|
80
|
+
if (!component) return placeholder(`missing component: ${id}`);
|
|
81
|
+
if (visited.has(id)) return placeholder("circular component reference");
|
|
82
|
+
visited.add(id);
|
|
83
|
+
try {
|
|
84
|
+
const renderer = catalog[component.type];
|
|
85
|
+
if (!renderer) return placeholder(`unknown component: ${component.type}`);
|
|
86
|
+
return renderer(component.props, ctx, dom);
|
|
87
|
+
} finally {
|
|
88
|
+
visited.delete(id);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const rootComponent = surface.components.get("root");
|
|
93
|
+
if (!rootComponent) {
|
|
94
|
+
root.appendChild(placeholder("surface has no root component"));
|
|
95
|
+
return root;
|
|
96
|
+
}
|
|
97
|
+
root.appendChild(renderComponent("root", 0));
|
|
98
|
+
return root;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function resolveBinding(value: unknown, dataModel: unknown): unknown {
|
|
102
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
103
|
+
const path = (value as { path?: unknown }).path;
|
|
104
|
+
if (typeof path === "string" && path.startsWith("/")) {
|
|
105
|
+
const resolved = resolvePointer(dataModel, path);
|
|
106
|
+
return resolved === undefined ? undefined : resolved;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Built-in framework-free default catalog: Text, Container/Column/Row, Button. */
|
|
113
|
+
export const DEFAULT_A2UI_CATALOG: A2UiCatalog = {
|
|
114
|
+
Text: (props, ctx, dom) => {
|
|
115
|
+
const node = dom.createElement("div");
|
|
116
|
+
node.setAttribute("class", "a2ui-text");
|
|
117
|
+
const text = ctx.resolve(props.text);
|
|
118
|
+
node.appendChild(dom.createTextNode(text === null || text === undefined ? "" : String(text)));
|
|
119
|
+
return node;
|
|
120
|
+
},
|
|
121
|
+
Container: container("div"),
|
|
122
|
+
Column: container("div"),
|
|
123
|
+
Row: container("div"),
|
|
124
|
+
Button: (props, ctx, dom) => {
|
|
125
|
+
const node = dom.createElement("button");
|
|
126
|
+
node.setAttribute("class", "a2ui-button");
|
|
127
|
+
const label = ctx.resolve(props.label ?? props.text);
|
|
128
|
+
node.appendChild(dom.createTextNode(label === null || label === undefined ? "" : String(label)));
|
|
129
|
+
const actionName = typeof props.actionName === "string" ? props.actionName : typeof props.name === "string" ? props.name : "click";
|
|
130
|
+
node.addEventListener("click", () => {
|
|
131
|
+
ctx.emitAction({
|
|
132
|
+
type: "a2ui-action",
|
|
133
|
+
surfaceId: ctx.surfaceId,
|
|
134
|
+
actionName,
|
|
135
|
+
...(props.payload === undefined ? {} : { payload: props.payload }),
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
return node;
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
function container(tag: string): A2UiComponentRenderer {
|
|
143
|
+
return (props, ctx, dom) => {
|
|
144
|
+
const node = dom.createElement(tag);
|
|
145
|
+
node.setAttribute("class", "a2ui-container");
|
|
146
|
+
const children = Array.isArray(props.children) ? props.children : props.child !== undefined ? [props.child] : [];
|
|
147
|
+
for (const child of children) {
|
|
148
|
+
if (typeof child === "string") node.appendChild(ctx.renderComponent(child));
|
|
149
|
+
}
|
|
150
|
+
return node;
|
|
151
|
+
};
|
|
152
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task 14: DOM-free A2UI renderer core.
|
|
3
|
+
* Pure state machine: A2UI v0.9 operations -> surface/component model.
|
|
4
|
+
* No DOM, no framework, no host build step. Testable without a browser.
|
|
5
|
+
*/
|
|
6
|
+
import { type AGUIEvent, EventType } from "@ag-ui/core";
|
|
7
|
+
import {
|
|
8
|
+
A2UI_ACTIVITY_TYPE,
|
|
9
|
+
A2UI_OPERATIONS_KEY,
|
|
10
|
+
A2UI_VERSION,
|
|
11
|
+
type ResolvedAgUiA2UiLimits,
|
|
12
|
+
truncateA2UiText,
|
|
13
|
+
validateA2UiOp,
|
|
14
|
+
} from "../a2ui.js";
|
|
15
|
+
import { DEFAULT_AG_UI_LIMITS, type ResolvedAgUiLimits } from "../limits.js";
|
|
16
|
+
|
|
17
|
+
export interface A2UiComponentModel {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly type: string;
|
|
20
|
+
/** Flat component properties (A2UI v0.9), minus `id`/`component`. */
|
|
21
|
+
readonly props: Readonly<Record<string, unknown>>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface A2UiSurfaceModel {
|
|
25
|
+
readonly surfaceId: string;
|
|
26
|
+
readonly catalogId?: string;
|
|
27
|
+
readonly components: ReadonlyMap<string, A2UiComponentModel>;
|
|
28
|
+
readonly dataModel: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface A2UiRenderError {
|
|
32
|
+
readonly code: string;
|
|
33
|
+
readonly message: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface A2UiReduceResult {
|
|
37
|
+
/** Surface ids whose model changed in this batch (in first-touch order). */
|
|
38
|
+
readonly changed: readonly string[];
|
|
39
|
+
/** Present when the whole batch was dropped closed (invalid/oversized). */
|
|
40
|
+
readonly error?: A2UiRenderError;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Mutable internal state; exposed as `A2UiSurfaceModel`. */
|
|
44
|
+
export class A2UiSurfaceState implements A2UiSurfaceModel {
|
|
45
|
+
readonly surfaceId: string;
|
|
46
|
+
readonly catalogId: string | undefined;
|
|
47
|
+
readonly components = new Map<string, A2UiComponentModel>();
|
|
48
|
+
dataModel: unknown;
|
|
49
|
+
|
|
50
|
+
constructor(surfaceId: string, catalogId: string | undefined) {
|
|
51
|
+
this.surfaceId = surfaceId;
|
|
52
|
+
this.catalogId = catalogId;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Apply one A2UI operation batch to the renderer model.
|
|
58
|
+
* Mirrors the server painter's fail-closed rules: a batch with too many ops,
|
|
59
|
+
* an invalid op, or a surface cap breach is dropped whole with a bounded
|
|
60
|
+
* error event; nothing partial is applied.
|
|
61
|
+
*
|
|
62
|
+
* `replace` mirrors ACTIVITY_SNAPSHOT semantics (streaming mode sends
|
|
63
|
+
* cumulative ops under a stable message id; fixed-schema sends one snapshot
|
|
64
|
+
* then deltas): each touched surface is reset before the batch applies.
|
|
65
|
+
*/
|
|
66
|
+
export function reduceA2UiOps(
|
|
67
|
+
surfaces: Map<string, A2UiSurfaceState>,
|
|
68
|
+
ops: readonly unknown[],
|
|
69
|
+
a2uiLimits: ResolvedAgUiA2UiLimits,
|
|
70
|
+
base: ResolvedAgUiLimits = DEFAULT_AG_UI_LIMITS,
|
|
71
|
+
replace = false,
|
|
72
|
+
): A2UiReduceResult {
|
|
73
|
+
if (ops.length === 0) return { changed: [] };
|
|
74
|
+
if (ops.length > a2uiLimits.maxOperationsPerMessage) {
|
|
75
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_LIMIT", "Too many A2UI operations", base) };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const validated: Record<string, unknown>[] = [];
|
|
79
|
+
for (const item of ops) {
|
|
80
|
+
const op = validateA2UiOp(item, a2uiLimits, base);
|
|
81
|
+
if (!op) return { changed: [], error: limitError("ERR_PRISM_A2UI_OP", "Invalid A2UI operation", base) };
|
|
82
|
+
validated.push(op);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Surface-cap check first, fail closed like the server painter.
|
|
86
|
+
const toCreate = validated.filter(
|
|
87
|
+
(op) => "createSurface" in op && !surfaces.has(String((op.createSurface as { surfaceId?: unknown }).surfaceId)),
|
|
88
|
+
);
|
|
89
|
+
if (toCreate.length > 0 && surfaces.size + toCreate.length > a2uiLimits.maxSurfacesPerRun) {
|
|
90
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_LIMIT", "Too many A2UI surfaces", base) };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Structural pre-pass: every op must be applicable before any mutation
|
|
94
|
+
// (fail closed atomically — no partial batch). createSurface ops in this
|
|
95
|
+
// batch count as known surfaces.
|
|
96
|
+
const known = new Set(surfaces.keys());
|
|
97
|
+
for (const op of validated) {
|
|
98
|
+
if ("createSurface" in op) known.add(String((op.createSurface as { surfaceId: string }).surfaceId));
|
|
99
|
+
}
|
|
100
|
+
for (const op of validated) {
|
|
101
|
+
if ("updateComponents" in op) {
|
|
102
|
+
const body = op.updateComponents as { surfaceId: string; components: unknown };
|
|
103
|
+
if (!known.has(body.surfaceId)) {
|
|
104
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_OP", "createSurface required before updates", base) };
|
|
105
|
+
}
|
|
106
|
+
if (!validComponents(body.components)) {
|
|
107
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_OP", "Invalid A2UI operation", base) };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if ("updateDataModel" in op) {
|
|
111
|
+
const body = op.updateDataModel as { surfaceId: string; path?: string };
|
|
112
|
+
if (!known.has(body.surfaceId)) {
|
|
113
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_OP", "createSurface required before updates", base) };
|
|
114
|
+
}
|
|
115
|
+
const pointer = body.path ?? "/";
|
|
116
|
+
if (pointer.length > 4096 || !pointer.startsWith("/")) {
|
|
117
|
+
return { changed: [], error: limitError("ERR_PRISM_A2UI_OP", "Invalid A2UI operation", base) };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const changed = new Set<string>();
|
|
123
|
+
const touched = new Set<string>();
|
|
124
|
+
const resetDone = new Set<string>();
|
|
125
|
+
for (const op of validated) {
|
|
126
|
+
if ("createSurface" in op) {
|
|
127
|
+
const body = op.createSurface as { surfaceId: string; catalogId?: string };
|
|
128
|
+
if (surfaces.has(body.surfaceId)) continue; // streaming snapshots re-send createSurface
|
|
129
|
+
surfaces.set(body.surfaceId, new A2UiSurfaceState(body.surfaceId, body.catalogId));
|
|
130
|
+
touched.add(body.surfaceId);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if ("updateComponents" in op) {
|
|
134
|
+
const body = op.updateComponents as { surfaceId: string; components: unknown };
|
|
135
|
+
const state = surfaces.get(body.surfaceId)!;
|
|
136
|
+
if (replace && !resetDone.has(body.surfaceId)) {
|
|
137
|
+
resetSurface(state);
|
|
138
|
+
resetDone.add(body.surfaceId);
|
|
139
|
+
}
|
|
140
|
+
touched.add(body.surfaceId);
|
|
141
|
+
applyComponents(state, body.components);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if ("updateDataModel" in op) {
|
|
145
|
+
const body = op.updateDataModel as { surfaceId: string; path?: string; value?: unknown };
|
|
146
|
+
const state = surfaces.get(body.surfaceId)!;
|
|
147
|
+
if (replace && !resetDone.has(body.surfaceId)) {
|
|
148
|
+
resetSurface(state);
|
|
149
|
+
resetDone.add(body.surfaceId);
|
|
150
|
+
}
|
|
151
|
+
touched.add(body.surfaceId);
|
|
152
|
+
state.dataModel = setAtPointer(state.dataModel, body.path ?? "/", body.value);
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if ("deleteSurface" in op) {
|
|
156
|
+
const body = op.deleteSurface as { surfaceId: string };
|
|
157
|
+
if (surfaces.delete(body.surfaceId)) touched.add(body.surfaceId); // safe no-op when absent
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
for (const id of touched) if (surfaces.has(id)) changed.add(id);
|
|
162
|
+
return { changed: [...changed] };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Extract the A2UI operation batch from one AG-UI activity event.
|
|
167
|
+
* Snapshot -> `a2ui_operations` (replace); delta -> RFC 6902 adds to
|
|
168
|
+
* `/a2ui_operations/-` (append). Returns undefined for unrelated events.
|
|
169
|
+
*/
|
|
170
|
+
export function readA2UiBatch(event: AGUIEvent): { ops: unknown[]; replace: boolean } | undefined {
|
|
171
|
+
if (event.type === EventType.ACTIVITY_SNAPSHOT && event.activityType === A2UI_ACTIVITY_TYPE) {
|
|
172
|
+
const content = event.content as Record<string, unknown> | undefined;
|
|
173
|
+
const ops = content?.[A2UI_OPERATIONS_KEY];
|
|
174
|
+
return Array.isArray(ops) ? { ops, replace: true } : undefined;
|
|
175
|
+
}
|
|
176
|
+
if (event.type === EventType.ACTIVITY_DELTA && event.activityType === A2UI_ACTIVITY_TYPE && Array.isArray(event.patch)) {
|
|
177
|
+
const ops: unknown[] = [];
|
|
178
|
+
for (const entry of event.patch) {
|
|
179
|
+
if (
|
|
180
|
+
entry &&
|
|
181
|
+
typeof entry === "object" &&
|
|
182
|
+
(entry as { op?: unknown }).op === "add" &&
|
|
183
|
+
(entry as { path?: unknown }).path === `/${A2UI_OPERATIONS_KEY}/-` &&
|
|
184
|
+
Object.hasOwn(entry as object, "value")
|
|
185
|
+
) {
|
|
186
|
+
ops.push((entry as { value: unknown }).value);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return ops.length > 0 ? { ops, replace: false } : undefined;
|
|
190
|
+
}
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Resolve a JSON Pointer against a value (used for `{"path": "/..."}` bindings). */
|
|
195
|
+
export function resolvePointer(root: unknown, pointer: string): unknown {
|
|
196
|
+
if (!pointer.startsWith("/")) return undefined;
|
|
197
|
+
let current = root;
|
|
198
|
+
for (const raw of pointer.slice(1).split("/")) {
|
|
199
|
+
const token = raw.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
200
|
+
if (current === null || current === undefined) return undefined;
|
|
201
|
+
if (Array.isArray(current)) {
|
|
202
|
+
const index = /^(0|[1-9][0-9]*)$/.test(token) ? Number(token) : -1;
|
|
203
|
+
if (index < 0 || index >= current.length) return undefined;
|
|
204
|
+
current = current[index];
|
|
205
|
+
} else if (typeof current === "object" && Object.hasOwn(current as object, token)) {
|
|
206
|
+
current = (current as Record<string, unknown>)[token];
|
|
207
|
+
} else {
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return current;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function setAtPointer(root: unknown, pointer: string, value: unknown): unknown {
|
|
215
|
+
const tokens = pointer
|
|
216
|
+
.slice(1)
|
|
217
|
+
.split("/")
|
|
218
|
+
.map((t) => t.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
219
|
+
if (tokens.length === 1 && tokens[0] === "") return value; // "/" replaces the whole model
|
|
220
|
+
if (root === null || root === undefined || typeof root !== "object" || Array.isArray(root)) root = {};
|
|
221
|
+
let current: unknown = root;
|
|
222
|
+
for (let i = 0; i < tokens.length - 1; i += 1) {
|
|
223
|
+
const token = tokens[i]!;
|
|
224
|
+
const record = current as Record<string, unknown>;
|
|
225
|
+
if (typeof record[token] !== "object" || record[token] === null) record[token] = {};
|
|
226
|
+
current = record[token];
|
|
227
|
+
}
|
|
228
|
+
const last = tokens[tokens.length - 1]!;
|
|
229
|
+
const record = current as Record<string, unknown>;
|
|
230
|
+
if (value === undefined) delete record[last];
|
|
231
|
+
else record[last] = value;
|
|
232
|
+
return root;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function validComponents(raw: unknown): boolean {
|
|
236
|
+
if (!Array.isArray(raw)) return false;
|
|
237
|
+
for (const item of raw) {
|
|
238
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) return false;
|
|
239
|
+
const comp = item as Record<string, unknown>;
|
|
240
|
+
if (typeof comp.id !== "string" || comp.id.length === 0 || comp.id.length > 128) return false;
|
|
241
|
+
if (typeof comp.component !== "string" || comp.component.length === 0 || comp.component.length > 256) return false;
|
|
242
|
+
}
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function applyComponents(state: A2UiSurfaceState, raw: unknown): void {
|
|
247
|
+
for (const item of raw as Record<string, unknown>[]) {
|
|
248
|
+
const comp = item;
|
|
249
|
+
const props: Record<string, unknown> = {};
|
|
250
|
+
for (const [key, value] of Object.entries(comp)) {
|
|
251
|
+
if (key === "id" || key === "component") continue;
|
|
252
|
+
props[key] = value;
|
|
253
|
+
}
|
|
254
|
+
state.components.set(String(comp.id), { id: String(comp.id), type: String(comp.component), props });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function resetSurface(state: A2UiSurfaceState): void {
|
|
259
|
+
state.components.clear();
|
|
260
|
+
state.dataModel = undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function limitError(code: string, message: string, base: ResolvedAgUiLimits): A2UiRenderError {
|
|
264
|
+
return {
|
|
265
|
+
code: truncateA2UiText(code, 128),
|
|
266
|
+
message: truncateA2UiText(message, Math.min(base.maxErrorBytes, 2_048)),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export { A2UI_VERSION };
|