@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,790 @@
|
|
|
1
|
+
// Plan 079 Task 7: experimental signal-cli v0.14.8 Unix-socket adapter. Importing and
|
|
2
|
+
// construction are inert: hosts run and supervise signal-cli; this code only connects on start().
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { createConnection, type Socket } from "node:net";
|
|
5
|
+
import type { Agent, OwnershipScope } from "@arnilo/prism";
|
|
6
|
+
import type { CheckpointStore, LeaseRecord, LeaseStore } from "./checkpoint-contract.js";
|
|
7
|
+
import { bindChannelHostUi } from "./host-ui.js";
|
|
8
|
+
import { retryableAdmission } from "./admission.js";
|
|
9
|
+
import { resolveChannelSecretRef, createChannelRedactor } from "./secret-ref.js";
|
|
10
|
+
import { createMemoryCheckpointStore, createMemoryLeaseStore } from "./memory-stores.js";
|
|
11
|
+
import { createChannelRuntime } from "./runtime.js";
|
|
12
|
+
import type {
|
|
13
|
+
ChannelAdapter,
|
|
14
|
+
ChannelAuthorizeInput,
|
|
15
|
+
ChannelAuthorization,
|
|
16
|
+
ChannelConnectionHandle,
|
|
17
|
+
ChannelInboundEvent,
|
|
18
|
+
ChannelReceive,
|
|
19
|
+
ChannelReply,
|
|
20
|
+
ChannelSendResult,
|
|
21
|
+
} from "./types.js";
|
|
22
|
+
|
|
23
|
+
export type { ChannelConnectionHandle };
|
|
24
|
+
|
|
25
|
+
/** Only this externally operated signal-cli release's JSON-RPC shape is supported. */
|
|
26
|
+
export const SIGNAL_CLI_VERSION = "0.14.8";
|
|
27
|
+
|
|
28
|
+
const DEFAULT_FRAME_BYTES = 128 * 1024;
|
|
29
|
+
const HARD_FRAME_BYTES = 512 * 1024;
|
|
30
|
+
const DEFAULT_PENDING_REQUESTS = 16;
|
|
31
|
+
const HARD_PENDING_REQUESTS = 64;
|
|
32
|
+
const DEFAULT_PENDING_EVENTS = 32;
|
|
33
|
+
const HARD_PENDING_EVENTS = 128;
|
|
34
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
|
|
35
|
+
const DEFAULT_RECONNECT_DELAY_MS = 1_000;
|
|
36
|
+
const DEFAULT_MAX_RECONNECT_DELAY_MS = 30_000;
|
|
37
|
+
const DEFAULT_LEASE_TTL_MS = 90_000;
|
|
38
|
+
const SIGNAL_TEXT_CODE_UNITS = 2_000;
|
|
39
|
+
const RECEIVER_LEASE_NAMESPACE = "prism.channels.v1.signal.receiver";
|
|
40
|
+
const RECEIVER_READY_NAMESPACE = "prism.channels.v1.signal.receiver";
|
|
41
|
+
const RECEIVER_KEY_PREFIX = "r1:";
|
|
42
|
+
const SERVICE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
43
|
+
|
|
44
|
+
/** Explicit host attestation; Prism does not decide Signal acceptable use or GPL obligations. */
|
|
45
|
+
export interface SignalPolicyGate {
|
|
46
|
+
readonly acceptableUse: "operator_approved";
|
|
47
|
+
readonly gplDistribution: "operator_approved";
|
|
48
|
+
/** Host's recorded current Signal Terms version/date; revisiting it is an operator obligation. */
|
|
49
|
+
readonly termsVersion: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface SignalAdapterOptions {
|
|
53
|
+
/** Stable host-selected connection id; never read from Signal input. */
|
|
54
|
+
readonly connectionId: string;
|
|
55
|
+
/** Absolute, host-selected private Unix socket path; TCP and HTTP bridges are unsupported. */
|
|
56
|
+
readonly socketPath: string;
|
|
57
|
+
/** Account selected by the externally supervised signal-cli daemon. */
|
|
58
|
+
readonly account: string;
|
|
59
|
+
/** Must be the adapter's fixed compatibility target, `SIGNAL_CLI_VERSION`. */
|
|
60
|
+
readonly signalCliVersion: typeof SIGNAL_CLI_VERSION;
|
|
61
|
+
/** Explicit operator policy/license gate; construction rejects a missing or malformed attestation. */
|
|
62
|
+
readonly policy: SignalPolicyGate;
|
|
63
|
+
/** Probed before subscription so unavailable durable storage prevents receipt. */
|
|
64
|
+
readonly checkpoints: CheckpointStore;
|
|
65
|
+
/** Service-owned receiver lease; one subscriber per connection. */
|
|
66
|
+
readonly leases: LeaseStore;
|
|
67
|
+
readonly cursorOwnership: OwnershipScope;
|
|
68
|
+
/** Set only for a signal-cli daemon started without `-a`; RPCs then include the configured account. */
|
|
69
|
+
readonly multiAccount?: boolean;
|
|
70
|
+
/** Test seam. Defaults to Node's `createConnection(socketPath)`. */
|
|
71
|
+
readonly connect?: (socketPath: string) => Socket;
|
|
72
|
+
readonly maxFrameBytes?: number;
|
|
73
|
+
readonly maxPendingRequests?: number;
|
|
74
|
+
readonly maxPendingEvents?: number;
|
|
75
|
+
readonly requestTimeoutMs?: number;
|
|
76
|
+
readonly reconnectDelayMs?: number;
|
|
77
|
+
readonly maxReconnectDelayMs?: number;
|
|
78
|
+
readonly leaseTtlMs?: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface SignalAdapterHealth {
|
|
82
|
+
readonly bridge: "unavailable" | "connected";
|
|
83
|
+
readonly subscription: "inactive" | "active" | "paused";
|
|
84
|
+
readonly account: "unverified" | "ready" | "mismatch" | "identity_changed";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Channel adapter plus bounded, payload-free bridge/subscription/account status. */
|
|
88
|
+
export type SignalAdapter = ChannelAdapter & { health(): SignalAdapterHealth };
|
|
89
|
+
|
|
90
|
+
type Pending = {
|
|
91
|
+
readonly resolve: (value: unknown) => void;
|
|
92
|
+
readonly reject: (error: Error) => void;
|
|
93
|
+
readonly timer: ReturnType<typeof setTimeout>;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
class SignalRpcError extends Error {
|
|
97
|
+
constructor(readonly detail: string) {
|
|
98
|
+
super("Signal RPC request failed");
|
|
99
|
+
this.name = "SignalRpcError";
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
class SignalTransportError extends Error {
|
|
104
|
+
constructor() {
|
|
105
|
+
super("Signal bridge unavailable");
|
|
106
|
+
this.name = "SignalTransportError";
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
class SignalDeliveryUnknownError extends Error {
|
|
111
|
+
constructor() {
|
|
112
|
+
super("Signal delivery outcome unknown");
|
|
113
|
+
this.name = "SignalDeliveryUnknownError";
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
class SignalLineReader {
|
|
118
|
+
private buffer = Buffer.alloc(0);
|
|
119
|
+
|
|
120
|
+
constructor(private readonly maxFrameBytes: number) {}
|
|
121
|
+
|
|
122
|
+
push(chunk: Buffer): unknown[] {
|
|
123
|
+
if (chunk.byteLength > this.maxFrameBytes || this.buffer.byteLength + chunk.byteLength > this.maxFrameBytes + 1) {
|
|
124
|
+
throw new RangeError("Signal JSON-RPC frame exceeds maxFrameBytes");
|
|
125
|
+
}
|
|
126
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
127
|
+
const messages: unknown[] = [];
|
|
128
|
+
for (;;) {
|
|
129
|
+
const newline = this.buffer.indexOf(0x0a);
|
|
130
|
+
if (newline < 0) break;
|
|
131
|
+
const line = this.buffer.subarray(0, newline);
|
|
132
|
+
this.buffer = this.buffer.subarray(newline + 1);
|
|
133
|
+
if (line.byteLength === 0) continue;
|
|
134
|
+
if (line.byteLength > this.maxFrameBytes) throw new RangeError("Signal JSON-RPC frame exceeds maxFrameBytes");
|
|
135
|
+
try {
|
|
136
|
+
messages.push(JSON.parse(line.subarray(0, line.byteLength > 0 && line.at(-1) === 0x0d ? -1 : undefined).toString("utf8")));
|
|
137
|
+
} catch {
|
|
138
|
+
throw new TypeError("Signal JSON-RPC frame is malformed");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return messages;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
146
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function bounded(value: number | undefined, fallback: number, min: number, max: number, name: string): number {
|
|
150
|
+
const resolved = value ?? fallback;
|
|
151
|
+
if (!Number.isSafeInteger(resolved) || resolved < min || resolved > max) {
|
|
152
|
+
throw new TypeError(`Signal ${name} must be an integer between ${min} and ${max}`);
|
|
153
|
+
}
|
|
154
|
+
return resolved;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function scope(ownership: OwnershipScope): OwnershipScope {
|
|
158
|
+
return {
|
|
159
|
+
...(ownership.tenantId === undefined ? {} : { tenantId: ownership.tenantId }),
|
|
160
|
+
...(ownership.accountId === undefined ? {} : { accountId: ownership.accountId }),
|
|
161
|
+
...(ownership.userId === undefined ? {} : { userId: ownership.userId }),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function receiverKey(connectionId: string): string {
|
|
166
|
+
return `${RECEIVER_KEY_PREFIX}${connectionId}`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function rpcId(value: unknown): string | undefined {
|
|
170
|
+
return typeof value === "string" && value.length > 0 && value.length <= 128 ? value : undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function integer(value: unknown): number | undefined {
|
|
174
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function serviceId(value: unknown): string | undefined {
|
|
178
|
+
return typeof value === "string" && SERVICE_ID.test(value) ? value.toLowerCase() : undefined;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function chunkText(text: string): string[] {
|
|
182
|
+
const chunks: string[] = [];
|
|
183
|
+
let chunk = "";
|
|
184
|
+
for (const point of text) {
|
|
185
|
+
if (chunk.length > 0 && chunk.length + point.length > SIGNAL_TEXT_CODE_UNITS) {
|
|
186
|
+
chunks.push(chunk);
|
|
187
|
+
chunk = "";
|
|
188
|
+
}
|
|
189
|
+
chunk += point;
|
|
190
|
+
}
|
|
191
|
+
if (chunk.length > 0) chunks.push(chunk);
|
|
192
|
+
return chunks;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function approvalText(controls: ChannelReply["controls"]): string | undefined {
|
|
196
|
+
if (controls === undefined) return undefined;
|
|
197
|
+
if (controls.length === 0 || controls.length > 8) return undefined;
|
|
198
|
+
const commands: string[] = [];
|
|
199
|
+
for (const control of controls) {
|
|
200
|
+
const uiMatch = /^q:([A-Za-z0-9_-]{43}):([0-7])$/.exec(control.value);
|
|
201
|
+
if (uiMatch) {
|
|
202
|
+
if (typeof control.label !== "string" || !control.label.length || Buffer.byteLength(control.label) > 64) return undefined;
|
|
203
|
+
commands.push(`Reply /answer ${uiMatch[1]} ${uiMatch[2]} (${control.label})`);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const match = /^p:([ad]):([A-Za-z0-9_-]{32,64})$/.exec(control.value);
|
|
207
|
+
if (match === null || match[1] === undefined || match[2] === undefined) return undefined;
|
|
208
|
+
commands.push(match[1] === "a" ? `Reply /approve ${match[2]} to allow once.` : `Reply /deny ${match[2]} to deny.`);
|
|
209
|
+
}
|
|
210
|
+
return commands.join("\n");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function replyChunks(reply: ChannelReply): string[] | undefined {
|
|
214
|
+
const controls = approvalText(reply.controls);
|
|
215
|
+
if (reply.controls !== undefined && controls === undefined) return undefined;
|
|
216
|
+
const chunks = chunkText(reply.text);
|
|
217
|
+
if (controls === undefined) return chunks;
|
|
218
|
+
if (chunks.length === 0) return chunkText(controls);
|
|
219
|
+
const last = chunks.length - 1;
|
|
220
|
+
const combined = `${chunks[last]}\n\n${controls}`;
|
|
221
|
+
if (combined.length <= SIGNAL_TEXT_CODE_UNITS) {
|
|
222
|
+
chunks[last] = combined;
|
|
223
|
+
} else {
|
|
224
|
+
chunks.push(...chunkText(controls));
|
|
225
|
+
}
|
|
226
|
+
return chunks;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function rpcFailureReason(
|
|
230
|
+
error: SignalRpcError,
|
|
231
|
+
): "signal_rate_limited" | "signal_captcha_required" | "signal_relink_required" | "signal_identity_changed" | "signal_rpc_error" {
|
|
232
|
+
const detail = error.detail.toLowerCase();
|
|
233
|
+
if (detail.includes("captcha")) return "signal_captcha_required";
|
|
234
|
+
if (detail.includes("rate") || detail.includes("429")) return "signal_rate_limited";
|
|
235
|
+
if (detail.includes("untrusted identity") || detail.includes("identity key")) return "signal_identity_changed";
|
|
236
|
+
if (detail.includes("relink") || detail.includes("unregistered")) return "signal_relink_required";
|
|
237
|
+
return "signal_rpc_error";
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function notificationEvent(
|
|
241
|
+
value: unknown,
|
|
242
|
+
connectionId: string,
|
|
243
|
+
account: string,
|
|
244
|
+
subscription: number | undefined,
|
|
245
|
+
): ChannelInboundEvent | "account_mismatch" | undefined {
|
|
246
|
+
const message = asRecord(value);
|
|
247
|
+
if (message?.jsonrpc !== "2.0" || message.method !== "receive") return undefined;
|
|
248
|
+
const params = asRecord(message.params);
|
|
249
|
+
const result = params === undefined ? undefined : asRecord(params.result);
|
|
250
|
+
if (result === undefined || integer(params?.subscription) !== subscription) return undefined;
|
|
251
|
+
if (result.account !== account) return "account_mismatch";
|
|
252
|
+
const envelope = asRecord(result.envelope);
|
|
253
|
+
const actorId = serviceId(envelope?.sourceUuid);
|
|
254
|
+
const timestamp = integer(envelope?.timestamp);
|
|
255
|
+
const sourceDevice = integer(envelope?.sourceDevice);
|
|
256
|
+
const dataMessage = asRecord(envelope?.dataMessage);
|
|
257
|
+
if (
|
|
258
|
+
actorId === undefined ||
|
|
259
|
+
timestamp === undefined ||
|
|
260
|
+
sourceDevice === undefined ||
|
|
261
|
+
dataMessage === undefined ||
|
|
262
|
+
typeof dataMessage.message !== "string" ||
|
|
263
|
+
dataMessage.groupInfo !== undefined ||
|
|
264
|
+
(dataMessage.attachments !== undefined && (!Array.isArray(dataMessage.attachments) || dataMessage.attachments.length > 0))
|
|
265
|
+
) {
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
const eventId = createHash("sha256")
|
|
269
|
+
.update(
|
|
270
|
+
`${connectionId}\u0000${account}\u0000${actorId}\u0000${sourceDevice}\u0000${timestamp}\u0000${integer(dataMessage.timestamp) ?? timestamp}`,
|
|
271
|
+
)
|
|
272
|
+
.digest("base64url");
|
|
273
|
+
return {
|
|
274
|
+
connectionId,
|
|
275
|
+
externalConversationId: actorId,
|
|
276
|
+
externalActorId: actorId,
|
|
277
|
+
eventId,
|
|
278
|
+
text: dataMessage.message,
|
|
279
|
+
receivedAt: new Date().toISOString(),
|
|
280
|
+
claims: { platform: "signal", messageType: "direct_text" },
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function validateOptions(options: SignalAdapterOptions): void {
|
|
285
|
+
if (
|
|
286
|
+
typeof options.connectionId !== "string" ||
|
|
287
|
+
options.connectionId.length === 0 ||
|
|
288
|
+
Buffer.byteLength(options.connectionId, "utf8") > 256
|
|
289
|
+
) {
|
|
290
|
+
throw new TypeError("Signal connectionId must be a bounded non-empty string");
|
|
291
|
+
}
|
|
292
|
+
if (
|
|
293
|
+
typeof options.socketPath !== "string" ||
|
|
294
|
+
!options.socketPath.startsWith("/") ||
|
|
295
|
+
options.socketPath.includes("\0") ||
|
|
296
|
+
Buffer.byteLength(options.socketPath, "utf8") > 1024
|
|
297
|
+
) {
|
|
298
|
+
throw new TypeError("Signal socketPath must be a bounded absolute Unix socket path");
|
|
299
|
+
}
|
|
300
|
+
if (typeof options.account !== "string" || options.account.length === 0 || Buffer.byteLength(options.account, "utf8") > 128) {
|
|
301
|
+
throw new TypeError("Signal account must be a bounded non-empty string");
|
|
302
|
+
}
|
|
303
|
+
if (options.signalCliVersion !== SIGNAL_CLI_VERSION) throw new TypeError(`Signal adapter supports signal-cli ${SIGNAL_CLI_VERSION} only`);
|
|
304
|
+
if (
|
|
305
|
+
options.policy?.acceptableUse !== "operator_approved" ||
|
|
306
|
+
options.policy.gplDistribution !== "operator_approved" ||
|
|
307
|
+
typeof options.policy.termsVersion !== "string" ||
|
|
308
|
+
!/^\S{1,64}$/.test(options.policy.termsVersion)
|
|
309
|
+
) {
|
|
310
|
+
throw new TypeError("Signal requires an explicit operator policy and GPL attestation");
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Creates a Node-only adapter for an externally supervised, manual-receive signal-cli v0.14.8
|
|
316
|
+
* Unix socket. It exposes only subscribe/unsubscribe/send JSON-RPC methods and never spawns,
|
|
317
|
+
* registers, links, trusts identities, or opens a TCP/HTTP bridge.
|
|
318
|
+
*/
|
|
319
|
+
export function createSignalAdapter(options: SignalAdapterOptions): SignalAdapter {
|
|
320
|
+
validateOptions(options);
|
|
321
|
+
const maxFrameBytes = bounded(options.maxFrameBytes, DEFAULT_FRAME_BYTES, 1024, HARD_FRAME_BYTES, "maxFrameBytes");
|
|
322
|
+
const maxPendingRequests = bounded(options.maxPendingRequests, DEFAULT_PENDING_REQUESTS, 1, HARD_PENDING_REQUESTS, "maxPendingRequests");
|
|
323
|
+
const maxPendingEvents = bounded(options.maxPendingEvents, DEFAULT_PENDING_EVENTS, 1, HARD_PENDING_EVENTS, "maxPendingEvents");
|
|
324
|
+
const requestTimeoutMs = bounded(options.requestTimeoutMs, DEFAULT_REQUEST_TIMEOUT_MS, 100, 60_000, "requestTimeoutMs");
|
|
325
|
+
const reconnectDelayMs = bounded(options.reconnectDelayMs, DEFAULT_RECONNECT_DELAY_MS, 1, 60_000, "reconnectDelayMs");
|
|
326
|
+
const maxReconnectDelayMs = bounded(
|
|
327
|
+
options.maxReconnectDelayMs,
|
|
328
|
+
DEFAULT_MAX_RECONNECT_DELAY_MS,
|
|
329
|
+
reconnectDelayMs,
|
|
330
|
+
60_000,
|
|
331
|
+
"maxReconnectDelayMs",
|
|
332
|
+
);
|
|
333
|
+
const leaseTtlMs = bounded(options.leaseTtlMs, DEFAULT_LEASE_TTL_MS, 5_000, 300_000, "leaseTtlMs");
|
|
334
|
+
const ownerId = `signal-receiver-${randomUUID()}`;
|
|
335
|
+
const connect = options.connect ?? ((socketPath: string) => createConnection(socketPath));
|
|
336
|
+
const pending = new Map<string, Pending>();
|
|
337
|
+
let health: SignalAdapterHealth = { bridge: "unavailable", subscription: "inactive", account: "unverified" };
|
|
338
|
+
let socket: Socket | undefined;
|
|
339
|
+
let lease: LeaseRecord | undefined;
|
|
340
|
+
let controller: AbortController | undefined;
|
|
341
|
+
let renewTimer: ReturnType<typeof setInterval> | undefined;
|
|
342
|
+
let reconnecting: Promise<void> | undefined;
|
|
343
|
+
let receive: ChannelReceive | undefined;
|
|
344
|
+
let subscription: number | undefined;
|
|
345
|
+
let accepting = false;
|
|
346
|
+
let queuedEvents = 0;
|
|
347
|
+
let nextRequestId = 0;
|
|
348
|
+
let stopped = false;
|
|
349
|
+
|
|
350
|
+
function setHealth(next: Partial<SignalAdapterHealth>): void {
|
|
351
|
+
health = { ...health, ...next };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function rejectPending(error: Error): void {
|
|
355
|
+
for (const entry of pending.values()) {
|
|
356
|
+
clearTimeout(entry.timer);
|
|
357
|
+
entry.reject(error);
|
|
358
|
+
}
|
|
359
|
+
pending.clear();
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function rpcParams(params: Record<string, unknown>): Record<string, unknown> {
|
|
363
|
+
return options.multiAccount ? { account: options.account, ...params } : params;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function write(payload: Record<string, unknown>): void {
|
|
367
|
+
const current = socket;
|
|
368
|
+
const frame = Buffer.from(`${JSON.stringify(payload)}\n`, "utf8");
|
|
369
|
+
if (current === undefined || current.destroyed || !current.writable) throw new SignalTransportError();
|
|
370
|
+
if (frame.byteLength > maxFrameBytes) throw new RangeError("Signal JSON-RPC request exceeds maxFrameBytes");
|
|
371
|
+
try {
|
|
372
|
+
current.write(frame);
|
|
373
|
+
} catch {
|
|
374
|
+
throw new SignalTransportError();
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function notify(method: "unsubscribeReceive", params: Record<string, unknown>): void {
|
|
379
|
+
write({ jsonrpc: "2.0", method, params: rpcParams(params) });
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function request(method: "subscribeReceive" | "unsubscribeReceive" | "send", params: Record<string, unknown>): Promise<unknown> {
|
|
383
|
+
if (pending.size >= maxPendingRequests)
|
|
384
|
+
return Promise.reject(new RangeError("Signal pending JSON-RPC requests exceed maxPendingRequests"));
|
|
385
|
+
const id = `p${++nextRequestId}`;
|
|
386
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
387
|
+
const timer = setTimeout(() => {
|
|
388
|
+
pending.delete(id);
|
|
389
|
+
reject(new SignalTransportError());
|
|
390
|
+
}, requestTimeoutMs);
|
|
391
|
+
pending.set(id, { resolve, reject, timer });
|
|
392
|
+
try {
|
|
393
|
+
write({ jsonrpc: "2.0", id, method, params: rpcParams(params) });
|
|
394
|
+
} catch (error) {
|
|
395
|
+
pending.delete(id);
|
|
396
|
+
clearTimeout(timer);
|
|
397
|
+
reject(error instanceof Error ? error : new SignalTransportError());
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async function probeWriter(): Promise<void> {
|
|
403
|
+
const current = await options.checkpoints.loadCheckpoint({
|
|
404
|
+
namespace: RECEIVER_READY_NAMESPACE,
|
|
405
|
+
key: receiverKey(options.connectionId),
|
|
406
|
+
...scope(options.cursorOwnership),
|
|
407
|
+
});
|
|
408
|
+
await options.checkpoints.saveCheckpoint({
|
|
409
|
+
namespace: RECEIVER_READY_NAMESPACE,
|
|
410
|
+
key: receiverKey(options.connectionId),
|
|
411
|
+
...scope(options.cursorOwnership),
|
|
412
|
+
category: "channel-signal-receiver",
|
|
413
|
+
expectedVersion: current?.version ?? 0,
|
|
414
|
+
version: (current?.version ?? 0) + 1,
|
|
415
|
+
value: { schema: 1, updatedAt: new Date().toISOString() },
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
async function renew(): Promise<void> {
|
|
420
|
+
const current = lease;
|
|
421
|
+
const signal = controller?.signal;
|
|
422
|
+
if (current === undefined || signal === undefined || signal.aborted) return;
|
|
423
|
+
try {
|
|
424
|
+
const renewed = await options.leases.renewLease({
|
|
425
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
426
|
+
key: receiverKey(options.connectionId),
|
|
427
|
+
...scope(options.cursorOwnership),
|
|
428
|
+
ownerId,
|
|
429
|
+
token: current.token,
|
|
430
|
+
ttlMs: leaseTtlMs,
|
|
431
|
+
signal,
|
|
432
|
+
});
|
|
433
|
+
if (renewed === null) throw new Error("lease lost");
|
|
434
|
+
lease = renewed;
|
|
435
|
+
} catch {
|
|
436
|
+
accepting = false;
|
|
437
|
+
setHealth({ bridge: "unavailable", subscription: "paused" });
|
|
438
|
+
controller?.abort(new Error("Signal receiver lease lost"));
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
async function release(): Promise<void> {
|
|
443
|
+
const current = lease;
|
|
444
|
+
lease = undefined;
|
|
445
|
+
if (current === undefined) return;
|
|
446
|
+
try {
|
|
447
|
+
await options.leases.releaseLease({
|
|
448
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
449
|
+
key: receiverKey(options.connectionId),
|
|
450
|
+
...scope(options.cursorOwnership),
|
|
451
|
+
ownerId,
|
|
452
|
+
token: current.token,
|
|
453
|
+
});
|
|
454
|
+
} catch {
|
|
455
|
+
// A lease expiry/release failure cannot make this process the receiver again.
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function pause(forAccountMismatch = false): void {
|
|
460
|
+
if (!accepting && health.subscription === "paused") return;
|
|
461
|
+
accepting = false;
|
|
462
|
+
const currentSubscription = subscription;
|
|
463
|
+
subscription = undefined;
|
|
464
|
+
setHealth({ subscription: "paused", ...(forAccountMismatch ? { account: "mismatch" as const } : {}) });
|
|
465
|
+
if (currentSubscription !== undefined) {
|
|
466
|
+
try {
|
|
467
|
+
notify("unsubscribeReceive", { subscription: currentSubscription });
|
|
468
|
+
} catch {
|
|
469
|
+
// Closing the socket removes this subscriber even when the unsubscribe write was ambiguous.
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
socket?.destroy();
|
|
473
|
+
if (!forAccountMismatch && receive !== undefined) startReconnect();
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function enqueueNotification(message: unknown): void {
|
|
477
|
+
const event = notificationEvent(message, options.connectionId, options.account, subscription);
|
|
478
|
+
if (event === "account_mismatch") {
|
|
479
|
+
pause(true);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
if (event === undefined || !accepting || receive === undefined) return;
|
|
483
|
+
if (queuedEvents >= maxPendingEvents) {
|
|
484
|
+
pause();
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
const receiver = receive;
|
|
488
|
+
queuedEvents += 1;
|
|
489
|
+
void Promise.resolve()
|
|
490
|
+
.then(async () => {
|
|
491
|
+
if (!accepting) return;
|
|
492
|
+
const admission = await receiver(event);
|
|
493
|
+
if (retryableAdmission(admission)) pause();
|
|
494
|
+
})
|
|
495
|
+
.catch(() => pause())
|
|
496
|
+
.finally(() => {
|
|
497
|
+
queuedEvents -= 1;
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function handleMessage(message: unknown): void {
|
|
502
|
+
const response = asRecord(message);
|
|
503
|
+
if (response?.jsonrpc !== "2.0") throw new TypeError("Signal JSON-RPC response is malformed");
|
|
504
|
+
const id = rpcId(response.id);
|
|
505
|
+
if (id !== undefined) {
|
|
506
|
+
const entry = pending.get(id);
|
|
507
|
+
if (entry === undefined) return;
|
|
508
|
+
pending.delete(id);
|
|
509
|
+
clearTimeout(entry.timer);
|
|
510
|
+
const error = asRecord(response.error);
|
|
511
|
+
if (error !== undefined) {
|
|
512
|
+
entry.reject(new SignalRpcError(typeof error.message === "string" ? error.message.slice(0, 256) : "rpc error"));
|
|
513
|
+
} else {
|
|
514
|
+
entry.resolve(response.result);
|
|
515
|
+
}
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
if (response.method === "receive") enqueueNotification(response);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function startReconnect(): void {
|
|
522
|
+
if (reconnecting !== undefined || stopped || controller?.signal.aborted) return;
|
|
523
|
+
reconnecting = (async () => {
|
|
524
|
+
let delayMs = reconnectDelayMs;
|
|
525
|
+
while (!stopped && !controller?.signal.aborted) {
|
|
526
|
+
await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
|
|
527
|
+
if (stopped || controller?.signal.aborted) return;
|
|
528
|
+
try {
|
|
529
|
+
await probeWriter();
|
|
530
|
+
await open();
|
|
531
|
+
return;
|
|
532
|
+
} catch {
|
|
533
|
+
delayMs = Math.min(maxReconnectDelayMs, delayMs * 2);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
})().finally(() => {
|
|
537
|
+
reconnecting = undefined;
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
async function open(): Promise<void> {
|
|
542
|
+
const signal = controller?.signal;
|
|
543
|
+
if (signal === undefined || signal.aborted) throw new SignalTransportError();
|
|
544
|
+
const current = await new Promise<Socket>((resolve, reject) => {
|
|
545
|
+
let candidate: Socket;
|
|
546
|
+
try {
|
|
547
|
+
candidate = connect(options.socketPath);
|
|
548
|
+
} catch {
|
|
549
|
+
reject(new SignalTransportError());
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const cleanup = () => {
|
|
553
|
+
candidate.removeListener("connect", onConnect);
|
|
554
|
+
candidate.removeListener("error", onError);
|
|
555
|
+
};
|
|
556
|
+
const onConnect = () => {
|
|
557
|
+
cleanup();
|
|
558
|
+
resolve(candidate);
|
|
559
|
+
};
|
|
560
|
+
const onError = () => {
|
|
561
|
+
cleanup();
|
|
562
|
+
candidate.destroy();
|
|
563
|
+
reject(new SignalTransportError());
|
|
564
|
+
};
|
|
565
|
+
candidate.once("connect", onConnect);
|
|
566
|
+
candidate.once("error", onError);
|
|
567
|
+
signal.addEventListener(
|
|
568
|
+
"abort",
|
|
569
|
+
() => {
|
|
570
|
+
cleanup();
|
|
571
|
+
candidate.destroy();
|
|
572
|
+
reject(new SignalTransportError());
|
|
573
|
+
},
|
|
574
|
+
{ once: true },
|
|
575
|
+
);
|
|
576
|
+
});
|
|
577
|
+
if (signal.aborted) {
|
|
578
|
+
current.destroy();
|
|
579
|
+
throw new SignalTransportError();
|
|
580
|
+
}
|
|
581
|
+
const reader = new SignalLineReader(maxFrameBytes);
|
|
582
|
+
socket = current;
|
|
583
|
+
setHealth({ bridge: "connected", subscription: "inactive" });
|
|
584
|
+
const disconnect = () => {
|
|
585
|
+
if (socket !== current) return;
|
|
586
|
+
const paused = health.subscription === "paused";
|
|
587
|
+
const wasSubscribed = subscription !== undefined;
|
|
588
|
+
socket = undefined;
|
|
589
|
+
accepting = false;
|
|
590
|
+
subscription = undefined;
|
|
591
|
+
setHealth({ bridge: "unavailable", subscription: paused ? "paused" : "inactive" });
|
|
592
|
+
rejectPending(new SignalTransportError());
|
|
593
|
+
if (wasSubscribed && !paused && !stopped && !signal.aborted && receive !== undefined) startReconnect();
|
|
594
|
+
};
|
|
595
|
+
current.on("data", (chunk: Buffer) => {
|
|
596
|
+
try {
|
|
597
|
+
for (const message of reader.push(Buffer.from(chunk))) handleMessage(message);
|
|
598
|
+
} catch {
|
|
599
|
+
current.destroy();
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
current.on("error", () => {
|
|
603
|
+
current.destroy();
|
|
604
|
+
disconnect();
|
|
605
|
+
});
|
|
606
|
+
current.on("close", disconnect);
|
|
607
|
+
try {
|
|
608
|
+
const subscribed = integer(await request("subscribeReceive", {}));
|
|
609
|
+
if (subscribed === undefined) throw new TypeError("Signal subscription response is malformed");
|
|
610
|
+
subscription = subscribed;
|
|
611
|
+
accepting = true;
|
|
612
|
+
setHealth({ subscription: "active", account: "ready" });
|
|
613
|
+
} catch (error) {
|
|
614
|
+
current.destroy();
|
|
615
|
+
throw error;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
return {
|
|
620
|
+
connectionId: options.connectionId,
|
|
621
|
+
capabilities: { acknowledgement: "none", controls: "command", maxTextCodeUnits: SIGNAL_TEXT_CODE_UNITS },
|
|
622
|
+
health: () => ({ ...health }),
|
|
623
|
+
async start(receiver) {
|
|
624
|
+
if (stopped) throw new Error("Signal adapter is stopped");
|
|
625
|
+
if (controller !== undefined) throw new Error("Signal adapter is already started");
|
|
626
|
+
controller = new AbortController();
|
|
627
|
+
receive = receiver;
|
|
628
|
+
try {
|
|
629
|
+
const acquired = await options.leases.tryAcquireLease({
|
|
630
|
+
namespace: RECEIVER_LEASE_NAMESPACE,
|
|
631
|
+
key: receiverKey(options.connectionId),
|
|
632
|
+
...scope(options.cursorOwnership),
|
|
633
|
+
ownerId,
|
|
634
|
+
ttlMs: leaseTtlMs,
|
|
635
|
+
signal: controller.signal,
|
|
636
|
+
});
|
|
637
|
+
if (acquired === null) throw new Error("Signal receiver is already active");
|
|
638
|
+
lease = acquired;
|
|
639
|
+
await probeWriter();
|
|
640
|
+
await open();
|
|
641
|
+
renewTimer = setInterval(() => void renew(), Math.max(1_000, Math.floor(leaseTtlMs / 2)));
|
|
642
|
+
renewTimer.unref?.();
|
|
643
|
+
} catch (error) {
|
|
644
|
+
controller.abort();
|
|
645
|
+
controller = undefined;
|
|
646
|
+
receive = undefined;
|
|
647
|
+
await release();
|
|
648
|
+
throw error instanceof Error && error.message === "Signal receiver is already active"
|
|
649
|
+
? error
|
|
650
|
+
: new Error("Signal adapter start failed");
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
async send(reply): Promise<ChannelSendResult> {
|
|
654
|
+
if (reply.connectionId !== options.connectionId || serviceId(reply.externalConversationId) === undefined) {
|
|
655
|
+
return { delivered: false, reason: "invalid_destination" };
|
|
656
|
+
}
|
|
657
|
+
if (health.account === "mismatch") return { delivered: false, reason: "signal_account_mismatch" };
|
|
658
|
+
if (health.account === "identity_changed") return { delivered: false, reason: "signal_identity_changed" };
|
|
659
|
+
const chunks = replyChunks(reply);
|
|
660
|
+
if (chunks === undefined) return { delivered: false, reason: "invalid_controls" };
|
|
661
|
+
if (chunks.length === 0) return { delivered: false, reason: "empty_reply" };
|
|
662
|
+
if (socket === undefined) return { delivered: false, reason: "signal_unavailable" };
|
|
663
|
+
let messageId: string | undefined;
|
|
664
|
+
let sent = false;
|
|
665
|
+
try {
|
|
666
|
+
for (const message of chunks) {
|
|
667
|
+
const result = asRecord(await request("send", { recipient: [reply.externalConversationId], message }));
|
|
668
|
+
const timestamp = integer(result?.timestamp);
|
|
669
|
+
if (timestamp !== undefined) messageId = String(timestamp);
|
|
670
|
+
sent = true;
|
|
671
|
+
}
|
|
672
|
+
return { delivered: true, ...(messageId === undefined ? {} : { messageId }) };
|
|
673
|
+
} catch (error) {
|
|
674
|
+
if (error instanceof SignalRpcError && !sent) {
|
|
675
|
+
const reason = rpcFailureReason(error);
|
|
676
|
+
if (reason === "signal_identity_changed") setHealth({ account: "identity_changed" });
|
|
677
|
+
return { delivered: false, reason };
|
|
678
|
+
}
|
|
679
|
+
throw new SignalDeliveryUnknownError();
|
|
680
|
+
}
|
|
681
|
+
},
|
|
682
|
+
async stop() {
|
|
683
|
+
if (stopped) return;
|
|
684
|
+
stopped = true;
|
|
685
|
+
clearInterval(renewTimer);
|
|
686
|
+
renewTimer = undefined;
|
|
687
|
+
accepting = false;
|
|
688
|
+
const currentSubscription = subscription;
|
|
689
|
+
subscription = undefined;
|
|
690
|
+
if (currentSubscription !== undefined && socket !== undefined) {
|
|
691
|
+
try {
|
|
692
|
+
await request("unsubscribeReceive", { subscription: currentSubscription });
|
|
693
|
+
} catch {
|
|
694
|
+
// Socket closure makes an unconfirmed unsubscribe non-delivery explicit, not retried.
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
controller?.abort(new Error("Signal adapter stopped"));
|
|
698
|
+
socket?.destroy();
|
|
699
|
+
socket = undefined;
|
|
700
|
+
rejectPending(new SignalTransportError());
|
|
701
|
+
await reconnecting;
|
|
702
|
+
await release();
|
|
703
|
+
setHealth({ bridge: "unavailable", subscription: "inactive" });
|
|
704
|
+
},
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
export interface SignalConnectOptions {
|
|
709
|
+
readonly limits?: import("./types.js").ChannelLimits;
|
|
710
|
+
/** Signal account credential reference (env: or keyring:). Literal string throws ChannelTokenLiteralError. */
|
|
711
|
+
readonly account: string;
|
|
712
|
+
readonly socketPath: string;
|
|
713
|
+
readonly connectionId?: string;
|
|
714
|
+
readonly signalCliVersion?: typeof SIGNAL_CLI_VERSION;
|
|
715
|
+
readonly policy?: SignalPolicyGate;
|
|
716
|
+
readonly checkpoints?: CheckpointStore;
|
|
717
|
+
readonly leases?: LeaseStore;
|
|
718
|
+
readonly cursorOwnership?: OwnershipScope;
|
|
719
|
+
readonly connect?: (socketPath: string) => Socket;
|
|
720
|
+
readonly authorize?: (
|
|
721
|
+
input: ChannelAuthorizeInput,
|
|
722
|
+
) => ChannelAuthorization | false | undefined | Promise<ChannelAuthorization | false | undefined>;
|
|
723
|
+
readonly multiAccount?: boolean;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
export async function connectSignal(agent: Agent, options: SignalConnectOptions): Promise<ChannelConnectionHandle> {
|
|
727
|
+
const resolvedAccount = await resolveChannelSecretRef(agent, options.account);
|
|
728
|
+
const secretRedactor = createChannelRedactor(resolvedAccount, agent.config?.redactor);
|
|
729
|
+
const connectionId = options.connectionId ?? "signal-default";
|
|
730
|
+
const checkpoints = options.checkpoints ?? createMemoryCheckpointStore();
|
|
731
|
+
const leases = options.leases ?? createMemoryLeaseStore();
|
|
732
|
+
const cursorOwnership = options.cursorOwnership ?? { tenantId: "default", accountId: "default", userId: "service" };
|
|
733
|
+
const policy = options.policy ?? { acceptableUse: "operator_approved", gplDistribution: "operator_approved", termsVersion: "current" };
|
|
734
|
+
|
|
735
|
+
const adapter = createSignalAdapter({
|
|
736
|
+
connectionId,
|
|
737
|
+
socketPath: options.socketPath,
|
|
738
|
+
account: resolvedAccount,
|
|
739
|
+
signalCliVersion: options.signalCliVersion ?? SIGNAL_CLI_VERSION,
|
|
740
|
+
policy,
|
|
741
|
+
checkpoints,
|
|
742
|
+
leases,
|
|
743
|
+
cursorOwnership,
|
|
744
|
+
multiAccount: options.multiAccount,
|
|
745
|
+
connect: options.connect,
|
|
746
|
+
});
|
|
747
|
+
|
|
748
|
+
const runtime = createChannelRuntime(agent, {
|
|
749
|
+
deliver: (reply) => adapter.send(reply),
|
|
750
|
+
checkpoints,
|
|
751
|
+
leases,
|
|
752
|
+
redactor: secretRedactor,
|
|
753
|
+
authorize: options.authorize,
|
|
754
|
+
limits: options.limits,
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
const handle: ChannelConnectionHandle = {
|
|
758
|
+
async handle(update: unknown): Promise<unknown> {
|
|
759
|
+
if (typeof update === "object" && update !== null && "connectionId" in update && "externalActorId" in update && "eventId" in update) {
|
|
760
|
+
return await runtime.admit(update as ChannelInboundEvent);
|
|
761
|
+
}
|
|
762
|
+
const event =
|
|
763
|
+
notificationEvent(update, connectionId, resolvedAccount, undefined) ??
|
|
764
|
+
notificationEvent(update, connectionId, resolvedAccount, (update as { params?: { subscription?: number } })?.params?.subscription);
|
|
765
|
+
if (event && event !== "account_mismatch") {
|
|
766
|
+
return await runtime.admit(event);
|
|
767
|
+
}
|
|
768
|
+
return undefined;
|
|
769
|
+
},
|
|
770
|
+
async start() {
|
|
771
|
+
await adapter.start((event) => runtime.admit(event));
|
|
772
|
+
},
|
|
773
|
+
async close() {
|
|
774
|
+
const stopping = runtime.stop();
|
|
775
|
+
try {
|
|
776
|
+
await adapter.stop();
|
|
777
|
+
} finally {
|
|
778
|
+
await stopping;
|
|
779
|
+
}
|
|
780
|
+
},
|
|
781
|
+
async stop() {
|
|
782
|
+
await handle.close();
|
|
783
|
+
},
|
|
784
|
+
async drain(opts) {
|
|
785
|
+
return await runtime.drain(opts);
|
|
786
|
+
},
|
|
787
|
+
};
|
|
788
|
+
bindChannelHostUi(handle, runtime, connectionId);
|
|
789
|
+
return handle;
|
|
790
|
+
}
|