@indigoai-us/hq-cli 5.345.214 → 5.345.215-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/command-catalog.generated.d.ts +134 -7
  3. package/dist/command-catalog.generated.js +168 -7
  4. package/dist/commands/agents.d.ts +51 -1
  5. package/dist/commands/agents.js +154 -2
  6. package/dist/commands/bot-jobs.d.ts +2 -15
  7. package/dist/commands/bot-jobs.js +2 -94
  8. package/dist/commands/bot-runtime.d.ts +46 -5
  9. package/dist/commands/bot-runtime.js +228 -18
  10. package/dist/commands/bot.d.ts +16 -9
  11. package/dist/commands/bot.js +169 -51
  12. package/dist/commands/cloud.d.ts +66 -13
  13. package/dist/commands/cloud.js +120 -39
  14. package/dist/commands/company-restore.d.ts +23 -0
  15. package/dist/commands/company-restore.js +128 -0
  16. package/dist/commands/company.js +2 -0
  17. package/dist/commands/integrations-connect.d.ts +10 -3
  18. package/dist/commands/integrations-connect.js +87 -13
  19. package/dist/commands/lanes.js +26 -9
  20. package/dist/commands/sources.js +6 -0
  21. package/dist/commands/storage-offload.d.ts +12 -0
  22. package/dist/commands/storage-offload.js +41 -3
  23. package/dist/commands/sync-mode.js +5 -0
  24. package/dist/commands/whoami.js +4 -0
  25. package/dist/lib/bot/config.d.ts +1 -0
  26. package/dist/lib/bot/config.js +10 -0
  27. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  28. package/dist/lib/bot/eventbridge-cron.js +104 -0
  29. package/dist/lib/bot/fleet-local.d.ts +33 -1
  30. package/dist/lib/bot/fleet-local.js +215 -31
  31. package/dist/lib/bot/fleet-python.d.ts +3 -0
  32. package/dist/lib/bot/fleet-python.js +34 -4
  33. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  34. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  36. package/dist/lib/bot/legacy-provider-login.js +19 -2
  37. package/dist/lib/bot/prompt.js +1 -1
  38. package/dist/lib/bot/readiness.d.ts +8 -0
  39. package/dist/lib/bot/readiness.js +17 -3
  40. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  41. package/dist/lib/bot/runtime-auth.js +94 -3
  42. package/dist/lib/bot/status.d.ts +2 -0
  43. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  44. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  45. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  46. package/dist/lib/capacity/collectors/grok.js +56 -5
  47. package/dist/lib/daemon/catalog.js +11 -1
  48. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  49. package/dist/lib/db/sqlite-binding.js +1 -1
  50. package/dist/lib/delivery/artifacts.d.ts +99 -0
  51. package/dist/lib/delivery/artifacts.js +548 -0
  52. package/dist/lib/delivery/backup.d.ts +78 -0
  53. package/dist/lib/delivery/backup.js +343 -0
  54. package/dist/lib/delivery/cache.d.ts +29 -0
  55. package/dist/lib/delivery/cache.js +33 -0
  56. package/dist/lib/delivery/contracts.d.ts +142 -0
  57. package/dist/lib/delivery/contracts.js +289 -0
  58. package/dist/lib/delivery/credentials.d.ts +54 -0
  59. package/dist/lib/delivery/credentials.js +119 -0
  60. package/dist/lib/delivery/enrollment.d.ts +142 -0
  61. package/dist/lib/delivery/enrollment.js +382 -0
  62. package/dist/lib/delivery/identity.d.ts +25 -0
  63. package/dist/lib/delivery/identity.js +82 -0
  64. package/dist/lib/delivery/inbox.d.ts +116 -0
  65. package/dist/lib/delivery/inbox.js +260 -0
  66. package/dist/lib/delivery/migrations.d.ts +139 -0
  67. package/dist/lib/delivery/migrations.js +623 -0
  68. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  69. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  70. package/dist/lib/delivery/mqtt.d.ts +61 -0
  71. package/dist/lib/delivery/mqtt.js +112 -0
  72. package/dist/lib/delivery/outbox.d.ts +95 -0
  73. package/dist/lib/delivery/outbox.js +187 -0
  74. package/dist/lib/delivery/provenance.d.ts +129 -0
  75. package/dist/lib/delivery/provenance.js +93 -0
  76. package/dist/lib/delivery/reconciler.d.ts +151 -0
  77. package/dist/lib/delivery/reconciler.js +492 -0
  78. package/dist/lib/delivery/restore.d.ts +35 -0
  79. package/dist/lib/delivery/restore.js +134 -0
  80. package/dist/lib/delivery/store.d.ts +161 -0
  81. package/dist/lib/delivery/store.js +940 -0
  82. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  83. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  84. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  85. package/dist/lib/delivery/workers/macos.js +901 -0
  86. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  87. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  88. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  89. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  90. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  91. package/dist/lib/delivery/workers/windows.js +608 -0
  92. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  93. package/dist/lib/install/provider-wrappers.js +68 -3
  94. package/dist/utils/cognito-callback-port.d.ts +14 -0
  95. package/dist/utils/cognito-callback-port.js +24 -0
  96. package/dist/utils/cognito-session.js +3 -3
  97. package/dist/utils/deleted-company-notice.d.ts +59 -0
  98. package/dist/utils/deleted-company-notice.js +156 -0
  99. package/dist/utils/login-browser.d.ts +1 -1
  100. package/dist/utils/login-browser.js +7 -5
  101. package/dist/utils/resident-package-preload.js +30 -15
  102. package/dist/utils/vault-api.js +7 -0
  103. package/package.json +7 -7
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Real MQTT adapter for delivery notifications (US-005 phase 01b).
3
+ *
4
+ * Implements NotificationBroker over mqtt.js with QoS 1:
5
+ * - publish() resolves only when the broker's PUBACK arrives. It rejects at
6
+ * once while disconnected and rejects when no ack arrives within
7
+ * `ackTimeoutMs`. It never resolves without an ack.
8
+ * - A subscriber handler that returns or resolves sends the PUBACK. One that
9
+ * throws or rejects sends no PUBACK; the adapter then drops the connection
10
+ * after a backoff delay so the broker redelivers the unacked message on
11
+ * reconnect. A message with no local handler yet is treated the same way,
12
+ * so a queued message that arrives before subscribe() is not lost.
13
+ * - The session is persistent (clean session off) under the caller's stable
14
+ * client id, so queued QoS 1 messages survive a client reconnect.
15
+ * - Reconnect uses bounded exponential backoff (`reconnect`). Subscriptions
16
+ * are sent again on every connect, because a restarted broker without
17
+ * persistence has forgotten them.
18
+ *
19
+ * The broker URL and client id are explicit arguments. The adapter reads no
20
+ * environment, has no host default and sets no credentials.
21
+ */
22
+ import mqtt from "mqtt";
23
+ import { topicMatches } from "./mqtt.js";
24
+ import { backoffDelay } from "./outbox.js";
25
+ const DEFAULT_RECONNECT = { baseMs: 500, maxMs: 30_000 };
26
+ export class MqttBroker {
27
+ client;
28
+ ackTimeoutMs;
29
+ backoff;
30
+ handlers = new Map();
31
+ closed = false;
32
+ reconnectFailures = 0;
33
+ reconnectTimer = null;
34
+ redeliverFailures = 0;
35
+ redeliverTimer = null;
36
+ subscribing = Promise.resolve(true);
37
+ connectWaiters = [];
38
+ constructor(client, ackTimeoutMs, backoff) {
39
+ this.client = client;
40
+ this.ackTimeoutMs = ackTimeoutMs;
41
+ this.backoff = backoff;
42
+ }
43
+ /** Connect to the broker and resolve on the first CONNACK. */
44
+ static async connect(opts) {
45
+ if (typeof opts.url !== "string" || opts.url.length === 0)
46
+ throw new Error("MQTT broker url is required");
47
+ if (typeof opts.clientId !== "string" || opts.clientId.length === 0)
48
+ throw new Error("MQTT client id is required");
49
+ const connectTimeoutMs = opts.connectTimeoutMs ?? 10_000;
50
+ const client = mqtt.connect(opts.url, {
51
+ clientId: opts.clientId,
52
+ clean: false,
53
+ protocolVersion: 4,
54
+ keepalive: opts.keepaliveSeconds ?? 30,
55
+ connectTimeout: connectTimeoutMs,
56
+ reconnectPeriod: 0,
57
+ resubscribe: false,
58
+ });
59
+ const broker = new MqttBroker(client, opts.ackTimeoutMs ?? 10_000, opts.reconnect ?? DEFAULT_RECONNECT);
60
+ // Install the message hook before the CONNACK: a persistent session's
61
+ // queued messages can arrive right after it, and the default hook would
62
+ // ack them with no handler.
63
+ client.handleMessage = (packet, callback) => broker.onMessage(packet, callback);
64
+ try {
65
+ await new Promise((resolve, reject) => {
66
+ const timer = setTimeout(() => finish(new Error(`MQTT connect timed out after ${connectTimeoutMs} ms`)), connectTimeoutMs);
67
+ const onConnect = () => finish(null);
68
+ const onError = (err) => finish(err);
69
+ const onClose = () => finish(new Error("MQTT connection closed before connect"));
70
+ function finish(err) {
71
+ clearTimeout(timer);
72
+ client.off("connect", onConnect);
73
+ client.off("error", onError);
74
+ client.off("close", onClose);
75
+ if (err)
76
+ reject(err);
77
+ else
78
+ resolve();
79
+ }
80
+ client.once("connect", onConnect);
81
+ client.once("error", onError);
82
+ client.once("close", onClose);
83
+ });
84
+ }
85
+ catch (err) {
86
+ broker.closed = true;
87
+ client.end(true);
88
+ throw err;
89
+ }
90
+ broker.wire();
91
+ return broker;
92
+ }
93
+ get connected() {
94
+ return !this.closed && this.client.connected;
95
+ }
96
+ publish(topic, payload) {
97
+ if (this.closed)
98
+ return Promise.reject(new Error("MQTT adapter is closed"));
99
+ if (!this.client.connected)
100
+ return Promise.reject(new Error("MQTT broker unavailable: not connected"));
101
+ return new Promise((resolve, reject) => {
102
+ let settled = false;
103
+ const timer = setTimeout(() => {
104
+ settled = true;
105
+ reject(new Error(`MQTT publish not acked within ${this.ackTimeoutMs} ms`));
106
+ }, this.ackTimeoutMs);
107
+ this.client.publish(topic, payload, { qos: 1 }, (err) => {
108
+ if (settled)
109
+ return;
110
+ settled = true;
111
+ clearTimeout(timer);
112
+ if (err)
113
+ reject(err);
114
+ else
115
+ resolve();
116
+ });
117
+ });
118
+ }
119
+ subscribe(filter, handler) {
120
+ let set = this.handlers.get(filter);
121
+ const isNew = !set;
122
+ if (!set) {
123
+ set = new Set();
124
+ this.handlers.set(filter, set);
125
+ }
126
+ set.add(handler);
127
+ if (isNew && this.client.connected)
128
+ this.subscribeAll();
129
+ return () => {
130
+ const current = this.handlers.get(filter);
131
+ if (!current)
132
+ return;
133
+ current.delete(handler);
134
+ if (current.size > 0)
135
+ return;
136
+ this.handlers.delete(filter);
137
+ if (this.client.connected && !this.closed)
138
+ this.client.unsubscribe(filter);
139
+ };
140
+ }
141
+ /** Resolve once every current subscription has its SUBACK on the live connection. */
142
+ async whenSubscribed() {
143
+ for (;;) {
144
+ if (this.closed)
145
+ throw new Error("MQTT adapter is closed");
146
+ if (!this.client.connected) {
147
+ await new Promise((resolve) => this.connectWaiters.push(resolve));
148
+ continue;
149
+ }
150
+ const round = this.subscribing;
151
+ const ok = await round;
152
+ if (ok && round === this.subscribing && this.client.connected)
153
+ return;
154
+ if (!ok && round === this.subscribing && this.client.connected)
155
+ this.subscribeAll();
156
+ }
157
+ }
158
+ /**
159
+ * Disconnect without ending the persistent session, so the broker keeps
160
+ * queuing for this client id. With a publish still waiting for its ack the
161
+ * connection is dropped at once instead of waiting on the broker.
162
+ */
163
+ async close() {
164
+ if (this.closed)
165
+ return;
166
+ this.closed = true;
167
+ if (this.reconnectTimer)
168
+ clearTimeout(this.reconnectTimer);
169
+ if (this.redeliverTimer)
170
+ clearTimeout(this.redeliverTimer);
171
+ this.reconnectTimer = null;
172
+ this.redeliverTimer = null;
173
+ for (const w of this.connectWaiters.splice(0))
174
+ w();
175
+ const force = !this.client.connected || Object.keys(this.client.outgoing).length > 0;
176
+ await new Promise((resolve) => this.client.end(force, {}, () => resolve()));
177
+ }
178
+ wire() {
179
+ this.client.on("connect", () => {
180
+ this.reconnectFailures = 0;
181
+ if (this.handlers.size > 0)
182
+ this.subscribeAll();
183
+ for (const w of this.connectWaiters.splice(0))
184
+ w();
185
+ });
186
+ this.client.on("close", () => this.scheduleReconnect());
187
+ // mqtt.js emits connection errors as events; the close handler retries.
188
+ this.client.on("error", () => undefined);
189
+ }
190
+ subscribeAll() {
191
+ const filters = [...this.handlers.keys()];
192
+ this.subscribing = Promise.all(filters.map((filter) => new Promise((resolve) => this.client.subscribe(filter, { qos: 1 }, (err, granted) => resolve(!err && !(granted ?? []).some((g) => g.qos === 128)))))).then((all) => all.every(Boolean));
193
+ }
194
+ scheduleReconnect() {
195
+ if (this.closed || this.reconnectTimer)
196
+ return;
197
+ this.reconnectFailures += 1;
198
+ this.reconnectTimer = setTimeout(() => {
199
+ this.reconnectTimer = null;
200
+ if (!this.closed && !this.client.connected)
201
+ this.client.reconnect();
202
+ }, backoffDelay(this.backoff, this.reconnectFailures));
203
+ }
204
+ /** No PUBACK was sent: drop the connection after a backoff so the broker resends on reconnect. */
205
+ scheduleRedelivery() {
206
+ if (this.closed || this.redeliverTimer)
207
+ return;
208
+ this.redeliverFailures += 1;
209
+ this.redeliverTimer = setTimeout(() => {
210
+ this.redeliverTimer = null;
211
+ if (!this.closed && this.client.connected)
212
+ this.client.stream.destroy();
213
+ }, backoffDelay(this.backoff, this.redeliverFailures));
214
+ }
215
+ onMessage(packet, callback) {
216
+ const message = {
217
+ id: packet.messageId ?? 0,
218
+ topic: packet.topic,
219
+ payload: Buffer.isBuffer(packet.payload) ? packet.payload.toString("utf8") : String(packet.payload),
220
+ };
221
+ const matched = [];
222
+ for (const [filter, set] of this.handlers)
223
+ if (topicMatches(filter, message.topic))
224
+ matched.push(...set);
225
+ if (matched.length === 0) {
226
+ callback(new Error("no handler for topic yet"));
227
+ this.scheduleRedelivery();
228
+ return;
229
+ }
230
+ (async () => {
231
+ for (const h of matched)
232
+ await h(message);
233
+ })().then(() => {
234
+ this.redeliverFailures = 0;
235
+ callback();
236
+ }, (err) => {
237
+ callback(err instanceof Error ? err : new Error("handler failed"));
238
+ this.scheduleRedelivery();
239
+ });
240
+ }
241
+ }
242
+ //# sourceMappingURL=mqtt-adapter.js.map
@@ -0,0 +1,61 @@
1
+ /**
2
+ * MQTT transport for delivery notifications (US-005).
3
+ *
4
+ * Notifications are hints. A message on the broker never authorizes, creates
5
+ * or claims a job: the consumer re-reads the ledger through the access layer
6
+ * before any claim, and reconciliation finds ready work without the broker.
7
+ * A broker ack is a transport fact only and is never written to the ledger.
8
+ *
9
+ * This module defines the broker interface (QoS 1 semantics: publish resolves
10
+ * on the broker's ack; a subscriber handler that returns or resolves acks the
11
+ * message, one that throws leaves it for redelivery) and an in-process fake
12
+ * for tests. No production broker or credential is used here.
13
+ */
14
+ export interface BrokerMessage {
15
+ /** Broker-assigned delivery id. Redeliveries of one message keep the same id. */
16
+ id: number;
17
+ topic: string;
18
+ payload: string;
19
+ }
20
+ export type BrokerHandler = (message: BrokerMessage) => void | Promise<void>;
21
+ export interface NotificationBroker {
22
+ /** Resolves when the broker has acked the message; rejects when it is unavailable. */
23
+ publish(topic: string, payload: string): Promise<void>;
24
+ /** Handler return or resolve acks the message; a throw or rejection leaves it unacked. */
25
+ subscribe(filter: string, handler: BrokerHandler): () => void;
26
+ }
27
+ export declare const NOTIFICATION_TOPIC_ROOT = "hq/delivery/v1";
28
+ /** The one topic a tenant's notifications use. Tenant ids that could widen a filter are refused. */
29
+ export declare function notificationTopic(tenantId: string): string;
30
+ /** MQTT topic filter matching with `+` (one level) and a trailing `#` (any remaining levels). */
31
+ export declare function topicMatches(filter: string, topic: string): boolean;
32
+ /**
33
+ * In-process fake broker. Messages stay queued until every matching
34
+ * subscriber acks them. A message with no matching subscriber stays queued.
35
+ * `restart()` models a broker that loses its queue; `outage()` makes publish
36
+ * fail until `restore()`.
37
+ */
38
+ export declare class InMemoryBroker implements NotificationBroker {
39
+ private queue;
40
+ private readonly subscribers;
41
+ private down;
42
+ private nextId;
43
+ publish(topic: string, payload: string): Promise<void>;
44
+ subscribe(filter: string, handler: BrokerHandler): () => void;
45
+ /** Put a message on the queue as any client could, bypassing the outbox. */
46
+ inject(topic: string, payload: string): void;
47
+ outage(): void;
48
+ restore(): void;
49
+ /** The broker restarts without persistence: every queued message is lost. */
50
+ restart(): void;
51
+ queued(): BrokerMessage[];
52
+ /**
53
+ * Deliver each queued message once to its matching subscribers, in queue
54
+ * order. Returns how many messages were handed to at least one subscriber.
55
+ * With `dropAcks`, acks are lost in transit and every message stays queued.
56
+ */
57
+ deliver(options?: {
58
+ dropAcks?: boolean;
59
+ }): Promise<number>;
60
+ }
61
+ //# sourceMappingURL=mqtt.d.ts.map
@@ -0,0 +1,112 @@
1
+ /**
2
+ * MQTT transport for delivery notifications (US-005).
3
+ *
4
+ * Notifications are hints. A message on the broker never authorizes, creates
5
+ * or claims a job: the consumer re-reads the ledger through the access layer
6
+ * before any claim, and reconciliation finds ready work without the broker.
7
+ * A broker ack is a transport fact only and is never written to the ledger.
8
+ *
9
+ * This module defines the broker interface (QoS 1 semantics: publish resolves
10
+ * on the broker's ack; a subscriber handler that returns or resolves acks the
11
+ * message, one that throws leaves it for redelivery) and an in-process fake
12
+ * for tests. No production broker or credential is used here.
13
+ */
14
+ export const NOTIFICATION_TOPIC_ROOT = "hq/delivery/v1";
15
+ const TOPIC_SEGMENT = /^[A-Za-z0-9._-]+$/;
16
+ /** The one topic a tenant's notifications use. Tenant ids that could widen a filter are refused. */
17
+ export function notificationTopic(tenantId) {
18
+ if (!TOPIC_SEGMENT.test(tenantId)) {
19
+ throw new Error("tenant id is not a valid notification topic segment");
20
+ }
21
+ return `${NOTIFICATION_TOPIC_ROOT}/${tenantId}/events`;
22
+ }
23
+ /** MQTT topic filter matching with `+` (one level) and a trailing `#` (any remaining levels). */
24
+ export function topicMatches(filter, topic) {
25
+ const f = filter.split("/");
26
+ const t = topic.split("/");
27
+ for (let i = 0; i < f.length; i += 1) {
28
+ if (f[i] === "#")
29
+ return i === f.length - 1;
30
+ if (i >= t.length)
31
+ return false;
32
+ if (f[i] !== "+" && f[i] !== t[i])
33
+ return false;
34
+ }
35
+ return f.length === t.length;
36
+ }
37
+ /**
38
+ * In-process fake broker. Messages stay queued until every matching
39
+ * subscriber acks them. A message with no matching subscriber stays queued.
40
+ * `restart()` models a broker that loses its queue; `outage()` makes publish
41
+ * fail until `restore()`.
42
+ */
43
+ export class InMemoryBroker {
44
+ queue = [];
45
+ subscribers = [];
46
+ down = false;
47
+ nextId = 1;
48
+ async publish(topic, payload) {
49
+ if (this.down)
50
+ throw new Error("broker unavailable");
51
+ this.queue.push({ id: this.nextId++, topic, payload });
52
+ }
53
+ subscribe(filter, handler) {
54
+ const entry = { filter, handler };
55
+ this.subscribers.push(entry);
56
+ return () => {
57
+ const i = this.subscribers.indexOf(entry);
58
+ if (i >= 0)
59
+ this.subscribers.splice(i, 1);
60
+ };
61
+ }
62
+ /** Put a message on the queue as any client could, bypassing the outbox. */
63
+ inject(topic, payload) {
64
+ this.queue.push({ id: this.nextId++, topic, payload });
65
+ }
66
+ outage() {
67
+ this.down = true;
68
+ }
69
+ restore() {
70
+ this.down = false;
71
+ }
72
+ /** The broker restarts without persistence: every queued message is lost. */
73
+ restart() {
74
+ this.queue = [];
75
+ }
76
+ queued() {
77
+ return this.queue.map((m) => ({ ...m }));
78
+ }
79
+ /**
80
+ * Deliver each queued message once to its matching subscribers, in queue
81
+ * order. Returns how many messages were handed to at least one subscriber.
82
+ * With `dropAcks`, acks are lost in transit and every message stays queued.
83
+ */
84
+ async deliver(options = {}) {
85
+ if (this.down)
86
+ return 0;
87
+ let delivered = 0;
88
+ const kept = [];
89
+ for (const message of this.queue.splice(0)) {
90
+ const handlers = this.subscribers.filter((s) => topicMatches(s.filter, message.topic));
91
+ if (handlers.length === 0) {
92
+ kept.push(message);
93
+ continue;
94
+ }
95
+ delivered += 1;
96
+ let acked = true;
97
+ for (const s of handlers) {
98
+ try {
99
+ await s.handler({ ...message });
100
+ }
101
+ catch {
102
+ acked = false;
103
+ }
104
+ }
105
+ if (!acked || options.dropAcks)
106
+ kept.push(message);
107
+ }
108
+ this.queue.unshift(...kept);
109
+ return delivered;
110
+ }
111
+ }
112
+ //# sourceMappingURL=mqtt.js.map
@@ -0,0 +1,95 @@
1
+ import type { DeliveryAccess } from "./enrollment.js";
2
+ import type { StoreState } from "./migrations.js";
3
+ import { type NotificationBroker } from "./mqtt.js";
4
+ export declare const NOTIFICATION_SCHEMA = "hq-delivery.notification.v1";
5
+ /** Larger payloads are refused unparsed. */
6
+ export declare const MAX_NOTIFICATION_BYTES: number;
7
+ export type LedgerEventType = "job.accepted" | "attempt.resolved";
8
+ export interface LedgerEvent {
9
+ schemaVersion: typeof NOTIFICATION_SCHEMA;
10
+ eventId: string;
11
+ type: LedgerEventType;
12
+ tenantId: string;
13
+ runId: string;
14
+ jobId: string;
15
+ attemptId: string | null;
16
+ /** Epoch of the commit that wrote the record: acceptedEpoch or resolvedEpoch. */
17
+ epoch: number;
18
+ }
19
+ /** Every event the committed ledger implies, in ledger order: accepted jobs, then resolved attempts. */
20
+ export declare function ledgerEvents(state: Readonly<StoreState>): LedgerEvent[];
21
+ /** Strict parse of a notification payload. Anything else, including extra keys, is null. */
22
+ export declare function parseNotification(payload: string): LedgerEvent | null;
23
+ /** True when two events carry the same values in every field. */
24
+ export declare function sameEvent(a: LedgerEvent, b: LedgerEvent): boolean;
25
+ export interface SqliteHandle {
26
+ exec(sql: string): unknown;
27
+ prepare(sql: string): {
28
+ run(...params: unknown[]): unknown;
29
+ get(...params: unknown[]): unknown;
30
+ all(...params: unknown[]): unknown[];
31
+ };
32
+ close(): void;
33
+ }
34
+ /** Open a transport-side sqlite file (outbox progress or consumer inbox) with WAL and a busy timeout. */
35
+ export declare function openTransportDb(path: string): SqliteHandle;
36
+ export interface BackoffPolicy {
37
+ baseMs: number;
38
+ maxMs: number;
39
+ }
40
+ export declare const DEFAULT_BACKOFF: BackoffPolicy;
41
+ export declare function backoffDelay(policy: BackoffPolicy, failures: number): number;
42
+ export interface PublishReport {
43
+ published: number;
44
+ /** Events still unpublished after this call. */
45
+ remaining: number;
46
+ /** Broker error text when this call stopped early, else null. */
47
+ error: string | null;
48
+ /** Suggested wait before the next call: 0 after success, growing after consecutive failures. */
49
+ nextDelayMs: number;
50
+ }
51
+ export interface OutboxOptions {
52
+ access: DeliveryAccess;
53
+ broker: NotificationBroker;
54
+ /** Path of the publisher's own sqlite file. Not the ledger. */
55
+ path: string;
56
+ /** Most events one publishPending call sends. Default 100. */
57
+ batchSize?: number;
58
+ backoff?: BackoffPolicy;
59
+ clock?: () => number;
60
+ /**
61
+ * Test-only crash barrier, inert unless passed. Called after the broker
62
+ * acks an event and before its published row is written.
63
+ * process-crash.test.ts uses it to SIGKILL a child at that point.
64
+ */
65
+ testBarrier?: (stage: "acked", eventId: string) => void;
66
+ }
67
+ export declare const MAX_BATCH = 1000;
68
+ export declare function checkBatch(size: number): number;
69
+ export declare class OutboxPublisher {
70
+ private readonly access;
71
+ private readonly broker;
72
+ private readonly db;
73
+ private readonly batchSize;
74
+ private readonly backoff;
75
+ private readonly clock;
76
+ private readonly testBarrier;
77
+ private failures;
78
+ private crashAfterAck;
79
+ private constructor();
80
+ static open(opts: OutboxOptions): OutboxPublisher;
81
+ /** Committed events the broker has not acked yet, in ledger order. */
82
+ pending(): LedgerEvent[];
83
+ /** Event ids the broker has acked, in ack order. */
84
+ published(): string[];
85
+ /**
86
+ * Publish up to one batch of pending events, oldest first. Stops at the
87
+ * first broker error and reports a backoff delay; nothing is lost because
88
+ * the events stay derivable from the ledger.
89
+ */
90
+ publishPending(): Promise<PublishReport>;
91
+ /** Test hook: the next publishPending throws after the first broker ack and before its row is written. */
92
+ crashAfterAckForTest(): void;
93
+ close(): void;
94
+ }
95
+ //# sourceMappingURL=outbox.d.ts.map