@overcy/hive 0.0.1 → 0.2.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 (134) hide show
  1. package/README.md +209 -4
  2. package/dist/api.d.ts +31 -0
  3. package/dist/api.js +83 -0
  4. package/dist/atomic.d.ts +1 -0
  5. package/dist/atomic.js +24 -0
  6. package/dist/binding.d.ts +5 -0
  7. package/dist/binding.js +16 -0
  8. package/dist/bootstrap/deps.d.ts +3 -0
  9. package/dist/bootstrap/deps.js +35 -0
  10. package/dist/bootstrap/doctor.d.ts +29 -0
  11. package/dist/bootstrap/doctor.js +80 -0
  12. package/dist/bootstrap/engine.d.ts +29 -0
  13. package/dist/bootstrap/engine.js +160 -0
  14. package/dist/bootstrap/forwarder.d.ts +11 -0
  15. package/dist/bootstrap/forwarder.js +30 -0
  16. package/dist/bootstrap/identity.d.ts +7 -0
  17. package/dist/bootstrap/identity.js +52 -0
  18. package/dist/bootstrap/index.d.ts +36 -0
  19. package/dist/bootstrap/index.js +40 -0
  20. package/dist/bootstrap/kit.d.ts +9 -0
  21. package/dist/bootstrap/kit.js +56 -0
  22. package/dist/bootstrap/manifest.d.ts +73 -0
  23. package/dist/bootstrap/manifest.js +309 -0
  24. package/dist/bootstrap/model-access.d.ts +43 -0
  25. package/dist/bootstrap/model-access.js +74 -0
  26. package/dist/bootstrap/pin.d.ts +2 -0
  27. package/dist/bootstrap/pin.js +16 -0
  28. package/dist/bootstrap/plan.d.ts +49 -0
  29. package/dist/bootstrap/plan.js +69 -0
  30. package/dist/bootstrap/prompt.d.ts +3 -0
  31. package/dist/bootstrap/prompt.js +35 -0
  32. package/dist/bootstrap/registry.d.ts +85 -0
  33. package/dist/bootstrap/registry.js +38 -0
  34. package/dist/bootstrap/secrets.d.ts +11 -0
  35. package/dist/bootstrap/secrets.js +105 -0
  36. package/dist/bootstrap/steps/agents.d.ts +9 -0
  37. package/dist/bootstrap/steps/agents.js +75 -0
  38. package/dist/bootstrap/steps/auth.d.ts +8 -0
  39. package/dist/bootstrap/steps/auth.js +138 -0
  40. package/dist/bootstrap/steps/cron.d.ts +7 -0
  41. package/dist/bootstrap/steps/cron.js +74 -0
  42. package/dist/bootstrap/steps/drift.d.ts +5 -0
  43. package/dist/bootstrap/steps/drift.js +67 -0
  44. package/dist/bootstrap/steps/env.d.ts +6 -0
  45. package/dist/bootstrap/steps/env.js +108 -0
  46. package/dist/bootstrap/steps/files.d.ts +7 -0
  47. package/dist/bootstrap/steps/files.js +28 -0
  48. package/dist/bootstrap/steps/lanes.d.ts +14 -0
  49. package/dist/bootstrap/steps/lanes.js +153 -0
  50. package/dist/bootstrap/steps/model-access.d.ts +10 -0
  51. package/dist/bootstrap/steps/model-access.js +122 -0
  52. package/dist/bootstrap/steps/preflight.d.ts +3 -0
  53. package/dist/bootstrap/steps/preflight.js +49 -0
  54. package/dist/bootstrap/steps/reporter.d.ts +12 -0
  55. package/dist/bootstrap/steps/reporter.js +155 -0
  56. package/dist/bootstrap/system.d.ts +5 -0
  57. package/dist/bootstrap/system.js +69 -0
  58. package/dist/bootstrap/types.d.ts +157 -0
  59. package/dist/bootstrap/types.js +14 -0
  60. package/dist/cli.d.ts +2 -0
  61. package/dist/cli.js +23 -0
  62. package/dist/collect.d.ts +28 -0
  63. package/dist/collect.js +63 -0
  64. package/dist/commands/connect.d.ts +33 -0
  65. package/dist/commands/connect.js +306 -0
  66. package/dist/commands/doctor.d.ts +7 -0
  67. package/dist/commands/doctor.js +13 -0
  68. package/dist/commands/login.d.ts +3 -0
  69. package/dist/commands/login.js +118 -0
  70. package/dist/commands/logout.d.ts +2 -0
  71. package/dist/commands/logout.js +37 -0
  72. package/dist/commands/node-add.d.ts +7 -0
  73. package/dist/commands/node-add.js +56 -0
  74. package/dist/commands/node.d.ts +19 -0
  75. package/dist/commands/node.js +43 -0
  76. package/dist/commands/prEvents.d.ts +7 -0
  77. package/dist/commands/prEvents.js +32 -0
  78. package/dist/commands/setup.d.ts +15 -0
  79. package/dist/commands/setup.js +35 -0
  80. package/dist/commands/status.d.ts +18 -0
  81. package/dist/commands/status.js +71 -0
  82. package/dist/commands/threads.d.ts +6 -0
  83. package/dist/commands/threads.js +36 -0
  84. package/dist/config.d.ts +71 -0
  85. package/dist/config.js +121 -0
  86. package/dist/context.d.ts +26 -0
  87. package/dist/context.js +31 -0
  88. package/dist/crypto.d.ts +7 -0
  89. package/dist/crypto.js +50 -0
  90. package/dist/machine.d.ts +66 -0
  91. package/dist/machine.js +103 -0
  92. package/dist/node/cli.d.ts +25 -0
  93. package/dist/node/cli.js +130 -0
  94. package/dist/node/engine.d.ts +47 -0
  95. package/dist/node/engine.js +463 -0
  96. package/dist/node/ingress.d.ts +102 -0
  97. package/dist/node/ingress.js +473 -0
  98. package/dist/node/layout.d.ts +56 -0
  99. package/dist/node/layout.js +55 -0
  100. package/dist/node/leave.d.ts +8 -0
  101. package/dist/node/leave.js +32 -0
  102. package/dist/node/lock.d.ts +19 -0
  103. package/dist/node/lock.js +99 -0
  104. package/dist/node/modelAccess.d.ts +2 -0
  105. package/dist/node/modelAccess.js +44 -0
  106. package/dist/node/repair.d.ts +28 -0
  107. package/dist/node/repair.js +78 -0
  108. package/dist/node/services.d.ts +58 -0
  109. package/dist/node/services.js +171 -0
  110. package/dist/node/state.d.ts +127 -0
  111. package/dist/node/state.js +95 -0
  112. package/dist/node/steps.d.ts +74 -0
  113. package/dist/node/steps.js +158 -0
  114. package/dist/node/supervisor.d.ts +22 -0
  115. package/dist/node/supervisor.js +95 -0
  116. package/dist/node/tick.d.ts +47 -0
  117. package/dist/node/tick.js +278 -0
  118. package/dist/node/toolchain.d.ts +50 -0
  119. package/dist/node/toolchain.js +230 -0
  120. package/dist/nodeContract.d.ts +101 -0
  121. package/dist/nodeContract.js +192 -0
  122. package/dist/package.d.ts +3 -0
  123. package/dist/package.js +5 -0
  124. package/dist/prEvents.d.ts +109 -0
  125. package/dist/prEvents.js +374 -0
  126. package/dist/run.d.ts +19 -0
  127. package/dist/run.js +487 -0
  128. package/dist/specs/device-client.json +920 -0
  129. package/dist/threads.d.ts +88 -0
  130. package/dist/threads.js +268 -0
  131. package/dist/version.d.ts +1 -0
  132. package/dist/version.js +1 -0
  133. package/package.json +33 -7
  134. package/bin/hive.js +0 -2
