@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,356 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { HostUi, HostUiRequest, HostUiRequestKind, HostUiResponse, OwnershipScope } from "@arnilo/prism";
|
|
3
|
+
import { createChannelUiRequestStore } from "./approvals.js";
|
|
4
|
+
import { ownershipFromIdentity } from "./identity.js";
|
|
5
|
+
import { createChannelPairingStore } from "./pairing.js";
|
|
6
|
+
import type { RuntimeCore } from "./runtime-core.js";
|
|
7
|
+
import type { RuntimeContext } from "./runtime-types.js";
|
|
8
|
+
import type {
|
|
9
|
+
ChannelAdmission,
|
|
10
|
+
ChannelConnectionHandle,
|
|
11
|
+
ChannelInboundEvent,
|
|
12
|
+
ChannelReply,
|
|
13
|
+
ChannelReplyControl,
|
|
14
|
+
ChannelReplyRecord,
|
|
15
|
+
ChannelRuntime,
|
|
16
|
+
ChannelSendResult,
|
|
17
|
+
} from "./types.js";
|
|
18
|
+
|
|
19
|
+
export interface ChannelHostUiOptions {
|
|
20
|
+
readonly connection: ChannelConnectionHandle;
|
|
21
|
+
/** `pair:<token>` for a pairing already consumed by the trusted host. */
|
|
22
|
+
readonly chat: string;
|
|
23
|
+
readonly ownership: OwnershipScope;
|
|
24
|
+
readonly kinds?: readonly HostUiRequestKind[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const unavailable = { status: "unavailable" } as const;
|
|
28
|
+
const bindings = new WeakMap<object, { service: ReturnType<typeof createChannelUi>; connectionId: string }>();
|
|
29
|
+
const runtimes = new WeakMap<ChannelRuntime, ReturnType<typeof createChannelUi>>();
|
|
30
|
+
const supported = ["confirm", "select", "input", "notify"];
|
|
31
|
+
|
|
32
|
+
export function channelHostUi(options: ChannelHostUiOptions): HostUi {
|
|
33
|
+
const ownership = { ...options.ownership };
|
|
34
|
+
const kinds = options.kinds && [...options.kinds];
|
|
35
|
+
const { connection, chat } = options;
|
|
36
|
+
return {
|
|
37
|
+
async request<K extends HostUiRequestKind>(request: Extract<HostUiRequest, { kind: K }>): Promise<HostUiResponse<K>> {
|
|
38
|
+
const bound = bindings.get(connection);
|
|
39
|
+
if (!bound || !supported.includes(request.kind) || (kinds && !kinds.includes(request.kind))) return unavailable;
|
|
40
|
+
try {
|
|
41
|
+
return (await bound.service.request(bound.connectionId, chat, ownership, structuredClone(request))) as HostUiResponse<K>;
|
|
42
|
+
} catch {
|
|
43
|
+
return unavailable;
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Internal connection binding; only the library's constructed connections are accepted. */
|
|
50
|
+
export function bindChannelHostUi(connection: ChannelConnectionHandle, runtime: ChannelRuntime, connectionId: string): void {
|
|
51
|
+
const service = runtimes.get(runtime);
|
|
52
|
+
if (service) bindings.set(connection, { service, connectionId });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function registerChannelHostUi(runtime: ChannelRuntime, ctx: RuntimeContext, core: RuntimeCore) {
|
|
56
|
+
const service = createChannelUi(ctx, core);
|
|
57
|
+
runtimes.set(runtime, service);
|
|
58
|
+
return service;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sameOwnership(a: OwnershipScope, b: OwnershipScope): boolean {
|
|
62
|
+
return a.tenantId === b.tenantId && a.accountId === b.accountId && a.userId === b.userId;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function createChannelUi(ctx: RuntimeContext, core: RuntimeCore) {
|
|
66
|
+
const store = ctx.options.checkpoints && createChannelUiRequestStore(ctx.options.checkpoints);
|
|
67
|
+
const pairings = ctx.options.checkpoints && createChannelPairingStore({ checkpoints: ctx.options.checkpoints });
|
|
68
|
+
const pending = new Map<
|
|
69
|
+
string,
|
|
70
|
+
{
|
|
71
|
+
binding: string;
|
|
72
|
+
token?: string;
|
|
73
|
+
request: HostUiRequest;
|
|
74
|
+
finish: (answer: HostUiResponse) => void;
|
|
75
|
+
}
|
|
76
|
+
>();
|
|
77
|
+
const waiting = new Set<() => void>();
|
|
78
|
+
let closed = false;
|
|
79
|
+
|
|
80
|
+
async function send(ownership: OwnershipScope, reply: ChannelReply, requestId?: string): Promise<boolean> {
|
|
81
|
+
if (closed || ctx.stopped || !ctx.replies || (requestId !== undefined && !pending.has(requestId))) return false;
|
|
82
|
+
const now = new Date().toISOString();
|
|
83
|
+
const operationId = `chan-ui-${randomUUID()}`;
|
|
84
|
+
const key = { ownership, connectionId: reply.connectionId, operationId };
|
|
85
|
+
const record: ChannelReplyRecord = { ...reply, operationId, state: "pending", attempts: 0, createdAt: now, updatedAt: now };
|
|
86
|
+
const staged = await ctx.replies.stage(key, record);
|
|
87
|
+
if (!staged || closed || ctx.stopped || (requestId !== undefined && !pending.has(requestId))) return false;
|
|
88
|
+
let result: ChannelSendResult;
|
|
89
|
+
try {
|
|
90
|
+
result = await ctx.options.deliver(reply);
|
|
91
|
+
} catch {
|
|
92
|
+
await ctx.replies.mark(
|
|
93
|
+
key,
|
|
94
|
+
{ ...record, state: "delivery_unknown", attempts: 1, updatedAt: new Date().toISOString() },
|
|
95
|
+
staged.version,
|
|
96
|
+
);
|
|
97
|
+
ctx.counters.deliveryFailures++;
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
const delivered = result.delivered;
|
|
101
|
+
const marked = await ctx.replies.mark(
|
|
102
|
+
key,
|
|
103
|
+
{
|
|
104
|
+
...record,
|
|
105
|
+
state: delivered ? "delivered" : "delivery_failed",
|
|
106
|
+
attempts: 1,
|
|
107
|
+
...(result.messageId === undefined ? {} : { messageId: result.messageId }),
|
|
108
|
+
updatedAt: new Date().toISOString(),
|
|
109
|
+
},
|
|
110
|
+
staged.version,
|
|
111
|
+
);
|
|
112
|
+
if (delivered) ctx.counters.deliveries++;
|
|
113
|
+
else ctx.counters.deliveryFailures++;
|
|
114
|
+
return delivered && marked !== null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function request(connectionId: string, chat: string, ownership: OwnershipScope, request: HostUiRequest): Promise<HostUiResponse> {
|
|
118
|
+
if (closed || ctx.stopped || waiting.size >= ctx.limits.maxPendingPerProcess) return unavailable;
|
|
119
|
+
const deadline = Date.now() + ctx.limits.approvalTtlMs;
|
|
120
|
+
const requestId = randomUUID();
|
|
121
|
+
let cancel = () => {};
|
|
122
|
+
const cancelled = new Promise<HostUiResponse>((resolve) => {
|
|
123
|
+
cancel = () => resolve(unavailable);
|
|
124
|
+
});
|
|
125
|
+
waiting.add(cancel);
|
|
126
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
127
|
+
try {
|
|
128
|
+
return await Promise.race([
|
|
129
|
+
cancelled,
|
|
130
|
+
offer(connectionId, chat, ownership, request, deadline, requestId),
|
|
131
|
+
new Promise<HostUiResponse>((resolve) => {
|
|
132
|
+
timer = setTimeout(() => resolve(unavailable), ctx.limits.approvalTtlMs);
|
|
133
|
+
}),
|
|
134
|
+
]);
|
|
135
|
+
} finally {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
waiting.delete(cancel);
|
|
138
|
+
pending.get(requestId)?.finish(unavailable);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function offer(
|
|
143
|
+
connectionId: string,
|
|
144
|
+
chat: string,
|
|
145
|
+
ownership: OwnershipScope,
|
|
146
|
+
request: HostUiRequest,
|
|
147
|
+
deadline: number,
|
|
148
|
+
requestId: string,
|
|
149
|
+
): Promise<HostUiResponse> {
|
|
150
|
+
if (closed || ctx.stopped || !ctx.options.authorize || !store || !pairings || !/^pair:[A-Za-z0-9_-]{43}$/.test(chat))
|
|
151
|
+
return unavailable;
|
|
152
|
+
if (
|
|
153
|
+
request.kind === "notify"
|
|
154
|
+
? typeof request.message !== "string"
|
|
155
|
+
: !("title" in request) ||
|
|
156
|
+
typeof request.title !== "string" ||
|
|
157
|
+
("detail" in request && request.detail !== undefined && typeof request.detail !== "string")
|
|
158
|
+
)
|
|
159
|
+
return unavailable;
|
|
160
|
+
try {
|
|
161
|
+
const pair = await pairings.resolve({ ...ownership, connectionId, token: chat.slice(5) });
|
|
162
|
+
if (!pair || closed || ctx.stopped || Date.now() >= deadline) return unavailable;
|
|
163
|
+
const event: ChannelInboundEvent = {
|
|
164
|
+
connectionId,
|
|
165
|
+
externalConversationId: pair.externalConversationId,
|
|
166
|
+
externalActorId: pair.externalActorId,
|
|
167
|
+
...(pair.threadId === undefined ? {} : { threadId: pair.threadId }),
|
|
168
|
+
eventId: `ui-${randomUUID()}`,
|
|
169
|
+
text: "",
|
|
170
|
+
};
|
|
171
|
+
if (!core.validEvent(event)) return unavailable;
|
|
172
|
+
const authorization = await core.authorizeEvent(event, "approval");
|
|
173
|
+
if (
|
|
174
|
+
"status" in authorization ||
|
|
175
|
+
authorization.grantRevision !== pair.grantRevision ||
|
|
176
|
+
!sameOwnership(ownership, ownershipFromIdentity(authorization.identity)) ||
|
|
177
|
+
closed ||
|
|
178
|
+
ctx.stopped ||
|
|
179
|
+
Date.now() >= deadline
|
|
180
|
+
)
|
|
181
|
+
return unavailable;
|
|
182
|
+
if (
|
|
183
|
+
request.kind === "select" &&
|
|
184
|
+
(!Array.isArray(request.options) ||
|
|
185
|
+
request.options.length < 1 ||
|
|
186
|
+
request.options.length > 8 ||
|
|
187
|
+
(request.multiple !== undefined && typeof request.multiple !== "boolean") ||
|
|
188
|
+
request.options.some((o) => !o || typeof o.value !== "string" || (o.label !== undefined && typeof o.label !== "string")) ||
|
|
189
|
+
new Set(request.options.map((o) => o.value)).size !== request.options.length)
|
|
190
|
+
)
|
|
191
|
+
return unavailable;
|
|
192
|
+
if (request.kind !== "notify" && request.kind !== "confirm" && request.kind !== "select" && request.kind !== "input")
|
|
193
|
+
return unavailable;
|
|
194
|
+
const binding = JSON.stringify([
|
|
195
|
+
connectionId,
|
|
196
|
+
ownership.tenantId,
|
|
197
|
+
ownership.accountId,
|
|
198
|
+
ownership.userId,
|
|
199
|
+
pair.externalConversationId,
|
|
200
|
+
pair.externalActorId,
|
|
201
|
+
pair.threadId,
|
|
202
|
+
]);
|
|
203
|
+
if (
|
|
204
|
+
pending.size >= ctx.limits.maxPendingPerProcess ||
|
|
205
|
+
[...pending.values()].filter((p) => p.binding === binding).length >= ctx.limits.maxPendingPerBinding
|
|
206
|
+
)
|
|
207
|
+
return unavailable;
|
|
208
|
+
return await new Promise<HostUiResponse>((resolve) => {
|
|
209
|
+
const finish = (answer: HostUiResponse) => {
|
|
210
|
+
if (!pending.delete(requestId)) return;
|
|
211
|
+
resolve(answer);
|
|
212
|
+
};
|
|
213
|
+
const waiter = { binding, request, finish, token: undefined as string | undefined };
|
|
214
|
+
pending.set(requestId, waiter);
|
|
215
|
+
const deliver = async () => {
|
|
216
|
+
let token: string | undefined;
|
|
217
|
+
if (request.kind !== "notify") {
|
|
218
|
+
const created = await store.create({
|
|
219
|
+
ownership,
|
|
220
|
+
identity: authorization.identity,
|
|
221
|
+
...event,
|
|
222
|
+
grantRevision: authorization.grantRevision,
|
|
223
|
+
requestId,
|
|
224
|
+
valueKind: request.kind,
|
|
225
|
+
ttlMs: Math.max(1, deadline - Date.now()),
|
|
226
|
+
});
|
|
227
|
+
token = created.token;
|
|
228
|
+
waiter.token = token;
|
|
229
|
+
}
|
|
230
|
+
if (!pending.has(requestId) || closed || ctx.stopped) return;
|
|
231
|
+
let text =
|
|
232
|
+
request.kind === "notify" ? request.message : [request.title, request.detail].filter((v) => v !== undefined).join("\n\n");
|
|
233
|
+
let controls: ChannelReplyControl[] | undefined;
|
|
234
|
+
if (request.kind === "confirm") controls = ["Yes", "No"].map((label, i) => ({ label, value: `q:${token}:${i}` }));
|
|
235
|
+
if (request.kind === "select") {
|
|
236
|
+
if (request.multiple)
|
|
237
|
+
text += `\n\n${request.options.map((o, i) => `${i}: ${o.label ?? o.value}`).join("\n")}\nReply /answer ${token} <comma-separated indexes>`;
|
|
238
|
+
else controls = request.options.map((o, i) => ({ label: o.label ?? o.value, value: `q:${token}:${i}` }));
|
|
239
|
+
}
|
|
240
|
+
if (request.kind === "input") text += `\n\nReply /answer ${token} <text>`;
|
|
241
|
+
text = core.redact(text);
|
|
242
|
+
controls = controls?.map((c) => ({ ...c, label: core.redact(c.label) }));
|
|
243
|
+
// Both transports fit one message, including Signal's rendered reply commands.
|
|
244
|
+
const rendered =
|
|
245
|
+
text +
|
|
246
|
+
(controls
|
|
247
|
+
? `\n\n${controls.map((c) => `Reply /answer ${c.value.split(":")[1]} ${c.value.split(":")[2]} (${c.label})`).join("\n")}`
|
|
248
|
+
: "");
|
|
249
|
+
if (
|
|
250
|
+
typeof text !== "string" ||
|
|
251
|
+
!text.length ||
|
|
252
|
+
rendered.length > 2000 ||
|
|
253
|
+
Buffer.byteLength(rendered) > ctx.limits.maxResponseBytes ||
|
|
254
|
+
controls?.some((c) => !c.label.length || Buffer.byteLength(c.label) > 64)
|
|
255
|
+
) {
|
|
256
|
+
finish(unavailable);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const delivered = await send(
|
|
260
|
+
ownership,
|
|
261
|
+
{
|
|
262
|
+
connectionId,
|
|
263
|
+
externalConversationId: pair.externalConversationId,
|
|
264
|
+
...(pair.threadId === undefined ? {} : { threadId: pair.threadId }),
|
|
265
|
+
text,
|
|
266
|
+
kind: "notice",
|
|
267
|
+
...(controls ? { controls } : {}),
|
|
268
|
+
},
|
|
269
|
+
requestId,
|
|
270
|
+
);
|
|
271
|
+
if (!delivered) finish(unavailable);
|
|
272
|
+
else if (request.kind === "notify") finish({ status: "answered", value: undefined });
|
|
273
|
+
};
|
|
274
|
+
void deliver().catch(() => {
|
|
275
|
+
ctx.counters.storageFailures++;
|
|
276
|
+
finish(unavailable);
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
} catch {
|
|
280
|
+
ctx.counters.storageFailures++;
|
|
281
|
+
return unavailable;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
async function admit(event: ChannelInboundEvent): Promise<ChannelAdmission | undefined> {
|
|
286
|
+
if (!/^\/answer(?:\s|$)/.test(event.text)) return undefined;
|
|
287
|
+
if (!ctx.options.authorize || !store) return core.denial("rejected");
|
|
288
|
+
const authorization = await core.authorizeEvent(event, "approval");
|
|
289
|
+
if ("status" in authorization) return authorization;
|
|
290
|
+
const match = /^\/answer ([A-Za-z0-9_-]{43}) ([\s\S]*)$/.exec(event.text);
|
|
291
|
+
if (!match) return core.denial("rejected");
|
|
292
|
+
const [, token, value] = match;
|
|
293
|
+
const ownership = ownershipFromIdentity(authorization.identity);
|
|
294
|
+
try {
|
|
295
|
+
const key = { ownership, connectionId: event.connectionId, token };
|
|
296
|
+
const stored = await store.load(key);
|
|
297
|
+
if (!stored) return core.denial("rejected");
|
|
298
|
+
const r = stored.record;
|
|
299
|
+
if (
|
|
300
|
+
r.externalConversationId !== event.externalConversationId ||
|
|
301
|
+
r.externalActorId !== event.externalActorId ||
|
|
302
|
+
r.threadId !== event.threadId ||
|
|
303
|
+
r.principalKind !== authorization.identity.principal.kind ||
|
|
304
|
+
r.principalId !== authorization.identity.principal.id ||
|
|
305
|
+
r.grantRevision !== authorization.grantRevision
|
|
306
|
+
)
|
|
307
|
+
return core.denial("rejected");
|
|
308
|
+
const waiter = pending.get(r.requestId);
|
|
309
|
+
const expired = async () => {
|
|
310
|
+
await send(ownership, {
|
|
311
|
+
connectionId: event.connectionId,
|
|
312
|
+
externalConversationId: event.externalConversationId,
|
|
313
|
+
...(event.threadId === undefined ? {} : { threadId: event.threadId }),
|
|
314
|
+
text: "This request has expired.",
|
|
315
|
+
kind: "notice",
|
|
316
|
+
});
|
|
317
|
+
return { status: "accepted" } as const;
|
|
318
|
+
};
|
|
319
|
+
if (r.state !== "pending" || Date.parse(r.expiresAt) <= Date.now() || !waiter || waiter.token !== token) return await expired();
|
|
320
|
+
const req = waiter.request;
|
|
321
|
+
if (r.valueKind !== req.kind) return core.denial("rejected");
|
|
322
|
+
let answer: HostUiResponse;
|
|
323
|
+
if (req.kind === "input") answer = { status: "answered", value };
|
|
324
|
+
else if (req.kind === "confirm" && /^[01]$/.test(value)) answer = { status: "answered", value: value === "0" };
|
|
325
|
+
else if (req.kind === "select") {
|
|
326
|
+
const parts = value.split(",");
|
|
327
|
+
if (
|
|
328
|
+
(!req.multiple && parts.length !== 1) ||
|
|
329
|
+
parts.some((p) => !/^[0-7]$/.test(p) || Number(p) >= req.options.length) ||
|
|
330
|
+
new Set(parts).size !== parts.length
|
|
331
|
+
)
|
|
332
|
+
return core.denial("rejected");
|
|
333
|
+
const values = parts.map((p) => req.options[Number(p)].value);
|
|
334
|
+
answer = { status: "answered", value: req.multiple ? values : values[0] };
|
|
335
|
+
} else return core.denial("rejected");
|
|
336
|
+
const consumed = await store.consume({ ...key, expectedVersion: stored.version });
|
|
337
|
+
if (consumed !== "consumed" || pending.get(r.requestId) !== waiter || closed || ctx.stopped) return await expired();
|
|
338
|
+
waiter.finish(answer);
|
|
339
|
+
ctx.counters.admitted++;
|
|
340
|
+
return { status: "accepted" };
|
|
341
|
+
} catch {
|
|
342
|
+
ctx.counters.storageFailures++;
|
|
343
|
+
return core.denial("unavailable");
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return {
|
|
348
|
+
request,
|
|
349
|
+
admit,
|
|
350
|
+
close() {
|
|
351
|
+
closed = true;
|
|
352
|
+
for (const cancel of waiting) cancel();
|
|
353
|
+
for (const waiter of pending.values()) waiter.finish(unavailable);
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { OwnershipScope, Principal } from "@arnilo/prism";
|
|
2
|
+
|
|
3
|
+
export interface AgentIdentity {
|
|
4
|
+
readonly tenantId: string;
|
|
5
|
+
readonly accountId?: string;
|
|
6
|
+
readonly userId?: string;
|
|
7
|
+
readonly principal: Principal;
|
|
8
|
+
readonly sponsor?: Principal;
|
|
9
|
+
readonly owner?: Principal;
|
|
10
|
+
readonly delegatedFrom?: Principal;
|
|
11
|
+
readonly scopes: readonly string[];
|
|
12
|
+
readonly credentialRefs?: readonly string[];
|
|
13
|
+
readonly issuedAt: string;
|
|
14
|
+
readonly expiresAt?: string;
|
|
15
|
+
readonly revokedAt?: string;
|
|
16
|
+
readonly metadata?: Readonly<Record<string, unknown>>;
|
|
17
|
+
readonly verified: true;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function ownershipFromIdentity(identity: AgentIdentity): OwnershipScope {
|
|
21
|
+
return {
|
|
22
|
+
tenantId: identity.tenantId,
|
|
23
|
+
...(identity.accountId !== undefined ? { accountId: identity.accountId } : {}),
|
|
24
|
+
...(identity.userId !== undefined ? { userId: identity.userId } : {}),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function assertIdentityActive(identity: AgentIdentity): void {
|
|
29
|
+
if (identity.verified !== true) throw new Error("Identity is not host-verified");
|
|
30
|
+
const now = Date.now();
|
|
31
|
+
if (identity.revokedAt !== undefined) {
|
|
32
|
+
const revokedAt = Date.parse(identity.revokedAt);
|
|
33
|
+
if (!Number.isFinite(revokedAt) || revokedAt <= now) throw new Error("Identity has been revoked");
|
|
34
|
+
}
|
|
35
|
+
if (identity.expiresAt !== undefined) {
|
|
36
|
+
const expiresAt = Date.parse(identity.expiresAt);
|
|
37
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= now) throw new Error("Identity has expired");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function assertIdentityMatchesOwnership(identity: AgentIdentity, ownership?: OwnershipScope): void {
|
|
42
|
+
if (!ownership) return;
|
|
43
|
+
if (identity.tenantId !== ownership.tenantId) throw new Error("Identity tenant mismatch");
|
|
44
|
+
if (ownership.accountId !== undefined && identity.accountId !== ownership.accountId) throw new Error("Identity account mismatch");
|
|
45
|
+
if (ownership.userId !== undefined && identity.userId !== ownership.userId) throw new Error("Identity user mismatch");
|
|
46
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export type { ChannelDeliveryJournal, ChannelDeliveryJournalOptions, ChannelReplyKeyInput } from "./delivery.js";
|
|
2
|
+
export { createChannelDeliveryJournal, emptyPruneResult, isSettledReply } from "./delivery.js";
|
|
3
|
+
export { DEFAULT_CHANNEL_LIMITS, HARD_CHANNEL_LIMITS, resolveChannelLimits } from "./limits.js";
|
|
4
|
+
export type {
|
|
5
|
+
ChannelPairingConsumption,
|
|
6
|
+
ChannelPairingGrant,
|
|
7
|
+
ChannelPairingRecord,
|
|
8
|
+
ChannelPairingStore,
|
|
9
|
+
ChannelPairingStoreOptions,
|
|
10
|
+
ConsumeChannelPairingInput,
|
|
11
|
+
CreateChannelPairingInput,
|
|
12
|
+
} from "./pairing.js";
|
|
13
|
+
export { createChannelPairingStore, DEFAULT_PAIRING_TTL_MS, HARD_PAIRING_TTL_MS } from "./pairing.js";
|
|
14
|
+
export type { ChannelApprovalStore } from "./approvals.js";
|
|
15
|
+
export { createChannelApprovalStore } from "./approvals.js";
|
|
16
|
+
export { createMemoryCheckpointStore, createMemoryLeaseStore } from "./memory-stores.js";
|
|
17
|
+
export {
|
|
18
|
+
ChannelTokenLiteralError,
|
|
19
|
+
CHANNEL_TOKEN_LITERAL_CODE,
|
|
20
|
+
type ChannelSecretSource,
|
|
21
|
+
resolveChannelSecretRef,
|
|
22
|
+
createChannelRedactor,
|
|
23
|
+
} from "./secret-ref.js";
|
|
24
|
+
export { createChannelRuntime } from "./runtime.js";
|
|
25
|
+
export type {
|
|
26
|
+
ChannelBindingKeyInput,
|
|
27
|
+
ChannelBindingRecord,
|
|
28
|
+
ChannelCursorKeyInput,
|
|
29
|
+
ChannelCursorRecord,
|
|
30
|
+
ChannelJournalEntry,
|
|
31
|
+
ChannelJournalNamespace,
|
|
32
|
+
ChannelOperationKeyInput,
|
|
33
|
+
ChannelStateStore,
|
|
34
|
+
ChannelStateStoreOptions,
|
|
35
|
+
StoredChannelRecord,
|
|
36
|
+
} from "./state.js";
|
|
37
|
+
export { CHANNEL_JOURNAL_NAMESPACES, createChannelStateStore, UNRESOLVED_OPERATION_STATES } from "./state.js";
|
|
38
|
+
export type {
|
|
39
|
+
ChannelAction,
|
|
40
|
+
ChannelAdapter,
|
|
41
|
+
ChannelAdmission,
|
|
42
|
+
ChannelAdmissionStatus,
|
|
43
|
+
ChannelApprovalControl,
|
|
44
|
+
ChannelApprovalOutcome,
|
|
45
|
+
ChannelAssistantDelta,
|
|
46
|
+
ChannelAttachmentBytes,
|
|
47
|
+
ChannelAttachmentKind,
|
|
48
|
+
ChannelAttachmentRef,
|
|
49
|
+
ChannelAuthorization,
|
|
50
|
+
ChannelAuthorizeInput,
|
|
51
|
+
ChannelBinding,
|
|
52
|
+
ChannelBindingInput,
|
|
53
|
+
ChannelCapabilities,
|
|
54
|
+
ChannelConnectionHandle,
|
|
55
|
+
ChannelDenialReason,
|
|
56
|
+
ChannelDiagnostics,
|
|
57
|
+
ChannelDrainResult,
|
|
58
|
+
ChannelInboundEvent,
|
|
59
|
+
ChannelLimits,
|
|
60
|
+
ChannelNotifyInput,
|
|
61
|
+
ChannelOperationRecord,
|
|
62
|
+
ChannelOperationState,
|
|
63
|
+
ChannelPruneResult,
|
|
64
|
+
ChannelReceive,
|
|
65
|
+
ChannelReconcileInput,
|
|
66
|
+
ChannelReconcileOutcome,
|
|
67
|
+
ChannelReconcileResult,
|
|
68
|
+
ChannelReply,
|
|
69
|
+
ChannelReplyControl,
|
|
70
|
+
ChannelReplyRecord,
|
|
71
|
+
ChannelReplyState,
|
|
72
|
+
ChannelRuntime,
|
|
73
|
+
ChannelRuntimeOptions,
|
|
74
|
+
ChannelSendResult,
|
|
75
|
+
ChannelUnresolvedOperation,
|
|
76
|
+
ChannelUnsupportedReason,
|
|
77
|
+
ResolvedChannelLimits,
|
|
78
|
+
} from "./types.js";
|
|
79
|
+
export { connectTelegram, type TelegramConnectOptions } from "./telegram.js";
|
|
80
|
+
export { connectSignal, type SignalConnectOptions } from "./signal.js";
|
|
81
|
+
|
|
82
|
+
export { channelHostUi, type ChannelHostUiOptions } from "./host-ui.js";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Plan 079 Task 2: channel limits. Defaults come from the Task 1 review section 6; hard caps
|
|
2
|
+
// cannot be raised, only lowered (the store/platform ceilings in that table stay above them).
|
|
3
|
+
import type { ChannelLimits, ResolvedChannelLimits } from "./types.js";
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_CHANNEL_LIMITS: ResolvedChannelLimits = {
|
|
6
|
+
maxInputBytes: 32 * 1024,
|
|
7
|
+
maxResponseBytes: 64 * 1024,
|
|
8
|
+
maxPendingPerBinding: 8,
|
|
9
|
+
maxPendingPerProcess: 100,
|
|
10
|
+
maxActiveSessions: 4,
|
|
11
|
+
maxRoutes: 1_000,
|
|
12
|
+
maxSeenEventsPerConnection: 1_000,
|
|
13
|
+
stopDeadlineMs: 30_000,
|
|
14
|
+
retentionDays: 7,
|
|
15
|
+
maxJournalPage: 100,
|
|
16
|
+
maxJournalRecordBytes: 128 * 1024,
|
|
17
|
+
leaseTtlMs: 30_000,
|
|
18
|
+
approvalTtlMs: 5 * 60_000,
|
|
19
|
+
maxAttachmentBytes: 1024 * 1024,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const HARD_CHANNEL_LIMITS: ResolvedChannelLimits = {
|
|
23
|
+
maxInputBytes: 64 * 1024,
|
|
24
|
+
maxResponseBytes: 128 * 1024,
|
|
25
|
+
maxPendingPerBinding: 32,
|
|
26
|
+
maxPendingPerProcess: 500,
|
|
27
|
+
maxActiveSessions: 16,
|
|
28
|
+
maxRoutes: 10_000,
|
|
29
|
+
maxSeenEventsPerConnection: 10_000,
|
|
30
|
+
stopDeadlineMs: 5 * 60_000,
|
|
31
|
+
retentionDays: 90,
|
|
32
|
+
maxJournalPage: 500,
|
|
33
|
+
maxJournalRecordBytes: 512 * 1024,
|
|
34
|
+
leaseTtlMs: 5 * 60_000,
|
|
35
|
+
approvalTtlMs: 5 * 60_000,
|
|
36
|
+
maxAttachmentBytes: 4 * 1024 * 1024,
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export function resolveChannelLimits(input: ChannelLimits = {}): ResolvedChannelLimits {
|
|
40
|
+
const out = {} as Record<keyof ResolvedChannelLimits, number>;
|
|
41
|
+
for (const key of Object.keys(DEFAULT_CHANNEL_LIMITS) as (keyof ResolvedChannelLimits)[]) {
|
|
42
|
+
const value = input[key] ?? DEFAULT_CHANNEL_LIMITS[key];
|
|
43
|
+
if (!Number.isFinite(value) || value < 1 || value > HARD_CHANNEL_LIMITS[key]) {
|
|
44
|
+
throw new TypeError(`Channel limit ${key} must be a positive number no greater than ${HARD_CHANNEL_LIMITS[key]}`);
|
|
45
|
+
}
|
|
46
|
+
out[key] = value;
|
|
47
|
+
}
|
|
48
|
+
return out as ResolvedChannelLimits;
|
|
49
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { OwnershipScope } from "@arnilo/prism";
|
|
2
|
+
import type { CheckpointStore, LeaseRecord, LeaseStore } from "./checkpoint-contract.js";
|
|
3
|
+
|
|
4
|
+
export function createMemoryCheckpointStore(): CheckpointStore {
|
|
5
|
+
const records = new Map<string, any>();
|
|
6
|
+
const keyOf = (ns: string, key: string, scope?: OwnershipScope) =>
|
|
7
|
+
`${ns}:${scope?.tenantId ?? "-"}:${scope?.accountId ?? "-"}:${scope?.userId ?? "-"}:${key}`;
|
|
8
|
+
|
|
9
|
+
return {
|
|
10
|
+
async saveCheckpoint(input) {
|
|
11
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
12
|
+
const existing = records.get(id);
|
|
13
|
+
if (input.expectedVersion !== undefined && input.expectedVersion !== (existing?.version ?? 0)) {
|
|
14
|
+
const err = new Error(`Checkpoint CAS failed (expected ${input.expectedVersion}, got ${existing?.version ?? 0})`);
|
|
15
|
+
err.name = "CheckpointConflictError";
|
|
16
|
+
throw err;
|
|
17
|
+
}
|
|
18
|
+
const record = {
|
|
19
|
+
namespace: input.namespace,
|
|
20
|
+
key: input.key,
|
|
21
|
+
tenantId: input.tenantId,
|
|
22
|
+
accountId: input.accountId,
|
|
23
|
+
userId: input.userId,
|
|
24
|
+
category: input.category,
|
|
25
|
+
version: input.version,
|
|
26
|
+
fencingToken: input.fencingToken,
|
|
27
|
+
value: input.value,
|
|
28
|
+
createdAt: existing?.createdAt ?? new Date().toISOString(),
|
|
29
|
+
updatedAt: new Date().toISOString(),
|
|
30
|
+
};
|
|
31
|
+
records.set(id, record);
|
|
32
|
+
return record;
|
|
33
|
+
},
|
|
34
|
+
async loadCheckpoint(input) {
|
|
35
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
36
|
+
return records.get(id) ?? null;
|
|
37
|
+
},
|
|
38
|
+
async listCheckpoints(query) {
|
|
39
|
+
const prefix = query?.namespace ? `${query.namespace}:` : "";
|
|
40
|
+
const matches = Array.from(records.values()).filter((r) => !prefix || r.namespace === query?.namespace);
|
|
41
|
+
return { items: matches, hasMore: false };
|
|
42
|
+
},
|
|
43
|
+
async deleteCheckpoint(input) {
|
|
44
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
45
|
+
return records.delete(id);
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createMemoryLeaseStore(): LeaseStore {
|
|
51
|
+
const records = new Map<string, LeaseRecord>();
|
|
52
|
+
const keyOf = (ns: string, key: string, scope?: OwnershipScope) =>
|
|
53
|
+
`${ns}:${scope?.tenantId ?? "-"}:${scope?.accountId ?? "-"}:${scope?.userId ?? "-"}:${key}`;
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
async getLease(input) {
|
|
57
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
58
|
+
const current = records.get(id);
|
|
59
|
+
if (!current) return null;
|
|
60
|
+
if (Date.parse(current.expiresAt) <= Date.now()) {
|
|
61
|
+
records.delete(id);
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
return current;
|
|
65
|
+
},
|
|
66
|
+
async tryAcquireLease(input) {
|
|
67
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
68
|
+
const current = records.get(id);
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
if (current && Date.parse(current.expiresAt) > now) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
const timestamp = new Date(now).toISOString();
|
|
74
|
+
const record: LeaseRecord = {
|
|
75
|
+
namespace: input.namespace,
|
|
76
|
+
key: input.key,
|
|
77
|
+
ownerId: input.ownerId,
|
|
78
|
+
token: crypto.randomUUID(),
|
|
79
|
+
fencingToken: (current?.fencingToken ?? 0) + 1,
|
|
80
|
+
acquiredAt: timestamp,
|
|
81
|
+
expiresAt: new Date(now + input.ttlMs).toISOString(),
|
|
82
|
+
updatedAt: timestamp,
|
|
83
|
+
tenantId: input.tenantId,
|
|
84
|
+
accountId: input.accountId,
|
|
85
|
+
userId: input.userId,
|
|
86
|
+
};
|
|
87
|
+
records.set(id, record);
|
|
88
|
+
return record;
|
|
89
|
+
},
|
|
90
|
+
async renewLease(input) {
|
|
91
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
92
|
+
const current = records.get(id);
|
|
93
|
+
if (!current || current.token !== input.token) return null;
|
|
94
|
+
const now = Date.now();
|
|
95
|
+
const timestamp = new Date(now).toISOString();
|
|
96
|
+
const updated: LeaseRecord = {
|
|
97
|
+
...current,
|
|
98
|
+
expiresAt: new Date(now + input.ttlMs).toISOString(),
|
|
99
|
+
updatedAt: timestamp,
|
|
100
|
+
};
|
|
101
|
+
records.set(id, updated);
|
|
102
|
+
return updated;
|
|
103
|
+
},
|
|
104
|
+
async releaseLease(input) {
|
|
105
|
+
const id = keyOf(input.namespace, input.key, input);
|
|
106
|
+
const current = records.get(id);
|
|
107
|
+
if (!current || current.token !== input.token) return false;
|
|
108
|
+
records.delete(id);
|
|
109
|
+
return true;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|