@indigoai-us/hq-cli 5.345.214 → 5.345.215

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.
Files changed (200) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +180 -13
  4. package/dist/command-catalog.generated.js +221 -13
  5. package/dist/commands/agents.d.ts +51 -1
  6. package/dist/commands/agents.js +154 -2
  7. package/dist/commands/bot-jobs.d.ts +2 -15
  8. package/dist/commands/bot-jobs.js +2 -94
  9. package/dist/commands/bot-runtime.d.ts +46 -5
  10. package/dist/commands/bot-runtime.js +228 -18
  11. package/dist/commands/bot.d.ts +16 -9
  12. package/dist/commands/bot.js +231 -55
  13. package/dist/commands/capacity.d.ts +4 -1
  14. package/dist/commands/capacity.js +46 -10
  15. package/dist/commands/cloud.d.ts +66 -13
  16. package/dist/commands/cloud.js +121 -40
  17. package/dist/commands/company-restore.d.ts +23 -0
  18. package/dist/commands/company-restore.js +128 -0
  19. package/dist/commands/company.js +2 -0
  20. package/dist/commands/core-delegate-w1b.js +15 -1
  21. package/dist/commands/core-policy.js +67 -8
  22. package/dist/commands/daemon.js +5 -0
  23. package/dist/commands/files-browse.d.ts +11 -4
  24. package/dist/commands/files-browse.js +21 -4
  25. package/dist/commands/files.d.ts +1 -1
  26. package/dist/commands/files.js +25 -11
  27. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  28. package/dist/commands/integrations-auth-rules.js +79 -0
  29. package/dist/commands/integrations-connect.d.ts +10 -3
  30. package/dist/commands/integrations-connect.js +87 -13
  31. package/dist/commands/integrations-import.js +124 -12
  32. package/dist/commands/lanes.js +28 -11
  33. package/dist/commands/mesh.d.ts +2 -0
  34. package/dist/commands/mesh.js +60 -35
  35. package/dist/commands/sources.js +6 -0
  36. package/dist/commands/storage-offload.d.ts +12 -0
  37. package/dist/commands/storage-offload.js +41 -3
  38. package/dist/commands/sync-held.js +5 -2
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/lazy-commands.js +3 -5
  42. package/dist/lib/bot/config.d.ts +1 -0
  43. package/dist/lib/bot/config.js +10 -0
  44. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  45. package/dist/lib/bot/eventbridge-cron.js +104 -0
  46. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  47. package/dist/lib/bot/fleet-cron.js +35 -3
  48. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  49. package/dist/lib/bot/fleet-daemon.js +99 -1
  50. package/dist/lib/bot/fleet-local.d.ts +33 -1
  51. package/dist/lib/bot/fleet-local.js +215 -31
  52. package/dist/lib/bot/fleet-python.d.ts +3 -0
  53. package/dist/lib/bot/fleet-python.js +34 -4
  54. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  55. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  56. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  57. package/dist/lib/bot/legacy-provider-login.js +19 -2
  58. package/dist/lib/bot/probe.js +7 -1
  59. package/dist/lib/bot/prompt.js +1 -1
  60. package/dist/lib/bot/readiness.d.ts +8 -0
  61. package/dist/lib/bot/readiness.js +17 -3
  62. package/dist/lib/bot/run.js +20 -1
  63. package/dist/lib/bot/runtime/codex.js +1 -1
  64. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  65. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  66. package/dist/lib/bot/runtime/index.js +19 -9
  67. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  68. package/dist/lib/bot/runtime/types.d.ts +15 -0
  69. package/dist/lib/bot/runtime/types.js +9 -0
  70. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  71. package/dist/lib/bot/runtime-auth.js +94 -3
  72. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  73. package/dist/lib/bot/runtime-failure.js +43 -1
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/accounts.d.ts +8 -0
  76. package/dist/lib/capacity/accounts.js +19 -0
  77. package/dist/lib/capacity/available.d.ts +154 -0
  78. package/dist/lib/capacity/available.js +905 -0
  79. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  80. package/dist/lib/capacity/codex-availability.js +26 -1
  81. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  82. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  83. package/dist/lib/capacity/collectors/codex.js +10 -7
  84. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  85. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  86. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  87. package/dist/lib/capacity/collectors/grok.js +56 -5
  88. package/dist/lib/capacity/ledger.d.ts +37 -1
  89. package/dist/lib/capacity/ledger.js +207 -30
  90. package/dist/lib/capacity/project.d.ts +26 -0
  91. package/dist/lib/capacity/project.js +137 -8
  92. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  93. package/dist/lib/capacity/refusal-rows.js +61 -0
  94. package/dist/lib/capacity/refusal.d.ts +53 -2
  95. package/dist/lib/capacity/refusal.js +284 -65
  96. package/dist/lib/capacity/route.js +46 -11
  97. package/dist/lib/capacity/widget.d.ts +12 -1
  98. package/dist/lib/capacity/widget.js +91 -3
  99. package/dist/lib/daemon/catalog.js +11 -1
  100. package/dist/lib/daemon/resolver.d.ts +2 -0
  101. package/dist/lib/daemon/resolver.js +3 -0
  102. package/dist/lib/daemon/run.d.ts +9 -0
  103. package/dist/lib/daemon/run.js +54 -1
  104. package/dist/lib/daemon/server.d.ts +2 -0
  105. package/dist/lib/daemon/server.js +10 -1
  106. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  107. package/dist/lib/daemon/tcc-eperm.js +310 -0
  108. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  109. package/dist/lib/db/sqlite-binding.js +1 -1
  110. package/dist/lib/delivery/admission.d.ts +86 -0
  111. package/dist/lib/delivery/admission.js +148 -0
  112. package/dist/lib/delivery/artifacts.d.ts +105 -0
  113. package/dist/lib/delivery/artifacts.js +567 -0
  114. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  115. package/dist/lib/delivery/attempt-id.js +16 -0
  116. package/dist/lib/delivery/backup.d.ts +78 -0
  117. package/dist/lib/delivery/backup.js +343 -0
  118. package/dist/lib/delivery/cache.d.ts +29 -0
  119. package/dist/lib/delivery/cache.js +33 -0
  120. package/dist/lib/delivery/contracts.d.ts +142 -0
  121. package/dist/lib/delivery/contracts.js +289 -0
  122. package/dist/lib/delivery/credentials.d.ts +54 -0
  123. package/dist/lib/delivery/credentials.js +119 -0
  124. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  125. package/dist/lib/delivery/disposable-target.js +111 -0
  126. package/dist/lib/delivery/effects.d.ts +136 -0
  127. package/dist/lib/delivery/effects.js +541 -0
  128. package/dist/lib/delivery/enrollment.d.ts +146 -0
  129. package/dist/lib/delivery/enrollment.js +460 -0
  130. package/dist/lib/delivery/escalations.d.ts +51 -0
  131. package/dist/lib/delivery/escalations.js +60 -0
  132. package/dist/lib/delivery/identity.d.ts +25 -0
  133. package/dist/lib/delivery/identity.js +82 -0
  134. package/dist/lib/delivery/inbox.d.ts +116 -0
  135. package/dist/lib/delivery/inbox.js +260 -0
  136. package/dist/lib/delivery/lease.d.ts +80 -0
  137. package/dist/lib/delivery/lease.js +134 -0
  138. package/dist/lib/delivery/migrations.d.ts +255 -0
  139. package/dist/lib/delivery/migrations.js +823 -0
  140. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  141. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  142. package/dist/lib/delivery/mqtt.d.ts +63 -0
  143. package/dist/lib/delivery/mqtt.js +119 -0
  144. package/dist/lib/delivery/outbox.d.ts +95 -0
  145. package/dist/lib/delivery/outbox.js +187 -0
  146. package/dist/lib/delivery/provenance.d.ts +129 -0
  147. package/dist/lib/delivery/provenance.js +93 -0
  148. package/dist/lib/delivery/reconciler.d.ts +215 -0
  149. package/dist/lib/delivery/reconciler.js +703 -0
  150. package/dist/lib/delivery/restore.d.ts +35 -0
  151. package/dist/lib/delivery/restore.js +134 -0
  152. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  153. package/dist/lib/delivery/rpc/client.js +159 -0
  154. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  155. package/dist/lib/delivery/rpc/port.js +16 -0
  156. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  157. package/dist/lib/delivery/rpc/server.js +205 -0
  158. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  159. package/dist/lib/delivery/rpc/wire.js +143 -0
  160. package/dist/lib/delivery/store.d.ts +163 -0
  161. package/dist/lib/delivery/store.js +944 -0
  162. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  163. package/dist/lib/delivery/windows-service-install.js +892 -0
  164. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  165. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  166. package/dist/lib/delivery/workers/macos.d.ts +191 -0
  167. package/dist/lib/delivery/workers/macos.js +943 -0
  168. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  169. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  170. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  171. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  172. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  173. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  174. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  175. package/dist/lib/delivery/workers/windows-service.js +584 -0
  176. package/dist/lib/delivery/workers/windows.d.ts +251 -0
  177. package/dist/lib/delivery/workers/windows.js +594 -0
  178. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  179. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  180. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  181. package/dist/lib/hot-channels/signals-pass.js +71 -2
  182. package/dist/lib/hot-channels/signals-redo.js +10 -2
  183. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  184. package/dist/lib/install/provider-wrappers.js +68 -3
  185. package/dist/lib/lanes/watcher.js +35 -0
  186. package/dist/lib/signals/steps/extract.js +40 -4
  187. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  188. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  189. package/dist/utils/catalog-runtime-paths.js +53 -0
  190. package/dist/utils/cognito-callback-port.d.ts +14 -0
  191. package/dist/utils/cognito-callback-port.js +24 -0
  192. package/dist/utils/cognito-session.js +3 -3
  193. package/dist/utils/deleted-company-notice.d.ts +59 -0
  194. package/dist/utils/deleted-company-notice.js +156 -0
  195. package/dist/utils/files-browse-acl.js +1 -1
  196. package/dist/utils/login-browser.d.ts +1 -1
  197. package/dist/utils/login-browser.js +7 -5
  198. package/dist/utils/resident-package-preload.js +30 -15
  199. package/dist/utils/vault-api.js +7 -0
  200. package/package.json +7 -7