@@ -0,0 +1,374 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { link, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { t3StatePath, threadWireId } from "./threads.js";
6
+ export const PR_EVENTS_PATH = '/api/v0/hivecode/pr-events';
7
+ export const LEDGER_FILE = 'pr-events.json';
8
+ export const LOCK_FILE = 'pr-events.lock';
9
+ export const PAGE_LIMIT = 50;
10
+ export const MAX_SENDS = 20;
11
+ export const MAX_FAILS_IN_A_ROW = 3;
12
+ export const MAX_RETRIES = 200;
13
+ export const GIVE_UP_ATTEMPTS = 10;
14
+ export const GIVE_UP_AFTER_MS = 24 * 3600 * 1000;
15
+ export const FIRST_RUN_MAX_AGE_MS = 3600 * 1000;
16
+ /** A thread id as Hive lists it: the relay's `threadWireId` of the T3 Code id. It may hold a colon, as `mcp:<uuid>` and `<id>:fork` do. */
17
+ const WIRE_ID = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,79}$/;
18
+ /** A T3 Code thread id as the local server knows it, such as `mcp:launch:<hex>`. It never starts with `-`. */
19
+ export const NATIVE_ID = /^[A-Za-z0-9][A-Za-z0-9:._-]{0,199}$/;
20
+ const BUSY = ['queued', 'preparing', 'starting', 'running', 'waiting'];
21
+ /** A failed send waits this long after its last attempt before it is checked and sent again, so one that lands late is seen. */
22
+ export const RESEND_AFTER_MS = 2 * 60_000;
23
+ export const MAX_CLAIMS = 5000;
24
+ export const LIMITS = { passMs: 45_000, sendMs: 30_000, minSendMs: 5_000 };
25
+ export function prEventsEnabled(env) {
26
+ return env.HIVE_PR_EVENTS === 'on';
27
+ }
28
+ function oneLine(text, max) {
29
+ return [...text.replace(/[\x00-\x1F\x7F]+/g, ' ').replace(/\s+/g, ' ').trim()].slice(0, max).join('');
30
+ }
31
+ export function messageFor(event) {
32
+ const reason = event.reason === null ? '' : oneLine(event.reason, 120);
33
+ return `[hive pr-event] #${event.number} ${event.kind} at ${event.head_sha.slice(0, 8)}${reason === '' ? '' : ` (${reason})`} - act per your chain rules.`;
34
+ }
35
+ function parseEvent(raw) {
36
+ if (typeof raw !== 'object' || raw === null)
37
+ return null;
38
+ const e = raw;
39
+ if (!Number.isSafeInteger(e.id) || e.id < 1)
40
+ return null;
41
+ if (!Number.isSafeInteger(e.number) || e.number < 1)
42
+ return null;
43
+ if (typeof e.kind !== 'string' || !/^[a-z_]{1,32}$/.test(e.kind))
44
+ return null;
45
+ if (typeof e.head_sha !== 'string' || !/^[0-9a-f]{7,64}$/i.test(e.head_sha))
46
+ return null;
47
+ const threads = Array.isArray(e.threads) ? [...new Set(e.threads.filter((t) => typeof t === 'string' && WIRE_ID.test(t)))] : [];
48
+ return {
49
+ id: e.id,
50
+ repo: typeof e.repo === 'string' ? oneLine(e.repo, 200) : '',
51
+ number: e.number,
52
+ head_sha: e.head_sha,
53
+ kind: e.kind,
54
+ reason: typeof e.reason === 'string' && e.reason.trim() !== '' ? e.reason : null,
55
+ occurred_at: typeof e.occurred_at === 'string' ? e.occurred_at : '',
56
+ threads,
57
+ };
58
+ }
59
+ function loadLedger(saved, now) {
60
+ const startedAt = typeof saved?.started_at === 'string' && !Number.isNaN(Date.parse(saved.started_at)) ? saved.started_at : now.toISOString();
61
+ return {
62
+ cursor: Number.isSafeInteger(saved?.cursor) ? saved.cursor : 0,
63
+ started_at: startedAt,
64
+ delivered: typeof saved?.delivered === 'object' && saved.delivered !== null ? saved.delivered : {},
65
+ claimed: Array.isArray(saved?.claimed) ? saved.claimed.filter((c) => typeof c?.native === 'string' && typeof c.id === 'string' && typeof c.at === 'string') : [],
66
+ retries: Array.isArray(saved?.retries) ? saved.retries.filter((r) => typeof r?.native === 'string' && NATIVE_ID.test(r.native) && typeof r.thread === 'string' && typeof r.message === 'string') : [],
67
+ };
68
+ }
69
+ /**
70
+ * Reads the T3 Code projection read-only. Hive lists threads by the relay's wire id, so each one is mapped back to the
71
+ * native id here. `matches` lists the ids of user messages in a thread with the given text, oldest first, which covers
72
+ * a queued message too, since T3 Code records it with its queued run.
73
+ */
74
+ async function openLocal(dbPath) {
75
+ const { DatabaseSync } = await import('node:sqlite');
76
+ const db = new DatabaseSync(dbPath, { readOnly: true });
77
+ try {
78
+ db.exec('PRAGMA busy_timeout = 2000; PRAGMA query_only = 1;');
79
+ const byWire = new Map();
80
+ for (const row of db.prepare('SELECT thread_id FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL').all()) {
81
+ if (typeof row.thread_id === 'string' && NATIVE_ID.test(row.thread_id))
82
+ byWire.set(threadWireId(row.thread_id), row.thread_id);
83
+ }
84
+ const message = db.prepare("SELECT message_id FROM orchestration_v2_projection_messages WHERE thread_id = ? AND role = 'user' AND created_at >= ? AND trim(json_extract(payload_json, '$.text')) = ? ORDER BY created_at, message_id LIMIT 100");
85
+ const busy = db.prepare(`SELECT 1 FROM orchestration_v2_projection_runs WHERE thread_id = ? AND status IN (${BUSY.map(() => '?').join(', ')}) LIMIT 1`);
86
+ return {
87
+ resolve: (wire) => byWire.get(wire) ?? null,
88
+ matches: (native, text, since) => message.all(native, since, text).map((row) => row.message_id),
89
+ busy: (native) => busy.get(native, ...BUSY) !== undefined,
90
+ close: () => db.close(),
91
+ };
92
+ }
93
+ catch (error) {
94
+ db.close();
95
+ throw error;
96
+ }
97
+ }
98
+ /**
99
+ * One pass at a time per config directory. The lock is written whole (a temp file linked into place), so a reader
100
+ * never sees it half-written. A lock is stale when its process is gone, when it names this process, or when it is
101
+ * older than a pass can run. Release removes the lock only while it is still this pass's.
102
+ */
103
+ async function lock(dir, staleMs) {
104
+ const path = join(dir, LOCK_FILE);
105
+ await mkdir(dir, { recursive: true, mode: 0o700 });
106
+ const token = `${process.pid} ${randomBytes(8).toString('hex')}`;
107
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}`;
108
+ await writeFile(temp, token, { mode: 0o600 });
109
+ try {
110
+ for (let attempt = 0; attempt < 3; attempt++) {
111
+ try {
112
+ await link(temp, path);
113
+ return async () => {
114
+ if ((await readFile(path, 'utf8').catch(() => '')) === token)
115
+ await rm(path, { force: true });
116
+ };
117
+ }
118
+ catch (error) {
119
+ if (error.code !== 'EEXIST')
120
+ throw error;
121
+ }
122
+ const [held, info] = await Promise.all([readFile(path, 'utf8').catch(() => null), stat(path).catch(() => null)]);
123
+ if (held === null || info === null)
124
+ continue;
125
+ const pid = Number(held.split(' ')[0]);
126
+ const fresh = Date.now() - info.mtimeMs < staleMs;
127
+ if (fresh && Number.isSafeInteger(pid) && pid > 0 && pid !== process.pid && alive(pid))
128
+ return null;
129
+ await rm(path, { force: true });
130
+ }
131
+ return null;
132
+ }
133
+ finally {
134
+ await rm(temp, { force: true });
135
+ }
136
+ }
137
+ function alive(pid) {
138
+ try {
139
+ process.kill(pid, 0);
140
+ return true;
141
+ }
142
+ catch (error) {
143
+ return error.code === 'EPERM';
144
+ }
145
+ }
146
+ /**
147
+ * One bounded pass, under a lock. Retries go first: a retry is done if its message is already in the thread, waits
148
+ * while the thread is busy, and is sent again only to a settled thread without it. Then new events are pulled after
149
+ * the cursor and sent to each listed thread on this node. A pending retry is saved before every send and removed after
150
+ * it succeeds. The cursor moves past an event once each of its threads was sent it, is in `retries`, or is not on this
151
+ * node. The pass stops before a send that would run past its deadline, on shutdown, after MAX_SENDS sends, or after
152
+ * MAX_FAILS_IN_A_ROW failures, and then holds the cursor before the event it stopped in.
153
+ */
154
+ export async function pullPrEvents(deps, node, key, options = {}) {
155
+ const dryRun = options.dryRun === true;
156
+ const dbPath = t3StatePath(deps.env);
157
+ if (dbPath === null)
158
+ throw new Error('No T3 Code state found. Set HIVE_T3_HOME to the T3 Code home, the directory that holds userdata/statev2.sqlite.');
159
+ const unlock = dryRun ? async () => { } : await lock(deps.store.dir, (deps.limits ?? LIMITS).passMs + 60_000);
160
+ if (unlock === null) {
161
+ deps.io.err('Another PR event pass is running here, so this one was skipped.');
162
+ return { events: 0, sent: 0, failed: 0, cursor: -1, retries: 0, skipped: 'locked' };
163
+ }
164
+ const local = await openLocal(dbPath).catch(async (error) => {
165
+ await unlock();
166
+ throw error;
167
+ });
168
+ try {
169
+ return await pass(deps, node, key, local, dryRun, options.signal);
170
+ }
171
+ finally {
172
+ local.close();
173
+ await unlock();
174
+ }
175
+ }
176
+ async function pass(deps, node, key, local, dryRun, signal) {
177
+ const limits = deps.limits ?? LIMITS;
178
+ const deadline = Date.now() + limits.passMs;
179
+ const ledger = loadLedger(await deps.store.read(LEDGER_FILE), deps.now());
180
+ const transport = deps.transport ?? t3Transport(deps.env);
181
+ const save = async () => {
182
+ if (!dryRun)
183
+ await deps.store.write(LEDGER_FILE, ledger);
184
+ };
185
+ let sent = 0;
186
+ let failed = 0;
187
+ let failsInARow = 0;
188
+ let calls = 0;
189
+ const stop = () => calls >= MAX_SENDS || failsInARow >= MAX_FAILS_IN_A_ROW || signal?.aborted === true || deadline - Date.now() < limits.minSendMs;
190
+ const budget = () => Math.min(limits.sendMs, deadline - Date.now());
191
+ const detail = (error) => (error instanceof Error ? error.message : String(error));
192
+ const drop = (retry) => {
193
+ ledger.retries = ledger.retries.filter((r) => r !== retry);
194
+ };
195
+ const claimedIds = new Set(ledger.claimed.map((c) => `${c.native}\n${c.id}`));
196
+ const claim = (native, id) => {
197
+ claimedIds.add(`${native}\n${id}`);
198
+ ledger.claimed.push({ native, id, at: deps.now().toISOString() });
199
+ };
200
+ /** The oldest message with this text since `since` that no confirmed send or earlier retry accounts for. */
201
+ const unclaimed = (native, text, since) => local.matches(native, text, since).find((id) => !claimedIds.has(`${native}\n${id}`));
202
+ const attempt = async (retry) => {
203
+ calls += 1;
204
+ const started = new Date(deps.now().getTime() - 1000).toISOString();
205
+ retry.last_at = deps.now().toISOString();
206
+ try {
207
+ const result = await transport.send(retry.native, retry.message, budget());
208
+ const id = result.messageId ?? unclaimed(retry.native, retry.message, started);
209
+ if (id !== undefined)
210
+ claim(retry.native, id);
211
+ if (result.delivery === 'steered' || result.delivery === 'restarted')
212
+ deps.io.err(`PR event ${retry.event_id} to thread ${retry.native}: T3 Code reported ${result.delivery}, not queued.`);
213
+ drop(retry);
214
+ sent += 1;
215
+ failsInARow = 0;
216
+ }
217
+ catch (error) {
218
+ failed += 1;
219
+ failsInARow += 1;
220
+ retry.count += 1;
221
+ if (retry.count >= GIVE_UP_ATTEMPTS && deps.now().getTime() - Date.parse(retry.first_at) >= GIVE_UP_AFTER_MS) {
222
+ deps.io.err(`PR event ${retry.event_id} to thread ${retry.native} failed ${retry.count} times since ${retry.first_at}, giving up: ${detail(error)}`);
223
+ drop(retry);
224
+ }
225
+ else {
226
+ deps.io.err(`PR event ${retry.event_id} to thread ${retry.native} failed, will check and retry: ${detail(error)}`);
227
+ }
228
+ }
229
+ await save();
230
+ };
231
+ if (!dryRun) {
232
+ const ordered = [...ledger.retries].sort((a, b) => a.first_at.localeCompare(b.first_at) || a.event_id - b.event_id);
233
+ for (const retry of ordered) {
234
+ const since = new Date(Date.parse(retry.first_at) - 60_000).toISOString();
235
+ const found = unclaimed(retry.native, retry.message, since);
236
+ if (found !== undefined) {
237
+ claim(retry.native, found);
238
+ drop(retry);
239
+ await save();
240
+ }
241
+ else if (!local.busy(retry.native) && deps.now().getTime() - Date.parse(retry.last_at ?? retry.first_at) >= RESEND_AFTER_MS) {
242
+ if (stop())
243
+ break;
244
+ await attempt(retry);
245
+ }
246
+ }
247
+ }
248
+ const page = await deps.api.json('GET', PR_EVENTS_PATH, {
249
+ query: { after: String(ledger.cursor), limit: String(PAGE_LIMIT) },
250
+ token: node.token,
251
+ key,
252
+ timeoutMs: Math.max(1000, deadline - Date.now()),
253
+ ...(signal ? { signal } : {}),
254
+ });
255
+ const raw = Array.isArray(page.events) ? page.events : [];
256
+ const events = raw.map(parseEvent).filter((e) => e !== null && e.id > ledger.cursor).sort((a, b) => a.id - b.id);
257
+ let stopped = false;
258
+ let cursor = ledger.cursor;
259
+ for (const event of events) {
260
+ const id = String(event.id);
261
+ const done = new Set(ledger.delivered[id] ?? []);
262
+ const stale = Date.parse(event.occurred_at) < Date.parse(ledger.started_at) - FIRST_RUN_MAX_AGE_MS;
263
+ const message = messageFor(event);
264
+ for (const thread of stale ? [] : event.threads) {
265
+ if (done.has(thread))
266
+ continue;
267
+ const native = local.resolve(thread);
268
+ if (native === null) {
269
+ deps.io.err(`PR event ${event.id}: thread ${thread} is not in this machine's T3 Code, skipped.`);
270
+ }
271
+ else if (dryRun) {
272
+ deps.io.out(`Would send to ${native}: ${message}`);
273
+ continue;
274
+ }
275
+ else if (stop()) {
276
+ stopped = true;
277
+ break;
278
+ }
279
+ done.add(thread);
280
+ if (dryRun)
281
+ continue;
282
+ ledger.delivered[id] = [...done];
283
+ if (native === null) {
284
+ await save();
285
+ continue;
286
+ }
287
+ const retry = { event_id: event.id, thread, native, message, count: 0, first_at: deps.now().toISOString() };
288
+ ledger.retries.push(retry);
289
+ await save();
290
+ await attempt(retry);
291
+ }
292
+ if (stopped)
293
+ break;
294
+ if (!dryRun)
295
+ cursor = event.id;
296
+ }
297
+ const next = page.next_cursor;
298
+ if (!stopped && !dryRun && Number.isSafeInteger(next) && next > cursor)
299
+ cursor = next;
300
+ if (!dryRun) {
301
+ ledger.cursor = cursor;
302
+ for (const id of Object.keys(ledger.delivered))
303
+ if (Number(id) <= cursor)
304
+ delete ledger.delivered[id];
305
+ const keepFrom = Math.min(deps.now().getTime(), ...ledger.retries.map((r) => Date.parse(r.first_at))) - 2 * 3600 * 1000;
306
+ ledger.claimed = ledger.claimed.filter((c) => Date.parse(c.at) >= keepFrom).slice(-MAX_CLAIMS);
307
+ if (ledger.retries.length > MAX_RETRIES) {
308
+ for (const dropped of ledger.retries.splice(0, ledger.retries.length - MAX_RETRIES))
309
+ deps.io.err(`PR event ${dropped.event_id} to thread ${dropped.native} dropped: more than ${MAX_RETRIES} retries are waiting.`);
310
+ }
311
+ await save();
312
+ }
313
+ return { events: events.length, sent, failed, cursor, retries: ledger.retries.length };
314
+ }
315
+ /**
316
+ * Sends through the `t3 thread send` CLI that ships with T3 Code. Each call signs in to the running server with the
317
+ * server's own local auth and revokes that session after, so no token passes through this process. A busy thread gets
318
+ * the message queued as its next turn and is never steered or interrupted.
319
+ */
320
+ export function t3Transport(env) {
321
+ const bin = env.HIVE_T3_BIN && env.HIVE_T3_BIN !== '' ? env.HIVE_T3_BIN : 't3';
322
+ const base = env.HIVE_T3_HOME && env.HIVE_T3_HOME !== '' ? ['--base-dir', env.HIVE_T3_HOME] : [];
323
+ let modeFlag = null;
324
+ return {
325
+ async send(nativeId, message, timeoutMs) {
326
+ if (!NATIVE_ID.test(nativeId))
327
+ throw new Error('The thread id is not one T3 Code issues.');
328
+ const started = Date.now();
329
+ if (modeFlag === null) {
330
+ const help = await runT3(bin, ['thread', 'send', '--help'], '', env, Math.min(10_000, timeoutMs));
331
+ // Where `--mode` exists its default can steer a running turn, so ask for queue. Without it, only a `t3` that
332
+ // says it queues (as T3 Code 0.1.9 does, with `mode: "queue"` built in) is used.
333
+ modeFlag = /--mode\b/.test(help) ? ['--mode', 'queue'] : /nothing is interrupted/i.test(help) ? [] : 'unsafe';
334
+ }
335
+ if (modeFlag === 'unsafe')
336
+ throw new Error(`${bin} thread send has no --mode and does not say it queues, so it could steer a running turn. Update T3 Code.`);
337
+ const out = await runT3(bin, ['thread', 'send', ...base, ...modeFlag, '--json', nativeId, '-'], message, env, Math.max(1000, timeoutMs - (Date.now() - started)));
338
+ let parsed = {};
339
+ try {
340
+ parsed = JSON.parse(out);
341
+ }
342
+ catch {
343
+ parsed = {};
344
+ }
345
+ return { messageId: typeof parsed.messageId === 'string' ? parsed.messageId : null, delivery: typeof parsed.delivery === 'string' ? parsed.delivery : null };
346
+ },
347
+ };
348
+ }
349
+ function runT3(bin, args, input, env, timeoutMs) {
350
+ return new Promise((resolve, reject) => {
351
+ const child = spawn(bin, args, { env, stdio: ['pipe', 'pipe', 'pipe'], timeout: timeoutMs });
352
+ let out = '';
353
+ let err = '';
354
+ child.stdout.on('data', (chunk) => {
355
+ if (out.length < 1_048_576)
356
+ out += chunk.toString('utf8');
357
+ });
358
+ child.stderr.on('data', (chunk) => {
359
+ if (err.length < 4096)
360
+ err += chunk.toString('utf8');
361
+ });
362
+ child.on('error', (error) => reject(new Error(`Could not run ${bin}: ${error.message}`)));
363
+ child.on('close', (code, signal) => {
364
+ if (code === 0)
365
+ resolve(out);
366
+ else if (signal !== null)
367
+ reject(new Error(`${bin} ${args[1]} timed out after ${timeoutMs}ms`));
368
+ else
369
+ reject(new Error(`${bin} ${args[1]} exited ${code}${err.trim() === '' ? '' : `: ${oneLine(err, 300)}`}`));
370
+ });
371
+ child.stdin.on('error', () => { });
372
+ child.stdin.end(input);
373
+ });
374
+ }
package/dist/run.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { type SetupDeps } from './bootstrap/types.ts';
2
+ import { type Context, type Io } from './context.ts';
3
+ import type { Fetch } from './api.ts';
4
+ import { VERSION } from './version.ts';
5
+ export { VERSION };
6
+ export type Overrides = {
7
+ imdsFetch?: Fetch;
8
+ fetch?: Fetch;
9
+ sleep?: Context['sleep'];
10
+ now?: Context['now'];
11
+ registrationTimeoutMs?: number;
12
+ random?: () => number;
13
+ setup?: Partial<SetupDeps>;
14
+ };
15
+ export declare function parseFlags(args: string[]): {
16
+ flags: Map<string, string | true>;
17
+ positional: string[];
18
+ };
19
+ export declare function run(argv: string[], env: NodeJS.ProcessEnv, io: Io, signal: AbortSignal, overrides?: Overrides): Promise<number>;