@arnilo/prism-hosts 0.0.0-stage → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +394 -0
- package/LICENSE +21 -0
- package/README.md +34 -2
- package/acp/README.md +87 -0
- package/acp/src/capabilities.ts +184 -0
- package/acp/src/errors.ts +24 -0
- package/acp/src/host.ts +36 -0
- package/acp/src/index.ts +25 -0
- package/acp/src/limits.ts +49 -0
- package/acp/src/mapper.ts +419 -0
- package/acp/src/permission.ts +37 -0
- package/acp/src/projection.ts +39 -0
- package/acp/src/prompt.ts +170 -0
- package/acp/src/serve.ts +345 -0
- package/acp/src/session-map.ts +49 -0
- package/ag-ui/README.md +56 -0
- package/ag-ui/src/a2ui.ts +570 -0
- package/ag-ui/src/ag-ui-mapper.ts +507 -0
- package/ag-ui/src/encrypted-value.ts +40 -0
- package/ag-ui/src/errors.ts +29 -0
- package/ag-ui/src/handler.ts +642 -0
- package/ag-ui/src/index.ts +177 -0
- package/ag-ui/src/input.ts +190 -0
- package/ag-ui/src/limits.ts +279 -0
- package/ag-ui/src/mcp-apps.ts +256 -0
- package/ag-ui/src/mcp.ts +94 -0
- package/ag-ui/src/projection.ts +201 -0
- package/ag-ui/src/projectors.ts +272 -0
- package/ag-ui/src/renderer/bind.ts +152 -0
- package/ag-ui/src/renderer/core.ts +270 -0
- package/ag-ui/src/renderer/index.ts +165 -0
- package/ag-ui/src/replay.ts +189 -0
- package/ag-ui/src/types.ts +66 -0
- package/channels/README.md +139 -0
- package/channels/src/admission.ts +8 -0
- package/channels/src/approvals.ts +262 -0
- package/channels/src/checkpoint-contract.ts +97 -0
- package/channels/src/delivery.ts +116 -0
- package/channels/src/host-ui.ts +356 -0
- package/channels/src/identity.ts +46 -0
- package/channels/src/index.ts +82 -0
- package/channels/src/limits.ts +49 -0
- package/channels/src/memory-stores.ts +112 -0
- package/channels/src/pairing.ts +178 -0
- package/channels/src/runtime-admit.ts +389 -0
- package/channels/src/runtime-core.ts +621 -0
- package/channels/src/runtime-reconcile.ts +299 -0
- package/channels/src/runtime-turn.ts +664 -0
- package/channels/src/runtime-types.ts +95 -0
- package/channels/src/runtime.ts +86 -0
- package/channels/src/secret-ref.ts +42 -0
- package/channels/src/signal.ts +790 -0
- package/channels/src/state.ts +355 -0
- package/channels/src/telegram.ts +1317 -0
- package/channels/src/types.ts +442 -0
- package/devtools/README.md +92 -0
- package/devtools/bin/prism-devtools.ts +63 -0
- package/devtools/src/args.ts +71 -0
- package/devtools/src/bun.d.ts +27 -0
- package/devtools/src/compare.ts +190 -0
- package/devtools/src/errors.ts +15 -0
- package/devtools/src/index.ts +25 -0
- package/devtools/src/replay.ts +36 -0
- package/devtools/src/security.ts +80 -0
- package/devtools/src/serve.ts +259 -0
- package/devtools/src/ui/assets.ts +108 -0
- package/devtools/src/ui/inspector.ts +182 -0
- package/driver-process/README.md +197 -0
- package/driver-process/src/abort.ts +74 -0
- package/driver-process/src/adapter.ts +211 -0
- package/driver-process/src/driver.ts +303 -0
- package/driver-process/src/errors.ts +17 -0
- package/driver-process/src/extend.ts +72 -0
- package/driver-process/src/index.ts +5 -0
- package/driver-process/src/inspect.ts +33 -0
- package/driver-process/src/session.ts +72 -0
- package/driver-process/src/testing.ts +394 -0
- package/driver-process/src/transports/json-rpc.ts +147 -0
- package/driver-process/src/transports/jsonl-stream.ts +12 -0
- package/driver-process/src/transports/types.ts +11 -0
- package/driver-process/src/turn.ts +106 -0
- package/evals/README.md +843 -0
- package/evals/src/calibration.ts +179 -0
- package/evals/src/citation-integrity.ts +98 -0
- package/evals/src/citations.ts +45 -0
- package/evals/src/compare-experiments.ts +153 -0
- package/evals/src/comparison.ts +230 -0
- package/evals/src/curate.ts +257 -0
- package/evals/src/dataset.ts +81 -0
- package/evals/src/erp-invariants.ts +163 -0
- package/evals/src/errors.ts +23 -0
- package/evals/src/experiment.ts +537 -0
- package/evals/src/failure-injection.ts +77 -0
- package/evals/src/feedback.ts +53 -0
- package/evals/src/index.ts +198 -0
- package/evals/src/injection.ts +247 -0
- package/evals/src/judge-panel.ts +109 -0
- package/evals/src/judge.ts +89 -0
- package/evals/src/limits.ts +50 -0
- package/evals/src/report-record.ts +47 -0
- package/evals/src/rubric-judge.ts +334 -0
- package/evals/src/scenario-runner.ts +317 -0
- package/evals/src/scenarios.ts +81 -0
- package/evals/src/score.ts +328 -0
- package/evals/src/scorer.ts +21 -0
- package/evals/src/state-match.ts +130 -0
- package/evals/src/stats.ts +635 -0
- package/evals/src/threshold.ts +117 -0
- package/evals/src/timeline.ts +38 -0
- package/evals/src/toolless-session.ts +33 -0
- package/evals/src/trace.ts +80 -0
- package/evals/src/trajectory.ts +623 -0
- package/evals/src/types.ts +672 -0
- package/evals/src/user-simulator.ts +101 -0
- package/evals/src/util.ts +207 -0
- package/headless/README.md +172 -0
- package/headless/src/answers.ts +91 -0
- package/headless/src/authority.ts +32 -0
- package/headless/src/errors.ts +36 -0
- package/headless/src/index.ts +17 -0
- package/headless/src/limits.ts +11 -0
- package/headless/src/pending.ts +16 -0
- package/headless/src/policy.ts +36 -0
- package/headless/src/resume.ts +103 -0
- package/headless/src/route.ts +153 -0
- package/headless/src/scheduler/clock.ts +22 -0
- package/headless/src/scheduler/cron.ts +19 -0
- package/headless/src/scheduler/firing.ts +58 -0
- package/headless/src/scheduler/index.ts +399 -0
- package/headless/src/scheduler/lease.ts +38 -0
- package/headless/src/scheduler/missed.ts +12 -0
- package/headless/src/scheduler/state.ts +132 -0
- package/host-builder/README.md +251 -0
- package/host-builder/bin/prism-host-builder.ts +169 -0
- package/host-builder/data/api.json +6167 -0
- package/host-builder/data/errors.json +546 -0
- package/host-builder/data/examples/acp.ts +63 -0
- package/host-builder/data/examples/adapters/conformance.ts +34 -0
- package/host-builder/data/examples/adapters/fixtures/rpc-server.json +26 -0
- package/host-builder/data/examples/adapters/fixtures/stream-cli.json +27 -0
- package/host-builder/data/examples/adapters/fixtures/workspace-config.json +28 -0
- package/host-builder/data/examples/adapters/rpc-server.dialect.ts +218 -0
- package/host-builder/data/examples/adapters/rpc-server.ts +309 -0
- package/host-builder/data/examples/adapters/stream-cli.dialect.ts +165 -0
- package/host-builder/data/examples/adapters/stream-cli.ts +256 -0
- package/host-builder/data/examples/adapters/workspace-config.dialect.ts +172 -0
- package/host-builder/data/examples/adapters/workspace-config.ts +251 -0
- package/host-builder/data/examples/advisor.ts +94 -0
- package/host-builder/data/examples/ag-ui-a2ui.ts +80 -0
- package/host-builder/data/examples/ag-ui-mcp-apps.ts +44 -0
- package/host-builder/data/examples/ag-ui-server.ts +118 -0
- package/host-builder/data/examples/agent-durable-approval.ts +43 -0
- package/host-builder/data/examples/api-key-auth.ts +23 -0
- package/host-builder/data/examples/approval.ts +92 -0
- package/host-builder/data/examples/attention-compiler.ts +81 -0
- package/host-builder/data/examples/autonomous-coding-loop.ts +343 -0
- package/host-builder/data/examples/behavior-evaluation.ts +303 -0
- package/host-builder/data/examples/build-workflow.ts +334 -0
- package/host-builder/data/examples/cache-aware-prompt-assembly.ts +139 -0
- package/host-builder/data/examples/caveman-ponytail.ts +197 -0
- package/host-builder/data/examples/cli.ts +31 -0
- package/host-builder/data/examples/coding-approval.ts +115 -0
- package/host-builder/data/examples/coding-browser-evaluation.ts +208 -0
- package/host-builder/data/examples/coding-compaction.ts +30 -0
- package/host-builder/data/examples/coding-goal-verify.ts +121 -0
- package/host-builder/data/examples/coding-tools-capability-gaps.ts +75 -0
- package/host-builder/data/examples/compaction.ts +36 -0
- package/host-builder/data/examples/connected-slack-mcp.ts +67 -0
- package/host-builder/data/examples/context.ts +29 -0
- package/host-builder/data/examples/custom-adapter.ts +256 -0
- package/host-builder/data/examples/custom-builders.ts +66 -0
- package/host-builder/data/examples/custom-loop.ts +89 -0
- package/host-builder/data/examples/custom-provider.ts +70 -0
- package/host-builder/data/examples/custom-session-store.ts +72 -0
- package/host-builder/data/examples/custom-tools-skills-context.ts +97 -0
- package/host-builder/data/examples/decision-models.ts +98 -0
- package/host-builder/data/examples/define-package.ts +188 -0
- package/host-builder/data/examples/delegate.ts +200 -0
- package/host-builder/data/examples/discover-skills.ts +65 -0
- package/host-builder/data/examples/drive-rag-sync.ts +44 -0
- package/host-builder/data/examples/durable-approval.ts +139 -0
- package/host-builder/data/examples/durable-investigation.ts +93 -0
- package/host-builder/data/examples/durable-loops-and-approvals.ts +94 -0
- package/host-builder/data/examples/enterprise-identity.ts +21 -0
- package/host-builder/data/examples/enterprise-policy-audit.ts +50 -0
- package/host-builder/data/examples/enterprise-work-connectors.ts +103 -0
- package/host-builder/data/examples/eval-injection.ts +73 -0
- package/host-builder/data/examples/eval-judges.ts +145 -0
- package/host-builder/data/examples/evals.ts +86 -0
- package/host-builder/data/examples/evaluation-gate.ts +40 -0
- package/host-builder/data/examples/execution-timeline.ts +173 -0
- package/host-builder/data/examples/external-agent.ts +541 -0
- package/host-builder/data/examples/external-app-db-backed.ts +344 -0
- package/host-builder/data/examples/governance-deny.ts +122 -0
- package/host-builder/data/examples/guardrail-packs.ts +240 -0
- package/host-builder/data/examples/headless-host.ts +245 -0
- package/host-builder/data/examples/hooks-audit-command.mjs +31 -0
- package/host-builder/data/examples/hooks-json.ts +87 -0
- package/host-builder/data/examples/host-builder-agent.ts +150 -0
- package/host-builder/data/examples/host-hooks.ts +71 -0
- package/host-builder/data/examples/host-step-loop-timeline.ts +212 -0
- package/host-builder/data/examples/hosted-sandbox.ts +48 -0
- package/host-builder/data/examples/instruction-injection.ts +127 -0
- package/host-builder/data/examples/jsonl-stores-branching.ts +49 -0
- package/host-builder/data/examples/long-term-memory.ts +158 -0
- package/host-builder/data/examples/manifest.ts +112 -0
- package/host-builder/data/examples/mcp-server.ts +48 -0
- package/host-builder/data/examples/mcp-trust.ts +173 -0
- package/host-builder/data/examples/memory-and-wiki.ts +315 -0
- package/host-builder/data/examples/memory-lifecycle.ts +302 -0
- package/host-builder/data/examples/memory-system.ts +252 -0
- package/host-builder/data/examples/messaging-agent.ts +70 -0
- package/host-builder/data/examples/minimal-host-app.ts +41 -0
- package/host-builder/data/examples/model-router-aggregate-budgets.ts +364 -0
- package/host-builder/data/examples/model-router.ts +106 -0
- package/host-builder/data/examples/obscura.ts +48 -0
- package/host-builder/data/examples/observability.ts +116 -0
- package/host-builder/data/examples/open-connector-sidecar.ts +105 -0
- package/host-builder/data/examples/openai-compatible.ts +70 -0
- package/host-builder/data/examples/package-skills.ts +85 -0
- package/host-builder/data/examples/phase9-coding-intelligence.ts +221 -0
- package/host-builder/data/examples/provider-registration.ts +29 -0
- package/host-builder/data/examples/provider-resolver.ts +39 -0
- package/host-builder/data/examples/rag.ts +40 -0
- package/host-builder/data/examples/remote-agent-server.ts +45 -0
- package/host-builder/data/examples/remote-agent.ts +124 -0
- package/host-builder/data/examples/research-ledger.ts +79 -0
- package/host-builder/data/examples/revocation-propagation.ts +287 -0
- package/host-builder/data/examples/run-feedback.ts +93 -0
- package/host-builder/data/examples/scanned-document-rag.ts +48 -0
- package/host-builder/data/examples/sdk-basics.ts +21 -0
- package/host-builder/data/examples/secure-agent.ts +55 -0
- package/host-builder/data/examples/semantic-memory.ts +52 -0
- package/host-builder/data/examples/serve-tools.ts +495 -0
- package/host-builder/data/examples/session-memory.ts +317 -0
- package/host-builder/data/examples/session-search.ts +131 -0
- package/host-builder/data/examples/session.ts +52 -0
- package/host-builder/data/examples/side-call.ts +64 -0
- package/host-builder/data/examples/signal-agent.ts +9 -0
- package/host-builder/data/examples/skills-progressive-disclosure.ts +88 -0
- package/host-builder/data/examples/skills.ts +19 -0
- package/host-builder/data/examples/sqlite-resume.ts +147 -0
- package/host-builder/data/examples/system-project-prompts.ts +74 -0
- package/host-builder/data/examples/system-prompts.ts +19 -0
- package/host-builder/data/examples/telegram-agent.ts +30 -0
- package/host-builder/data/examples/tool-narrowing-planes.ts +99 -0
- package/host-builder/data/examples/tools.ts +29 -0
- package/host-builder/data/examples/validator.ts +67 -0
- package/host-builder/data/examples/web-no-key.ts +85 -0
- package/host-builder/data/examples/web-research.ts +35 -0
- package/host-builder/data/examples/workflow-event-sink.ts +114 -0
- package/host-builder/data/examples/workflow-loop.ts +93 -0
- package/host-builder/data/examples/workflow-multimodal-document.ts +94 -0
- package/host-builder/data/examples/workflow-parallel-research.ts +111 -0
- package/host-builder/data/examples/workflow-postgres-resume.ts +75 -0
- package/host-builder/data/examples/workflow-research-and-review.ts +98 -0
- package/host-builder/data/examples/workflow-sqlite-resume.ts +163 -0
- package/host-builder/data/examples.json +130 -0
- package/host-builder/skills/prism-host-builder/SKILL.md +85 -0
- package/host-builder/skills/prism-host-builder/references/choosing.md +101 -0
- package/host-builder/skills/prism-host-builder/references/layout.md +52 -0
- package/host-builder/skills/prism-host-builder/references/pitfalls.md +50 -0
- package/host-builder/skills/prism-host-builder/references/recipes.md +129 -0
- package/host-builder/skills/prism-host-builder/references/security.md +52 -0
- package/host-builder/skills/prism-host-builder/references/upgrading.md +67 -0
- package/host-builder/skills/prism-host-builder/references/verification.md +108 -0
- package/host-builder/src/check/child.ts +108 -0
- package/host-builder/src/check/conformance.ts +13 -0
- package/host-builder/src/check/inspect.ts +20 -0
- package/host-builder/src/check/manifest.ts +23 -0
- package/host-builder/src/check/runner.ts +181 -0
- package/host-builder/src/check/targets.ts +65 -0
- package/host-builder/src/errors.ts +35 -0
- package/host-builder/src/index.ts +25 -0
- package/host-builder/src/indexes.ts +145 -0
- package/host-builder/src/install/install.ts +400 -0
- package/host-builder/src/install/targets.ts +50 -0
- package/host-builder/src/lookup/api.ts +127 -0
- package/host-builder/src/lookup/bound.ts +38 -0
- package/host-builder/src/lookup/docs.ts +238 -0
- package/host-builder/src/lookup/errors.ts +92 -0
- package/host-builder/src/lookup/examples.ts +117 -0
- package/host-builder/src/lookup/text.ts +60 -0
- package/host-builder/src/server.ts +300 -0
- package/host-builder/src/version.ts +38 -0
- package/mcp-server/README.md +219 -0
- package/mcp-server/src/bounds.ts +23 -0
- package/mcp-server/src/host.ts +31 -0
- package/mcp-server/src/index.ts +27 -0
- package/mcp-server/src/serve-tools.ts +408 -0
- package/mcp-server/src/serve.ts +329 -0
- package/mcp-server/src/server.ts +331 -0
- package/mcp-server/src/session-map.ts +47 -0
- package/mcp-server/src/skill-resources.ts +85 -0
- package/mcp-server/src/types.ts +215 -0
- package/package.json +130 -4
- package/remote/README.md +244 -0
- package/remote/src/attribution.ts +22 -0
- package/remote/src/auth.ts +30 -0
- package/remote/src/bun-module.d.ts +34 -0
- package/remote/src/channel.ts +86 -0
- package/remote/src/connect.ts +212 -0
- package/remote/src/dispatcher.ts +282 -0
- package/remote/src/errors.ts +59 -0
- package/remote/src/host-ui.ts +152 -0
- package/remote/src/http-gate.ts +43 -0
- package/remote/src/index.ts +53 -0
- package/remote/src/jsonl.ts +69 -0
- package/remote/src/limits.ts +43 -0
- package/remote/src/mirror.ts +90 -0
- package/remote/src/pending.ts +22 -0
- package/remote/src/protocol.ts +107 -0
- package/remote/src/serve.ts +560 -0
- package/remote/src/session-proxy.ts +219 -0
- package/remote/src/sse.ts +38 -0
- package/remote/src/stdio-client.ts +41 -0
- package/remote/src/testing-fixtures/serve-stdio.ts +32 -0
- package/remote/src/testing.ts +230 -0
- package/remote/src/transport.ts +139 -0
- package/remote/src/transports/client.ts +126 -0
- package/remote/src/transports/network.ts +268 -0
- package/remote/src/wire.ts +244 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Task 14: reference framework-free frontend renderer for AG-UI/A2UI surfaces.
|
|
3
|
+
* `createA2UiRenderer({ stream, catalog?, limits? })` consumes an AG-UI event
|
|
4
|
+
* stream (SSE or in-memory AsyncIterable) and renders `a2ui-surface` activity
|
|
5
|
+
* into DOM surfaces from a host component catalog, enforcing the same frozen
|
|
6
|
+
* A2UI caps as the server painter.
|
|
7
|
+
*/
|
|
8
|
+
import { type AGUIEvent } from "@ag-ui/core";
|
|
9
|
+
import { type AgUiA2UiLimitOptions, resolveAgUiA2UiLimits } from "../a2ui.js";
|
|
10
|
+
import { AgUiError } from "../errors.js";
|
|
11
|
+
import { DEFAULT_AG_UI_LIMITS } from "../limits.js";
|
|
12
|
+
import { type A2UiCatalog, DEFAULT_A2UI_CATALOG, type Dom, type DomNode, renderA2UiSurface } from "./bind.js";
|
|
13
|
+
import {
|
|
14
|
+
A2UI_VERSION,
|
|
15
|
+
type A2UiRenderError,
|
|
16
|
+
type A2UiSurfaceModel,
|
|
17
|
+
A2UiSurfaceState,
|
|
18
|
+
readA2UiBatch,
|
|
19
|
+
reduceA2UiOps,
|
|
20
|
+
resolvePointer,
|
|
21
|
+
} from "./core.js";
|
|
22
|
+
|
|
23
|
+
export type { A2UiCatalog, A2UiComponentRenderer, A2UiRenderContext, Dom, DomNode, RenderA2UiSurfaceOptions } from "./bind.js";
|
|
24
|
+
export type {
|
|
25
|
+
A2UiComponentModel,
|
|
26
|
+
A2UiReduceResult,
|
|
27
|
+
A2UiRenderError,
|
|
28
|
+
A2UiSurfaceModel,
|
|
29
|
+
} from "./core.js";
|
|
30
|
+
|
|
31
|
+
// Host FR (0.0.27): the DOM-free A2UI core as values, so hosts can drive
|
|
32
|
+
// the validated surface state machine without mounting a renderer. Same
|
|
33
|
+
// exports as dist/renderer/core.js; behavior and frozen caps unchanged.
|
|
34
|
+
export { A2UI_VERSION, A2UiSurfaceState, readA2UiBatch, reduceA2UiOps, resolvePointer };
|
|
35
|
+
|
|
36
|
+
export interface CreateA2UiRendererOptions {
|
|
37
|
+
/** AG-UI event stream: SSE via `@ag-ui/client`, or any AsyncIterable. */
|
|
38
|
+
readonly stream: AsyncIterable<AGUIEvent>;
|
|
39
|
+
/** Host component catalog; defaults to the built-in text/container set. */
|
|
40
|
+
readonly catalog?: A2UiCatalog;
|
|
41
|
+
/** A2UI caps; defaults clamp into the frozen hard limits. */
|
|
42
|
+
readonly limits?: AgUiA2UiLimitOptions;
|
|
43
|
+
/** Receives user actions emitted by interactive catalog components. */
|
|
44
|
+
readonly onAction?: (action: { type: "a2ui-action"; surfaceId: string; actionName: string; payload?: unknown }) => void;
|
|
45
|
+
/** Receives bounded drop-closed error events (host logging). */
|
|
46
|
+
readonly onError?: (error: A2UiRenderError) => void;
|
|
47
|
+
/** DOM binding; defaults to `document` in browsers. Required to mount. */
|
|
48
|
+
readonly dom?: Dom;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface A2UiRenderer {
|
|
52
|
+
/** Detached DOM node for a surface, kept in sync with the stream. */
|
|
53
|
+
surface(surfaceId: string): Promise<DomNode>;
|
|
54
|
+
/** Snapshot of the current renderer model (DOM-free). */
|
|
55
|
+
model(): readonly A2UiSurfaceModel[];
|
|
56
|
+
/** Stop consuming the stream and detach all mounted surfaces. */
|
|
57
|
+
dispose(): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createA2UiRenderer(options: CreateA2UiRendererOptions): A2UiRenderer {
|
|
61
|
+
const a2uiLimits = resolveAgUiA2UiLimits(options.limits);
|
|
62
|
+
const catalog = options.catalog ?? DEFAULT_A2UI_CATALOG;
|
|
63
|
+
const dom = options.dom ?? (typeof document === "undefined" ? undefined : browserDom());
|
|
64
|
+
const surfaces = new Map<string, A2UiSurfaceState>();
|
|
65
|
+
const mounts = new Map<string, DomNode>();
|
|
66
|
+
const waiters = new Map<string, Array<() => void>>();
|
|
67
|
+
let disposed = false;
|
|
68
|
+
let iterator: AsyncIterator<AGUIEvent> | undefined;
|
|
69
|
+
let drain: Promise<void> | undefined;
|
|
70
|
+
|
|
71
|
+
const resolveWaiters = (surfaceId: string): void => {
|
|
72
|
+
const list = waiters.get(surfaceId);
|
|
73
|
+
if (!list) return;
|
|
74
|
+
waiters.delete(surfaceId);
|
|
75
|
+
for (const resolve of list) resolve();
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const renderMount = (surfaceId: string): void => {
|
|
79
|
+
const mount = mounts.get(surfaceId);
|
|
80
|
+
if (!mount) return;
|
|
81
|
+
const state = surfaces.get(surfaceId);
|
|
82
|
+
if (!state) {
|
|
83
|
+
mount.replaceChildren(); // deleteSurface detaches content
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
mount.replaceChildren(renderA2UiSurface(state, catalog, dom!, { onAction: options.onAction }));
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const onBatch = (): void => {
|
|
90
|
+
for (const surfaceId of [...mounts.keys()]) renderMount(surfaceId);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const consume = async (): Promise<void> => {
|
|
94
|
+
iterator = options.stream[Symbol.asyncIterator]();
|
|
95
|
+
try {
|
|
96
|
+
for (;;) {
|
|
97
|
+
const next = await iterator.next();
|
|
98
|
+
if (next.done || disposed) return;
|
|
99
|
+
const batch = readA2UiBatch(next.value);
|
|
100
|
+
if (!batch) continue;
|
|
101
|
+
const result = reduceA2UiOps(surfaces, batch.ops, a2uiLimits, DEFAULT_AG_UI_LIMITS, batch.replace);
|
|
102
|
+
if (result.error) options.onError?.(result.error);
|
|
103
|
+
for (const surfaceId of result.changed) resolveWaiters(surfaceId);
|
|
104
|
+
onBatch();
|
|
105
|
+
}
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (!disposed) {
|
|
108
|
+
options.onError?.({
|
|
109
|
+
code: "ERR_PRISM_A2UI_STREAM",
|
|
110
|
+
message: error instanceof Error ? error.message : "A2UI stream failed",
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
return {
|
|
117
|
+
surface(surfaceId) {
|
|
118
|
+
if (!dom) throw new AgUiError("ERR_PRISM_AG_UI_LIMIT", "renderer requires a DOM binding (browser or options.dom)");
|
|
119
|
+
const existing = mounts.get(surfaceId);
|
|
120
|
+
if (existing) return Promise.resolve(existing);
|
|
121
|
+
if (disposed) return Promise.reject(new AgUiError("ERR_PRISM_AG_UI_LIMIT", "renderer disposed"));
|
|
122
|
+
const mount = dom.createElement("div");
|
|
123
|
+
mount.setAttribute("class", "a2ui-surface-host");
|
|
124
|
+
mount.setAttribute("data-surface-id", surfaceId);
|
|
125
|
+
mounts.set(surfaceId, mount);
|
|
126
|
+
const state = surfaces.get(surfaceId);
|
|
127
|
+
if (state) {
|
|
128
|
+
renderMount(surfaceId);
|
|
129
|
+
return Promise.resolve(mount);
|
|
130
|
+
}
|
|
131
|
+
drain ??= consume();
|
|
132
|
+
return new Promise<DomNode>((resolve, reject) => {
|
|
133
|
+
const list = waiters.get(surfaceId) ?? [];
|
|
134
|
+
list.push(() => {
|
|
135
|
+
renderMount(surfaceId);
|
|
136
|
+
resolve(mount);
|
|
137
|
+
});
|
|
138
|
+
waiters.set(surfaceId, list);
|
|
139
|
+
if (disposed) {
|
|
140
|
+
waiters.delete(surfaceId);
|
|
141
|
+
reject(new AgUiError("ERR_PRISM_AG_UI_LIMIT", "renderer disposed"));
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
model() {
|
|
146
|
+
return [...surfaces.values()];
|
|
147
|
+
},
|
|
148
|
+
async dispose() {
|
|
149
|
+
disposed = true;
|
|
150
|
+
for (const surfaceId of [...waiters.keys()]) resolveWaiters(surfaceId);
|
|
151
|
+
for (const mount of mounts.values()) mount.replaceChildren();
|
|
152
|
+
mounts.clear();
|
|
153
|
+
if (iterator) await iterator.return?.();
|
|
154
|
+
if (drain) await drain;
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function browserDom(): Dom {
|
|
160
|
+
const doc = document;
|
|
161
|
+
return {
|
|
162
|
+
createElement: (tag) => doc.createElement(tag) as unknown as DomNode,
|
|
163
|
+
createTextNode: (text) => doc.createTextNode(text) as unknown as DomNode,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AgentEventRecord,
|
|
3
|
+
AgentEventSource,
|
|
4
|
+
DurableAgentEventRecord,
|
|
5
|
+
OwnershipScope,
|
|
6
|
+
ProductionPersistenceStore,
|
|
7
|
+
} from "@arnilo/prism";
|
|
8
|
+
import { isTerminalAgentEventType } from "@arnilo/prism";
|
|
9
|
+
import { AgUiError } from "./errors.js";
|
|
10
|
+
import type { ResolvedAgUiLimits } from "./limits.js";
|
|
11
|
+
import type { AgUiRunReference, CoWorkContext, CoWorkEvent } from "./types.js";
|
|
12
|
+
|
|
13
|
+
export interface AgUiReplayRequest<Authorization> {
|
|
14
|
+
readonly threadId: string;
|
|
15
|
+
readonly runId: string;
|
|
16
|
+
readonly cursor?: string;
|
|
17
|
+
readonly authorization: Authorization;
|
|
18
|
+
readonly signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface AgUiReplayPage {
|
|
22
|
+
readonly records: readonly AgentEventRecord[];
|
|
23
|
+
readonly nextCursor?: string;
|
|
24
|
+
readonly terminal: boolean;
|
|
25
|
+
readonly run: AgUiRunReference;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface AgUiReplayEvent {
|
|
29
|
+
readonly record: DurableAgentEventRecord;
|
|
30
|
+
readonly cursor: string;
|
|
31
|
+
readonly run: AgUiRunReference;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface AgUiReplay<Authorization> {
|
|
35
|
+
page(input: AgUiReplayRequest<Authorization>): Promise<AgUiReplayPage>;
|
|
36
|
+
/** Optional durable replay-to-live stream. When present, handler never opens a local session for replay. */
|
|
37
|
+
subscribe?(input: AgUiReplayRequest<Authorization>): AsyncIterable<AgUiReplayEvent>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface PersistenceAgUiReplayOptions<Authorization> {
|
|
41
|
+
/** Host authorization binds untrusted AG-UI thread/run selectors to internal IDs. */
|
|
42
|
+
readonly resolveRun: (input: AgUiReplayRequest<Authorization>) => AgUiRunReference | undefined | Promise<AgUiRunReference | undefined>;
|
|
43
|
+
readonly ownership: (authorization: Authorization) => import("@arnilo/prism").OwnershipScope | undefined;
|
|
44
|
+
readonly limits?: Pick<ResolvedAgUiLimits, "maxCursorBytes" | "maxReplayEvents">;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Adapts one bounded, ownership-scoped durable event page. */
|
|
48
|
+
export function createPersistenceAgUiReplay<Authorization>(
|
|
49
|
+
store: Pick<ProductionPersistenceStore, "queryEvents">,
|
|
50
|
+
options: PersistenceAgUiReplayOptions<Authorization>,
|
|
51
|
+
): AgUiReplay<Authorization> {
|
|
52
|
+
const limits = options.limits ?? { maxCursorBytes: 4 * 1024, maxReplayEvents: 100 };
|
|
53
|
+
return {
|
|
54
|
+
async page(input) {
|
|
55
|
+
input.signal?.throwIfAborted();
|
|
56
|
+
if (input.cursor && Buffer.byteLength(input.cursor, "utf8") > limits.maxCursorBytes)
|
|
57
|
+
throw new AgUiError("ERR_PRISM_AG_UI_LIMIT", "Replay cursor exceeds maxCursorBytes");
|
|
58
|
+
const run = await options.resolveRun(input);
|
|
59
|
+
if (!run) throw new AgUiError("ERR_PRISM_AG_UI_FORBIDDEN", "Run is unavailable");
|
|
60
|
+
const page = await store.queryEvents({
|
|
61
|
+
sessionId: run.ref.sessionId,
|
|
62
|
+
runId: run.ref.runId,
|
|
63
|
+
cursor: input.cursor,
|
|
64
|
+
limit: limits.maxReplayEvents,
|
|
65
|
+
order: "asc",
|
|
66
|
+
...options.ownership(input.authorization),
|
|
67
|
+
});
|
|
68
|
+
if (page.items.length > limits.maxReplayEvents || page.items.some((record) => !record.redacted)) {
|
|
69
|
+
throw new AgUiError("ERR_PRISM_AG_UI_REPLAY", "Replay page is unavailable");
|
|
70
|
+
}
|
|
71
|
+
if (page.nextCursor && Buffer.byteLength(page.nextCursor, "utf8") > limits.maxCursorBytes) {
|
|
72
|
+
throw new AgUiError("ERR_PRISM_AG_UI_REPLAY", "Replay cursor is invalid");
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
records: page.items,
|
|
76
|
+
nextCursor: page.nextCursor,
|
|
77
|
+
terminal: page.items.some((record) => isTerminalAgentEventType(record.event.type)),
|
|
78
|
+
run,
|
|
79
|
+
};
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface AgentEventSourceAgUiReplayOptions<Authorization> {
|
|
85
|
+
/** Host authorization binds untrusted AG-UI thread/run selectors to internal IDs. */
|
|
86
|
+
readonly resolveRun: (input: AgUiReplayRequest<Authorization>) => AgUiRunReference | undefined | Promise<AgUiRunReference | undefined>;
|
|
87
|
+
readonly ownership: (authorization: Authorization) => OwnershipScope;
|
|
88
|
+
readonly limits?: Pick<ResolvedAgUiLimits, "maxCursorBytes" | "maxReplayEvents">;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Adapts one durable source for both pages and gap-free replay-to-live follow. */
|
|
92
|
+
export function createAgentEventSourceAgUiReplay<Authorization>(
|
|
93
|
+
source: AgentEventSource,
|
|
94
|
+
options: AgentEventSourceAgUiReplayOptions<Authorization>,
|
|
95
|
+
): AgUiReplay<Authorization> {
|
|
96
|
+
const limits = options.limits ?? { maxCursorBytes: 4 * 1024, maxReplayEvents: 100 };
|
|
97
|
+
const resolve = async (input: AgUiReplayRequest<Authorization>) => {
|
|
98
|
+
input.signal?.throwIfAborted();
|
|
99
|
+
if (input.cursor && Buffer.byteLength(input.cursor, "utf8") > limits.maxCursorBytes) {
|
|
100
|
+
throw new AgUiError("ERR_PRISM_AG_UI_LIMIT", "Replay cursor exceeds maxCursorBytes");
|
|
101
|
+
}
|
|
102
|
+
const run = await options.resolveRun(input);
|
|
103
|
+
if (!run?.ref.sessionId) throw new AgUiError("ERR_PRISM_AG_UI_FORBIDDEN", "Run is unavailable");
|
|
104
|
+
return { run, sessionId: run.ref.sessionId, ownership: options.ownership(input.authorization) };
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
async page(input) {
|
|
108
|
+
const { run, sessionId, ownership } = await resolve(input);
|
|
109
|
+
const page = await source.page({
|
|
110
|
+
ownership,
|
|
111
|
+
sessionId,
|
|
112
|
+
runId: run.ref.runId,
|
|
113
|
+
after: input.cursor,
|
|
114
|
+
limit: limits.maxReplayEvents,
|
|
115
|
+
signal: input.signal,
|
|
116
|
+
});
|
|
117
|
+
return { records: page.items.map((item) => item.record), nextCursor: page.nextCursor, terminal: page.terminal, run };
|
|
118
|
+
},
|
|
119
|
+
subscribe(input) {
|
|
120
|
+
return {
|
|
121
|
+
async *[Symbol.asyncIterator]() {
|
|
122
|
+
const { run, sessionId, ownership } = await resolve(input);
|
|
123
|
+
for await (const item of source.subscribe({
|
|
124
|
+
ownership,
|
|
125
|
+
sessionId,
|
|
126
|
+
runId: run.ref.runId,
|
|
127
|
+
after: input.cursor,
|
|
128
|
+
limit: limits.maxReplayEvents,
|
|
129
|
+
signal: input.signal,
|
|
130
|
+
})) {
|
|
131
|
+
if (!item.record.redacted) throw new AgUiError("ERR_PRISM_AG_UI_REPLAY", "Replay record is unavailable");
|
|
132
|
+
yield { ...item, run };
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface CoWorkReplayRequest<Authorization> {
|
|
141
|
+
readonly context: CoWorkContext;
|
|
142
|
+
readonly cursor?: string;
|
|
143
|
+
readonly authorization: Authorization;
|
|
144
|
+
readonly signal?: AbortSignal;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface CoWorkReplayPage {
|
|
148
|
+
readonly events: readonly CoWorkEvent[];
|
|
149
|
+
readonly nextCursor?: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Host-owned, ownership-scoped durable co-work state (artifacts/drafts/snapshots). */
|
|
153
|
+
export interface CoWorkSource<Authorization> {
|
|
154
|
+
page(input: CoWorkReplayRequest<Authorization>): Promise<CoWorkReplayPage>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export interface CoWorkReplay<Authorization> {
|
|
158
|
+
page(input: CoWorkReplayRequest<Authorization>): Promise<CoWorkReplayPage>;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface CoWorkReplayOptions<Authorization> {
|
|
162
|
+
readonly source: CoWorkSource<Authorization>;
|
|
163
|
+
readonly limits?: Pick<ResolvedAgUiLimits, "maxCursorBytes" | "maxReplayEvents">;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Bounds one durable co-work page behind the frozen cursor/event caps. Pure read + map by
|
|
168
|
+
* the caller's mapper, so disconnect/resume from a cursor replays state without duplicate
|
|
169
|
+
* side effects. Oversized cursors and over-limit pages fail closed.
|
|
170
|
+
*/
|
|
171
|
+
export function createCoWorkReplay<Authorization>(options: CoWorkReplayOptions<Authorization>): CoWorkReplay<Authorization> {
|
|
172
|
+
const limits = options.limits ?? { maxCursorBytes: 4 * 1024, maxReplayEvents: 100 };
|
|
173
|
+
return {
|
|
174
|
+
async page(input) {
|
|
175
|
+
input.signal?.throwIfAborted();
|
|
176
|
+
if (input.cursor && Buffer.byteLength(input.cursor, "utf8") > limits.maxCursorBytes) {
|
|
177
|
+
throw new AgUiError("ERR_PRISM_AG_UI_LIMIT", "Co-work replay cursor exceeds maxCursorBytes");
|
|
178
|
+
}
|
|
179
|
+
const page = await options.source.page(input);
|
|
180
|
+
if (page.events.length > limits.maxReplayEvents) {
|
|
181
|
+
throw new AgUiError("ERR_PRISM_AG_UI_REPLAY", "Co-work replay page is unavailable");
|
|
182
|
+
}
|
|
183
|
+
if (page.nextCursor && Buffer.byteLength(page.nextCursor, "utf8") > limits.maxCursorBytes) {
|
|
184
|
+
throw new AgUiError("ERR_PRISM_AG_UI_REPLAY", "Co-work replay cursor is invalid");
|
|
185
|
+
}
|
|
186
|
+
return page;
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { OwnershipScope } from "@arnilo/prism";
|
|
2
|
+
|
|
3
|
+
/** Result of host authorization. Prism never derives ownership from client identifiers. */
|
|
4
|
+
export interface AgUiAuthorization {
|
|
5
|
+
readonly ownership?: OwnershipScope;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Host-owned correlation between AG-UI selectors and a durable Prism run. */
|
|
9
|
+
export interface AgUiRunReference {
|
|
10
|
+
readonly ref: { readonly runId: string; readonly sessionId?: string };
|
|
11
|
+
readonly agentId?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Co-work event kinds projected over the durable-resume stream (Phase 9 / 0.0.14).
|
|
16
|
+
* Producer outputs (progress/snapshot/draft/download-link) and reviewer requests
|
|
17
|
+
* (approval) flow as redacted, bounded metadata — never file bodies, paths, or secrets.
|
|
18
|
+
*/
|
|
19
|
+
export type CoWorkKind =
|
|
20
|
+
| "artifact.progress"
|
|
21
|
+
| "artifact.approval.requested"
|
|
22
|
+
| "draft.connector.pending"
|
|
23
|
+
| "browser.snapshot"
|
|
24
|
+
| "artifact.download.link";
|
|
25
|
+
|
|
26
|
+
/** Thread/artifact context threaded through the handler so hosts render co-work review. */
|
|
27
|
+
export interface CoWorkContext {
|
|
28
|
+
readonly threadId: string;
|
|
29
|
+
readonly artifactId?: string;
|
|
30
|
+
/** Redacted actor reference (e.g. `user:user-1`); never a raw credential. */
|
|
31
|
+
readonly identity?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type CoWorkEvent =
|
|
35
|
+
| {
|
|
36
|
+
readonly kind: "artifact.progress";
|
|
37
|
+
readonly artifactId: string;
|
|
38
|
+
readonly version: number;
|
|
39
|
+
readonly status: string;
|
|
40
|
+
readonly progress?: number;
|
|
41
|
+
}
|
|
42
|
+
| {
|
|
43
|
+
readonly kind: "artifact.approval.requested";
|
|
44
|
+
readonly artifactId: string;
|
|
45
|
+
readonly version: number;
|
|
46
|
+
readonly reviewer?: string;
|
|
47
|
+
readonly reason?: string;
|
|
48
|
+
}
|
|
49
|
+
| {
|
|
50
|
+
readonly kind: "draft.connector.pending";
|
|
51
|
+
readonly connectorId: string;
|
|
52
|
+
readonly scope: string;
|
|
53
|
+
readonly status: string;
|
|
54
|
+
}
|
|
55
|
+
| {
|
|
56
|
+
readonly kind: "browser.snapshot";
|
|
57
|
+
readonly snapshotId: string;
|
|
58
|
+
readonly summary: string;
|
|
59
|
+
}
|
|
60
|
+
| {
|
|
61
|
+
readonly kind: "artifact.download.link";
|
|
62
|
+
readonly artifactId: string;
|
|
63
|
+
readonly version: number;
|
|
64
|
+
readonly link: string;
|
|
65
|
+
readonly expiresAt: string;
|
|
66
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# @arnilo/prism-hosts/channels
|
|
2
|
+
|
|
3
|
+
Host library connecting one Prism `Agent` to Telegram and Signal messaging channels without building another agent runtime, conversation store, or turn queue.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
- **One Agent per connection** — `connectTelegram(agent, options)` and `connectSignal(agent, options)` bind one host-configured Prism `Agent` directly to chat transports. Each inbound conversation binds to `agent.session({ id })` in the channel state store and runs turns through `session.run(text, { interactive: false })`.
|
|
8
|
+
- **Durable journal** — bindings, `/new` generations, admission deduplication, claims, and staged replies live in host-owned checkpoint and lease stores. Recovery is explicit via `reconcile()`, never an uncoordinated replay. The package declares the two store shapes it accepts locally (`src/checkpoint-contract.ts`, not re-exported) instead of depending on the workflows engine that owns the `checkpoints`/`leases` services.
|
|
9
|
+
- **Durable approvals** — when a tool call suspends the run (`RunResult.pending`), opaque one-use controls bind the decision to the external sender, conversation, and expiry. Telegram renders inline callback buttons; Signal renders `/approve <token>` and `/deny <token>` commands. The user's reply maps directly to `session.resume(decisions, { interactive: false })`.
|
|
10
|
+
- **Ref-only credentials** — Telegram bot tokens, the Telegram `webhookSecret`, and Signal account credentials MUST be references (`env:<VAR>` or `keyring:<KEY>`), resolved through the agent's assigned credentials slot (`AgentConfig.slots.credentials`, else the kernel's `env:` resolver). Literal credentials fail immediately at connection time with `ChannelTokenLiteralError` (`ERR_PRISM_CHANNEL_TOKEN_LITERAL`). The low-level `createTelegramAdapter` / `createTelegramWebhookHandler` take `botToken` and `webhookSecret` as a `ChannelSecretSource` (`() => Promise<string>`), never a literal string. Tokens and webhook secrets never leak into delivered messages, errors, or diagnostics.
|
|
11
|
+
- **Deny by default** — transport inputs are never trusted implicitly. Inbound updates pass through host authorization (`authorize`), verified principal identity, and ownership scopes before any session work begins.
|
|
12
|
+
- **Streaming previews** — opt-in drafts (`sendDrafts: true`) forward partial text through Telegram `sendMessageDraft` previews while the turn is generating. Previews are never journaled and never replace the final reply.
|
|
13
|
+
- **Bounded attachments** — attachments carry identifiers only (kinds, transport file IDs, byte counts), never raw bodies or URLs. Inbound voice and document text resolve through host transcribe and extraction hooks before admission.
|
|
14
|
+
|
|
15
|
+
## Answering `HostUi` requests
|
|
16
|
+
|
|
17
|
+
`channelHostUi({ connection, chat, ownership, kinds? })` lets a paired Telegram or Signal chat answer questions from another agent. Replies pass through the connection's existing `authorize` callback and never start a channel agent turn.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { channelHostUi, connectTelegram, createChannelPairingStore } from "@arnilo/prism-hosts/channels";
|
|
21
|
+
|
|
22
|
+
// checkpoints, ownership, channelAgent and authorizePairedSender belong to the host.
|
|
23
|
+
// The authorizer verifies the exact sender/chat/thread and returns an active identity
|
|
24
|
+
// in this ownership scope plus the current grantRevision, or false.
|
|
25
|
+
const connection = await connectTelegram(channelAgent, {
|
|
26
|
+
token: "env:TELEGRAM_TOKEN", checkpoints, authorize: authorizePairedSender,
|
|
27
|
+
});
|
|
28
|
+
const pairings = createChannelPairingStore({ checkpoints });
|
|
29
|
+
const pairing = await pairings.create({
|
|
30
|
+
...ownership, connectionId: "telegram-default",
|
|
31
|
+
externalConversationId: "101", externalActorId: "202", grantRevision: "1",
|
|
32
|
+
});
|
|
33
|
+
// Consume only after the operator confirms the pairing in a trusted host interface.
|
|
34
|
+
const confirmed = await pairings.consume({ ...ownership, connectionId: "telegram-default", token: pairing.token });
|
|
35
|
+
if (confirmed.status !== "consumed") throw new Error("Pairing was not confirmed");
|
|
36
|
+
const ui = channelHostUi({
|
|
37
|
+
connection, chat: `pair:${pairing.token}`, ownership,
|
|
38
|
+
kinds: ["confirm", "select", "input", "notify"],
|
|
39
|
+
});
|
|
40
|
+
// Pass ui as another agent's host.ui, or as a routeHostUi route.
|
|
41
|
+
const answer = await ui.request({ kind: "confirm", title: "Deploy the release?" });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`chat` is a reference to a consumed pairing token in the connection's checkpoint store, scoped to `ownership`; it is not a chat id or alias. Keep the reference in trusted host configuration. `ChannelPairingStore.resolve` reads the confirmed destination; an unconsumed token is refused. The pairing token's initial expiry bounds confirmation; continued use of a consumed pairing requires the authorizer's active grant at the same revision. Revoke or change that grant to disable it. HostUi uses the existing `approval` authorization action, including for notifications. The outbound check supplies the paired ids, a synthetic `ui-...` event id and empty text; it carries no transport claims. Incoming checks carry the actual reply context. Connections constructed by `connectTelegram` or `connectSignal` support this private binding; fabricated connection objects return `unavailable`. Signal must be started before it can send.
|
|
45
|
+
|
|
46
|
+
| Request | Chat behavior |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `confirm` | Telegram Yes/No buttons; Signal equivalent `/answer <token> 0` or `1` commands. No returns `answered: false`. |
|
|
49
|
+
| `select` | Up to eight unique values; Telegram buttons or Signal indexed reply commands. Multi-select lists zero-based indexes and expects `/answer <token> 0,2`. |
|
|
50
|
+
| `input` | Prompt expects `/answer <token> <text>` on either transport, so concurrent questions stay distinct. Initial input values are not echoed. |
|
|
51
|
+
| `notify` | Sends the message and returns `answered` only when delivery and its journal update succeed. |
|
|
52
|
+
| Other kinds | `unavailable`; no outbound message. |
|
|
53
|
+
|
|
54
|
+
Prompts and labels are plain text, with credential redaction. One bounded message is sent per request: the rendered prompt, including Signal command controls, must fit 2,000 UTF-16 code units and `limits.maxResponseBytes`; overlong prompts/labels return `unavailable`. Both connect functions accept existing channel `limits`, including `approvalTtlMs`, `maxPendingPerBinding`, and `maxPendingPerProcess`. These limits are shared across HostUi instances on the same connection runtime. No dependency or model call is added.
|
|
55
|
+
|
|
56
|
+
Each question writes a hashed-token correlation record and stages the outbound prompt in the existing delivery journal before sending; settlement consumes the token with CAS. The journal holds outbound prompts and controls, never input answers. Identity, principal, grant revision, ownership, conversation, actor and thread must match at reply time. Missing authorizers, unconfirmed pairings, revoked identities, changed grants, persistence failures and failed delivery fail closed. `/answer` is reserved: malformed, unknown, expired and already-consumed replies cannot become ordinary prompts. An authenticated reply to a settled/expired question gets an expired notice; foreign senders get no notice.
|
|
57
|
+
|
|
58
|
+
Waiters expire within `approvalTtlMs` (default and hard maximum five minutes) and resolve `unavailable` when the connection closes. A router timeout does not cancel a channel question: late inline answers are discarded by the router, and a fresh suspension offer can duplicate the prompt. Neither transport currently exposes message editing through this library. Waiters and answer values are not persisted; after restart, offer the suspended decision again. Old tokens receive an expired notice and cannot answer the fresh offer. Original channel-owned `/approve` and `/deny` approvals retain their durable resume behavior.
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
### Telegram
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { createAgent } from "@arnilo/prism";
|
|
66
|
+
import { connectTelegram } from "@arnilo/prism-hosts/channels/telegram";
|
|
67
|
+
|
|
68
|
+
const agent = await createAgent({
|
|
69
|
+
id: "support-agent",
|
|
70
|
+
model: "anthropic:claude-3-5-sonnet",
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Connect to Telegram using an environment variable reference
|
|
74
|
+
const bot = await connectTelegram(agent, {
|
|
75
|
+
token: "env:TELEGRAM_BOT_TOKEN",
|
|
76
|
+
sendDrafts: true,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// Long polling
|
|
80
|
+
await bot.start();
|
|
81
|
+
|
|
82
|
+
// Or mount directly into an HTTP server (e.g. Bun.serve / Hono / Node http)
|
|
83
|
+
export default {
|
|
84
|
+
port: 8080,
|
|
85
|
+
fetch: (req: Request) => bot.handle(req),
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Signal
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { createAgent } from "@arnilo/prism";
|
|
93
|
+
import { connectSignal } from "@arnilo/prism-hosts/channels/signal";
|
|
94
|
+
|
|
95
|
+
const agent = await createAgent({
|
|
96
|
+
id: "signal-bot",
|
|
97
|
+
model: "anthropic:claude-3-5-sonnet",
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Connect to signal-cli via Unix domain socket
|
|
101
|
+
const bot = await connectSignal(agent, {
|
|
102
|
+
account: "env:SIGNAL_ACCOUNT",
|
|
103
|
+
socketPath: "/run/prism/signal.sock",
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
await bot.start();
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Connection Handle
|
|
110
|
+
|
|
111
|
+
Both `connectTelegram` and `connectSignal` return a `ChannelConnectionHandle`:
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
export interface ChannelConnectionHandle {
|
|
115
|
+
handle(update: unknown): Promise<unknown>;
|
|
116
|
+
start(): Promise<void>;
|
|
117
|
+
close(): Promise<void>;
|
|
118
|
+
stop(): Promise<void>;
|
|
119
|
+
drain(options?: { readonly deadlineMs?: number }): Promise<ChannelDrainResult>;
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
- `handle(update)`: synchronously admits an inbound message, callback query, or webhook Request to the runtime queue and returns an admission result.
|
|
124
|
+
- `start()`: begins polling or socket subscription.
|
|
125
|
+
- `drain()`: waits for all in-flight turns and reply deliveries to settle.
|
|
126
|
+
- `close()` / `stop()`: closes network listeners and shuts down the channel runtime cleanly.
|
|
127
|
+
|
|
128
|
+
## Security & Failure Containment
|
|
129
|
+
|
|
130
|
+
- **Fail-closed authentication**: unverified identities and expired/foreign approval callbacks are immediately rejected.
|
|
131
|
+
- **Secret redaction**: bot tokens and credentials are automatically registered with the agent's secret redactor and redacted from logs, traces, and outgoing chat replies.
|
|
132
|
+
- **No agent construction**: the channel host library never calls `createAgent` internally; the host constructs the `Agent` and passes it in.
|
|
133
|
+
|
|
134
|
+
## Examples
|
|
135
|
+
|
|
136
|
+
- [examples/telegram-agent.ts](../../../examples/telegram-agent.ts) — Telegram bot with polling and webhook mounting.
|
|
137
|
+
- [examples/signal-agent.ts](../../../examples/signal-agent.ts) — Signal adapter over signal-cli.
|
|
138
|
+
- [examples/messaging-agent.ts](../../../examples/messaging-agent.ts) — SQLite-backed network-free demo.
|
|
139
|
+
- examples/messaging-outbox.ts — PostgreSQL ERP-outbox composition.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function retryableAdmission(value: unknown): boolean {
|
|
2
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
3
|
+
const admission = value as { readonly status?: unknown; readonly reason?: unknown };
|
|
4
|
+
return (
|
|
5
|
+
admission.status === "denied" &&
|
|
6
|
+
(admission.reason === "capacity" || admission.reason === "unavailable" || admission.reason === "stopped")
|
|
7
|
+
);
|
|
8
|
+
}
|