@@ -0,0 +1,35 @@
1
+ import { type BackupManifest, type BackupSigning } from "./backup.js";
2
+ export declare const RESTORE_RECORD_FILE = "restore.activated.json";
3
+ export interface RestoreReport {
4
+ targetDir: string;
5
+ manifest: BackupManifest;
6
+ }
7
+ /** Restore `backupPath` into the clean directory `targetDir`, pending activation. */
8
+ export declare function restoreBackup(opts: {
9
+ backupPath: string;
10
+ targetDir: string;
11
+ signing: BackupSigning;
12
+ clock?: () => number;
13
+ }): RestoreReport;
14
+ export type RetireTarget = {
15
+ dir: string;
16
+ } | {
17
+ unreachable: {
18
+ reason: string;
19
+ };
20
+ };
21
+ export interface ActivationReport {
22
+ /** The epoch the restored controller's next open takes. */
23
+ authorityEpoch: number;
24
+ /** The retired old store, or null when it was declared unreachable. */
25
+ retiredDir: string | null;
26
+ backupId: string;
27
+ }
28
+ /** Move authority to a restored store. See the header for the steps. */
29
+ export declare function activateRestore(opts: {
30
+ targetDir: string;
31
+ retire: RetireTarget;
32
+ clock?: () => number;
33
+ gateWaitMs?: number;
34
+ }): ActivationReport;
35
+ //# sourceMappingURL=restore.d.ts.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Restore a verified backup into a clean controller directory and move
3
+ * authority to it (US-010). See docs/delivery-recovery.md.
4
+ *
5
+ * restoreBackup verifies the backup (manifest signature, state digest and
6
+ * load, every blob digest and provenance signature), writes it into a
7
+ * sibling temp directory with restore.pending.json first, re-checks every
8
+ * written blob, and renames it to the target. The target must not exist or
9
+ * be empty. A pending store refuses to open (RESTORE_PENDING).
10
+ *
11
+ * activateRestore is the explicit authority transfer:
12
+ * 1. Retire the old store when it is reachable (retireStore): under its
13
+ * store lock it records the highest epoch it reached and removes its
14
+ * owner lock, so the old controller's next commit is FENCED and every
15
+ * later open of it is refused with STORE_RETIRED, including a
16
+ * stale-pid takeover after a restart. When it is not reachable, an
17
+ * operator reason is required and recorded instead.
18
+ * 2. Raise the restored state's epoch to at least that epoch, so the
19
+ * restored controller's first open takes a strictly higher authority
20
+ * epoch than any the old controller held.
21
+ * 3. Record the activation and remove restore.pending.json.
22
+ * Attempts open in the backup are from earlier epochs; the restored
23
+ * controller abandons them on open (reconciler recovery rule), so their
24
+ * late reports are refused with ATTEMPT_ABANDONED and each job allows one
25
+ * new attempt. Every step is safe to re-run after a crash.
26
+ */
27
+ import { randomBytes } from "node:crypto";
28
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, rmdirSync, unlinkSync } from "node:fs";
29
+ import { dirname, join } from "node:path";
30
+ import { blobRelativePath } from "./artifacts.js";
31
+ import { backupInvalid, fsyncDirectory, resolveKey, verifyBackup, writeFileDurable, } from "./backup.js";
32
+ import { DeliveryStoreError, parseStoreText, serializeState } from "./migrations.js";
33
+ import { sha256Hex, signatureMatches } from "./provenance.js";
34
+ import { RESTORE_PENDING_FILE, retireStore, STATE_FILE } from "./store.js";
35
+ export const RESTORE_RECORD_FILE = "restore.activated.json";
36
+ /** Restore `backupPath` into the clean directory `targetDir`, pending activation. */
37
+ export function restoreBackup(opts) {
38
+ const manifest = verifyBackup(opts.backupPath, opts.signing);
39
+ if (existsSync(opts.targetDir) && readdirSync(opts.targetDir).length > 0) {
40
+ throw backupInvalid(`restore target ${opts.targetDir} is not empty`, "a missing or empty directory", "Restore into a clean directory. Nothing was written.");
41
+ }
42
+ const stateText = readFileSync(join(opts.backupPath, STATE_FILE), "utf8");
43
+ const state = parseStoreText(stateText, join(opts.backupPath, STATE_FILE)).state;
44
+ const key = resolveKey(opts.signing);
45
+ for (const a of state.artifacts) {
46
+ if (!signatureMatches(a, key)) {
47
+ throw backupInvalid(`artifact ${a.record.artifactId}: provenance signature does not verify`, "provenance signed with the configured key");
48
+ }
49
+ }
50
+ const parent = dirname(opts.targetDir);
51
+ mkdirSync(parent, { recursive: true });
52
+ const temp = join(parent, `.restoring-${randomBytes(6).toString("hex")}`);
53
+ try {
54
+ mkdirSync(temp, { mode: 0o700 });
55
+ const pending = {
56
+ backupId: manifest.backupId,
57
+ restoredAt: new Date((opts.clock ?? Date.now)()).toISOString(),
58
+ backupEpoch: manifest.epoch,
59
+ };
60
+ writeFileDurable(join(temp, RESTORE_PENDING_FILE), Buffer.from(`${JSON.stringify(pending)}\n`), 0o600);
61
+ fsyncDirectory(temp);
62
+ for (const e of manifest.artifacts) {
63
+ const bytes = readFileSync(join(opts.backupPath, e.file));
64
+ const rel = blobRelativePath(e.tenantId, e.partition, e.digest);
65
+ const dest = join(temp, rel);
66
+ if (existsSync(dest))
67
+ continue;
68
+ mkdirSync(dirname(dest), { recursive: true, mode: 0o700 });
69
+ writeFileDurable(dest, bytes);
70
+ if (sha256Hex(readFileSync(dest)) !== e.digest)
71
+ throw backupInvalid(`restored blob ${rel} does not match ${e.digest}`, "an exact copy");
72
+ fsyncDirectory(dirname(dest));
73
+ }
74
+ writeFileDurable(join(temp, STATE_FILE), Buffer.from(stateText), 0o600);
75
+ fsyncDirectory(temp);
76
+ if (existsSync(opts.targetDir))
77
+ rmdirSync(opts.targetDir); // empty; checked above
78
+ renameSync(temp, opts.targetDir);
79
+ fsyncDirectory(parent);
80
+ }
81
+ catch (err) {
82
+ rmSync(temp, { recursive: true, force: true });
83
+ throw err;
84
+ }
85
+ return { targetDir: opts.targetDir, manifest };
86
+ }
87
+ /** Move authority to a restored store. See the header for the steps. */
88
+ export function activateRestore(opts) {
89
+ const now = new Date((opts.clock ?? Date.now)()).toISOString();
90
+ const pendingPath = join(opts.targetDir, RESTORE_PENDING_FILE);
91
+ if (!existsSync(pendingPath)) {
92
+ throw new DeliveryStoreError("INVALID_RECORD", {
93
+ found: `no ${RESTORE_PENDING_FILE} in ${opts.targetDir}`,
94
+ expected: "a directory written by restoreBackup and not yet activated",
95
+ action: "Restore a backup into the directory first. Nothing was changed.",
96
+ });
97
+ }
98
+ const pending = JSON.parse(readFileSync(pendingPath, "utf8"));
99
+ let observedEpoch = 0;
100
+ let retiredDir = null;
101
+ let note;
102
+ if ("dir" in opts.retire) {
103
+ const rec = retireStore(opts.retire.dir, { successorDir: opts.targetDir, backupId: pending.backupId, now, waitMs: opts.gateWaitMs });
104
+ observedEpoch = rec.observedEpoch;
105
+ retiredDir = opts.retire.dir;
106
+ note = `retired ${opts.retire.dir} at epoch ${rec.observedEpoch}`;
107
+ }
108
+ else {
109
+ const reason = opts.retire.unreachable?.reason;
110
+ if (typeof reason !== "string" || reason.trim() === "") {
111
+ throw new DeliveryStoreError("INVALID_RECORD", {
112
+ found: "an unreachable old store with no operator reason",
113
+ expected: "a reason saying why the old controller cannot publish (host destroyed, disk lost)",
114
+ action: "Retire the old store directory, or give the reason. Nothing was changed.",
115
+ });
116
+ }
117
+ note = `old store unreachable: ${reason}`;
118
+ }
119
+ const statePath = join(opts.targetDir, STATE_FILE);
120
+ const state = parseStoreText(readFileSync(statePath, "utf8"), statePath).state;
121
+ state.epoch = Math.max(state.epoch, observedEpoch, pending.backupEpoch);
122
+ const temp = `${statePath}.tmp-restore-${randomBytes(4).toString("hex")}`;
123
+ writeFileDurable(temp, Buffer.from(serializeState(state)), 0o600);
124
+ renameSync(temp, statePath);
125
+ const authorityEpoch = state.epoch + 1;
126
+ const recordPath = join(opts.targetDir, RESTORE_RECORD_FILE);
127
+ if (existsSync(recordPath))
128
+ unlinkSync(recordPath);
129
+ writeFileDurable(recordPath, Buffer.from(`${JSON.stringify({ backupId: pending.backupId, activatedAt: now, authorityEpoch, retiredDir, note })}\n`), 0o600);
130
+ unlinkSync(pendingPath);
131
+ fsyncDirectory(opts.targetDir);
132
+ return { authorityEpoch, retiredDir, backupId: pending.backupId };
133
+ }
134
+ //# sourceMappingURL=restore.js.map
@@ -0,0 +1,22 @@
1
+ import type { WorkerIdentity } from "../identity.js";
2
+ import type { WorkerAccessPort } from "./port.js";
3
+ import { type RpcMethod } from "./wire.js";
4
+ export interface WorkerRpcClientOptions {
5
+ port: number;
6
+ /** Default "127.0.0.1". */
7
+ host?: string;
8
+ /** Required to dial anything but 127.0.0.1, ::1 or localhost. */
9
+ allowNonLoopback?: boolean;
10
+ /** Deadline of one call, connect to answer. Default DEFAULT_RPC_TIMEOUT_MS. */
11
+ timeoutMs?: number;
12
+ /** Retries after RPC_TIMEOUT, RPC_CLOSED or RPC_UNREACHABLE. Default 2. */
13
+ retries?: number;
14
+ /** The attemptId for a claim or dispatch that does not pass one. Default attempt-<uuid>. */
15
+ attemptIds?: () => string;
16
+ }
17
+ export type WorkerRpcClient = WorkerAccessPort & {
18
+ /** One allowlisted call with retries; resolves with the raw wire value. */
19
+ call(method: RpcMethod, identity: WorkerIdentity, args: unknown[]): Promise<unknown>;
20
+ };
21
+ export declare function workerRpcClient(opts: WorkerRpcClientOptions): WorkerRpcClient;
22
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The worker side of the worker RPC (US-011 slice 4 B): a WorkerAccessPort
3
+ * over loopback TCP. See wire.ts for the format.
4
+ *
5
+ * - Dials 127.0.0.1 by default; any host but 127.0.0.1, ::1 or localhost is
6
+ * refused with RPC_NOT_LOOPBACK unless allowNonLoopback is true.
7
+ * - Each call has its own deadline (timeoutMs, default 10 s). No answer by
8
+ * then is RPC_TIMEOUT and the connection is destroyed, so a silent drop
9
+ * cannot hang the worker. A refused connection is RPC_UNREACHABLE; a
10
+ * connection that closes before the answer is RPC_CLOSED.
11
+ * - Those three are retried `retries` times (default 2) with the same request.
12
+ * That is safe for every allowlisted method: a claim or dispatch carries an
13
+ * attemptId fixed for the logical call, so a retry after a lost answer
14
+ * replays the stored claim instead of opening a second attempt; a repeated
15
+ * report with the same outcome and a repeated return are replays; a repeated
16
+ * renewal extends the lease again; reads are reads.
17
+ * - A refusal is rebuilt as the DeliveryStoreError the controller raised.
18
+ * - A request over MAX_REQUEST_BYTES is refused before it is sent.
19
+ */
20
+ import { randomUUID } from "node:crypto";
21
+ import { connect } from "node:net";
22
+ import { isSafeAttemptId } from "../attempt-id.js";
23
+ import { DeliveryStoreError } from "../migrations.js";
24
+ import { DEFAULT_RPC_TIMEOUT_MS, MAX_ANSWER_BYTES, MAX_REQUEST_BYTES, RPC_WIRE_VERSION, encodeLine, errorFromBody, isLoopbackDialHost, notLoopback, rpcError, } from "./wire.js";
25
+ const RETRYABLE = new Set(["RPC_TIMEOUT", "RPC_CLOSED", "RPC_UNREACHABLE", "RPC_BUSY"]);
26
+ /** A claim answer is used as a path by the worker: its attempt id must be a safe name (review I5). */
27
+ function checkedClaim(value, method) {
28
+ if (!isSafeAttemptId(value?.attempt?.attemptId)) {
29
+ throw rpcError("RPC_BAD_ANSWER", `a ${method} answer whose attempt id is not a safe name`, "an attempt id of letters, digits, dot, underscore or dash", "Do not use the answer. Check what is listening on the controller's port.");
30
+ }
31
+ return value;
32
+ }
33
+ /** Rebuild Dispatch's credentials from the wire's refs and values, with the same redacting JSON as in process. */
34
+ function dispatchFromWire(raw) {
35
+ const d = raw;
36
+ const refs = Object.freeze([...d.credentials.refs]);
37
+ const values = new Map(Object.entries(d.credentials.values));
38
+ const describe = () => `[credentials ${refs.join(", ")}]`;
39
+ const credentials = Object.freeze({
40
+ refs,
41
+ has: (ref) => values.has(ref),
42
+ get: (ref) => {
43
+ const v = values.get(ref);
44
+ if (v === undefined) {
45
+ throw new DeliveryStoreError("PRIVILEGE_REJECTED", { found: `credential ${ref} was not injected`, expected: `one of ${refs.join(", ") || "no credentials"}`, action: "Request it in dispatch. Nothing was read." });
46
+ }
47
+ return v;
48
+ },
49
+ toJSON: () => ({ refs: [...refs], values: "[credentials redacted]" }),
50
+ toString: describe,
51
+ });
52
+ return { claim: d.claim, jobClass: d.jobClass, credentials };
53
+ }
54
+ export function workerRpcClient(opts) {
55
+ const host = opts.host ?? "127.0.0.1";
56
+ if (!isLoopbackDialHost(host) && opts.allowNonLoopback !== true)
57
+ throw notLoopback(host, "dial");
58
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_RPC_TIMEOUT_MS;
59
+ const retries = opts.retries ?? 2;
60
+ if (!Number.isSafeInteger(retries) || retries < 0)
61
+ throw rpcError("RPC_BAD_REQUEST", `retries ${String(opts.retries)}`, "a non-negative integer", "Nothing was sent.");
62
+ const attemptIds = opts.attemptIds ?? (() => `attempt-${randomUUID()}`);
63
+ function once(line, method) {
64
+ return new Promise((resolve, reject) => {
65
+ let settled = false;
66
+ let connected = false;
67
+ const chunks = [];
68
+ let size = 0;
69
+ const sock = connect({ port: opts.port, host });
70
+ const timer = setTimeout(() => finish(rpcError("RPC_TIMEOUT", `no answer to ${method} within ${timeoutMs} ms`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments.")), timeoutMs);
71
+ function finish(err, value) {
72
+ if (settled)
73
+ return;
74
+ settled = true;
75
+ clearTimeout(timer);
76
+ sock.destroy();
77
+ if (err)
78
+ reject(err);
79
+ else
80
+ resolve(value);
81
+ }
82
+ sock.setNoDelay(true);
83
+ sock.on("error", (err) => {
84
+ if (!connected && (err.code === "ECONNREFUSED" || err.code === "EHOSTUNREACH" || err.code === "ENETUNREACH" || err.code === "EADDRNOTAVAIL")) {
85
+ finish(rpcError("RPC_UNREACHABLE", `no controller listening at ${host}:${opts.port} (${err.code})`, "a running controller RPC server", "Start the controller, or check the host and port. Nothing was sent."));
86
+ }
87
+ else {
88
+ finish(rpcError("RPC_CLOSED", `${method}: the connection failed (${err.code ?? err.message})`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments."));
89
+ }
90
+ });
91
+ sock.on("close", () => finish(rpcError("RPC_CLOSED", `${method}: the connection closed before an answer`, "an answer from the controller", "The call may have been applied; it is safe to retry with the same arguments.")));
92
+ sock.once("connect", () => {
93
+ connected = true;
94
+ sock.write(line);
95
+ });
96
+ sock.on("data", (b) => {
97
+ if (settled)
98
+ return;
99
+ const nl = b.indexOf(10);
100
+ if (size + (nl < 0 ? b.length : nl) > MAX_ANSWER_BYTES) {
101
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} over ${MAX_ANSWER_BYTES} bytes`, `at most ${MAX_ANSWER_BYTES} bytes`, "Check the controller. The call may have been applied."));
102
+ return;
103
+ }
104
+ if (nl < 0) {
105
+ chunks.push(b);
106
+ size += b.length;
107
+ return;
108
+ }
109
+ chunks.push(b.subarray(0, nl));
110
+ let res;
111
+ try {
112
+ res = JSON.parse(Buffer.concat(chunks).toString("utf8"));
113
+ }
114
+ catch {
115
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} that is not JSON`, "one JSON answer line", "Check that the controller runs a matching HQ version."));
116
+ return;
117
+ }
118
+ if (res?.v !== RPC_WIRE_VERSION)
119
+ finish(rpcError("RPC_BAD_ANSWER", `an answer to ${method} with wire version ${JSON.stringify(res?.v)}`, `version ${RPC_WIRE_VERSION}`, "Use a worker and controller of the same HQ version."));
120
+ else if (res.ok === true)
121
+ finish(null, res.value);
122
+ else
123
+ finish(errorFromBody(res.error, method));
124
+ });
125
+ });
126
+ }
127
+ async function call(method, identity, args) {
128
+ const line = encodeLine({ v: RPC_WIRE_VERSION, id: randomUUID(), method, identity, args });
129
+ if (Buffer.byteLength(line, "utf8") > MAX_REQUEST_BYTES) {
130
+ throw rpcError("RPC_TOO_LARGE", `a ${method} request over ${MAX_REQUEST_BYTES} bytes`, `at most ${MAX_REQUEST_BYTES} bytes per request`, "Send smaller arguments. Nothing was sent.");
131
+ }
132
+ for (let attempt = 0;; attempt += 1) {
133
+ try {
134
+ return await once(line, method);
135
+ }
136
+ catch (err) {
137
+ if (attempt < retries && err instanceof DeliveryStoreError && RETRYABLE.has(err.code))
138
+ continue;
139
+ throw err;
140
+ }
141
+ }
142
+ }
143
+ return {
144
+ call,
145
+ readRun: async (identity, runId) => (await call("readRun", identity, [runId])),
146
+ readyWork: async (identity, page) => (await call("readyWork", identity, [page])),
147
+ verifyNotification: async (identity, event) => (await call("verifyNotification", identity, [event])),
148
+ claim: async (identity, jobId, claimOpts) => checkedClaim((await call("claim", identity, [jobId, { attemptId: claimOpts?.attemptId ?? attemptIds() }])), "claim"),
149
+ dispatch: async (identity, jobId, request) => {
150
+ const d = dispatchFromWire(await call("dispatch", identity, [jobId, { credentials: request?.credentials, attemptId: request?.attemptId ?? attemptIds() }]));
151
+ checkedClaim(d.claim, "dispatch");
152
+ return d;
153
+ },
154
+ recordOutcome: async (identity, attemptId, outcome) => (await call("recordOutcome", identity, [attemptId, outcome])),
155
+ returnAttempt: async (identity, attemptId) => (await call("returnAttempt", identity, [attemptId])),
156
+ renewLease: async (identity, attemptId) => (await call("renewLease", identity, [attemptId])),
157
+ };
158
+ }
159
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The worker's view of the controller (US-011 slice 4 B): the allowlisted
3
+ * worker methods of DeliveryAccess, awaited. A worker runs against either the
4
+ * in-process access layer (inProcessPort) or the loopback RPC client
5
+ * (workerRpcClient); both answer and refuse identically.
6
+ *
7
+ * Methods may answer synchronously or with a promise, so a DeliveryAccess is
8
+ * itself a port; callers always await.
9
+ */
10
+ import type { LedgerEvent } from "../outbox.js";
11
+ import type { DeliveryAccess, Dispatch, ReadyPage } from "../enrollment.js";
12
+ import type { WorkerIdentity } from "../identity.js";
13
+ import type { AttemptView, ClaimResult, JobView, LeaseView } from "../reconciler.js";
14
+ import type { Run } from "../contracts.js";
15
+ export type Awaitable<T> = T | Promise<T>;
16
+ export interface WorkerAccessPort {
17
+ readRun(identity: WorkerIdentity, runId: string): Awaitable<{
18
+ run: Run;
19
+ jobs: JobView[];
20
+ }>;
21
+ readyWork(identity: WorkerIdentity, page: {
22
+ after: string | null;
23
+ limit: number;
24
+ }): Awaitable<ReadyPage>;
25
+ verifyNotification(identity: WorkerIdentity, event: LedgerEvent): Awaitable<string[]>;
26
+ /** opts.attemptId: claim again with the same id to replay a claim whose answer was lost. */
27
+ claim(identity: WorkerIdentity, jobId: string, opts?: {
28
+ attemptId?: string;
29
+ }): Awaitable<ClaimResult>;
30
+ dispatch(identity: WorkerIdentity, jobId: string, request: {
31
+ credentials: string[];
32
+ attemptId?: string;
33
+ }): Awaitable<Dispatch>;
34
+ recordOutcome(identity: WorkerIdentity, attemptId: string, outcome: "passed" | "failed"): Awaitable<AttemptView>;
35
+ returnAttempt(identity: WorkerIdentity, attemptId: string): Awaitable<AttemptView>;
36
+ renewLease(identity: WorkerIdentity, attemptId: string): Awaitable<LeaseView>;
37
+ }
38
+ /** The in-process port: each call goes straight to `access`, answered as a promise like the RPC client. */
39
+ export declare function inProcessPort(access: DeliveryAccess): WorkerAccessPort;
40
+ //# sourceMappingURL=port.d.ts.map
@@ -0,0 +1,16 @@
1
+ const _portMatchesAllowlist = true;
2
+ void _portMatchesAllowlist;
3
+ /** The in-process port: each call goes straight to `access`, answered as a promise like the RPC client. */
4
+ export function inProcessPort(access) {
5
+ return {
6
+ readRun: async (identity, runId) => access.readRun(identity, runId),
7
+ readyWork: async (identity, page) => access.readyWork(identity, page),
8
+ verifyNotification: async (identity, event) => access.verifyNotification(identity, event),
9
+ claim: async (identity, jobId, opts) => access.claim(identity, jobId, opts),
10
+ dispatch: async (identity, jobId, request) => access.dispatch(identity, jobId, request),
11
+ recordOutcome: async (identity, attemptId, outcome) => access.recordOutcome(identity, attemptId, outcome),
12
+ returnAttempt: async (identity, attemptId) => access.returnAttempt(identity, attemptId),
13
+ renewLease: async (identity, attemptId) => access.renewLease(identity, attemptId),
14
+ };
15
+ }
16
+ //# sourceMappingURL=port.js.map
@@ -0,0 +1,30 @@
1
+ import type { DeliveryAccess } from "../enrollment.js";
2
+ export interface WorkerRpcServerOptions {
3
+ access: DeliveryAccess;
4
+ /** Default "localhost": 127.0.0.1 and ::1. */
5
+ host?: string;
6
+ /** Default 0: any free port. */
7
+ port?: number;
8
+ /** Required to bind anything but 127.0.0.1, ::1 or localhost. */
9
+ allowNonLoopback?: boolean;
10
+ /** Close a connection that has not sent a complete request within this many ms. Default DEFAULT_SERVER_DEADLINE_MS. */
11
+ deadlineMs?: number;
12
+ /** Open connections held at once; past this a connection is answered RPC_BUSY and closed. Default DEFAULT_MAX_CONNECTIONS. */
13
+ maxConnections?: number;
14
+ /** Receives the full error whenever the wire carries less (an unexpected error, or a store-internal refusal). */
15
+ onError?: (err: unknown) => void;
16
+ }
17
+ export interface WorkerRpcServer {
18
+ readonly host: string;
19
+ readonly port: number;
20
+ /** The addresses actually bound, for example ["127.0.0.1", "::1"]. */
21
+ readonly addresses: string[];
22
+ /** Calls received for `method` (all methods when omitted), counted when a valid request line arrives. */
23
+ calls(method?: string): number;
24
+ /** Let the process exit while the server is listening. */
25
+ unref(): void;
26
+ /** Stop listening and close every open connection. Idempotent. */
27
+ close(): Promise<void>;
28
+ }
29
+ export declare function startWorkerRpcServer(opts: WorkerRpcServerOptions): Promise<WorkerRpcServer>;
30
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The controller side of the worker RPC (US-011 slice 4 B). See wire.ts for
3
+ * the format.
4
+ *
5
+ * - Binds loopback only by default: "localhost" (the default) listens on
6
+ * 127.0.0.1 and ::1 on the same port, and works with one family when the
7
+ * other is not available. Any other host is refused with RPC_NOT_LOOPBACK
8
+ * unless allowNonLoopback is true.
9
+ * - One call per connection. A request line over MAX_REQUEST_BYTES is answered
10
+ * RPC_TOO_LARGE; a connection that has not sent a complete line within
11
+ * deadlineMs is closed.
12
+ * - Only the RPC_METHODS allowlist is served. Each call hands the presented
13
+ * identity to DeliveryAccess, which authenticates it again inside the
14
+ * commit, so revocation, tenant and trust checks are exactly those of an
15
+ * in-process call.
16
+ */
17
+ import { createServer } from "node:net";
18
+ import { DEFAULT_MAX_CONNECTIONS, DEFAULT_SERVER_DEADLINE_MS, MAX_REQUEST_BYTES, RPC_WIRE_VERSION, encodeLine, errorBody, isLoopbackHost, notLoopback, parseRequest, redacted, rpcError, } from "./wire.js";
19
+ function text(v, name) {
20
+ if (typeof v !== "string")
21
+ throw rpcError("RPC_BAD_REQUEST", `${name} that is not a string`, `${name} as a string`, "Nothing was run.");
22
+ return v;
23
+ }
24
+ /** Dispatch's credentials are an object with methods and a redacting toJSON; they cross the wire as refs and values. */
25
+ function wireDispatch(d) {
26
+ const values = {};
27
+ for (const ref of d.credentials.refs)
28
+ values[ref] = d.credentials.get(ref);
29
+ return { claim: d.claim, jobClass: d.jobClass, credentials: { refs: [...d.credentials.refs], values } };
30
+ }
31
+ const HANDLERS = {
32
+ readRun: (a, id, [runId]) => a.readRun(id, text(runId, "runId")),
33
+ readyWork: (a, id, [page]) => a.readyWork(id, page),
34
+ verifyNotification: (a, id, [event]) => a.verifyNotification(id, event),
35
+ claim: (a, id, [jobId, opts]) => a.claim(id, text(jobId, "jobId"), (opts ?? {})),
36
+ dispatch: (a, id, [jobId, request]) => wireDispatch(a.dispatch(id, text(jobId, "jobId"), request)),
37
+ recordOutcome: (a, id, [attemptId, outcome]) => {
38
+ if (outcome !== "passed" && outcome !== "failed")
39
+ throw rpcError("RPC_BAD_REQUEST", "an outcome that is not passed or failed", "passed or failed", "Nothing was run.");
40
+ return a.recordOutcome(id, text(attemptId, "attemptId"), outcome);
41
+ },
42
+ returnAttempt: (a, id, [attemptId]) => a.returnAttempt(id, text(attemptId, "attemptId")),
43
+ renewLease: (a, id, [attemptId]) => a.renewLease(id, text(attemptId, "attemptId")),
44
+ };
45
+ /** Address families that may be missing on a host; binding them is skipped when another family bound. */
46
+ const FAMILY_UNAVAILABLE = new Set(["EADDRNOTAVAIL", "EAFNOSUPPORT", "EINVAL", "ENOTFOUND"]);
47
+ function listen(server, port, host) {
48
+ return new Promise((resolve, reject) => {
49
+ const onError = (err) => reject(err);
50
+ server.once("error", onError);
51
+ server.listen({ port, host, exclusive: true }, () => {
52
+ server.off("error", onError);
53
+ const addr = server.address();
54
+ resolve(addr && typeof addr === "object" ? addr.port : port);
55
+ });
56
+ });
57
+ }
58
+ function closeServer(server) {
59
+ return new Promise((resolve) => server.close(() => resolve()));
60
+ }
61
+ export async function startWorkerRpcServer(opts) {
62
+ const host = opts.host ?? "localhost";
63
+ if (!isLoopbackHost(host) && opts.allowNonLoopback !== true)
64
+ throw notLoopback(host, "bind");
65
+ const deadlineMs = opts.deadlineMs ?? DEFAULT_SERVER_DEADLINE_MS;
66
+ if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 1)
67
+ throw rpcError("RPC_BAD_REQUEST", `deadlineMs ${String(opts.deadlineMs)}`, "a positive integer of ms", "Nothing was opened.");
68
+ const maxConnections = opts.maxConnections ?? DEFAULT_MAX_CONNECTIONS;
69
+ if (!Number.isSafeInteger(maxConnections) || maxConnections < 1)
70
+ throw rpcError("RPC_BAD_REQUEST", `maxConnections ${String(opts.maxConnections)}`, "a positive integer", "Nothing was opened.");
71
+ const access = opts.access;
72
+ const received = new Map();
73
+ const sockets = new Set();
74
+ const onConnection = (sock) => {
75
+ if (sockets.size >= maxConnections) {
76
+ // Answer and close at once, so a flood of idle connections cannot hold descriptors past the limit.
77
+ sock.on("error", () => sock.destroy());
78
+ const body = errorBody(rpcError("RPC_BUSY", `${maxConnections} connections already open`, "a free connection slot", "Retry shortly. Nothing was run."));
79
+ sock.end(encodeLine({ v: RPC_WIRE_VERSION, id: "", ok: false, error: body }));
80
+ setTimeout(() => sock.destroy(), 250).unref();
81
+ return;
82
+ }
83
+ sockets.add(sock);
84
+ sock.setNoDelay(true);
85
+ const deadline = setTimeout(() => sock.destroy(), deadlineMs);
86
+ deadline.unref();
87
+ sock.on("close", () => {
88
+ clearTimeout(deadline);
89
+ sockets.delete(sock);
90
+ });
91
+ sock.on("error", () => sock.destroy());
92
+ const chunks = [];
93
+ let size = 0;
94
+ let answered = false;
95
+ const answer = (line, linger = false) => {
96
+ answered = true;
97
+ sock.removeListener("data", onData);
98
+ if (linger) {
99
+ // Discard the rest of an oversize request, then close, so the caller reads the refusal instead of a reset.
100
+ sock.resume();
101
+ sock.end(line);
102
+ setTimeout(() => sock.destroy(), 250).unref();
103
+ }
104
+ else {
105
+ sock.end(line);
106
+ }
107
+ };
108
+ const onData = (b) => {
109
+ if (answered)
110
+ return;
111
+ const nl = b.indexOf(10);
112
+ const lineBytes = size + (nl < 0 ? b.length : nl + 1);
113
+ if (lineBytes > MAX_REQUEST_BYTES) {
114
+ const body = errorBody(rpcError("RPC_TOO_LARGE", `a request over ${MAX_REQUEST_BYTES} bytes`, `at most ${MAX_REQUEST_BYTES} bytes per request`, "Send smaller arguments. Nothing was run."));
115
+ answer(encodeLine({ v: RPC_WIRE_VERSION, id: "", ok: false, error: body }), true);
116
+ return;
117
+ }
118
+ if (nl < 0) {
119
+ chunks.push(b);
120
+ size += b.length;
121
+ return;
122
+ }
123
+ chunks.push(b.subarray(0, nl));
124
+ const line = Buffer.concat(chunks).toString("utf8");
125
+ let id = "";
126
+ let reply;
127
+ try {
128
+ const req = parseRequest(line);
129
+ id = req.id;
130
+ received.set(req.method, (received.get(req.method) ?? 0) + 1);
131
+ const value = HANDLERS[req.method](access, req.identity, req.args);
132
+ reply = { v: RPC_WIRE_VERSION, id, ok: true, value: value ?? null };
133
+ }
134
+ catch (err) {
135
+ if (redacted(err)) {
136
+ try {
137
+ opts.onError?.(err);
138
+ }
139
+ catch {
140
+ // A failing log hook must not change the answer.
141
+ }
142
+ }
143
+ reply = { v: RPC_WIRE_VERSION, id, ok: false, error: errorBody(err) };
144
+ }
145
+ answer(encodeLine(reply));
146
+ };
147
+ sock.on("data", onData);
148
+ };
149
+ const binds = host === "localhost" ? ["127.0.0.1", "::1"] : [host];
150
+ const servers = [];
151
+ const addresses = [];
152
+ let port = opts.port ?? 0;
153
+ for (let tries = 0;; tries += 1) {
154
+ try {
155
+ for (const h of binds) {
156
+ const server = createServer(onConnection);
157
+ try {
158
+ port = await listen(server, port, h);
159
+ servers.push(server);
160
+ addresses.push(h);
161
+ }
162
+ catch (err) {
163
+ const code = err.code ?? "";
164
+ // A family the host lacks is skipped once another family is bound.
165
+ if (servers.length > 0 && FAMILY_UNAVAILABLE.has(code))
166
+ continue;
167
+ throw err;
168
+ }
169
+ }
170
+ break;
171
+ }
172
+ catch (err) {
173
+ for (const s of servers.splice(0))
174
+ await closeServer(s);
175
+ addresses.length = 0;
176
+ // With a free port chosen by the OS, the second family can collide with a port in use there: pick again.
177
+ const code = err.code ?? "";
178
+ if (opts.port === undefined && code === "EADDRINUSE" && tries < 5) {
179
+ port = 0;
180
+ continue;
181
+ }
182
+ throw err;
183
+ }
184
+ }
185
+ let closing = null;
186
+ return {
187
+ host,
188
+ port,
189
+ addresses: [...addresses],
190
+ calls: (method) => (method === undefined ? [...received.values()].reduce((a, b) => a + b, 0) : (received.get(method) ?? 0)),
191
+ unref: () => {
192
+ for (const s of servers)
193
+ s.unref();
194
+ },
195
+ close() {
196
+ closing ??= (async () => {
197
+ for (const s of sockets)
198
+ s.destroy();
199
+ await Promise.all(servers.map(closeServer));
200
+ })();
201
+ return closing;
202
+ },
203
+ };
204
+ }
205
+ //# sourceMappingURL=server.js.map