@overcy/hive 0.0.0-stage → 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 (133) hide show
  1. package/README.md +213 -2
  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 +35 -4
@@ -0,0 +1,88 @@
1
+ import type { KeyFile, NodeFile, Store } from './config.ts';
2
+ import type { Api } from './api.ts';
3
+ export declare const THREADS_PATH = "/api/v0/hivecode/threads";
4
+ export declare const MAX_THREADS = 200;
5
+ export declare const MAX_BYTES = 262144;
6
+ export declare const SENT_FILE = "threads.json";
7
+ export type ThreadStatus = 'queued' | 'running' | 'idle' | 'waiting' | 'review' | 'error' | 'completed';
8
+ export type ThreadSummary = {
9
+ id: string;
10
+ project: {
11
+ key: string;
12
+ name: string;
13
+ };
14
+ title: string;
15
+ status: ThreadStatus;
16
+ waiting_on_user: boolean;
17
+ last_activity_at: string;
18
+ pr: {
19
+ number: number;
20
+ url: string;
21
+ title?: string;
22
+ } | null;
23
+ };
24
+ export type ThreadBatch = {
25
+ threads: ThreadSummary[];
26
+ removed: string[];
27
+ stream_origin?: string | null;
28
+ };
29
+ export type T3ThreadRow = {
30
+ thread_id: string;
31
+ project_id: string;
32
+ project_title: string | null;
33
+ title: string;
34
+ updated_at: string;
35
+ payload_json: string;
36
+ run_status: string | null;
37
+ run_at: string | null;
38
+ pending: number;
39
+ };
40
+ type Columns = {
41
+ prepare(sql: string): {
42
+ all(...params: string[]): unknown[];
43
+ };
44
+ };
45
+ /** The tables and columns of `spec` (the relay's by default) that this T3 Code database lacks, as `table` or `table.column`. */
46
+ export declare function missingT3Columns(db: Columns, spec?: Readonly<Record<string, readonly string[]>>): string[];
47
+ export declare function findT3State(env: NodeJS.ProcessEnv): string | null;
48
+ /** The T3 Code projection under HIVE_T3_HOME (default ~/.t3), whatever HIVE_THREADS says. */
49
+ export declare function t3StatePath(env: NodeJS.ProcessEnv): string | null;
50
+ export declare function readT3Threads(dbPath: string, limit?: number): Promise<T3ThreadRow[]>;
51
+ export declare function wireId(raw: string, max: number): string;
52
+ /**
53
+ * A thread id on the wire. It is the T3 Code id itself when Hive accepts it, so a thread that an agent launches
54
+ * (`mcp:<uuid>`) or forks (`<id>:fork`) keeps its real id and the ingress, the stream token and the page agree on it.
55
+ * Hive's ingest allows a colon after the first character. Anything else it would refuse is hashed as `wireId` does.
56
+ */
57
+ export declare function threadWireId(raw: string): string;
58
+ export declare function toSummary(row: T3ThreadRow, now: Date): ThreadSummary;
59
+ export declare function streamOriginFrom(env: NodeJS.ProcessEnv): string | null | undefined;
60
+ export declare function buildBatch(rows: readonly T3ThreadRow[], previous: readonly string[], now: Date, streamOrigin?: string | null): {
61
+ batch: ThreadBatch;
62
+ remember: string[];
63
+ };
64
+ export type RelayDeps = {
65
+ env: NodeJS.ProcessEnv;
66
+ store: Store;
67
+ api: Api;
68
+ now: () => Date;
69
+ };
70
+ export type Collected = {
71
+ batch: ThreadBatch;
72
+ remember: string[];
73
+ };
74
+ export type RelayResult = {
75
+ kind: 'absent';
76
+ } | {
77
+ kind: 'sent';
78
+ threads: number;
79
+ removed: number;
80
+ response: Record<string, unknown>;
81
+ };
82
+ /**
83
+ * `origin` is the stream origin to publish. `undefined` falls back to `HIVE_T3_STREAM_ORIGIN`. On a node the ingress
84
+ * step decides it from desired state.
85
+ */
86
+ export declare function collectThreads(deps: Omit<RelayDeps, 'api'>, origin?: string | null): Promise<Collected | null>;
87
+ export declare function relayThreads(deps: RelayDeps, node: NodeFile, key: KeyFile, signal?: AbortSignal, origin?: string | null): Promise<RelayResult>;
88
+ export {};
@@ -0,0 +1,268 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ export const THREADS_PATH = '/api/v0/hivecode/threads';
5
+ export const MAX_THREADS = 200;
6
+ export const MAX_BYTES = 262_144;
7
+ export const SENT_FILE = 'threads.json';
8
+ const RUN_STATUS = {
9
+ queued: 'queued',
10
+ preparing: 'running',
11
+ starting: 'running',
12
+ running: 'running',
13
+ waiting: 'waiting',
14
+ failed: 'error',
15
+ };
16
+ const THREADS_SQL = `
17
+ WITH RECURSIVE asks(thread_id, kind) AS (
18
+ SELECT q.thread_id, CASE WHEN q.kind = 'user_input' AND json_extract(q.payload_json, '$.userOnly') = 1 THEN 'user_only' ELSE q.kind END
19
+ FROM orchestration_v2_projection_runtime_requests q
20
+ JOIN orchestration_v2_projection_threads o ON o.thread_id = q.thread_id
21
+ WHERE q.status = 'pending' AND q.kind <> 'auth_refresh'
22
+ AND (coalesce(json_extract(o.payload_json, '$.lineage.relationshipToParent'), '') <> 'subagent'
23
+ OR coalesce(json_extract(o.payload_json, '$.lineage.sideChat'), 0) = 1
24
+ OR EXISTS (SELECT 1 FROM orchestration_v2_projection_runs r WHERE r.thread_id = o.thread_id AND r.status IN ('preparing', 'starting', 'running', 'waiting')))
25
+ UNION
26
+ SELECT json_extract(c.payload_json, '$.lineage.parentThreadId'),
27
+ CASE WHEN json_extract(c.payload_json, '$.lineage.sideChat') = 1 AND a.kind = 'user_input' THEN 'user_only' ELSE a.kind END
28
+ FROM asks a JOIN orchestration_v2_projection_threads c ON c.thread_id = a.thread_id
29
+ WHERE json_extract(c.payload_json, '$.lineage.parentThreadId') IS NOT NULL
30
+ AND (json_extract(c.payload_json, '$.lineage.sideChat') = 1
31
+ OR (json_extract(c.payload_json, '$.lineage.relationshipToParent') = 'subagent' AND a.kind <> 'user_input'))
32
+ ),
33
+ listed AS (
34
+ SELECT t.thread_id, t.project_id, p.title AS project_title, t.title, t.updated_at, t.payload_json,
35
+ (SELECT r.status FROM orchestration_v2_projection_runs r WHERE r.thread_id = t.thread_id ORDER BY r.ordinal DESC LIMIT 1) AS run_status,
36
+ (SELECT max(coalesce(r.completed_at, r.requested_at)) FROM orchestration_v2_projection_runs r WHERE r.thread_id = t.thread_id) AS run_at,
37
+ (SELECT count(*) FROM asks a WHERE a.thread_id = t.thread_id) AS pending
38
+ FROM orchestration_v2_projection_threads t
39
+ LEFT JOIN projection_projects p ON p.project_id = t.project_id
40
+ WHERE t.archived_at IS NULL AND t.deleted_at IS NULL
41
+ AND coalesce(json_extract(t.payload_json, '$.lineage.relationshipToParent'), '') <> 'subagent'
42
+ AND coalesce(json_extract(t.payload_json, '$.lineage.sideChat'), 0) <> 1
43
+ )
44
+ SELECT thread_id, project_id, project_title, title, updated_at, payload_json, run_status, run_at, pending
45
+ FROM (
46
+ SELECT listed.*,
47
+ run_status IN ('queued', 'preparing', 'starting', 'running', 'waiting')
48
+ OR NOT (coalesce(json_extract(payload_json, '$.settledOverride'), '') = 'settled'
49
+ OR (json_type(payload_json, '$.settledAt') IS 'text'
50
+ AND (json_type(payload_json, '$.unsettledAt') IS NOT 'text' OR json_extract(payload_json, '$.unsettledAt') < json_extract(payload_json, '$.settledAt')))) AS open_work
51
+ FROM listed
52
+ )
53
+ ORDER BY
54
+ CASE
55
+ WHEN open_work AND lower(trim(coalesce(project_title, ''))) NOT IN ('', 'no project') THEN 0
56
+ WHEN open_work THEN 1
57
+ WHEN EXISTS (SELECT 1 FROM json_each(payload_json, '$.pullRequests') pr WHERE json_extract(pr.value, '$.snapshot.state') = 'open') THEN 2
58
+ ELSE 3
59
+ END,
60
+ updated_at DESC
61
+ LIMIT ?`;
62
+ /** The T3 Code projection columns the relay reads. A T3 upgrade that drops one stops the relay with a clear error instead of a wrong batch. */
63
+ const T3_COLUMNS = {
64
+ orchestration_v2_projection_threads: ['thread_id', 'project_id', 'title', 'updated_at', 'archived_at', 'deleted_at', 'payload_json'],
65
+ projection_projects: ['project_id', 'title'],
66
+ orchestration_v2_projection_runs: ['thread_id', 'ordinal', 'status', 'requested_at', 'completed_at'],
67
+ orchestration_v2_projection_runtime_requests: ['thread_id', 'kind', 'status', 'payload_json'],
68
+ };
69
+ /** The tables and columns of `spec` (the relay's by default) that this T3 Code database lacks, as `table` or `table.column`. */
70
+ export function missingT3Columns(db, spec = T3_COLUMNS) {
71
+ const missing = [];
72
+ for (const [table, columns] of Object.entries(spec)) {
73
+ const present = new Set(db.prepare('SELECT name FROM pragma_table_info(?)').all(table).map((column) => column.name));
74
+ if (present.size === 0) {
75
+ missing.push(table);
76
+ continue;
77
+ }
78
+ for (const column of columns)
79
+ if (!present.has(column))
80
+ missing.push(`${table}.${column}`);
81
+ }
82
+ return missing;
83
+ }
84
+ export function findT3State(env) {
85
+ return env.HIVE_THREADS === 'off' ? null : t3StatePath(env);
86
+ }
87
+ /** The T3 Code projection under HIVE_T3_HOME (default ~/.t3), whatever HIVE_THREADS says. */
88
+ export function t3StatePath(env) {
89
+ const base = env.HIVE_T3_HOME && env.HIVE_T3_HOME !== '' ? env.HIVE_T3_HOME : env.HOME && env.HOME !== '' ? join(env.HOME, '.t3') : null;
90
+ if (base === null)
91
+ return null;
92
+ for (const candidate of [join(base, 'userdata', 'statev2.sqlite'), join(base, 'statev2.sqlite')]) {
93
+ // An empty file is the database the node supervisor creates at 0660 before the engine's first start. It has no tables yet.
94
+ if (existsSync(candidate) && statSync(candidate).size > 0)
95
+ return candidate;
96
+ }
97
+ return null;
98
+ }
99
+ export async function readT3Threads(dbPath, limit = MAX_THREADS) {
100
+ let sqlite;
101
+ try {
102
+ sqlite = await import('node:sqlite');
103
+ }
104
+ catch {
105
+ throw new Error(`Relaying T3 Code threads needs node:sqlite, in Node 22.13 or later. This is Node ${process.versions.node}.`);
106
+ }
107
+ const { DatabaseSync } = sqlite;
108
+ const db = new DatabaseSync(dbPath, { readOnly: true });
109
+ try {
110
+ db.exec('PRAGMA busy_timeout = 2000; PRAGMA query_only = 1;');
111
+ const missing = missingT3Columns(db);
112
+ if (missing.length > 0) {
113
+ throw new Error(`T3 Code's state database changed shape (missing ${missing.join(', ')}), so no threads were relayed. Update @overcy/hive to a version that reads this T3 Code.`);
114
+ }
115
+ return db.prepare(THREADS_SQL).all(limit);
116
+ }
117
+ finally {
118
+ db.close();
119
+ }
120
+ }
121
+ export function wireId(raw, max) {
122
+ if (raw.length <= max && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(raw))
123
+ return raw;
124
+ const digest = createHash('sha256').update(raw).digest('hex').slice(0, 16);
125
+ const prefix = raw.replace(/[^A-Za-z0-9_-]/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, max - digest.length - 1);
126
+ return prefix === '' ? digest : `${prefix}-${digest}`;
127
+ }
128
+ /**
129
+ * A thread id on the wire. It is the T3 Code id itself when Hive accepts it, so a thread that an agent launches
130
+ * (`mcp:<uuid>`) or forks (`<id>:fork`) keeps its real id and the ingress, the stream token and the page agree on it.
131
+ * Hive's ingest allows a colon after the first character. Anything else it would refuse is hashed as `wireId` does.
132
+ */
133
+ export function threadWireId(raw) {
134
+ if (raw.length <= 80 && /^[A-Za-z0-9][A-Za-z0-9:_-]*$/.test(raw))
135
+ return raw;
136
+ const digest = createHash('sha256').update(raw).digest('hex').slice(0, 16);
137
+ const prefix = raw.replace(/[^A-Za-z0-9:_-]/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 80 - digest.length - 1);
138
+ return prefix === '' ? digest : `${prefix}-${digest}`;
139
+ }
140
+ const PR_NUMBER_MAX = 2_147_483_647;
141
+ function ingestablePrUrl(url) {
142
+ if (typeof url !== 'string' || Buffer.byteLength(url) > 500)
143
+ return false;
144
+ try {
145
+ const parsed = new URL(url);
146
+ return parsed.protocol === 'https:' && parsed.hostname !== '' && parsed.username === '' && parsed.password === '';
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ }
152
+ function clean(text, max, fallback) {
153
+ const stripped = (text ?? '').replace(/[\x00-\x1F\x7F]/g, '').trim();
154
+ return stripped === '' ? fallback : [...stripped].slice(0, max).join('');
155
+ }
156
+ function parsePayload(json) {
157
+ try {
158
+ const parsed = JSON.parse(json);
159
+ return typeof parsed === 'object' && parsed !== null ? parsed : {};
160
+ }
161
+ catch {
162
+ return {};
163
+ }
164
+ }
165
+ function isSettled(payload) {
166
+ if (payload.settledOverride === 'settled')
167
+ return true;
168
+ if (typeof payload.settledAt !== 'string')
169
+ return false;
170
+ return typeof payload.unsettledAt !== 'string' || payload.unsettledAt < payload.settledAt;
171
+ }
172
+ function pullRequestOf(payload) {
173
+ const ref = payload.linkedPullRequest ?? payload.branchPullRequest ?? null;
174
+ if (ref === null || typeof ref.number !== 'number' || !Number.isInteger(ref.number) || ref.number < 1 || ref.number > PR_NUMBER_MAX || !ingestablePrUrl(ref.url)) {
175
+ return { pr: null, open: false };
176
+ }
177
+ const snapshot = (payload.pullRequests ?? []).find((candidate) => candidate.number === ref.number && candidate.url === ref.url)?.snapshot;
178
+ const title = typeof snapshot?.title === 'string' && snapshot.title.trim() !== '' ? clean(snapshot.title, 200, '') : undefined;
179
+ return { pr: { number: ref.number, url: ref.url, ...(title ? { title } : {}) }, open: snapshot?.state === 'open' };
180
+ }
181
+ const ACTIVE_RUN = new Set(['queued', 'preparing', 'starting', 'running', 'waiting']);
182
+ /** A settled thread is finished unless a run is active, so a leftover pending request or a failed last run never keeps it open as a lane. */
183
+ function statusOf(row, payload, prOpen) {
184
+ const active = row.run_status !== null && ACTIVE_RUN.has(row.run_status);
185
+ if (!active && isSettled(payload))
186
+ return 'completed';
187
+ if (row.pending > 0)
188
+ return 'waiting';
189
+ const fromRun = row.run_status === null ? undefined : RUN_STATUS[row.run_status];
190
+ if (fromRun)
191
+ return fromRun;
192
+ return prOpen ? 'review' : 'idle';
193
+ }
194
+ function iso(at) {
195
+ const parsed = at === null ? NaN : Date.parse(at);
196
+ return Number.isNaN(parsed) ? 0 : parsed;
197
+ }
198
+ export function toSummary(row, now) {
199
+ const payload = parsePayload(row.payload_json);
200
+ const { pr, open } = pullRequestOf(payload);
201
+ const activity = Math.min(now.getTime(), Math.max(iso(row.updated_at), iso(row.run_at)) || now.getTime());
202
+ const status = statusOf(row, payload, open);
203
+ return {
204
+ id: threadWireId(row.thread_id),
205
+ project: { key: wireId(row.project_id, 64), name: clean(row.project_title, 128, 'No project') },
206
+ title: clean(row.title, 160, 'Untitled thread'),
207
+ status,
208
+ waiting_on_user: row.pending > 0 && status !== 'completed',
209
+ last_activity_at: new Date(activity).toISOString(),
210
+ pr,
211
+ };
212
+ }
213
+ export function streamOriginFrom(env) {
214
+ const configured = env.HIVE_T3_STREAM_ORIGIN;
215
+ if (!configured)
216
+ return undefined;
217
+ if (configured === 'off')
218
+ return null;
219
+ const url = URL.parse(configured);
220
+ if (url?.protocol !== 'https:' || url.origin.length > 200 || (configured !== url.origin && configured !== `${url.origin}/`)) {
221
+ throw new Error('HIVE_T3_STREAM_ORIGIN must be an HTTPS origin (no path, credentials, query or fragment), or off.');
222
+ }
223
+ return url.origin;
224
+ }
225
+ export function buildBatch(rows, previous, now, streamOrigin) {
226
+ const threads = [];
227
+ const origin = streamOrigin === undefined ? {} : { stream_origin: streamOrigin };
228
+ const seen = new Set();
229
+ for (const row of rows) {
230
+ const summary = toSummary(row, now);
231
+ if (seen.has(summary.id))
232
+ continue;
233
+ seen.add(summary.id);
234
+ threads.push(summary);
235
+ if (threads.length === MAX_THREADS)
236
+ break;
237
+ }
238
+ while (threads.length > 0 && Buffer.byteLength(JSON.stringify({ threads, removed: previous.slice(0, MAX_THREADS), ...origin })) > MAX_BYTES) {
239
+ seen.delete(threads.pop().id);
240
+ }
241
+ const gone = [...new Set(previous)].filter((id) => !seen.has(id));
242
+ const removed = gone.slice(0, MAX_THREADS);
243
+ return { batch: { threads, removed, ...origin }, remember: [...seen, ...gone.slice(MAX_THREADS)] };
244
+ }
245
+ /**
246
+ * `origin` is the stream origin to publish. `undefined` falls back to `HIVE_T3_STREAM_ORIGIN`. On a node the ingress
247
+ * step decides it from desired state.
248
+ */
249
+ export async function collectThreads(deps, origin) {
250
+ const streamOrigin = origin === undefined ? streamOriginFrom(deps.env) : origin;
251
+ const dbPath = findT3State(deps.env);
252
+ if (dbPath === null && streamOrigin !== null)
253
+ return null;
254
+ const sent = (await deps.store.read(SENT_FILE))?.ids ?? [];
255
+ if (dbPath === null) {
256
+ return { batch: { threads: [], removed: [], stream_origin: null }, remember: sent };
257
+ }
258
+ return buildBatch(await readT3Threads(dbPath), sent, deps.now(), streamOrigin);
259
+ }
260
+ export async function relayThreads(deps, node, key, signal, origin) {
261
+ const collected = await collectThreads(deps, origin);
262
+ if (collected === null)
263
+ return { kind: 'absent' };
264
+ const { batch, remember } = collected;
265
+ const response = await deps.api.json('POST', THREADS_PATH, { token: node.token, key, body: batch, ...(signal ? { signal } : {}) });
266
+ await deps.store.write(SENT_FILE, { ids: remember });
267
+ return { kind: 'sent', threads: batch.threads.length, removed: batch.removed.length, response };
268
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.2.0";
@@ -0,0 +1 @@
1
+ export const VERSION = '0.2.0';
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@overcy/hive",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Connect a machine to Hive: sign in, report status, see your nodes",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "bin": {
11
+ "hive": "dist/cli.js",
12
+ "overcy-hive": "dist/cli.js"
13
+ },
14
+ "exports": {
15
+ "./bootstrap": {
16
+ "types": "./dist/bootstrap/index.d.ts",
17
+ "default": "./dist/bootstrap/index.js"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.build.json && node -e \"require('node:fs').cpSync('src/specs', 'dist/specs', { recursive: true })\"",
29
+ "prepack": "npm run build",
30
+ "types:check": "tsc --noEmit",
31
+ "test": "node --test \"test/*.test.ts\" \"test/bootstrap/*.test.ts\" \"test/node/*.test.ts\""
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "22.20.5",
35
+ "typescript": "5.9.3"
36
+ }
37
+ }