@akshar5/cohall 0.12.6 → 0.12.7

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.
@@ -0,0 +1,2801 @@
1
+ import {
2
+ AttachmentDirection,
3
+ AttachmentName,
4
+ AuthSession,
5
+ AuthSessionId,
6
+ ClarificationId,
7
+ ConnectionRole,
8
+ Device,
9
+ DeviceId,
10
+ DeviceOperation,
11
+ DeviceOverview,
12
+ DevicePage,
13
+ DeviceUsage,
14
+ Message,
15
+ OperationId,
16
+ PairingCredential,
17
+ PairingResult,
18
+ Provider,
19
+ SocketEvent,
20
+ Task,
21
+ TaskAttachment,
22
+ TaskClarification,
23
+ TaskId,
24
+ TaskInbox,
25
+ TaskInboxItem,
26
+ TaskProgress,
27
+ TaskStatus,
28
+ TaskStatusCounts,
29
+ TaskTrace,
30
+ TaskTraceEvent,
31
+ Thread,
32
+ ThreadContext,
33
+ ThreadId,
34
+ Timestamp,
35
+ UsageSummary,
36
+ assertDeviceOperationSupport,
37
+ assertOwnerToken,
38
+ decodeAnswerTaskInput,
39
+ decodeCreatePairingInput,
40
+ decodeCreateTaskInput,
41
+ decodeCreateUpgradeOperationsInput,
42
+ decodeExchangePairingInput,
43
+ decodeRequestTaskInput,
44
+ decodeSocketEvent,
45
+ decodeTaskProgressInput,
46
+ isTerminalTask,
47
+ makeAuthSessionId,
48
+ makeDeviceId,
49
+ makeMessageId,
50
+ makeOperationId,
51
+ makeTaskId,
52
+ makeThreadId,
53
+ maxAttachmentBytes,
54
+ maxAuthTokenBytes,
55
+ maxDevicePageDevices,
56
+ maxDevicePageResponseBytes,
57
+ maxSocketPayloadBytes,
58
+ maxTaskAttachments,
59
+ maxTaskClarifications,
60
+ now,
61
+ taskDeadlineError,
62
+ taskDeadlinePassed,
63
+ taskSlot
64
+ } from "./chunk-04a27ybz.js";
65
+ import {
66
+ __export,
67
+ version
68
+ } from "./chunk-7dgeftrk.js";
69
+
70
+ // apps/relay/src/main.ts
71
+ import { Effect as Effect3, ManagedRuntime, Schema as Schema3, Schedule } from "effect";
72
+ import { createHash as createHash2, timingSafeEqual } from "node:crypto";
73
+ import { access as access2, chmod as chmod2 } from "node:fs/promises";
74
+ import { createServer } from "node:http";
75
+ import { platform as platform2 } from "node:os";
76
+ import { posix, win32 } from "node:path";
77
+ import { WebSocketServer } from "ws";
78
+
79
+ // apps/relay/src/config.ts
80
+ import { Effect, Schema } from "effect";
81
+ import { access, chmod, mkdir, readFile, writeFile } from "node:fs/promises";
82
+ import { homedir, platform } from "node:os";
83
+ import { isAbsolute, join, resolve } from "node:path";
84
+ var RelayConfiguration = Schema.Struct({
85
+ host: Schema.NonEmptyString,
86
+ port: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })),
87
+ token: Schema.String.check(Schema.isMinLength(32), Schema.isMaxLength(maxAuthTokenBytes)),
88
+ dataDirectory: Schema.NonEmptyString,
89
+ databasePath: Schema.NonEmptyString,
90
+ allowRemote: Schema.Boolean,
91
+ historyTaskLimit: Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 1e5 }))
92
+ });
93
+ var defaultDataDirectory = () => {
94
+ if (platform() === "win32") {
95
+ return join(process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), "Cohall");
96
+ }
97
+ if (platform() === "darwin") {
98
+ return join(homedir(), "Library", "Application Support", "Cohall", "relay");
99
+ }
100
+ const dataHome = process.env.XDG_DATA_HOME;
101
+ return join(dataHome !== undefined && isAbsolute(dataHome) ? dataHome : join(homedir(), ".local", "share"), "cohall");
102
+ };
103
+ var generatedToken = () => Array.from(crypto.getRandomValues(new Uint8Array(32)), (value) => value.toString(16).padStart(2, "0")).join("");
104
+ var tokenFrom = async (path) => {
105
+ if (await access(path).then(() => true).catch(() => false)) {
106
+ return (await readFile(path, "utf8")).trim();
107
+ }
108
+ const token = generatedToken();
109
+ await writeFile(path, `${token}
110
+ `, { mode: 384 });
111
+ if (platform() !== "win32") {
112
+ await chmod(path, 384);
113
+ }
114
+ return token;
115
+ };
116
+ var booleanEnvironment = (name) => {
117
+ const value = process.env[name];
118
+ if (value === undefined || value === "false" || value === "0") {
119
+ return false;
120
+ }
121
+ if (value === "true" || value === "1") {
122
+ return true;
123
+ }
124
+ throw new Error(`${name} must be true or false`);
125
+ };
126
+ var isLoopback = (host) => host === "127.0.0.1" || host === "localhost" || host === "::1";
127
+ var loadEnvironmentConfiguration = Effect.tryPromise({
128
+ try: async () => {
129
+ const host = process.env.COHALL_RELAY_HOST ?? "127.0.0.1";
130
+ const port = Number(process.env.COHALL_RELAY_PORT ?? "8787");
131
+ const allowRemote = booleanEnvironment("COHALL_RELAY_ALLOW_REMOTE");
132
+ if (!isLoopback(host) && !allowRemote) {
133
+ throw new Error("Remote relay binding is disabled. Use a private network or TLS reverse proxy, then set COHALL_RELAY_ALLOW_REMOTE=true.");
134
+ }
135
+ const dataDirectory = resolve(process.env.COHALL_DATA_DIR ?? defaultDataDirectory());
136
+ await mkdir(dataDirectory, { recursive: true, mode: 448 });
137
+ if (platform() !== "win32") {
138
+ await chmod(dataDirectory, 448);
139
+ }
140
+ const token = process.env.COHALL_TOKEN ?? await tokenFrom(join(dataDirectory, "owner-token"));
141
+ assertOwnerToken(token);
142
+ const historyTaskLimit = Number(process.env.COHALL_HISTORY_TASK_LIMIT ?? "1000");
143
+ return Schema.decodeUnknownSync(RelayConfiguration)({
144
+ host,
145
+ port,
146
+ token,
147
+ dataDirectory,
148
+ databasePath: join(dataDirectory, "cohall.db"),
149
+ allowRemote,
150
+ historyTaskLimit
151
+ });
152
+ },
153
+ catch: (cause) => cause instanceof Error ? cause : new Error(String(cause))
154
+ });
155
+
156
+ // apps/relay/src/hub.ts
157
+ import { WebSocket } from "ws";
158
+
159
+ class Hub {
160
+ #principals = new Map;
161
+ #devices = new Map;
162
+ #deviceIds = new Map;
163
+ #sessions = new Map;
164
+ #ownerSockets = new Set;
165
+ attach(socket, principal) {
166
+ if (principal.sessionId === undefined) {
167
+ if (this.#ownerSockets.size >= 16) {
168
+ return false;
169
+ }
170
+ this.#ownerSockets.add(socket);
171
+ } else {
172
+ const existing = this.#sessions.get(principal.sessionId);
173
+ if (existing !== undefined && existing.readyState === WebSocket.OPEN) {
174
+ return false;
175
+ }
176
+ this.#sessions.set(principal.sessionId, socket);
177
+ }
178
+ this.#principals.set(socket, principal);
179
+ if (socket.data.stageDeadline !== undefined) {
180
+ clearTimeout(socket.data.stageDeadline);
181
+ socket.data.stageDeadline = undefined;
182
+ }
183
+ return true;
184
+ }
185
+ isAuthorized(socket) {
186
+ if (socket.readyState !== WebSocket.OPEN) {
187
+ return false;
188
+ }
189
+ const principal = this.#principals.get(socket);
190
+ if (principal === undefined) {
191
+ return false;
192
+ }
193
+ if (principal.expiresAt !== undefined && Date.parse(principal.expiresAt) <= Date.now()) {
194
+ socket.close(4003, "Session expired");
195
+ return false;
196
+ }
197
+ return true;
198
+ }
199
+ boundDeviceId(socket) {
200
+ return this.#principals.get(socket)?.boundDeviceId;
201
+ }
202
+ registerDevice(deviceId, socket) {
203
+ if (this.#deviceIds.has(socket)) {
204
+ return false;
205
+ }
206
+ const previous = this.#devices.get(deviceId);
207
+ if (previous !== undefined && previous !== socket && previous.readyState === WebSocket.OPEN) {
208
+ return false;
209
+ }
210
+ this.#devices.set(deviceId, socket);
211
+ this.#deviceIds.set(socket, deviceId);
212
+ if (socket.data.stageDeadline !== undefined) {
213
+ clearTimeout(socket.data.stageDeadline);
214
+ socket.data.stageDeadline = undefined;
215
+ }
216
+ return true;
217
+ }
218
+ pendingConnections() {
219
+ return this.#principals.size - this.#deviceIds.size;
220
+ }
221
+ detach(socket) {
222
+ if (socket.data.stageDeadline !== undefined) {
223
+ clearTimeout(socket.data.stageDeadline);
224
+ }
225
+ const principal = this.#principals.get(socket);
226
+ this.#principals.delete(socket);
227
+ this.#ownerSockets.delete(socket);
228
+ if (principal?.sessionId !== undefined && this.#sessions.get(principal.sessionId) === socket) {
229
+ this.#sessions.delete(principal.sessionId);
230
+ }
231
+ const deviceId = this.#deviceIds.get(socket);
232
+ this.#deviceIds.delete(socket);
233
+ if (deviceId === undefined || this.#devices.get(deviceId) !== socket) {
234
+ return;
235
+ }
236
+ this.#devices.delete(deviceId);
237
+ return deviceId;
238
+ }
239
+ deviceId(socket) {
240
+ return this.#deviceIds.get(socket);
241
+ }
242
+ closeSession(sessionId) {
243
+ for (const [socket, principal] of this.#principals) {
244
+ if (principal.sessionId === sessionId) {
245
+ socket.close(4003, "Session revoked");
246
+ }
247
+ }
248
+ }
249
+ closeDevice(deviceId) {
250
+ this.#devices.get(deviceId)?.close(4003, "Device forgotten");
251
+ }
252
+ hasDevice(deviceId) {
253
+ return this.#devices.get(deviceId)?.readyState === WebSocket.OPEN;
254
+ }
255
+ sendToDevice(deviceId, event, beforeSend) {
256
+ const socket = this.#devices.get(deviceId);
257
+ if (socket?.readyState !== WebSocket.OPEN || !this.isAuthorized(socket)) {
258
+ return false;
259
+ }
260
+ const payload = JSON.stringify(event);
261
+ beforeSend?.();
262
+ try {
263
+ socket.send(payload);
264
+ return true;
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+ }
270
+
271
+ // apps/relay/src/store.ts
272
+ var exports_store = {};
273
+ __export(exports_store, {
274
+ layerFromDatabase: () => layerFromDatabase,
275
+ layer: () => layer,
276
+ TaskRequestError: () => TaskRequestError,
277
+ TaskProgressError: () => TaskProgressError,
278
+ TaskInputError: () => TaskInputError,
279
+ TaskDeadlineError: () => TaskDeadlineError,
280
+ Service: () => Service,
281
+ RelayStore: () => exports_store,
282
+ PersistenceError: () => PersistenceError
283
+ });
284
+ import { Context, Effect as Effect2, Layer, Schema as Schema2 } from "effect";
285
+ import { createHash, randomBytes } from "node:crypto";
286
+
287
+ // apps/relay/src/database.ts
288
+ import { DatabaseSync } from "node:sqlite";
289
+
290
+ class Statement {
291
+ #statement;
292
+ constructor(statement) {
293
+ this.#statement = statement;
294
+ }
295
+ get(...parameters) {
296
+ const row = this.#statement.get(...parameters);
297
+ return row === undefined ? null : row;
298
+ }
299
+ all(...parameters) {
300
+ return this.#statement.all(...parameters);
301
+ }
302
+ run(...parameters) {
303
+ const result = this.#statement.run(...parameters);
304
+ return { changes: Number(result.changes) };
305
+ }
306
+ }
307
+
308
+ class Database {
309
+ #database;
310
+ constructor(path) {
311
+ this.#database = new DatabaseSync(path);
312
+ }
313
+ query(sql) {
314
+ return new Statement(this.#database.prepare(sql));
315
+ }
316
+ exec(sql) {
317
+ this.#database.exec(sql);
318
+ }
319
+ transaction(operation) {
320
+ return () => {
321
+ this.#database.exec("BEGIN IMMEDIATE");
322
+ try {
323
+ const result = operation();
324
+ this.#database.exec("COMMIT");
325
+ return result;
326
+ } catch (cause) {
327
+ this.#database.exec("ROLLBACK");
328
+ throw cause;
329
+ }
330
+ };
331
+ }
332
+ close() {
333
+ this.#database.close();
334
+ }
335
+ }
336
+
337
+ // apps/relay/src/store.ts
338
+ class PersistenceError extends Schema2.TaggedErrorClass()("RelayStore.PersistenceError", {
339
+ operation: Schema2.String,
340
+ message: Schema2.String,
341
+ missingRecord: Schema2.optionalKey(Schema2.Literals(["task", "operation"]))
342
+ }) {
343
+ }
344
+
345
+ class TaskProgressError extends Schema2.TaggedErrorClass()("RelayStore.TaskProgressError", { status: Schema2.Literals([403, 409]), message: Schema2.String }) {
346
+ }
347
+
348
+ class TaskInputError extends Schema2.TaggedErrorClass()("RelayStore.TaskInputError", { status: Schema2.Literals([403, 409]), message: Schema2.String }) {
349
+ }
350
+
351
+ class TaskDeadlineError extends Schema2.TaggedErrorClass()("RelayStore.TaskDeadlineError", { status: Schema2.Literals([400, 409]), message: Schema2.String }) {
352
+ }
353
+
354
+ class TaskRequestError extends Schema2.TaggedErrorClass()("RelayStore.TaskRequestError", { status: Schema2.Literals([409, 410]), message: Schema2.String }) {
355
+ }
356
+
357
+ class Service extends Context.Service()("@cohall/RelayStore") {
358
+ }
359
+ var operationError = (operation) => (cause) => new PersistenceError({
360
+ operation,
361
+ message: cause instanceof Error ? cause.message : String(cause)
362
+ });
363
+ var decode = (operation, schema, value) => Schema2.decodeUnknownEffect(schema)(value).pipe(Effect2.mapError(operationError(operation)));
364
+ var threadFromRow = (row) => decode("RelayStore.decodeThread", Thread, {
365
+ id: row.id,
366
+ title: row.title,
367
+ createdAt: row.created_at,
368
+ updatedAt: row.updated_at,
369
+ ...row.default_device_id === null ? {} : { defaultDeviceId: row.default_device_id }
370
+ });
371
+ var messageFromRow = (row) => decode("RelayStore.decodeMessage", Message, {
372
+ id: row.id,
373
+ threadId: row.thread_id,
374
+ role: row.role === "tool" ? "agent" : row.role,
375
+ authorName: row.author_name,
376
+ content: row.content,
377
+ createdAt: row.created_at,
378
+ ...row.task_id === null ? {} : { taskId: row.task_id },
379
+ ...row.device_id === null ? {} : { deviceId: row.device_id }
380
+ });
381
+ var deviceFromRow = (row) => decode("RelayStore.decodeDevice", Device, {
382
+ id: row.id,
383
+ name: row.name,
384
+ ...row.description === null ? {} : { description: row.description },
385
+ hostname: row.hostname,
386
+ platform: row.platform,
387
+ architecture: row.architecture,
388
+ status: row.status,
389
+ providers: JSON.parse(row.providers_json),
390
+ ...row.bots_json === null ? {} : { bots: JSON.parse(row.bots_json) },
391
+ capabilities: JSON.parse(row.capabilities_json),
392
+ workspaces: JSON.parse(row.workspaces_json),
393
+ version: row.version,
394
+ lastSeenAt: row.last_seen_at,
395
+ ...row.connected_at === null ? {} : { connectedAt: row.connected_at },
396
+ ...row.queued_tasks === undefined ? {} : {
397
+ queue: {
398
+ queued: row.queued_tasks,
399
+ ...row.oldest_queued_at === undefined || row.oldest_queued_at === null ? {} : { oldestQueuedAt: row.oldest_queued_at }
400
+ }
401
+ }
402
+ });
403
+ var taskFromRow = (db, row) => Effect2.try({
404
+ try: () => db.query("SELECT name FROM task_attachments WHERE task_id = ? AND direction = 'input' ORDER BY name").all(row.id),
405
+ catch: operationError("RelayStore.taskAttachments")
406
+ }).pipe(Effect2.flatMap((attachments) => decode("RelayStore.decodeTask", Task, {
407
+ id: row.id,
408
+ ...row.run_id === null ? {} : { runId: row.run_id },
409
+ ...row.clarifications_json === null ? {} : { clarifications: JSON.parse(row.clarifications_json) },
410
+ threadId: row.thread_id,
411
+ prompt: row.prompt,
412
+ provider: row.provider,
413
+ ...row.bot_id === null ? {} : { botId: row.bot_id },
414
+ status: row.status,
415
+ targetDeviceId: row.target_device_id,
416
+ createdAt: row.created_at,
417
+ updatedAt: row.updated_at,
418
+ ...row.expires_at === null ? {} : { expiresAt: row.expires_at },
419
+ ...row.context === null ? {} : { context: row.context },
420
+ ...row.source_device_id === null ? {} : { sourceDeviceId: row.source_device_id },
421
+ ...row.parent_task_id === null ? {} : { parentTaskId: row.parent_task_id },
422
+ ...row.workspace === null ? {} : { workspace: row.workspace },
423
+ ...row.provider_session_id === null ? {} : { providerSessionId: row.provider_session_id },
424
+ ...row.result === null ? {} : { result: row.result },
425
+ ...attachments.length === 0 ? {} : { inputAttachmentNames: attachments.map((item) => item.name) },
426
+ ...row.error === null ? {} : { error: row.error },
427
+ ...row.progress_note === null ? {} : { progress: { note: row.progress_note, at: row.progress_at } },
428
+ ...row.started_at === null ? {} : { startedAt: row.started_at },
429
+ ...row.completed_at === null ? {} : { completedAt: row.completed_at }
430
+ })));
431
+ var inboxItemFromRow = (row) => decode("RelayStore.decodeInboxItem", TaskInboxItem, {
432
+ id: row.id,
433
+ threadId: row.thread_id,
434
+ targetDeviceId: row.target_device_id,
435
+ provider: row.provider,
436
+ ...row.bot_id === null ? {} : { botId: row.bot_id },
437
+ status: row.status,
438
+ promptPreview: row.prompt_preview,
439
+ ...row.completed_at === null ? {} : { completedAt: row.completed_at },
440
+ ...row.input_request_json === null ? {} : { inputRequest: JSON.parse(row.input_request_json) },
441
+ ...row.result_preview === null ? {} : { resultPreview: row.result_preview },
442
+ ...row.error_preview === null ? {} : { errorPreview: row.error_preview }
443
+ });
444
+ var operationFromRow = (row) => decode("RelayStore.decodeOperation", DeviceOperation, {
445
+ id: row.id,
446
+ kind: row.kind,
447
+ status: row.status,
448
+ targetDeviceId: row.target_device_id,
449
+ requestedVersion: row.requested_version,
450
+ restart: row.restart === 1,
451
+ createdAt: row.created_at,
452
+ updatedAt: row.updated_at,
453
+ ...row.result === null ? {} : { result: row.result },
454
+ ...row.error === null ? {} : { error: row.error },
455
+ ...row.completed_at === null ? {} : { completedAt: row.completed_at }
456
+ });
457
+ var emptyStatusCounts = () => ({
458
+ queued: 0,
459
+ assigned: 0,
460
+ running: 0,
461
+ needs_input: 0,
462
+ cancelling: 0,
463
+ completed: 0,
464
+ failed: 0,
465
+ cancelled: 0
466
+ });
467
+ var taskTraceEventFromRow = (row) => decode("RelayStore.decodeTaskTraceEvent", TaskTraceEvent, {
468
+ kind: row.kind,
469
+ at: row.created_at,
470
+ ...row.detail === null ? {} : { detail: row.detail }
471
+ });
472
+ var rolesFromRow = (row) => Schema2.decodeUnknownSync(Schema2.Array(ConnectionRole))(JSON.parse(row.roles_json));
473
+ var authSessionFromRow = (row) => {
474
+ const roles = rolesFromRow(row);
475
+ const role = roles[0];
476
+ return role === undefined ? Effect2.fail(new PersistenceError({
477
+ operation: "RelayStore.decodeAuthSession",
478
+ message: `Session ${row.id} has no role`
479
+ })) : decode("RelayStore.decodeAuthSession", AuthSession, {
480
+ id: row.id,
481
+ label: row.label,
482
+ role,
483
+ createdAt: row.created_at,
484
+ expiresAt: row.expires_at,
485
+ lastSeenAt: row.last_seen_at,
486
+ ...row.bound_device_id === null ? {} : { deviceId: row.bound_device_id },
487
+ ...row.revoked_at === null ? {} : { revokedAt: row.revoked_at }
488
+ });
489
+ };
490
+ var secret = (prefix) => {
491
+ return `cohall_${prefix}_${randomBytes(32).toString("hex")}`;
492
+ };
493
+ var tokenHash = (token) => createHash("sha256").update(token).digest("hex");
494
+ var providerName = (provider) => {
495
+ switch (provider) {
496
+ case "codex":
497
+ return "Codex";
498
+ case "claude-code":
499
+ return "Claude Code";
500
+ case "opencode":
501
+ return "OpenCode";
502
+ case "grok-bot":
503
+ return "Grok Bot";
504
+ }
505
+ };
506
+ var recentWithin = (items, byteBudget) => {
507
+ const encoder = new TextEncoder;
508
+ const selected = [];
509
+ let bytes = 0;
510
+ for (let index = items.length - 1;index >= 0; index -= 1) {
511
+ const item = items[index];
512
+ if (item === undefined) {
513
+ continue;
514
+ }
515
+ const itemBytes = encoder.encode(JSON.stringify(item)).byteLength;
516
+ if (bytes + itemBytes > byteBudget) {
517
+ break;
518
+ }
519
+ bytes += itemBytes;
520
+ selected.unshift(item);
521
+ }
522
+ return { items: selected, truncated: selected.length < items.length };
523
+ };
524
+ var derivedTraceEvents = (task) => {
525
+ const detail = "Derived from task timestamps; earlier trace events were not recorded";
526
+ const events = [
527
+ TaskTraceEvent.make({ kind: "queued", at: task.createdAt, detail })
528
+ ];
529
+ if (task.startedAt !== undefined) {
530
+ events.push(TaskTraceEvent.make({ kind: "running", at: task.startedAt, detail }));
531
+ } else if (task.status === "assigned") {
532
+ events.push(TaskTraceEvent.make({ kind: "assigned", at: task.updatedAt, detail }));
533
+ }
534
+ if (task.status === "cancelling") {
535
+ events.push(TaskTraceEvent.make({ kind: "cancelling", at: task.updatedAt, detail }));
536
+ }
537
+ if (task.completedAt !== undefined && (task.status === "completed" || task.status === "failed" || task.status === "cancelled")) {
538
+ events.push(TaskTraceEvent.make({ kind: task.status, at: task.completedAt, detail }));
539
+ }
540
+ return events;
541
+ };
542
+ var interruptedTaskStatus = `CASE
543
+ WHEN provider = 'grok-bot' AND json_array_length(clarifications_json) > 0
544
+ AND json_extract(clarifications_json, '$[#-1].answer') IS NULL THEN 'needs_input'
545
+ ELSE 'queued' END`;
546
+ var makeService = (db, retainedTerminalTasks = 1000) => {
547
+ const requestHash = (input) => {
548
+ const { requestId: _requestId, attachments, ...fields } = input;
549
+ const normalized = {
550
+ ...fields,
551
+ provider: input.provider ?? (input.botId === undefined ? "codex" : "grok-bot"),
552
+ ...attachments === undefined || attachments.length === 0 ? {} : {
553
+ attachments: attachments.map(({ name, data }) => [
554
+ name,
555
+ Buffer.from(data, "base64").toString("base64")
556
+ ])
557
+ }
558
+ };
559
+ return createHash("sha256").update(JSON.stringify(Object.entries(normalized).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0))).digest("hex");
560
+ };
561
+ const requestedTask = (input, principal) => {
562
+ if (input.requestId === undefined)
563
+ return null;
564
+ const saved = db.query("SELECT input_hash, task_id FROM task_requests WHERE requester_id = ? AND request_id = ?").get(principal === "owner" ? "owner" : principal.id, input.requestId.toLowerCase());
565
+ if (saved === null)
566
+ return null;
567
+ if (saved.input_hash !== requestHash(input))
568
+ throw new TaskRequestError({
569
+ status: 409,
570
+ message: "Request ID was already used with different task input"
571
+ });
572
+ if (saved.task_id === null)
573
+ throw new TaskRequestError({
574
+ status: 410,
575
+ message: "The original task is no longer retained; this request ID cannot be reused"
576
+ });
577
+ const task = db.query("SELECT * FROM tasks WHERE id = ?").get(saved.task_id);
578
+ if (task === null)
579
+ throw new Error(`Missing task ${saved.task_id} for retained request`);
580
+ return task;
581
+ };
582
+ const findDelegation = Effect2.fn("RelayStore.findDelegation")(function* (input, principal) {
583
+ const row = yield* Effect2.try({
584
+ try: () => requestedTask(input, principal),
585
+ catch: (cause) => cause instanceof TaskRequestError ? cause : operationError("RelayStore.findDelegation")(cause)
586
+ });
587
+ return row === null ? undefined : yield* taskFromRow(db, row);
588
+ });
589
+ const recordTaskTraceEvent = (taskId, kind, detail, createdAt = now()) => {
590
+ db.query(`INSERT INTO task_trace_events (task_id, kind, created_at, detail)
591
+ VALUES (?, ?, ?, ?)`).run(taskId, kind, createdAt, detail);
592
+ db.query(`DELETE FROM task_trace_events WHERE task_id = ? AND id NOT IN (
593
+ SELECT id FROM task_trace_events WHERE task_id = ? ORDER BY id DESC LIMIT 1000
594
+ )`).run(taskId, taskId);
595
+ };
596
+ const pruneTerminalHistory = (preserveTaskId) => {
597
+ const exclusion = preserveTaskId === undefined ? "" : "AND id <> ?";
598
+ const offset = preserveTaskId === undefined ? retainedTerminalTasks : retainedTerminalTasks - 1;
599
+ const staleTasks = `SELECT id FROM tasks
600
+ WHERE status IN ('completed', 'failed', 'cancelled')
601
+ ${exclusion}
602
+ ORDER BY completed_at DESC, updated_at DESC, id DESC
603
+ LIMIT -1 OFFSET ?`;
604
+ const parameters = preserveTaskId === undefined ? [offset] : [preserveTaskId, offset];
605
+ db.query(`DELETE FROM messages WHERE task_id IN (${staleTasks})`).run(...parameters);
606
+ db.query(`DELETE FROM tasks WHERE id IN (${staleTasks})`).run(...parameters);
607
+ db.query(`DELETE FROM threads
608
+ WHERE NOT EXISTS (SELECT 1 FROM tasks WHERE tasks.thread_id = threads.id)
609
+ AND NOT EXISTS (SELECT 1 FROM messages WHERE messages.thread_id = threads.id)`).run();
610
+ };
611
+ const pruneTerminalOperations = (preserveOperationId) => {
612
+ const exclusion = preserveOperationId === undefined ? "" : "AND id <> ?";
613
+ const offset = preserveOperationId === undefined ? retainedTerminalTasks : retainedTerminalTasks - 1;
614
+ const parameters = preserveOperationId === undefined ? [offset] : [preserveOperationId, offset];
615
+ db.query(`DELETE FROM device_operations
616
+ WHERE id IN (
617
+ SELECT id FROM device_operations
618
+ WHERE status IN ('completed', 'failed') ${exclusion}
619
+ ORDER BY completed_at DESC, updated_at DESC, id DESC
620
+ LIMIT -1 OFFSET ?
621
+ )`).run(...parameters);
622
+ };
623
+ const queryTask = (taskId) => db.query("SELECT * FROM tasks WHERE id = ?").get(taskId);
624
+ const inboxColumns = `id, thread_id, target_device_id, provider, bot_id, status,
625
+ substr(prompt, 1, 160) AS prompt_preview,
626
+ substr(result, 1, 512) AS result_preview,
627
+ substr(error, 1, 512) AS error_preview,
628
+ CASE WHEN status = 'needs_input' THEN NULL ELSE COALESCE(completed_at, updated_at) END AS completed_at,
629
+ CASE WHEN status = 'needs_input' THEN json_extract(clarifications_json, '$[#-1]') END AS input_request_json`;
630
+ const queryOperation = (operationId) => db.query("SELECT * FROM device_operations WHERE id = ?").get(operationId);
631
+ const getTask = Effect2.fn("RelayStore.getTask")(function* (taskId) {
632
+ const row = yield* Effect2.try({
633
+ try: () => queryTask(taskId),
634
+ catch: operationError("RelayStore.getTask")
635
+ });
636
+ if (row === null) {
637
+ return yield* Effect2.fail(new PersistenceError({
638
+ operation: "RelayStore.getTask",
639
+ message: `Unknown task ${taskId}`,
640
+ missingRecord: "task"
641
+ }));
642
+ }
643
+ return yield* taskFromRow(db, row);
644
+ });
645
+ const listAttachments = Effect2.fn("RelayStore.listAttachments")(function* (taskId) {
646
+ yield* getTask(taskId);
647
+ const rows = yield* Effect2.try({
648
+ try: () => db.query("SELECT name, direction, length(data) AS bytes FROM task_attachments WHERE task_id = ? ORDER BY direction, name").all(taskId),
649
+ catch: operationError("RelayStore.listAttachments")
650
+ });
651
+ return yield* Effect2.forEach(rows, (row) => decode("RelayStore.decodeAttachment", TaskAttachment, row));
652
+ });
653
+ const readAttachment = Effect2.fn("RelayStore.readAttachment")(function* (taskId, name, direction) {
654
+ yield* getTask(taskId);
655
+ const row = yield* Effect2.try({
656
+ try: () => direction === undefined ? db.query("SELECT data FROM task_attachments WHERE task_id = ? AND name = ? ORDER BY direction DESC LIMIT 1").get(taskId, name) : db.query("SELECT data FROM task_attachments WHERE task_id = ? AND name = ? AND direction = ?").get(taskId, name, direction),
657
+ catch: operationError("RelayStore.readAttachment")
658
+ });
659
+ if (row === null) {
660
+ return yield* new PersistenceError({
661
+ operation: "RelayStore.readAttachment",
662
+ message: `Unknown attachment ${name}`
663
+ });
664
+ }
665
+ return row.data;
666
+ });
667
+ const inboxFor = Effect2.fn("RelayStore.inboxFor")(function* (principal) {
668
+ const requesterId = principal === "owner" ? "owner" : principal.id;
669
+ const rows = yield* Effect2.try({
670
+ try: () => db.query(`SELECT ${inboxColumns} FROM tasks WHERE requester_id = ? AND completion_seen_at IS NULL
671
+ AND status IN ('needs_input', 'completed', 'failed', 'cancelled')
672
+ ORDER BY COALESCE(completed_at, updated_at) ASC, id ASC LIMIT 21`).all(requesterId),
673
+ catch: operationError("RelayStore.inboxFor")
674
+ });
675
+ return TaskInbox.make({
676
+ items: yield* Effect2.forEach(rows.slice(0, 20), inboxItemFromRow),
677
+ hasMore: rows.length > 20
678
+ });
679
+ });
680
+ const acknowledgeCompletion = Effect2.fn("RelayStore.acknowledgeCompletion")(function* (taskId, principal) {
681
+ const requesterId = principal === "owner" ? "owner" : principal.id;
682
+ const row = yield* Effect2.try({
683
+ try: () => db.query(`SELECT ${inboxColumns} FROM tasks WHERE id = ? AND requester_id = ?
684
+ AND status IN ('completed', 'failed', 'cancelled')`).get(taskId, requesterId),
685
+ catch: operationError("RelayStore.acknowledgeCompletion.read")
686
+ });
687
+ if (row === null) {
688
+ return yield* new PersistenceError({
689
+ operation: "RelayStore.acknowledgeCompletion",
690
+ message: `Unknown inbox task ${taskId}`
691
+ });
692
+ }
693
+ yield* Effect2.try({
694
+ try: () => db.query("UPDATE tasks SET completion_seen_at = COALESCE(completion_seen_at, ?) WHERE id = ?").run(now(), taskId),
695
+ catch: operationError("RelayStore.acknowledgeCompletion.write")
696
+ });
697
+ return yield* inboxItemFromRow(row);
698
+ });
699
+ const traceTask = Effect2.fn("RelayStore.traceTask")(function* (taskId) {
700
+ const task = yield* getTask(taskId);
701
+ const [deviceRow, eventRows] = yield* Effect2.try({
702
+ try: () => [
703
+ db.query("SELECT * FROM devices WHERE id = ?").get(task.targetDeviceId),
704
+ db.query(`SELECT * FROM (
705
+ SELECT id, kind, created_at, detail FROM task_trace_events
706
+ WHERE task_id = ? ORDER BY id DESC LIMIT 101
707
+ ) ORDER BY id`).all(taskId)
708
+ ],
709
+ catch: operationError("RelayStore.traceTask")
710
+ });
711
+ if (deviceRow === null) {
712
+ return yield* Effect2.fail(new PersistenceError({
713
+ operation: "RelayStore.traceTask.device",
714
+ message: `Unknown target device ${task.targetDeviceId}`
715
+ }));
716
+ }
717
+ const targetDevice = yield* deviceFromRow(deviceRow);
718
+ const selectedRows = eventRows.slice(-100);
719
+ const recordedEvents = yield* Effect2.forEach(selectedRows, taskTraceEventFromRow);
720
+ const events = recordedEvents.length === 0 ? derivedTraceEvents(task) : recordedEvents;
721
+ return TaskTrace.make({
722
+ taskId: task.id,
723
+ threadId: task.threadId,
724
+ status: task.status,
725
+ provider: task.provider,
726
+ ...task.botId === undefined ? {} : { botId: task.botId },
727
+ targetDevice,
728
+ createdAt: task.createdAt,
729
+ updatedAt: task.updatedAt,
730
+ events,
731
+ truncated: eventRows.length > 100 || recordedEvents.length === 0 || recordedEvents[0]?.kind !== "queued",
732
+ ...task.sourceDeviceId === undefined ? {} : { sourceDeviceId: task.sourceDeviceId },
733
+ ...task.parentTaskId === undefined ? {} : { parentTaskId: task.parentTaskId },
734
+ ...task.workspace === undefined ? {} : { workspace: task.workspace },
735
+ ...task.startedAt === undefined ? {} : { startedAt: task.startedAt },
736
+ ...task.completedAt === undefined ? {} : { completedAt: task.completedAt },
737
+ ...task.expiresAt === undefined ? {} : { expiresAt: task.expiresAt },
738
+ ...task.error === undefined ? {} : { error: task.error },
739
+ ...task.progress === undefined ? {} : { progress: task.progress },
740
+ ...task.clarifications === undefined ? {} : { clarifications: task.clarifications }
741
+ });
742
+ });
743
+ const listDevices = Effect2.fn("RelayStore.listDevices")(function* () {
744
+ const rows = yield* Effect2.try({
745
+ try: () => db.query(`SELECT devices.*, COUNT(tasks.id) AS queued_tasks,
746
+ MIN(tasks.created_at) AS oldest_queued_at
747
+ FROM devices LEFT JOIN tasks
748
+ ON tasks.target_device_id = devices.id AND tasks.status = 'queued'
749
+ WHERE devices.forgotten_at IS NULL
750
+ GROUP BY devices.id ORDER BY devices.name COLLATE NOCASE, devices.id`).all(),
751
+ catch: operationError("RelayStore.listDevices")
752
+ });
753
+ return yield* Effect2.forEach(rows, deviceFromRow);
754
+ });
755
+ const deviceOverview = Effect2.fn("RelayStore.deviceOverview")(function* () {
756
+ const rows = yield* Effect2.try({
757
+ try: () => db.query(`SELECT devices.id, devices.name, devices.description, devices.status, devices.version,
758
+ devices.last_seen_at AS lastSeenAt,
759
+ COUNT(CASE WHEN tasks.status = 'queued' THEN 1 END) AS queued,
760
+ COUNT(CASE WHEN tasks.status IN ('assigned', 'running') THEN 1 END) AS active,
761
+ COUNT(CASE WHEN tasks.status = 'needs_input' THEN 1 END) AS needsInput,
762
+ COUNT(CASE WHEN tasks.status = 'cancelling' THEN 1 END) AS cancelling,
763
+ MIN(CASE WHEN tasks.status = 'queued' THEN tasks.created_at END) AS oldestQueuedAt
764
+ FROM devices LEFT JOIN tasks ON tasks.target_device_id = devices.id
765
+ AND tasks.status IN ('queued', 'assigned', 'running', 'needs_input', 'cancelling')
766
+ WHERE devices.forgotten_at IS NULL
767
+ GROUP BY devices.id ORDER BY devices.name COLLATE NOCASE, devices.id`).all(),
768
+ catch: operationError("RelayStore.deviceOverview")
769
+ });
770
+ return yield* Effect2.forEach(rows, ({ description, oldestQueuedAt, ...row }) => decode("RelayStore.decodeDeviceOverview", DeviceOverview, {
771
+ ...row,
772
+ ...description === null ? {} : { description },
773
+ ...oldestQueuedAt === null ? {} : { oldestQueuedAt }
774
+ }));
775
+ });
776
+ const listDevicePage = Effect2.fn("RelayStore.listDevicePage")(function* (after) {
777
+ const nextRow = yield* Effect2.try({
778
+ try: () => db.query(`SELECT devices.*,
779
+ (SELECT COUNT(*) FROM tasks
780
+ WHERE target_device_id = devices.id AND status = 'queued') AS queued_tasks,
781
+ (SELECT MIN(created_at) FROM tasks
782
+ WHERE target_device_id = devices.id AND status = 'queued') AS oldest_queued_at
783
+ FROM devices WHERE forgotten_at IS NULL AND devices.id > ?
784
+ ORDER BY devices.id LIMIT 1`),
785
+ catch: operationError("RelayStore.listDevicePage.query")
786
+ });
787
+ const devices = [];
788
+ const targetBytes = 2 * 1024 * 1024 - 1024;
789
+ let bytes = 0;
790
+ let cursor = after ?? "";
791
+ while (devices.length < maxDevicePageDevices) {
792
+ const row = yield* Effect2.try({
793
+ try: () => nextRow.get(cursor),
794
+ catch: operationError("RelayStore.listDevicePage.read")
795
+ });
796
+ if (row === null)
797
+ break;
798
+ const device = yield* deviceFromRow(row);
799
+ const size = Buffer.byteLength(JSON.stringify(device)) + (devices.length === 0 ? 0 : 1);
800
+ if (devices.length > 0 && bytes + size > targetBytes)
801
+ break;
802
+ devices.push(device);
803
+ bytes += size;
804
+ cursor = device.id;
805
+ if (bytes > targetBytes)
806
+ break;
807
+ }
808
+ const last = devices.at(-1);
809
+ const hasMore = last !== undefined && (yield* Effect2.try({
810
+ try: () => db.query("SELECT 1 AS found FROM devices WHERE forgotten_at IS NULL AND id > ? ORDER BY id LIMIT 1").get(last.id) !== null,
811
+ catch: operationError("RelayStore.listDevicePage.hasMore")
812
+ }));
813
+ const page = DevicePage.make({
814
+ devices,
815
+ ...hasMore && last !== undefined ? { nextCursor: last.id } : {}
816
+ });
817
+ if (Buffer.byteLength(JSON.stringify(page)) > maxDevicePageResponseBytes)
818
+ return yield* new PersistenceError({
819
+ operation: "RelayStore.listDevicePage",
820
+ message: "A device page exceeds the transfer limit"
821
+ });
822
+ return page;
823
+ });
824
+ const usage = Effect2.fn("RelayStore.usage")(function* () {
825
+ const rows = yield* Effect2.try({
826
+ try: () => db.query(`SELECT tasks.target_device_id AS device_id, devices.name AS device_name,
827
+ tasks.status, tasks.provider, COUNT(*) AS tasks
828
+ FROM tasks
829
+ JOIN devices ON devices.id = tasks.target_device_id
830
+ GROUP BY tasks.target_device_id, devices.name, tasks.status, tasks.provider
831
+ ORDER BY devices.name COLLATE NOCASE, tasks.target_device_id, tasks.provider`).all(),
832
+ catch: operationError("RelayStore.usage")
833
+ });
834
+ const totalStatus = emptyStatusCounts();
835
+ const totalProviders = new Map;
836
+ const devices = new Map;
837
+ let retainedTasks = 0;
838
+ for (const row of rows) {
839
+ const status = Schema2.decodeUnknownSync(TaskStatus)(row.status);
840
+ const provider = Schema2.decodeUnknownSync(Provider)(row.provider);
841
+ const deviceId = Schema2.decodeUnknownSync(DeviceId)(row.device_id);
842
+ retainedTasks += row.tasks;
843
+ totalStatus[status] += row.tasks;
844
+ totalProviders.set(provider, (totalProviders.get(provider) ?? 0) + row.tasks);
845
+ const current = devices.get(deviceId) ?? {
846
+ name: row.device_name,
847
+ status: emptyStatusCounts(),
848
+ providers: new Map
849
+ };
850
+ current.status[status] += row.tasks;
851
+ current.providers.set(provider, (current.providers.get(provider) ?? 0) + row.tasks);
852
+ devices.set(deviceId, current);
853
+ }
854
+ const providerUsage = (providers) => Provider.literals.flatMap((provider) => {
855
+ const tasks = providers.get(provider);
856
+ return tasks === undefined ? [] : [{ provider, tasks }];
857
+ });
858
+ return UsageSummary.make({
859
+ retainedTasks,
860
+ byStatus: TaskStatusCounts.make(totalStatus),
861
+ byProvider: providerUsage(totalProviders),
862
+ devices: [...devices.entries()].map(([deviceId, device]) => DeviceUsage.make({
863
+ deviceId,
864
+ deviceName: device.name,
865
+ tasks: Object.values(device.status).reduce((sum, tasks) => sum + tasks, 0),
866
+ byStatus: TaskStatusCounts.make(device.status),
867
+ byProvider: providerUsage(device.providers)
868
+ }))
869
+ });
870
+ });
871
+ const getOperation = Effect2.fn("RelayStore.getOperation")(function* (operationId) {
872
+ const row = yield* Effect2.try({
873
+ try: () => queryOperation(operationId),
874
+ catch: operationError("RelayStore.getOperation")
875
+ });
876
+ if (row === null) {
877
+ return yield* Effect2.fail(new PersistenceError({
878
+ operation: "RelayStore.getOperation",
879
+ message: `Unknown device operation ${operationId}`,
880
+ missingRecord: "operation"
881
+ }));
882
+ }
883
+ return yield* operationFromRow(row);
884
+ });
885
+ const listOperations = Effect2.fn("RelayStore.listOperations")(function* () {
886
+ const rows = yield* Effect2.try({
887
+ try: () => db.query("SELECT * FROM device_operations ORDER BY created_at DESC, id DESC LIMIT 50").all(),
888
+ catch: operationError("RelayStore.listOperations")
889
+ });
890
+ return yield* Effect2.forEach(rows, operationFromRow);
891
+ });
892
+ const createUpgradeOperations = Effect2.fn("RelayStore.createUpgradeOperations")(function* (input) {
893
+ const timestamp = now();
894
+ const operations = yield* Effect2.try({
895
+ try: () => db.transaction(() => {
896
+ const devices = db.query("SELECT * FROM devices WHERE forgotten_at IS NULL ORDER BY name COLLATE NOCASE, id").all();
897
+ if (devices.length === 0) {
898
+ throw new Error("No Cohall devices are registered");
899
+ }
900
+ if (devices.length > 256) {
901
+ throw new Error("All-device operations support at most 256 registered devices");
902
+ }
903
+ assertDeviceOperationSupport(devices);
904
+ for (const device of devices) {
905
+ const outstanding = db.query(`SELECT COUNT(*) AS count FROM device_operations
906
+ WHERE target_device_id = ? AND status IN ('queued', 'assigned', 'running')`).get(device.id);
907
+ if ((outstanding?.count ?? 0) > 0) {
908
+ throw new Error(`${device.name} already has an upgrade operation in progress`);
909
+ }
910
+ }
911
+ pruneTerminalOperations();
912
+ return devices.map((device) => {
913
+ const operation = DeviceOperation.make({
914
+ id: makeOperationId(),
915
+ kind: "upgrade",
916
+ status: "queued",
917
+ targetDeviceId: DeviceId.make(device.id),
918
+ requestedVersion: input.target,
919
+ restart: input.restart,
920
+ createdAt: timestamp,
921
+ updatedAt: timestamp
922
+ });
923
+ db.query(`INSERT INTO device_operations (
924
+ id, kind, status, target_device_id, requested_version, restart,
925
+ created_at, updated_at
926
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(operation.id, operation.kind, operation.status, operation.targetDeviceId, operation.requestedVersion, operation.restart ? 1 : 0, operation.createdAt, operation.updatedAt);
927
+ return operation;
928
+ });
929
+ })(),
930
+ catch: operationError("RelayStore.createUpgradeOperations")
931
+ });
932
+ return operations;
933
+ });
934
+ const pendingOperationsFor = Effect2.fn("RelayStore.pendingOperationsFor")(function* (deviceId) {
935
+ const rows = yield* Effect2.try({
936
+ try: () => db.query(`SELECT * FROM device_operations WHERE target_device_id = ? AND status = 'queued'
937
+ ORDER BY created_at, id LIMIT 10`).all(deviceId),
938
+ catch: operationError("RelayStore.pendingOperationsFor")
939
+ });
940
+ return yield* Effect2.forEach(rows, operationFromRow);
941
+ });
942
+ const transitionOperation = Effect2.fn("RelayStore.transitionOperation")(function* (operationId, expected, status, result, error) {
943
+ const current = yield* getOperation(operationId);
944
+ if (!expected.includes(current.status)) {
945
+ return current;
946
+ }
947
+ const timestamp = now();
948
+ const completed = status === "completed" || status === "failed" ? timestamp : undefined;
949
+ const placeholders = expected.map(() => "?").join(", ");
950
+ yield* Effect2.try({
951
+ try: () => db.transaction(() => {
952
+ const updated = db.query(`UPDATE device_operations
953
+ SET status = ?, result = ?, error = ?, updated_at = ?, completed_at = ?
954
+ WHERE id = ? AND status IN (${placeholders})`).run(status, result ?? current.result ?? null, error ?? current.error ?? null, timestamp, completed ?? current.completedAt ?? null, operationId, ...expected);
955
+ if (updated.changes === 1 && completed !== undefined) {
956
+ pruneTerminalOperations(operationId);
957
+ }
958
+ })(),
959
+ catch: operationError("RelayStore.transitionOperation")
960
+ });
961
+ return yield* getOperation(operationId);
962
+ });
963
+ const requireOperationTarget = Effect2.fn("RelayStore.requireOperationTarget")(function* (operationId, deviceId) {
964
+ const operation = yield* getOperation(operationId);
965
+ if (operation.targetDeviceId !== deviceId) {
966
+ return yield* Effect2.fail(new PersistenceError({
967
+ operation: "RelayStore.requireOperationTarget",
968
+ message: `Device ${deviceId} cannot update operation ${operationId}`
969
+ }));
970
+ }
971
+ return operation;
972
+ });
973
+ const assignOperation = Effect2.fn("RelayStore.assignOperation")(function* (operationId) {
974
+ const current = yield* getOperation(operationId);
975
+ if (current.status !== "queued") {
976
+ return current;
977
+ }
978
+ const timestamp = now();
979
+ yield* Effect2.try({
980
+ try: () => db.query(`UPDATE device_operations SET status = 'assigned', updated_at = ?
981
+ WHERE id = ? AND status = 'queued'
982
+ AND NOT EXISTS (
983
+ SELECT 1 FROM tasks WHERE target_device_id = ?
984
+ AND status IN ('assigned', 'running', 'cancelling')
985
+ )
986
+ AND NOT EXISTS (
987
+ SELECT 1 FROM device_operations active
988
+ WHERE active.target_device_id = ? AND active.id <> ?
989
+ AND active.status IN ('assigned', 'running')
990
+ )`).run(timestamp, operationId, current.targetDeviceId, current.targetDeviceId, operationId),
991
+ catch: operationError("RelayStore.assignOperation")
992
+ });
993
+ return yield* getOperation(operationId);
994
+ });
995
+ const acceptOperation = (operationId, deviceId) => requireOperationTarget(operationId, deviceId).pipe(Effect2.flatMap(() => transitionOperation(operationId, ["assigned"], "running")));
996
+ const finishOperation = (operationId, deviceId, result) => requireOperationTarget(operationId, deviceId).pipe(Effect2.flatMap(() => transitionOperation(operationId, ["queued", "assigned", "running"], "completed", result)));
997
+ const failOperation = (operationId, deviceId, error) => requireOperationTarget(operationId, deviceId).pipe(Effect2.flatMap(() => transitionOperation(operationId, ["queued", "assigned", "running"], "failed", undefined, error)));
998
+ const abandonOperation = (operationId) => transitionOperation(operationId, ["queued", "assigned", "running"], "failed", undefined, "Abandoned by the relay owner");
999
+ const requeueOperationsFor = Effect2.fn("RelayStore.requeueOperationsFor")(function* (deviceId) {
1000
+ yield* Effect2.try({
1001
+ try: () => db.query(`UPDATE device_operations SET status = 'queued', updated_at = ?
1002
+ WHERE target_device_id = ? AND status IN ('assigned', 'running')`).run(now(), deviceId),
1003
+ catch: operationError("RelayStore.requeueOperationsFor")
1004
+ });
1005
+ });
1006
+ const forgetDevice = Effect2.fn("RelayStore.forgetDevice")(function* (deviceId) {
1007
+ const row = yield* Effect2.try({
1008
+ try: () => db.transaction(() => {
1009
+ const device = db.query("SELECT * FROM devices WHERE id = ? AND forgotten_at IS NULL").get(deviceId);
1010
+ if (device === null) {
1011
+ throw new Error(`Unknown device ${deviceId}`);
1012
+ }
1013
+ if (device.status !== "offline") {
1014
+ throw new Error(`Device ${deviceId} must be offline before it can be forgotten`);
1015
+ }
1016
+ const outstanding = db.query(`SELECT COUNT(*) AS count FROM tasks
1017
+ WHERE target_device_id = ? AND status NOT IN ('completed', 'failed', 'cancelled')`).get(deviceId);
1018
+ if ((outstanding?.count ?? 0) > 0) {
1019
+ throw new Error(`Device ${deviceId} still has outstanding tasks`);
1020
+ }
1021
+ const timestamp = now();
1022
+ db.query(`UPDATE device_operations
1023
+ SET status = 'failed', error = ?, updated_at = ?, completed_at = ?
1024
+ WHERE target_device_id = ? AND status IN ('queued', 'assigned', 'running')`).run("Target device was forgotten by the relay owner", timestamp, timestamp, deviceId);
1025
+ pruneTerminalOperations();
1026
+ db.query("UPDATE devices SET forgotten_at = ? WHERE id = ?").run(timestamp, deviceId);
1027
+ db.query("UPDATE auth_sessions SET revoked_at = ? WHERE bound_device_id = ? AND revoked_at IS NULL").run(timestamp, deviceId);
1028
+ return device;
1029
+ })(),
1030
+ catch: operationError("RelayStore.forgetDevice")
1031
+ });
1032
+ return yield* deviceFromRow(row);
1033
+ });
1034
+ const recover = Effect2.fn("RelayStore.recover")(function* () {
1035
+ yield* Effect2.try({
1036
+ try: () => db.transaction(() => {
1037
+ const timestamp = now();
1038
+ const interrupted = db.query(`SELECT id, ${interruptedTaskStatus} AS status FROM tasks WHERE status IN ('assigned', 'running')`).all();
1039
+ db.query("UPDATE devices SET status = 'offline'").run();
1040
+ db.query(`UPDATE tasks SET status = ${interruptedTaskStatus}, updated_at = ?, progress_note = NULL, progress_at = NULL,
1041
+ dispatched_at = CASE WHEN provider = 'grok-bot' THEN dispatched_at
1042
+ ELSE COALESCE(dispatched_at, started_at, updated_at) END
1043
+ WHERE status IN ('assigned', 'running')`).run(timestamp);
1044
+ db.query("UPDATE device_operations SET status = 'queued', updated_at = ? WHERE status IN ('assigned', 'running')").run(timestamp);
1045
+ for (const task of interrupted) {
1046
+ recordTaskTraceEvent(TaskId.make(task.id), task.status === "needs_input" ? "needs_input" : "requeued", "Relay restarted before the task completed", timestamp);
1047
+ }
1048
+ db.query("DELETE FROM auth_pairings WHERE expires_at <= ? OR used_at IS NOT NULL").run(timestamp);
1049
+ db.query("UPDATE auth_sessions SET revoked_at = ? WHERE revoked_at IS NULL AND roles_json LIKE '%,%'").run(timestamp);
1050
+ pruneTerminalHistory();
1051
+ pruneTerminalOperations();
1052
+ })(),
1053
+ catch: operationError("RelayStore.recover")
1054
+ });
1055
+ });
1056
+ const upsertDevice = Effect2.fn("RelayStore.upsertDevice")(function* (device) {
1057
+ yield* Effect2.try({
1058
+ try: () => db.query(`INSERT INTO devices (
1059
+ id, name, hostname, platform, architecture, status, providers_json,
1060
+ capabilities_json, workspaces_json, version, last_seen_at, connected_at, bots_json, description
1061
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1062
+ ON CONFLICT(id) DO UPDATE SET
1063
+ name = excluded.name, description = excluded.description,
1064
+ hostname = excluded.hostname, platform = excluded.platform,
1065
+ architecture = excluded.architecture, status = excluded.status,
1066
+ providers_json = excluded.providers_json, bots_json = excluded.bots_json,
1067
+ capabilities_json = excluded.capabilities_json,
1068
+ workspaces_json = excluded.workspaces_json, version = excluded.version,
1069
+ last_seen_at = excluded.last_seen_at, connected_at = excluded.connected_at,
1070
+ forgotten_at = NULL`).run(device.id, device.name, device.hostname, device.platform, device.architecture, device.status, JSON.stringify(device.providers), JSON.stringify(device.capabilities), JSON.stringify(device.workspaces), device.version, device.lastSeenAt, device.connectedAt ?? null, device.bots === undefined ? null : JSON.stringify(device.bots), device.description ?? null),
1071
+ catch: operationError("RelayStore.upsertDevice")
1072
+ });
1073
+ return device;
1074
+ });
1075
+ const updateDeviceStatus = Effect2.fn("RelayStore.updateDeviceStatus")(function* (deviceId, status, bots) {
1076
+ const timestamp = now();
1077
+ const result = yield* Effect2.try({
1078
+ try: () => db.query("UPDATE devices SET status = ?, last_seen_at = ?, bots_json = COALESCE(?, bots_json) WHERE id = ?").run(status, timestamp, bots === undefined ? null : JSON.stringify(bots), deviceId),
1079
+ catch: operationError("RelayStore.updateDeviceStatus")
1080
+ });
1081
+ if (result.changes !== 1) {
1082
+ return yield* Effect2.fail(new PersistenceError({
1083
+ operation: "RelayStore.updateDeviceStatus",
1084
+ message: `Unknown device ${deviceId}`
1085
+ }));
1086
+ }
1087
+ const row = db.query("SELECT * FROM devices WHERE id = ?").get(deviceId);
1088
+ if (row === null) {
1089
+ return yield* Effect2.fail(new PersistenceError({
1090
+ operation: "RelayStore.updateDeviceStatus.read",
1091
+ message: `Device ${deviceId} disappeared after update`
1092
+ }));
1093
+ }
1094
+ return yield* deviceFromRow(row);
1095
+ });
1096
+ const createDelegation = Effect2.fn("RelayStore.createDelegation")(function* (input, targetDeviceId, principal, providerSessionId, requestedInput = input) {
1097
+ const requesterId = principal === "owner" ? "owner" : principal.id;
1098
+ const boundDeviceId = principal === "owner" ? undefined : principal.deviceId;
1099
+ const sourceDeviceId = yield* Effect2.try({
1100
+ try: () => boundDeviceId === undefined || db.query("SELECT id FROM devices WHERE id = ? AND forgotten_at IS NULL").get(boundDeviceId) === null ? undefined : boundDeviceId,
1101
+ catch: operationError("RelayStore.createDelegation.source")
1102
+ });
1103
+ const submission = yield* Effect2.try({
1104
+ try: () => db.transaction(() => {
1105
+ const existing = requestedTask(requestedInput, principal);
1106
+ if (existing !== null)
1107
+ return { existing };
1108
+ if (input.expiresAt !== undefined) {
1109
+ if (input.provider === "grok-bot" || input.botId !== undefined)
1110
+ throw new TaskDeadlineError({
1111
+ status: 400,
1112
+ message: "Task deadlines require a coding provider"
1113
+ });
1114
+ if (taskDeadlinePassed(input))
1115
+ throw new TaskDeadlineError({
1116
+ status: 400,
1117
+ message: "Task deadline must be in the future"
1118
+ });
1119
+ }
1120
+ const timestamp = now();
1121
+ const threadId = input.threadId ?? makeThreadId();
1122
+ const task = Task.make({
1123
+ id: makeTaskId(),
1124
+ threadId,
1125
+ prompt: input.prompt,
1126
+ provider: input.provider ?? (input.botId === undefined ? "codex" : "grok-bot"),
1127
+ ...input.botId === undefined ? {} : { botId: input.botId },
1128
+ status: "queued",
1129
+ targetDeviceId,
1130
+ createdAt: timestamp,
1131
+ updatedAt: timestamp,
1132
+ ...input.expiresAt === undefined ? {} : { expiresAt: Timestamp.make(new Date(input.expiresAt).toISOString()) },
1133
+ ...input.context === undefined ? {} : { context: input.context },
1134
+ ...sourceDeviceId === undefined ? {} : { sourceDeviceId },
1135
+ ...input.parentTaskId === undefined ? {} : { parentTaskId: input.parentTaskId },
1136
+ ...input.workspace === undefined ? {} : { workspace: input.workspace },
1137
+ ...input.attachments === undefined || input.attachments.length === 0 ? {} : { inputAttachmentNames: input.attachments.map((attachment) => attachment.name) },
1138
+ ...providerSessionId === undefined ? {} : { providerSessionId }
1139
+ });
1140
+ const thread = input.threadId === undefined ? Thread.make({
1141
+ id: threadId,
1142
+ title: input.title ?? input.prompt.slice(0, 72),
1143
+ createdAt: timestamp,
1144
+ updatedAt: timestamp
1145
+ }) : undefined;
1146
+ const message = Message.make({
1147
+ id: makeMessageId(),
1148
+ threadId,
1149
+ role: "human",
1150
+ authorName: sourceDeviceId === undefined ? "User" : "Remote agent",
1151
+ content: input.prompt,
1152
+ createdAt: timestamp,
1153
+ taskId: task.id,
1154
+ ...sourceDeviceId === undefined ? {} : { deviceId: sourceDeviceId }
1155
+ });
1156
+ const outstanding = db.query(`SELECT COUNT(*) AS count FROM tasks WHERE target_device_id = ?
1157
+ AND status IN ('queued', 'assigned', 'running', 'needs_input', 'cancelling')`).get(targetDeviceId);
1158
+ if ((outstanding?.count ?? 0) >= 100) {
1159
+ throw new Error(`Device ${targetDeviceId} has reached its outstanding task limit`);
1160
+ }
1161
+ if (thread !== undefined) {
1162
+ db.query("INSERT INTO threads (id, title, created_at, updated_at) VALUES (?, ?, ?, ?)").run(thread.id, thread.title, thread.createdAt, thread.updatedAt);
1163
+ } else if (db.query("SELECT id FROM threads WHERE id = ?").get(threadId) === null) {
1164
+ throw new Error(`Unknown thread ${threadId}`);
1165
+ }
1166
+ db.query(`INSERT INTO tasks (
1167
+ id, thread_id, prompt, context, provider, status, source_device_id,
1168
+ requester_id, target_device_id, parent_task_id, workspace,
1169
+ provider_session_id, bot_id, created_at, updated_at, expires_at
1170
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(task.id, task.threadId, task.prompt, task.context ?? null, task.provider, task.status, task.sourceDeviceId ?? null, requesterId, task.targetDeviceId, task.parentTaskId ?? null, task.workspace ?? null, task.providerSessionId ?? null, task.botId ?? null, task.createdAt, task.updatedAt, task.expiresAt ?? null);
1171
+ for (const attachment of input.attachments ?? []) {
1172
+ const data = Buffer.from(attachment.data, "base64");
1173
+ if (data.length < 1 || data.length > maxAttachmentBytes) {
1174
+ throw new Error(`Attachment ${attachment.name} must be 1 to ${maxAttachmentBytes} bytes`);
1175
+ }
1176
+ db.query("INSERT INTO task_attachments (task_id, name, direction, data) VALUES (?, ?, 'input', ?)").run(task.id, attachment.name, data);
1177
+ }
1178
+ if (requestedInput.requestId !== undefined) {
1179
+ db.query("INSERT INTO task_requests (requester_id, request_id, input_hash, task_id) VALUES (?, ?, ?, ?)").run(requesterId, requestedInput.requestId.toLowerCase(), requestHash(requestedInput), task.id);
1180
+ }
1181
+ recordTaskTraceEvent(task.id, "queued", "Relay accepted the task", timestamp);
1182
+ db.query(`INSERT INTO messages (
1183
+ id, thread_id, role, kind, author_id, author_name, content, created_at,
1184
+ task_id, device_id
1185
+ ) VALUES (?, ?, ?, 'chat', ?, ?, ?, ?, ?, ?)`).run(message.id, message.threadId, message.role, sourceDeviceId ?? "user", message.authorName, message.content, message.createdAt, message.taskId ?? null, message.deviceId ?? null);
1186
+ db.query("UPDATE threads SET updated_at = ? WHERE id = ?").run(timestamp, threadId);
1187
+ return { created: task };
1188
+ })(),
1189
+ catch: (cause) => cause instanceof TaskRequestError || cause instanceof TaskDeadlineError ? cause : operationError("RelayStore.createDelegation")(cause)
1190
+ });
1191
+ return "existing" in submission ? yield* taskFromRow(db, submission.existing) : submission.created;
1192
+ });
1193
+ const threadContext = Effect2.fn("RelayStore.threadContext")(function* (threadId) {
1194
+ const threadRow = yield* Effect2.try({
1195
+ try: () => db.query("SELECT * FROM threads WHERE id = ?").get(threadId),
1196
+ catch: operationError("RelayStore.threadContext.thread")
1197
+ });
1198
+ if (threadRow === null) {
1199
+ return yield* Effect2.fail(new PersistenceError({
1200
+ operation: "RelayStore.threadContext",
1201
+ message: `Unknown thread ${threadId}`
1202
+ }));
1203
+ }
1204
+ const [messageRows, taskRows] = yield* Effect2.try({
1205
+ try: () => [
1206
+ db.query(`SELECT * FROM (
1207
+ SELECT *, rowid AS sequence FROM messages WHERE thread_id = ?
1208
+ ORDER BY created_at DESC, rowid DESC LIMIT 21
1209
+ ) ORDER BY created_at, sequence`).all(threadId),
1210
+ db.query(`SELECT * FROM (
1211
+ SELECT *, rowid AS sequence FROM tasks WHERE thread_id = ?
1212
+ ORDER BY created_at DESC, rowid DESC LIMIT 21
1213
+ ) ORDER BY created_at, sequence`).all(threadId)
1214
+ ],
1215
+ catch: operationError("RelayStore.threadContext.items")
1216
+ });
1217
+ const [thread, messages, tasks] = yield* Effect2.all([
1218
+ threadFromRow(threadRow),
1219
+ Effect2.forEach(messageRows.slice(-20), messageFromRow),
1220
+ Effect2.forEach(taskRows.slice(-20), (row) => taskFromRow(db, row))
1221
+ ]);
1222
+ const recentMessages = recentWithin(messages, 256 * 1024);
1223
+ const recentTasks = recentWithin(tasks, 768 * 1024);
1224
+ return ThreadContext.make({
1225
+ thread,
1226
+ messages: recentMessages.items,
1227
+ tasks: recentTasks.items,
1228
+ truncated: messageRows.length > 20 || taskRows.length > 20 || recentMessages.truncated || recentTasks.truncated
1229
+ });
1230
+ });
1231
+ const pendingTasksFor = Effect2.fn("RelayStore.pendingTasksFor")(function* (deviceId) {
1232
+ const rows = yield* Effect2.try({
1233
+ try: () => db.query(`SELECT * FROM tasks WHERE target_device_id = ?
1234
+ AND status IN ('queued', 'cancelling')
1235
+ ORDER BY dispatched_at IS NULL, created_at, rowid LIMIT 100`).all(deviceId),
1236
+ catch: operationError("RelayStore.pendingTasksFor")
1237
+ });
1238
+ return yield* Effect2.forEach(rows, (row) => taskFromRow(db, row));
1239
+ });
1240
+ const transition = Effect2.fn("RelayStore.transition")(function* (taskId, expected, update, event) {
1241
+ const current = yield* getTask(taskId);
1242
+ if (!expected.includes(current.status)) {
1243
+ return current;
1244
+ }
1245
+ const placeholders = expected.map(() => "?").join(", ");
1246
+ const timestamp = now();
1247
+ yield* Effect2.try({
1248
+ try: () => db.transaction(() => {
1249
+ const result = db.query(`UPDATE tasks SET status = ?, provider_session_id = ?, result = ?, error = ?,
1250
+ started_at = ?, completed_at = ?, updated_at = ?
1251
+ WHERE id = ? AND status IN (${placeholders})`).run(update.status ?? current.status, update.providerSessionId ?? current.providerSessionId ?? null, update.result ?? current.result ?? null, update.error ?? current.error ?? null, update.startedAt ?? current.startedAt ?? null, update.completedAt ?? current.completedAt ?? null, timestamp, taskId, ...expected);
1252
+ if (result.changes === 1 && event !== undefined) {
1253
+ recordTaskTraceEvent(taskId, event.kind, event.detail, timestamp);
1254
+ }
1255
+ if (result.changes === 1 && update.status !== undefined && ["completed", "failed", "cancelled"].includes(update.status)) {
1256
+ pruneTerminalHistory(taskId);
1257
+ }
1258
+ })(),
1259
+ catch: operationError("RelayStore.transition")
1260
+ });
1261
+ return yield* getTask(taskId);
1262
+ });
1263
+ const hasDispatchEvidence = Effect2.fn("RelayStore.hasDispatchEvidence")((taskId) => Effect2.try({
1264
+ try: () => db.query("SELECT 1 FROM tasks WHERE id = ? AND dispatched_at IS NOT NULL").get(taskId) !== null,
1265
+ catch: operationError("RelayStore.hasDispatchEvidence")
1266
+ }));
1267
+ const expireTask = Effect2.fn("RelayStore.expireTask")(function* (task) {
1268
+ if (!taskDeadlinePassed(task) || ["cancelling", "completed", "failed", "cancelled"].includes(task.status))
1269
+ return task;
1270
+ const neverDispatched = task.status === "queued" && task.runId === undefined && task.startedAt === undefined && !(yield* hasDispatchEvidence(task.id));
1271
+ return yield* transition(task.id, [task.status], {
1272
+ status: neverDispatched ? "failed" : "cancelling",
1273
+ error: taskDeadlineError,
1274
+ ...neverDispatched ? { completedAt: now() } : {}
1275
+ }, { kind: neverDispatched ? "failed" : "cancelling", detail: taskDeadlineError });
1276
+ });
1277
+ const expireTasks = Effect2.fn("RelayStore.expireTasks")(function* () {
1278
+ const rows = yield* Effect2.try({
1279
+ try: () => db.query(`SELECT * FROM tasks WHERE expires_at <= ? AND status IN ('queued', 'assigned', 'running', 'needs_input')
1280
+ ORDER BY expires_at, id LIMIT 100`).all(now()),
1281
+ catch: operationError("RelayStore.expireTasks")
1282
+ });
1283
+ return yield* Effect2.forEach(rows, (row) => taskFromRow(db, row).pipe(Effect2.flatMap(expireTask)));
1284
+ });
1285
+ const assignTask = Effect2.fn("RelayStore.assignTask")(function* (taskId) {
1286
+ const current = yield* getTask(taskId).pipe(Effect2.flatMap(expireTask));
1287
+ if (current.status !== "queued") {
1288
+ return current;
1289
+ }
1290
+ const timestamp = now();
1291
+ yield* Effect2.try({
1292
+ try: () => db.transaction(() => {
1293
+ const result = db.query(`UPDATE tasks SET status = 'assigned', updated_at = ?, run_id = CASE
1294
+ WHEN dispatched_at IS NOT NULL OR started_at IS NOT NULL OR (
1295
+ provider = 'grok-bot' AND NOT EXISTS (
1296
+ SELECT 1 FROM devices, json_each(devices.capabilities_json) capability
1297
+ WHERE devices.id = tasks.target_device_id
1298
+ AND json_extract(capability.value, '$.id') = 'task-clarification'
1299
+ )
1300
+ )
1301
+ THEN run_id ELSE COALESCE(run_id, ?) END,
1302
+ provider_session_id = CASE
1303
+ WHEN provider = 'grok-bot' THEN NULL
1304
+ WHEN started_at IS NULL THEN COALESCE((
1305
+ SELECT session_id FROM provider_sessions
1306
+ WHERE thread_id = tasks.thread_id AND device_id = tasks.target_device_id
1307
+ AND provider = tasks.provider
1308
+ ), provider_session_id)
1309
+ ELSE provider_session_id END
1310
+ WHERE id = ? AND status = 'queued' AND NOT EXISTS (
1311
+ SELECT 1 FROM tasks active
1312
+ WHERE active.target_device_id = ? AND active.id <> ?
1313
+ AND CASE WHEN active.provider = 'grok-bot'
1314
+ THEN 'grok-bot:' || active.bot_id ELSE 'cli' END = ?
1315
+ AND active.status IN ('assigned', 'running', 'cancelling')
1316
+ ) AND NOT EXISTS (
1317
+ SELECT 1 FROM device_operations active
1318
+ WHERE active.target_device_id = ?
1319
+ AND active.status IN ('assigned', 'running')
1320
+ )`).run(timestamp, crypto.randomUUID(), taskId, current.targetDeviceId, taskId, taskSlot(current), current.targetDeviceId);
1321
+ if (result.changes === 1) {
1322
+ recordTaskTraceEvent(taskId, "assigned", "Relay dispatched the task over the device WebSocket", timestamp);
1323
+ }
1324
+ })(),
1325
+ catch: operationError("RelayStore.assignTask")
1326
+ });
1327
+ return yield* getTask(taskId);
1328
+ });
1329
+ const requireTarget = Effect2.fn("RelayStore.requireTarget")(function* (taskId, deviceId) {
1330
+ const task = yield* getTask(taskId);
1331
+ if (task.targetDeviceId !== deviceId) {
1332
+ return yield* Effect2.fail(new PersistenceError({
1333
+ operation: "RelayStore.requireTarget",
1334
+ message: `Task ${taskId} belongs to another device`
1335
+ }));
1336
+ }
1337
+ return task;
1338
+ });
1339
+ const reportTaskProgress = Effect2.fn("RelayStore.reportTaskProgress")(function* (taskId, deviceId, note) {
1340
+ const task = yield* getTask(taskId);
1341
+ if (task.targetDeviceId !== deviceId) {
1342
+ return yield* new TaskProgressError({
1343
+ status: 403,
1344
+ message: "Only the target device can report progress"
1345
+ });
1346
+ }
1347
+ const progress = TaskProgress.make({ note, at: now() });
1348
+ const changed = yield* Effect2.try({
1349
+ try: () => db.query(`UPDATE tasks SET progress_note = ?, progress_at = ?, updated_at = ?
1350
+ WHERE id = ? AND target_device_id = ? AND status = 'running'`).run(note, progress.at, progress.at, taskId, deviceId).changes,
1351
+ catch: operationError("RelayStore.reportTaskProgress")
1352
+ });
1353
+ if (changed !== 1) {
1354
+ return yield* new TaskProgressError({
1355
+ status: 409,
1356
+ message: "Task must be running to report progress"
1357
+ });
1358
+ }
1359
+ return progress;
1360
+ });
1361
+ const requestTaskInput = Effect2.fn("RelayStore.requestTaskInput")(function* (taskId, deviceId, input, turnFinished = false) {
1362
+ const task = yield* getTask(taskId);
1363
+ if (task.targetDeviceId !== deviceId) {
1364
+ return yield* new TaskInputError({
1365
+ status: 403,
1366
+ message: "Only the target device can request input"
1367
+ });
1368
+ }
1369
+ if (taskDeadlinePassed(task))
1370
+ return yield* new TaskInputError({ status: 409, message: taskDeadlineError });
1371
+ const active = task.status === "running" || turnFinished && (task.status === "queued" || task.status === "assigned");
1372
+ if (!active || task.runId !== input.runId) {
1373
+ return yield* new TaskInputError({
1374
+ status: 409,
1375
+ message: "Input can only be requested by the current running turn"
1376
+ });
1377
+ }
1378
+ const row = yield* Effect2.try({
1379
+ try: () => db.query("SELECT * FROM devices WHERE id = ?").get(deviceId),
1380
+ catch: operationError("RelayStore.requestTaskInput.device")
1381
+ });
1382
+ const device = row === null ? undefined : yield* deviceFromRow(row);
1383
+ if (!device?.capabilities.some((capability) => capability.id === "task-clarification")) {
1384
+ return yield* new TaskInputError({
1385
+ status: 409,
1386
+ message: "Upgrade the target worker before requesting clarification"
1387
+ });
1388
+ }
1389
+ const history = task.clarifications ?? [];
1390
+ const pending = history.at(-1);
1391
+ if (pending !== undefined && pending.answer === undefined) {
1392
+ if (pending.question === input.question)
1393
+ return pending;
1394
+ return yield* new TaskInputError({
1395
+ status: 409,
1396
+ message: "This task already has an unanswered question"
1397
+ });
1398
+ }
1399
+ if (history.length >= maxTaskClarifications) {
1400
+ return yield* new TaskInputError({
1401
+ status: 409,
1402
+ message: `A task supports at most ${maxTaskClarifications} clarifications`
1403
+ });
1404
+ }
1405
+ const question = TaskClarification.make({
1406
+ id: ClarificationId.make(crypto.randomUUID()),
1407
+ question: input.question,
1408
+ at: now()
1409
+ });
1410
+ const changed = yield* Effect2.try({
1411
+ try: () => db.transaction(() => {
1412
+ const result = db.query(`UPDATE tasks SET clarifications_json = ?, updated_at = ?
1413
+ WHERE id = ? AND status = ? AND run_id = ?
1414
+ AND COALESCE(clarifications_json, '[]') = ?`).run(JSON.stringify([...history, question]), question.at, taskId, task.status, input.runId, JSON.stringify(history));
1415
+ if (result.changes === 1)
1416
+ recordTaskTraceEvent(taskId, "input_requested", "Worker requested clarification and is ending its turn", question.at);
1417
+ return result.changes;
1418
+ })(),
1419
+ catch: operationError("RelayStore.requestTaskInput")
1420
+ });
1421
+ if (changed !== 1)
1422
+ return yield* new TaskInputError({
1423
+ status: 409,
1424
+ message: "Task changed while requesting input; check its status"
1425
+ });
1426
+ return question;
1427
+ });
1428
+ const answerTaskInput = Effect2.fn("RelayStore.answerTaskInput")(function* (taskId, principal, input) {
1429
+ const task = yield* getTask(taskId);
1430
+ const requester = yield* Effect2.try({
1431
+ try: () => queryTask(taskId)?.requester_id,
1432
+ catch: operationError("RelayStore.answerTaskInput.requester")
1433
+ });
1434
+ if (principal !== "owner" && (principal.role !== "client" || requester !== principal.id)) {
1435
+ return yield* new TaskInputError({
1436
+ status: 403,
1437
+ message: "Only the original requester or relay owner can answer"
1438
+ });
1439
+ }
1440
+ if (taskDeadlinePassed(task))
1441
+ return yield* new TaskInputError({ status: 409, message: taskDeadlineError });
1442
+ const history = task.clarifications ?? [];
1443
+ const question = history.at(-1);
1444
+ if (task.status !== "needs_input" || question?.id !== input.requestId || question.answer !== undefined) {
1445
+ return yield* new TaskInputError({
1446
+ status: 409,
1447
+ message: "This question is no longer awaiting an answer; check task status"
1448
+ });
1449
+ }
1450
+ const timestamp = now();
1451
+ const answered = TaskClarification.make({
1452
+ ...question,
1453
+ answer: { text: input.answer, at: timestamp }
1454
+ });
1455
+ const changed = yield* Effect2.try({
1456
+ try: () => db.transaction(() => {
1457
+ const result = db.query(`UPDATE tasks SET status = 'queued', run_id = ?, clarifications_json = ?, updated_at = ?,
1458
+ result = NULL, error = NULL, completed_at = NULL, progress_note = NULL, progress_at = NULL,
1459
+ started_at = CASE WHEN provider = 'grok-bot' THEN NULL ELSE started_at END,
1460
+ dispatched_at = NULL
1461
+ WHERE id = ? AND status = 'needs_input' AND clarifications_json = ?`).run(crypto.randomUUID(), JSON.stringify([...history.slice(0, -1), answered]), timestamp, taskId, JSON.stringify(history));
1462
+ if (result.changes === 1) {
1463
+ recordTaskTraceEvent(taskId, "input_answered", "Requester answered the worker's question", timestamp);
1464
+ recordTaskTraceEvent(taskId, "queued", "Task queued to resume with the answer", timestamp);
1465
+ }
1466
+ return result.changes;
1467
+ })(),
1468
+ catch: operationError("RelayStore.answerTaskInput")
1469
+ });
1470
+ if (changed !== 1)
1471
+ return yield* new TaskInputError({
1472
+ status: 409,
1473
+ message: "Task changed while answering; check its status"
1474
+ });
1475
+ return yield* getTask(taskId);
1476
+ });
1477
+ const matchesTaskRun = (task, runId) => task.runId === undefined || task.runId === runId || runId === undefined && (task.clarifications?.length ?? 0) === 0;
1478
+ const terminal = Effect2.fn("RelayStore.terminal")(function* (taskId, deviceId, status, result, error, providerSessionId, attachments, runId) {
1479
+ const current = yield* requireTarget(taskId, deviceId);
1480
+ if (!matchesTaskRun(current, runId) || current.status === "cancelling" && status !== "cancelled" || ["completed", "failed", "cancelled"].includes(current.status)) {
1481
+ return current;
1482
+ }
1483
+ if (taskDeadlinePassed(current) && status !== "cancelled")
1484
+ return yield* expireTask(current);
1485
+ const deadlineExpired = taskDeadlinePassed(current) && (current.status !== "cancelling" || current.error === taskDeadlineError);
1486
+ const finalStatus = status === "cancelled" && deadlineExpired ? "failed" : status;
1487
+ const finalError = finalStatus === "failed" && deadlineExpired ? taskDeadlineError : error;
1488
+ const timestamp = now();
1489
+ yield* Effect2.try({
1490
+ try: () => db.transaction(() => {
1491
+ const saveProviderSession = () => {
1492
+ if (current.provider === "grok-bot" || providerSessionId === undefined)
1493
+ return;
1494
+ db.query(`INSERT INTO provider_sessions (thread_id, device_id, provider, session_id, updated_at)
1495
+ VALUES (?, ?, ?, ?, ?)
1496
+ ON CONFLICT(thread_id, device_id, provider) DO UPDATE SET
1497
+ session_id = excluded.session_id, updated_at = excluded.updated_at`).run(current.threadId, deviceId, current.provider, providerSessionId, timestamp);
1498
+ };
1499
+ if (current.status === "needs_input" && status !== "cancelled") {
1500
+ if (current.provider === "grok-bot" || providerSessionId === undefined)
1501
+ return;
1502
+ const updated2 = db.query(`UPDATE tasks SET provider_session_id = ?, updated_at = ?
1503
+ WHERE id = ? AND status = 'needs_input' AND run_id IS ?`).run(providerSessionId, timestamp, taskId, current.runId ?? null);
1504
+ if (updated2.changes === 1)
1505
+ saveProviderSession();
1506
+ return;
1507
+ }
1508
+ if (status !== "cancelled" && current.clarifications?.at(-1)?.answer === undefined && (current.clarifications?.length ?? 0) > 0) {
1509
+ const changed = db.query(`UPDATE tasks SET status = 'needs_input', provider_session_id = ?, updated_at = ?,
1510
+ progress_note = NULL, progress_at = NULL
1511
+ WHERE id = ? AND status = ? AND run_id IS ?`).run(current.provider === "grok-bot" ? null : providerSessionId ?? current.providerSessionId ?? null, timestamp, taskId, current.status, current.runId ?? null);
1512
+ if (changed.changes === 1) {
1513
+ saveProviderSession();
1514
+ recordTaskTraceEvent(taskId, "needs_input", "Worker paused for clarification", timestamp);
1515
+ }
1516
+ return;
1517
+ }
1518
+ const updated = db.query(`UPDATE tasks SET status = ?, result = ?, error = ?, provider_session_id = ?,
1519
+ completed_at = ?, updated_at = ?, progress_note = NULL, progress_at = NULL WHERE id = ?
1520
+ AND status NOT IN ('completed', 'failed', 'cancelled')
1521
+ AND (status <> 'needs_input' OR ? = 'cancelled')
1522
+ AND (status <> 'cancelling' OR ? = 'cancelled') AND run_id IS ?`).run(finalStatus, result ?? null, finalError ?? null, current.provider === "grok-bot" ? null : providerSessionId ?? current.providerSessionId ?? null, timestamp, timestamp, taskId, status, status, current.runId ?? null);
1523
+ if (updated.changes !== 1) {
1524
+ return;
1525
+ }
1526
+ db.query("DELETE FROM task_attachments WHERE task_id = ? AND direction = 'output'").run(taskId);
1527
+ if (finalStatus === "completed") {
1528
+ if ((attachments?.length ?? 0) > maxTaskAttachments) {
1529
+ throw new Error(`A task supports at most ${maxTaskAttachments} output files`);
1530
+ }
1531
+ for (const attachment of attachments ?? []) {
1532
+ const data = Buffer.from(attachment.data, "base64");
1533
+ if (data.length < 1 || data.length > maxAttachmentBytes) {
1534
+ throw new Error(`Attachment ${attachment.name} must be 1 to ${maxAttachmentBytes} bytes`);
1535
+ }
1536
+ db.query("INSERT INTO task_attachments (task_id, name, direction, data) VALUES (?, ?, 'output', ?)").run(taskId, attachment.name, data);
1537
+ }
1538
+ }
1539
+ recordTaskTraceEvent(taskId, finalStatus, finalStatus === "completed" ? "Target device completed the task" : finalStatus === "failed" ? "Target device reported a task failure" : "Target device acknowledged cancellation", timestamp);
1540
+ saveProviderSession();
1541
+ const content = result ?? finalError;
1542
+ if (content !== undefined) {
1543
+ const role = finalStatus === "completed" ? "agent" : "system";
1544
+ db.query(`INSERT INTO messages (
1545
+ id, thread_id, role, kind, author_id, author_name, content, created_at,
1546
+ task_id, device_id
1547
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(makeMessageId(), current.threadId, role, finalStatus === "failed" ? "error" : "chat", deviceId, finalStatus === "completed" ? providerName(current.provider) : "Cohall", content, timestamp, taskId, deviceId);
1548
+ db.query("UPDATE threads SET updated_at = ? WHERE id = ?").run(timestamp, current.threadId);
1549
+ }
1550
+ pruneTerminalHistory(taskId);
1551
+ })(),
1552
+ catch: operationError("RelayStore.terminal")
1553
+ });
1554
+ return yield* getTask(taskId);
1555
+ });
1556
+ const pauseTaskForInput = Effect2.fn("RelayStore.pauseTaskForInput")(function* (taskId, deviceId, input) {
1557
+ const task = yield* requireTarget(taskId, deviceId);
1558
+ if (task.runId !== input.runId || task.status !== "queued" && task.status !== "assigned" && task.status !== "running")
1559
+ return task;
1560
+ return yield* requestTaskInput(taskId, deviceId, input, true).pipe(Effect2.andThen(terminal(taskId, deviceId, "completed", "", undefined, undefined, undefined, input.runId)), Effect2.catchTag("RelayStore.TaskInputError", (cause) => terminal(taskId, deviceId, "failed", undefined, cause.message, undefined, undefined, input.runId)));
1561
+ });
1562
+ const requestCancellation = Effect2.fn("RelayStore.requestCancellation")(function* (taskId) {
1563
+ const current = yield* getTask(taskId).pipe(Effect2.flatMap(expireTask));
1564
+ if (["completed", "failed", "cancelled"].includes(current.status)) {
1565
+ return current;
1566
+ }
1567
+ const dispatched = yield* hasDispatchEvidence(taskId);
1568
+ if (current.provider === "grok-bot" && current.status !== "needs_input" && (current.status !== "queued" || current.startedAt !== undefined || dispatched)) {
1569
+ return yield* new PersistenceError({
1570
+ operation: "RelayStore.requestCancellation",
1571
+ message: "Stop this bot in Grok Bot; its gateway cannot cancel an individual Cohall request"
1572
+ });
1573
+ }
1574
+ if (current.status === "cancelling") {
1575
+ return current;
1576
+ }
1577
+ const timestamp = now();
1578
+ const neverDispatched = current.status === "queued" && !dispatched && (current.provider === "grok-bot" || current.runId === undefined && current.startedAt === undefined);
1579
+ return neverDispatched || current.status === "needs_input" && current.provider === "grok-bot" ? yield* transition(taskId, ["queued", "needs_input"], { status: "cancelled", completedAt: timestamp }, { kind: "cancelled", detail: "Client cancelled the task before dispatch" }) : yield* transition(taskId, ["queued", "assigned", "running", "needs_input"], {
1580
+ status: "cancelling"
1581
+ }, { kind: "cancelling", detail: "Client requested task cancellation" });
1582
+ });
1583
+ const requeueTasksFor = Effect2.fn("RelayStore.requeueTasksFor")(function* (deviceId) {
1584
+ const timestamp = now();
1585
+ yield* Effect2.try({
1586
+ try: () => db.transaction(() => {
1587
+ const interrupted = db.query(`SELECT id, ${interruptedTaskStatus} AS status FROM tasks WHERE target_device_id = ?
1588
+ AND status IN ('assigned', 'running')`).all(deviceId);
1589
+ db.query(`UPDATE tasks SET status = ${interruptedTaskStatus}, updated_at = ?, progress_note = NULL, progress_at = NULL,
1590
+ dispatched_at = CASE WHEN provider = 'grok-bot' THEN dispatched_at
1591
+ ELSE COALESCE(dispatched_at, started_at, updated_at) END
1592
+ WHERE target_device_id = ? AND status IN ('assigned', 'running')`).run(timestamp, deviceId);
1593
+ for (const task of interrupted) {
1594
+ recordTaskTraceEvent(TaskId.make(task.id), task.status === "needs_input" ? "needs_input" : "requeued", "Target device disconnected before task completion", timestamp);
1595
+ }
1596
+ })(),
1597
+ catch: operationError("RelayStore.requeueTasksFor")
1598
+ });
1599
+ });
1600
+ const sessionFor = Effect2.fn("RelayStore.sessionFor")(function* (threadId, deviceId, provider) {
1601
+ const row = yield* Effect2.try({
1602
+ try: () => db.query(`SELECT session_id FROM provider_sessions
1603
+ WHERE thread_id = ? AND device_id = ? AND provider = ?`).get(threadId, deviceId, provider),
1604
+ catch: operationError("RelayStore.sessionFor")
1605
+ });
1606
+ return row?.session_id;
1607
+ });
1608
+ const createPairing = Effect2.fn("RelayStore.createPairing")(function* (input) {
1609
+ const roles = [...new Set(input.roles)];
1610
+ if (roles.length === 0) {
1611
+ return yield* Effect2.fail(new PersistenceError({
1612
+ operation: "RelayStore.createPairing",
1613
+ message: "A pairing must allow at least one role"
1614
+ }));
1615
+ }
1616
+ const token = secret("pair");
1617
+ const expiresAt = new Date(Date.now() + 10 * 60 * 1000).toISOString();
1618
+ yield* Effect2.try({
1619
+ try: () => db.query(`INSERT INTO auth_pairings (token_hash, label, roles_json, expires_at, created_at)
1620
+ VALUES (?, ?, ?, ?, ?)`).run(tokenHash(token), input.label, JSON.stringify(roles), expiresAt, now()),
1621
+ catch: operationError("RelayStore.createPairing")
1622
+ });
1623
+ return PairingCredential.make({ token, expiresAt: Timestamp.make(expiresAt) });
1624
+ });
1625
+ const exchangePairing = Effect2.fn("RelayStore.exchangePairing")(function* (token) {
1626
+ const timestamp = now();
1627
+ const expiresAt = new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString();
1628
+ const created = yield* Effect2.try({
1629
+ try: () => db.transaction(() => {
1630
+ const pairing = db.query(`SELECT * FROM auth_pairings
1631
+ WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?`).get(tokenHash(token), timestamp);
1632
+ if (pairing === null) {
1633
+ throw new Error("Pairing credential is invalid, expired, or already used");
1634
+ }
1635
+ const roles = Schema2.decodeUnknownSync(Schema2.Array(ConnectionRole))(JSON.parse(pairing.roles_json));
1636
+ const deviceId = roles.includes("device") ? makeDeviceId() : undefined;
1637
+ const consumed = db.query("UPDATE auth_pairings SET used_at = ? WHERE token_hash = ? AND used_at IS NULL").run(timestamp, pairing.token_hash);
1638
+ if (consumed.changes !== 1) {
1639
+ throw new Error("Pairing credential was already used");
1640
+ }
1641
+ return [...new Set(roles)].map((role) => {
1642
+ const sessionToken = secret("session");
1643
+ const row = {
1644
+ id: makeAuthSessionId(),
1645
+ token_hash: tokenHash(sessionToken),
1646
+ label: pairing.label,
1647
+ roles_json: JSON.stringify([role]),
1648
+ created_at: timestamp,
1649
+ expires_at: expiresAt,
1650
+ last_seen_at: timestamp,
1651
+ bound_device_id: deviceId ?? null,
1652
+ revoked_at: null
1653
+ };
1654
+ db.query(`INSERT INTO auth_sessions (
1655
+ id, token_hash, label, roles_json, created_at, expires_at, last_seen_at,
1656
+ bound_device_id
1657
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(row.id, row.token_hash, row.label, row.roles_json, row.created_at, row.expires_at, row.last_seen_at, row.bound_device_id);
1658
+ return { token: sessionToken, row };
1659
+ });
1660
+ })(),
1661
+ catch: operationError("RelayStore.exchangePairing")
1662
+ });
1663
+ const credentials = yield* Effect2.forEach(created, ({ token: sessionToken, row }) => authSessionFromRow(row).pipe(Effect2.map((session) => ({ token: sessionToken, session }))));
1664
+ return PairingResult.make({ credentials });
1665
+ });
1666
+ const authenticateSession = Effect2.fn("RelayStore.authenticateSession")(function* (token, role) {
1667
+ const row = yield* Effect2.try({
1668
+ try: () => db.query(`SELECT * FROM auth_sessions
1669
+ WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > ?`).get(tokenHash(token), now()),
1670
+ catch: operationError("RelayStore.authenticateSession")
1671
+ });
1672
+ if (row === null || !rolesFromRow(row).includes(role)) {
1673
+ return;
1674
+ }
1675
+ const lastSeenAt = now();
1676
+ yield* Effect2.try({
1677
+ try: () => db.query("UPDATE auth_sessions SET last_seen_at = ? WHERE id = ?").run(lastSeenAt, row.id),
1678
+ catch: operationError("RelayStore.authenticateSession.touch")
1679
+ });
1680
+ const session = yield* authSessionFromRow(row);
1681
+ return AuthSession.make({ ...session, lastSeenAt });
1682
+ });
1683
+ const listAuthSessions = Effect2.fn("RelayStore.listAuthSessions")(function* () {
1684
+ const rows = yield* Effect2.try({
1685
+ try: () => db.query("SELECT * FROM auth_sessions ORDER BY created_at DESC, id LIMIT 1000").all(),
1686
+ catch: operationError("RelayStore.listAuthSessions")
1687
+ });
1688
+ return yield* Effect2.forEach(rows, authSessionFromRow);
1689
+ });
1690
+ const revokeAuthSession = Effect2.fn("RelayStore.revokeAuthSession")(function* (sessionId) {
1691
+ const revokedAt = now();
1692
+ const result = yield* Effect2.try({
1693
+ try: () => db.query("UPDATE auth_sessions SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL").run(revokedAt, sessionId),
1694
+ catch: operationError("RelayStore.revokeAuthSession")
1695
+ });
1696
+ if (result.changes !== 1) {
1697
+ return yield* Effect2.fail(new PersistenceError({
1698
+ operation: "RelayStore.revokeAuthSession",
1699
+ message: `Unknown or already revoked session ${sessionId}`
1700
+ }));
1701
+ }
1702
+ const row = db.query("SELECT * FROM auth_sessions WHERE id = ?").get(sessionId);
1703
+ if (row === null) {
1704
+ return yield* Effect2.fail(new PersistenceError({
1705
+ operation: "RelayStore.revokeAuthSession.read",
1706
+ message: `Session ${sessionId} disappeared after revocation`
1707
+ }));
1708
+ }
1709
+ return yield* authSessionFromRow(row);
1710
+ });
1711
+ return Service.of({
1712
+ recover,
1713
+ listDevices,
1714
+ deviceOverview,
1715
+ listDevicePage,
1716
+ usage,
1717
+ forgetDevice,
1718
+ upsertDevice,
1719
+ heartbeat: (deviceId, status, bots) => updateDeviceStatus(deviceId, status, bots),
1720
+ markDeviceOffline: (deviceId) => updateDeviceStatus(deviceId, "offline"),
1721
+ createDelegation,
1722
+ expireTasks,
1723
+ findDelegation,
1724
+ getTask,
1725
+ reportTaskProgress,
1726
+ requestTaskInput,
1727
+ pauseTaskForInput,
1728
+ answerTaskInput,
1729
+ listAttachments,
1730
+ readAttachment,
1731
+ inboxFor,
1732
+ acknowledgeCompletion,
1733
+ traceTask,
1734
+ threadContext,
1735
+ pendingTasksFor,
1736
+ assignTask,
1737
+ markTaskDispatched: (taskId) => Effect2.try({
1738
+ try: () => {
1739
+ db.query("UPDATE tasks SET dispatched_at = COALESCE(dispatched_at, ?) WHERE id = ? AND status = 'assigned'").run(now(), taskId);
1740
+ },
1741
+ catch: operationError("RelayStore.markTaskDispatched")
1742
+ }),
1743
+ rollbackAssignment: (taskId) => transition(taskId, ["assigned"], { status: "queued" }, { kind: "requeued", detail: "Target device was unavailable during dispatch" }),
1744
+ acceptTask: (taskId, deviceId, runId) => requireTarget(taskId, deviceId).pipe(Effect2.flatMap((task) => matchesTaskRun(task, runId) ? transition(taskId, ["assigned"], { status: "running", startedAt: task.startedAt ?? now() }, {
1745
+ kind: "running",
1746
+ detail: task.startedAt === undefined ? "Target device accepted the task and started the provider" : "Target device accepted the task again"
1747
+ }) : Effect2.succeed(task))),
1748
+ finishTask: (taskId, deviceId, result, providerSessionId, attachments, runId) => terminal(taskId, deviceId, "completed", result, undefined, providerSessionId, attachments, runId),
1749
+ failTask: (taskId, deviceId, error, runId) => terminal(taskId, deviceId, "failed", undefined, error, undefined, undefined, runId),
1750
+ acknowledgeCancellation: (taskId, deviceId, runId) => terminal(taskId, deviceId, "cancelled", undefined, undefined, undefined, undefined, runId),
1751
+ requestCancellation,
1752
+ requeueTasksFor,
1753
+ createUpgradeOperations,
1754
+ listOperations,
1755
+ abandonOperation,
1756
+ pendingOperationsFor,
1757
+ assignOperation,
1758
+ rollbackOperation: (operationId) => transitionOperation(operationId, ["assigned"], "queued"),
1759
+ acceptOperation,
1760
+ finishOperation,
1761
+ failOperation,
1762
+ requeueOperationsFor,
1763
+ sessionFor,
1764
+ createPairing,
1765
+ exchangePairing,
1766
+ authenticateSession,
1767
+ listAuthSessions,
1768
+ revokeAuthSession
1769
+ });
1770
+ };
1771
+ var migrate = (db) => Effect2.try({
1772
+ try: () => {
1773
+ db.exec("PRAGMA journal_mode = WAL");
1774
+ db.exec("PRAGMA foreign_keys = ON");
1775
+ db.exec("PRAGMA busy_timeout = 5000");
1776
+ db.exec(`
1777
+ CREATE TABLE IF NOT EXISTS devices (
1778
+ id TEXT PRIMARY KEY, name TEXT NOT NULL, hostname TEXT NOT NULL,
1779
+ platform TEXT NOT NULL, architecture TEXT NOT NULL, status TEXT NOT NULL,
1780
+ providers_json TEXT NOT NULL, bots_json TEXT, capabilities_json TEXT NOT NULL,
1781
+ workspaces_json TEXT NOT NULL, version TEXT NOT NULL, last_seen_at TEXT NOT NULL,
1782
+ connected_at TEXT, forgotten_at TEXT, description TEXT
1783
+ );
1784
+ CREATE TABLE IF NOT EXISTS threads (
1785
+ id TEXT PRIMARY KEY, title TEXT NOT NULL, created_at TEXT NOT NULL,
1786
+ updated_at TEXT NOT NULL, archived_at TEXT,
1787
+ default_device_id TEXT REFERENCES devices(id)
1788
+ );
1789
+ CREATE TABLE IF NOT EXISTS messages (
1790
+ id TEXT PRIMARY KEY, thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
1791
+ role TEXT NOT NULL, kind TEXT NOT NULL DEFAULT 'chat', author_id TEXT NOT NULL,
1792
+ author_name TEXT NOT NULL, content TEXT NOT NULL, created_at TEXT NOT NULL,
1793
+ task_id TEXT, reply_to TEXT, device_id TEXT REFERENCES devices(id)
1794
+ );
1795
+ CREATE INDEX IF NOT EXISTS messages_thread_created ON messages(thread_id, created_at);
1796
+ CREATE INDEX IF NOT EXISTS messages_task_id ON messages(task_id);
1797
+ CREATE TABLE IF NOT EXISTS tasks (
1798
+ id TEXT PRIMARY KEY, thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
1799
+ prompt TEXT NOT NULL, context TEXT, provider TEXT NOT NULL, bot_id TEXT, status TEXT NOT NULL,
1800
+ source_device_id TEXT REFERENCES devices(id),
1801
+ requester_id TEXT, completion_seen_at TEXT,
1802
+ target_device_id TEXT NOT NULL REFERENCES devices(id), parent_task_id TEXT,
1803
+ workspace TEXT, provider_session_id TEXT, result TEXT, error TEXT,
1804
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL, started_at TEXT, completed_at TEXT,
1805
+ dispatched_at TEXT, progress_note TEXT, progress_at TEXT,
1806
+ run_id TEXT, clarifications_json TEXT, expires_at TEXT
1807
+ );
1808
+ CREATE INDEX IF NOT EXISTS tasks_thread_created ON tasks(thread_id, created_at);
1809
+ CREATE INDEX IF NOT EXISTS tasks_target_status ON tasks(target_device_id, status);
1810
+ CREATE INDEX IF NOT EXISTS tasks_terminal_history
1811
+ ON tasks(completed_at DESC, updated_at DESC, id DESC)
1812
+ WHERE status IN ('completed', 'failed', 'cancelled');
1813
+ CREATE TABLE IF NOT EXISTS task_requests (
1814
+ requester_id TEXT NOT NULL, request_id TEXT NOT NULL, input_hash TEXT NOT NULL,
1815
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
1816
+ PRIMARY KEY(requester_id, request_id)
1817
+ );
1818
+ CREATE INDEX IF NOT EXISTS task_requests_retained_task
1819
+ ON task_requests(task_id) WHERE task_id IS NOT NULL;
1820
+ CREATE TABLE IF NOT EXISTS task_attachments (
1821
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1822
+ name TEXT NOT NULL, direction TEXT NOT NULL CHECK(direction IN ('input', 'output')),
1823
+ data BLOB NOT NULL CHECK(length(data) BETWEEN 1 AND ${maxAttachmentBytes}),
1824
+ PRIMARY KEY(task_id, direction, name)
1825
+ );
1826
+ CREATE TABLE IF NOT EXISTS task_trace_events (
1827
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1828
+ task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
1829
+ kind TEXT NOT NULL, created_at TEXT NOT NULL, detail TEXT
1830
+ );
1831
+ CREATE INDEX IF NOT EXISTS task_trace_events_task_id
1832
+ ON task_trace_events(task_id, id);
1833
+ CREATE TABLE IF NOT EXISTS provider_sessions (
1834
+ thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
1835
+ device_id TEXT NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
1836
+ provider TEXT NOT NULL, session_id TEXT NOT NULL, updated_at TEXT NOT NULL,
1837
+ PRIMARY KEY(thread_id, device_id, provider)
1838
+ );
1839
+ CREATE TABLE IF NOT EXISTS device_operations (
1840
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, status TEXT NOT NULL,
1841
+ target_device_id TEXT NOT NULL REFERENCES devices(id),
1842
+ requested_version TEXT NOT NULL, restart INTEGER NOT NULL,
1843
+ result TEXT, error TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
1844
+ completed_at TEXT
1845
+ );
1846
+ CREATE INDEX IF NOT EXISTS device_operations_target_status
1847
+ ON device_operations(target_device_id, status);
1848
+ CREATE TABLE IF NOT EXISTS auth_pairings (
1849
+ token_hash TEXT PRIMARY KEY, label TEXT NOT NULL, roles_json TEXT NOT NULL,
1850
+ expires_at TEXT NOT NULL, created_at TEXT NOT NULL, used_at TEXT
1851
+ );
1852
+ CREATE TABLE IF NOT EXISTS auth_sessions (
1853
+ id TEXT PRIMARY KEY, token_hash TEXT NOT NULL UNIQUE, label TEXT NOT NULL,
1854
+ roles_json TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL,
1855
+ last_seen_at TEXT NOT NULL, bound_device_id TEXT, revoked_at TEXT
1856
+ );
1857
+ CREATE INDEX IF NOT EXISTS auth_sessions_token ON auth_sessions(token_hash);
1858
+ `);
1859
+ const deviceColumns = db.query("PRAGMA table_info(devices)").all();
1860
+ if (!deviceColumns.some((column) => column.name === "forgotten_at")) {
1861
+ db.exec("ALTER TABLE devices ADD COLUMN forgotten_at TEXT");
1862
+ }
1863
+ if (!deviceColumns.some((column) => column.name === "bots_json")) {
1864
+ db.exec("ALTER TABLE devices ADD COLUMN bots_json TEXT");
1865
+ }
1866
+ if (!deviceColumns.some((column) => column.name === "description")) {
1867
+ db.exec("ALTER TABLE devices ADD COLUMN description TEXT");
1868
+ }
1869
+ const taskColumns = db.query("PRAGMA table_info(tasks)").all();
1870
+ if (!taskColumns.some((column) => column.name === "expires_at"))
1871
+ db.exec("ALTER TABLE tasks ADD COLUMN expires_at TEXT");
1872
+ db.exec("CREATE INDEX IF NOT EXISTS tasks_pending_deadline ON tasks(expires_at) WHERE status IN ('queued', 'assigned', 'running', 'needs_input')");
1873
+ if (!taskColumns.some((column) => column.name === "run_id"))
1874
+ db.exec("ALTER TABLE tasks ADD COLUMN run_id TEXT");
1875
+ if (!taskColumns.some((column) => column.name === "clarifications_json"))
1876
+ db.exec("ALTER TABLE tasks ADD COLUMN clarifications_json TEXT");
1877
+ if (!taskColumns.some((column) => column.name === "progress_note")) {
1878
+ db.exec("ALTER TABLE tasks ADD COLUMN progress_note TEXT");
1879
+ }
1880
+ if (!taskColumns.some((column) => column.name === "progress_at")) {
1881
+ db.exec("ALTER TABLE tasks ADD COLUMN progress_at TEXT");
1882
+ }
1883
+ if (!taskColumns.some((column) => column.name === "bot_id")) {
1884
+ db.exec("ALTER TABLE tasks ADD COLUMN bot_id TEXT");
1885
+ }
1886
+ if (!taskColumns.some((column) => column.name === "requester_id")) {
1887
+ db.exec("ALTER TABLE tasks ADD COLUMN requester_id TEXT");
1888
+ }
1889
+ if (!taskColumns.some((column) => column.name === "completion_seen_at")) {
1890
+ db.exec("ALTER TABLE tasks ADD COLUMN completion_seen_at TEXT");
1891
+ }
1892
+ db.exec(`CREATE INDEX IF NOT EXISTS tasks_unseen_inbox
1893
+ ON tasks(requester_id, COALESCE(completed_at, updated_at), id)
1894
+ WHERE completion_seen_at IS NULL
1895
+ AND status IN ('needs_input', 'completed', 'failed', 'cancelled')`);
1896
+ db.exec("DROP INDEX IF EXISTS tasks_inbox");
1897
+ if (!taskColumns.some((column) => column.name === "dispatched_at")) {
1898
+ db.transaction(() => {
1899
+ db.exec("ALTER TABLE tasks ADD COLUMN dispatched_at TEXT");
1900
+ db.exec(`UPDATE tasks SET dispatched_at = COALESCE(started_at, updated_at)
1901
+ WHERE provider = 'grok-bot' AND status NOT IN ('completed', 'failed', 'cancelled')`);
1902
+ })();
1903
+ }
1904
+ db.exec(`UPDATE tasks SET dispatched_at = COALESCE(started_at, updated_at)
1905
+ WHERE provider <> 'grok-bot' AND dispatched_at IS NULL AND run_id IS NULL
1906
+ AND status NOT IN ('completed', 'failed', 'cancelled')
1907
+ AND (status IN ('assigned', 'running') OR started_at IS NOT NULL OR EXISTS (
1908
+ SELECT 1 FROM task_trace_events
1909
+ WHERE task_id = tasks.id AND kind IN ('assigned', 'running')
1910
+ ))`);
1911
+ },
1912
+ catch: operationError("RelayStore.migrate")
1913
+ });
1914
+ var layer = (path, retainedTerminalTasks = 1000) => Layer.effect(Service, Effect2.acquireRelease(Effect2.try({
1915
+ try: () => new Database(path),
1916
+ catch: operationError("RelayStore.open")
1917
+ }).pipe(Effect2.tap(migrate)), (db) => Effect2.sync(() => db.close())).pipe(Effect2.map((db) => makeService(db, retainedTerminalTasks))));
1918
+ var layerFromDatabase = (db) => Layer.effect(Service, migrate(db).pipe(Effect2.map(() => makeService(db))));
1919
+
1920
+ // apps/relay/src/main.ts
1921
+ class RequestError extends Schema3.TaggedErrorClass()("Relay.RequestError", {
1922
+ status: Schema3.Int,
1923
+ message: Schema3.String
1924
+ }) {
1925
+ }
1926
+ var relayListenOptions = (configuration, environment = process.env, pid = process.pid) => {
1927
+ const listenPid = Number(environment.LISTEN_PID);
1928
+ const listenFds = Number(environment.LISTEN_FDS);
1929
+ if (listenPid !== pid || !Number.isInteger(listenFds) || listenFds < 1) {
1930
+ return { host: configuration.host, port: configuration.port };
1931
+ }
1932
+ const descriptorNames = environment.LISTEN_FDNAMES?.split(":") ?? [];
1933
+ const namedIndex = descriptorNames.indexOf("cohall-relay");
1934
+ if (namedIndex >= 0 && namedIndex < listenFds) {
1935
+ return { fd: 3 + namedIndex };
1936
+ }
1937
+ if (listenFds === 1) {
1938
+ return { fd: 3 };
1939
+ }
1940
+ throw new Error("Cohall received multiple systemd sockets but none was named cohall-relay");
1941
+ };
1942
+ var json = (value, status = 200) => Response.json(value, {
1943
+ status,
1944
+ headers: {
1945
+ "cache-control": "no-store",
1946
+ "x-content-type-options": "nosniff"
1947
+ }
1948
+ });
1949
+ var requestBody = (request, limit) => {
1950
+ if (request.method === "GET" || request.method === "HEAD") {
1951
+ return Promise.resolve(undefined);
1952
+ }
1953
+ return new Promise((resolve2, reject) => {
1954
+ const chunks = [];
1955
+ let size = 0;
1956
+ const cleanup = () => {
1957
+ request.off("data", onData);
1958
+ request.off("end", onEnd);
1959
+ request.off("error", onError);
1960
+ };
1961
+ const onData = (chunk) => {
1962
+ size += chunk.byteLength;
1963
+ if (size <= limit) {
1964
+ chunks.push(chunk);
1965
+ return;
1966
+ }
1967
+ cleanup();
1968
+ reject(new Error(`Request body exceeded ${Math.floor(limit / 1024)} KiB`));
1969
+ };
1970
+ const onEnd = () => {
1971
+ cleanup();
1972
+ resolve2(Buffer.concat(chunks, size));
1973
+ };
1974
+ const onError = (cause) => {
1975
+ cleanup();
1976
+ reject(cause);
1977
+ };
1978
+ request.on("data", onData);
1979
+ request.once("end", onEnd);
1980
+ request.once("error", onError);
1981
+ });
1982
+ };
1983
+ var maxTaskRequestBodyBytes = 3 * 1024 * 1024;
1984
+ var webRequest = async (request) => {
1985
+ const headers = new Headers;
1986
+ for (let index = 0;index < request.rawHeaders.length; index += 2) {
1987
+ const name = request.rawHeaders[index];
1988
+ const value = request.rawHeaders[index + 1];
1989
+ if (name !== undefined && value !== undefined) {
1990
+ headers.append(name, value);
1991
+ }
1992
+ }
1993
+ const pathname = new URL(request.url ?? "/", "http://cohall.local").pathname;
1994
+ const payload = await requestBody(request, pathname === "/api/tasks" ? maxTaskRequestBodyBytes : maxAttachmentBytes);
1995
+ return new Request(new URL(request.url ?? "/", "http://cohall.local"), {
1996
+ method: request.method ?? "GET",
1997
+ headers,
1998
+ ...payload === undefined ? {} : { body: new Uint8Array(payload) }
1999
+ });
2000
+ };
2001
+ var sendResponse = async (target, response) => {
2002
+ target.statusCode = response.status;
2003
+ response.headers.forEach((value, name) => target.setHeader(name, value));
2004
+ target.end(Buffer.from(await response.arrayBuffer()));
2005
+ };
2006
+ var socketText = (message) => {
2007
+ if (Buffer.isBuffer(message)) {
2008
+ return message.toString("utf8");
2009
+ }
2010
+ if (message instanceof ArrayBuffer) {
2011
+ return Buffer.from(message).toString("utf8");
2012
+ }
2013
+ if (Array.isArray(message)) {
2014
+ return Buffer.concat(message).toString("utf8");
2015
+ }
2016
+ return Buffer.from(message).toString("utf8");
2017
+ };
2018
+ var rejectUpgrade = (socket, status, message) => {
2019
+ socket.write(`HTTP/1.1 ${status} ${message}\r
2020
+ Connection: close\r
2021
+ Content-Length: 0\r
2022
+ \r
2023
+ `);
2024
+ if ("destroy" in socket && typeof socket.destroy === "function") {
2025
+ socket.destroy();
2026
+ }
2027
+ };
2028
+ var body = (request, decode2) => Effect3.tryPromise({
2029
+ try: () => request.json(),
2030
+ catch: () => new RequestError({ status: 400, message: "Expected a JSON request body" })
2031
+ }).pipe(Effect3.flatMap(decode2), Effect3.mapError((cause) => cause instanceof RequestError ? cause : new RequestError({ status: 400, message: String(cause).slice(0, 2048) })));
2032
+ var pathId = (schema, value) => Schema3.decodeUnknownEffect(schema)(value).pipe(Effect3.mapError(() => new RequestError({ status: 400, message: `Invalid identifier: ${value}` })));
2033
+ var scoreDevice = (device, input, sourceDeviceId) => {
2034
+ const prompt = `${input.prompt} ${input.context ?? ""}`.toLowerCase();
2035
+ const needsXcode = /\b(xcode|ios|macos|swiftui|app store)\b/.test(prompt);
2036
+ const needsBrowser = /\b(browser|chrome|youtube|twitter|logged[- ]?in|signed[- ]?in|x\.com)\b/.test(prompt);
2037
+ const paths = device.platform === "windows" ? win32 : posix;
2038
+ const workspace = input.workspace;
2039
+ const matchesWorkspace = workspace !== undefined && paths.isAbsolute(workspace) && device.workspaces.some(({ path }) => {
2040
+ const child = paths.relative(path, workspace);
2041
+ return child !== ".." && !child.startsWith(`..${paths.sep}`) && !paths.isAbsolute(child);
2042
+ });
2043
+ return (device.status === "offline" ? 0 : 100) + (matchesWorkspace ? 80 : 0) + (needsXcode && device.capabilities.some((capability) => capability.id === "xcode") ? 60 : 0) + (needsBrowser && device.capabilities.some((capability) => capability.id === "browser-session") ? 40 : 0) + (sourceDeviceId === device.id ? -5 : 0);
2044
+ };
2045
+ var resolveDelegation = (input, sourceDeviceId) => Effect3.gen(function* () {
2046
+ const store = yield* exports_store.Service;
2047
+ const ancestors = [];
2048
+ const seen = new Set;
2049
+ let nextParentId = input.parentTaskId;
2050
+ while (nextParentId !== undefined && !seen.has(nextParentId)) {
2051
+ const parentId = nextParentId;
2052
+ seen.add(parentId);
2053
+ const parent2 = yield* store.getTask(parentId).pipe(Effect3.catch((cause) => {
2054
+ const missing = cause.message === `Unknown task ${parentId}`;
2055
+ if (missing && ancestors.length > 0)
2056
+ return Effect3.succeed(undefined);
2057
+ return Effect3.fail(new RequestError({ status: missing ? 404 : 500, message: cause.message }));
2058
+ }));
2059
+ if (parent2 === undefined)
2060
+ break;
2061
+ ancestors.push(parent2);
2062
+ nextParentId = parent2.parentTaskId;
2063
+ }
2064
+ const parent = ancestors[0];
2065
+ if (parent !== undefined && input.threadId !== undefined && input.threadId !== parent.threadId) {
2066
+ return yield* new RequestError({
2067
+ status: 400,
2068
+ message: "A child task must use its parent's thread"
2069
+ });
2070
+ }
2071
+ const resolvedInput = parent === undefined ? input : { ...input, threadId: parent.threadId };
2072
+ const devices = yield* store.listDevices().pipe(Effect3.mapError((cause) => new RequestError({ status: 500, message: cause.message })));
2073
+ const provider = input.provider ?? (input.botId === undefined ? "codex" : "grok-bot");
2074
+ if (input.expiresAt !== undefined && provider === "grok-bot")
2075
+ return yield* new RequestError({
2076
+ status: 400,
2077
+ message: "Task deadlines require a coding provider"
2078
+ });
2079
+ const hasAttachments = (input.attachments?.length ?? 0) > 0;
2080
+ if (hasAttachments && provider === "grok-bot") {
2081
+ return yield* new RequestError({
2082
+ status: 400,
2083
+ message: "File attachments require a coding provider"
2084
+ });
2085
+ }
2086
+ const slot = taskSlot({
2087
+ provider,
2088
+ ...input.botId === undefined ? {} : { botId: input.botId }
2089
+ });
2090
+ const blocked = new Set(ancestors.filter((task) => !isTerminalTask(task) && task.status !== "needs_input" && taskSlot(task) === slot).map((task) => task.targetDeviceId));
2091
+ if (input.targetDeviceId !== undefined) {
2092
+ const target = devices.find((device) => device.id === input.targetDeviceId);
2093
+ if (target === undefined) {
2094
+ return yield* new RequestError({
2095
+ status: 404,
2096
+ message: `Unknown target device ${input.targetDeviceId}`
2097
+ });
2098
+ }
2099
+ if (!target.providers.includes(provider)) {
2100
+ return yield* new RequestError({
2101
+ status: 409,
2102
+ message: `${target.name} does not advertise the ${provider} provider`
2103
+ });
2104
+ }
2105
+ if (input.expiresAt !== undefined && !target.capabilities.some((capability) => capability.id === "task-deadlines"))
2106
+ return yield* new RequestError({
2107
+ status: 409,
2108
+ message: `${target.name} does not support task deadlines; upgrade its Cohall worker`
2109
+ });
2110
+ if (hasAttachments && !target.capabilities.some((capability) => capability.id === "task-attachments")) {
2111
+ return yield* new RequestError({
2112
+ status: 409,
2113
+ message: `${target.name} does not support file attachments; upgrade its Cohall worker`
2114
+ });
2115
+ }
2116
+ if (input.botId !== undefined && !target.bots?.some((bot) => bot.id === input.botId)) {
2117
+ return yield* new RequestError({
2118
+ status: 404,
2119
+ message: `${target.name} does not advertise bot ${input.botId}; refresh the bot list`
2120
+ });
2121
+ }
2122
+ if (blocked.has(target.id)) {
2123
+ return yield* new RequestError({
2124
+ status: 409,
2125
+ message: `${target.name} cannot run this task while an unfinished parent occupies the same worker slot; select another device or bot`
2126
+ });
2127
+ }
2128
+ return { input: resolvedInput, targetDeviceId: target.id };
2129
+ }
2130
+ const providerDevices = devices.filter((device) => device.providers.includes(provider) && (input.expiresAt === undefined || device.capabilities.some((capability) => capability.id === "task-deadlines")) && (input.botId === undefined || device.bots?.some((bot) => bot.id === input.botId)));
2131
+ const candidates = hasAttachments ? providerDevices.filter((device) => device.capabilities.some((capability) => capability.id === "task-attachments")) : providerDevices;
2132
+ if (input.botId !== undefined && candidates.length > 1) {
2133
+ return yield* new RequestError({
2134
+ status: 409,
2135
+ message: `Bot ${input.botId} is advertised by more than one device; select a device`
2136
+ });
2137
+ }
2138
+ const selected = candidates.filter((device) => !blocked.has(device.id)).sort((left, right) => scoreDevice(right, input, sourceDeviceId) - scoreDevice(left, input, sourceDeviceId))[0];
2139
+ if (selected === undefined) {
2140
+ return yield* new RequestError({
2141
+ status: 409,
2142
+ message: candidates.length > 0 ? "No available delegation target avoids an unfinished parent's worker slot; select another device or bot" : hasAttachments && providerDevices.length > 0 ? `No Cohall device advertising the ${provider} provider supports file attachments; upgrade a Cohall worker` : input.expiresAt !== undefined ? `No Cohall device advertising the ${provider} provider supports task deadlines; upgrade a Cohall worker` : input.botId === undefined ? `No Cohall device advertises the ${provider} provider` : `No Cohall device advertises bot ${input.botId}; refresh the bot list`
2143
+ });
2144
+ }
2145
+ return { input: resolvedInput, targetDeviceId: selected.id };
2146
+ });
2147
+ var canReadTaskAttachments = (principal, task) => principal === "owner" || principal.role === "client" || principal.deviceId === task.targetDeviceId;
2148
+ var requiresClarificationSupport = (task) => (task.clarifications?.length ?? 0) > 0 || task.provider === "grok-bot" && task.runId !== undefined;
2149
+ var canDispatchTaskToDevice = (task, device) => (task.expiresAt === undefined || device?.capabilities.some((capability) => capability.id === "task-deadlines") === true) && ((task.inputAttachmentNames?.length ?? 0) === 0 || device?.capabilities.some((capability) => capability.id === "task-attachments") === true) && (!requiresClarificationSupport(task) || device?.capabilities.some((capability) => capability.id === "task-clarification") === true);
2150
+ var runRelay = async () => {
2151
+ const configuration = await Effect3.runPromise(loadEnvironmentConfiguration);
2152
+ process.umask(63);
2153
+ const runtime = ManagedRuntime.make(exports_store.layer(configuration.databasePath, configuration.historyTaskLimit));
2154
+ const run = (effect) => runtime.runPromise(effect);
2155
+ await run(Effect3.gen(function* () {
2156
+ const store = yield* exports_store.Service;
2157
+ yield* store.recover();
2158
+ }));
2159
+ if (platform2() !== "win32" && await access2(configuration.databasePath).then(() => true).catch(() => false)) {
2160
+ await chmod2(configuration.databasePath, 384);
2161
+ }
2162
+ const hub = new Hub;
2163
+ let connections = 0;
2164
+ const tokenDigest = (token) => createHash2("sha256").update(token).digest();
2165
+ const ownerToken = (token) => timingSafeEqual(tokenDigest(token), tokenDigest(configuration.token));
2166
+ const authenticate = async (token, role) => {
2167
+ if (ownerToken(token)) {
2168
+ return "owner";
2169
+ }
2170
+ return run(Effect3.gen(function* () {
2171
+ const store = yield* exports_store.Service;
2172
+ return yield* store.authenticateSession(token, role);
2173
+ })).catch(() => {
2174
+ return;
2175
+ });
2176
+ };
2177
+ const principalFor = async (request, allowDevice = false) => {
2178
+ const authorization = request.headers.get("authorization");
2179
+ if (authorization?.startsWith("Bearer ") !== true) {
2180
+ return;
2181
+ }
2182
+ const token = authorization.slice("Bearer ".length);
2183
+ return await authenticate(token, "client") ?? (allowDevice ? authenticate(token, "device") : undefined);
2184
+ };
2185
+ const sendCancellation = (task) => {
2186
+ hub.sendToDevice(task.targetDeviceId, SocketEvent.make({
2187
+ _tag: "CancelTask",
2188
+ taskId: task.id,
2189
+ ...task.runId === undefined ? {} : { runId: task.runId }
2190
+ }));
2191
+ };
2192
+ const dispatch = async (task) => {
2193
+ const store = await run(exports_store.Service);
2194
+ if (task.expiresAt !== undefined || (task.inputAttachmentNames?.length ?? 0) > 0 || requiresClarificationSupport(task)) {
2195
+ const devices = await Effect3.runPromise(store.listDevices());
2196
+ const target = devices.find((device) => device.id === task.targetDeviceId);
2197
+ if (task.expiresAt !== undefined && !target?.capabilities.some((capability) => capability.id === "task-deadlines"))
2198
+ return task;
2199
+ if (requiresClarificationSupport(task) && !target?.capabilities.some((capability) => capability.id === "task-clarification"))
2200
+ return task;
2201
+ if (!canDispatchTaskToDevice(task, target)) {
2202
+ return Effect3.runPromise(store.failTask(task.id, task.targetDeviceId, "Target worker no longer supports task file attachments. Upgrade the worker and retry.", task.runId));
2203
+ }
2204
+ }
2205
+ if (!hub.hasDevice(task.targetDeviceId))
2206
+ return task;
2207
+ const assigned = await Effect3.runPromise(store.assignTask(task.id));
2208
+ if (assigned.status !== "assigned") {
2209
+ if (assigned.status === "cancelling")
2210
+ sendCancellation(assigned);
2211
+ return assigned;
2212
+ }
2213
+ const assignment = SocketEvent.make({ _tag: "TaskAssigned", task: assigned });
2214
+ if (Buffer.byteLength(JSON.stringify(assignment)) > maxSocketPayloadBytes) {
2215
+ return Effect3.runPromise(store.failTask(assigned.id, assigned.targetDeviceId, "Task prompt, context, and clarification history exceed the 1 MiB transfer limit. Retry with a shorter prompt or context.", assigned.runId));
2216
+ }
2217
+ if (hub.sendToDevice(assigned.targetDeviceId, assignment, assigned.provider === "grok-bot" ? () => Effect3.runSync(store.markTaskDispatched(assigned.id)) : undefined)) {
2218
+ return assigned;
2219
+ }
2220
+ return Effect3.runPromise(store.rollbackAssignment(task.id));
2221
+ };
2222
+ const dispatchOperation = async (operation) => {
2223
+ const assigned = await run(Effect3.gen(function* () {
2224
+ const store = yield* exports_store.Service;
2225
+ return yield* store.assignOperation(operation.id);
2226
+ }));
2227
+ if (assigned.status !== "assigned") {
2228
+ return assigned;
2229
+ }
2230
+ if (hub.sendToDevice(assigned.targetDeviceId, SocketEvent.make({ _tag: "OperationAssigned", operation: assigned }))) {
2231
+ return assigned;
2232
+ }
2233
+ return run(Effect3.gen(function* () {
2234
+ const store = yield* exports_store.Service;
2235
+ return yield* store.rollbackOperation(operation.id);
2236
+ }));
2237
+ };
2238
+ const dispatchPendingOperations = async (deviceId) => {
2239
+ const operations = await run(Effect3.gen(function* () {
2240
+ const store = yield* exports_store.Service;
2241
+ return yield* store.pendingOperationsFor(deviceId);
2242
+ }));
2243
+ for (const operation of operations) {
2244
+ await dispatchOperation(operation);
2245
+ }
2246
+ };
2247
+ const dispatchPendingTasks = async (deviceId) => {
2248
+ const tasks = await run(Effect3.gen(function* () {
2249
+ const store = yield* exports_store.Service;
2250
+ return yield* store.pendingTasksFor(deviceId);
2251
+ }));
2252
+ for (const task of tasks) {
2253
+ if (task.status === "cancelling") {
2254
+ sendCancellation(task);
2255
+ } else {
2256
+ await dispatch(task);
2257
+ }
2258
+ }
2259
+ };
2260
+ const dispatchPending = async (deviceId) => {
2261
+ await dispatchPendingOperations(deviceId);
2262
+ await dispatchPendingTasks(deviceId);
2263
+ };
2264
+ const sendError = (socket, code, message) => {
2265
+ socket.send(JSON.stringify(SocketEvent.make({
2266
+ _tag: "Error",
2267
+ code: code.slice(0, 64),
2268
+ message: message.slice(0, 2048)
2269
+ })));
2270
+ };
2271
+ const handleSocketEvent = async (socket, input) => {
2272
+ const event = await Effect3.runPromise(Effect3.try({
2273
+ try: () => JSON.parse(socketText(input)),
2274
+ catch: () => new RequestError({ status: 400, message: "Invalid socket JSON" })
2275
+ }).pipe(Effect3.flatMap(decodeSocketEvent))).catch((cause) => {
2276
+ sendError(socket, "invalid_event", cause instanceof Error ? cause.message : String(cause));
2277
+ return;
2278
+ });
2279
+ if (event === undefined) {
2280
+ return;
2281
+ }
2282
+ if (!hub.isAuthorized(socket)) {
2283
+ if (event._tag !== "Authenticate") {
2284
+ socket.close(4003, "Authentication required");
2285
+ return;
2286
+ }
2287
+ const principal = await authenticate(event.token, "device");
2288
+ if (principal === undefined) {
2289
+ socket.close(4003, "Authentication failed");
2290
+ return;
2291
+ }
2292
+ if (hub.pendingConnections() >= 64) {
2293
+ socket.close(4008, "Pending device connection limit reached");
2294
+ return;
2295
+ }
2296
+ const attached = hub.attach(socket, {
2297
+ ...principal === "owner" ? {} : { sessionId: principal.id },
2298
+ ...principal === "owner" || principal.deviceId === undefined ? {} : { boundDeviceId: principal.deviceId },
2299
+ ...principal === "owner" ? {} : { expiresAt: principal.expiresAt }
2300
+ });
2301
+ if (!attached) {
2302
+ socket.close(4008, "Credential connection limit reached");
2303
+ return;
2304
+ }
2305
+ socket.data.stageDeadline = setTimeout(() => {
2306
+ if (hub.deviceId(socket) === undefined) {
2307
+ socket.close(4003, "Device registration timeout");
2308
+ }
2309
+ }, 5000);
2310
+ socket.send(JSON.stringify(SocketEvent.make({
2311
+ _tag: "Connected",
2312
+ serverVersion: version,
2313
+ connectedAt: now(),
2314
+ taskAttachments: true,
2315
+ taskClarification: true,
2316
+ taskDeadlines: true
2317
+ })));
2318
+ return;
2319
+ }
2320
+ if (event._tag === "Authenticate") {
2321
+ return;
2322
+ }
2323
+ if (event._tag === "DeviceHello") {
2324
+ const bound = hub.boundDeviceId(socket);
2325
+ if (bound !== undefined && bound !== event.device.id) {
2326
+ socket.close(4003, "Device identity does not match its session");
2327
+ return;
2328
+ }
2329
+ const device = Device.make({
2330
+ ...event.device,
2331
+ status: "online",
2332
+ connectedAt: now(),
2333
+ lastSeenAt: now()
2334
+ });
2335
+ if (!hub.registerDevice(device.id, socket)) {
2336
+ socket.close(4009, "Device is already connected");
2337
+ return;
2338
+ }
2339
+ await run(Effect3.gen(function* () {
2340
+ const store = yield* exports_store.Service;
2341
+ yield* store.requeueTasksFor(device.id);
2342
+ yield* store.requeueOperationsFor(device.id);
2343
+ yield* store.upsertDevice(device);
2344
+ }));
2345
+ await dispatchPendingTasks(device.id);
2346
+ await dispatchPendingOperations(device.id);
2347
+ return;
2348
+ }
2349
+ const deviceId = hub.deviceId(socket);
2350
+ if (deviceId === undefined) {
2351
+ sendError(socket, "device_hello_required", "Send DeviceHello before device events");
2352
+ return;
2353
+ }
2354
+ const settle = (taskId, runId) => {
2355
+ socket.send(JSON.stringify(SocketEvent.make({
2356
+ _tag: "TaskSettled",
2357
+ taskId,
2358
+ ...runId === undefined ? {} : { runId }
2359
+ })));
2360
+ };
2361
+ const settleOperation = (operationId) => {
2362
+ socket.send(JSON.stringify(SocketEvent.make({ _tag: "OperationSettled", operationId })));
2363
+ };
2364
+ const taskTerminal = event._tag === "TaskFinished" || event._tag === "TaskInputRequested" || event._tag === "TaskFailed" || event._tag === "TaskCancelled";
2365
+ const operationTerminal = event._tag === "OperationFinished" || event._tag === "OperationFailed";
2366
+ const processed = await run(Effect3.gen(function* () {
2367
+ const store = yield* exports_store.Service;
2368
+ switch (event._tag) {
2369
+ case "DeviceHeartbeat":
2370
+ if (event.deviceId === deviceId) {
2371
+ yield* store.heartbeat(deviceId, event.status === "busy" ? "busy" : "online", event.bots);
2372
+ }
2373
+ return;
2374
+ case "TaskAccepted":
2375
+ yield* store.acceptTask(event.taskId, deviceId, event.runId);
2376
+ return;
2377
+ case "TaskFinished":
2378
+ yield* store.finishTask(event.taskId, deviceId, event.result, event.providerSessionId, event.attachments, event.runId);
2379
+ return;
2380
+ case "TaskInputRequested": {
2381
+ yield* store.pauseTaskForInput(event.taskId, deviceId, {
2382
+ runId: event.runId,
2383
+ question: event.question
2384
+ });
2385
+ return;
2386
+ }
2387
+ case "TaskFailed":
2388
+ yield* store.failTask(event.taskId, deviceId, event.error, event.runId);
2389
+ return;
2390
+ case "TaskCancelled":
2391
+ yield* store.acknowledgeCancellation(event.taskId, deviceId, event.runId);
2392
+ return;
2393
+ case "OperationAccepted":
2394
+ yield* store.acceptOperation(event.operationId, deviceId);
2395
+ return;
2396
+ case "OperationFinished":
2397
+ yield* store.finishOperation(event.operationId, deviceId, event.result);
2398
+ return;
2399
+ case "OperationFailed":
2400
+ yield* store.failOperation(event.operationId, deviceId, event.error);
2401
+ return;
2402
+ case "Connected":
2403
+ case "TaskAssigned":
2404
+ case "TaskSettled":
2405
+ case "CancelTask":
2406
+ case "OperationAssigned":
2407
+ case "OperationSettled":
2408
+ case "Error":
2409
+ return;
2410
+ }
2411
+ })).then(() => true).catch((cause) => {
2412
+ if (cause instanceof exports_store.PersistenceError && (taskTerminal && cause.missingRecord === "task" || operationTerminal && cause.missingRecord === "operation"))
2413
+ return true;
2414
+ sendError(socket, "event_failed", cause instanceof Error ? cause.message : String(cause));
2415
+ if (cause instanceof exports_store.PersistenceError && (taskTerminal || operationTerminal) && cause.operation !== "RelayStore.requireTarget" && cause.operation !== "RelayStore.requireOperationTarget") {
2416
+ socket.close(1011, "Could not persist worker reply");
2417
+ }
2418
+ return false;
2419
+ });
2420
+ if (processed && taskTerminal) {
2421
+ settle(event.taskId, event.runId);
2422
+ await dispatchPending(deviceId);
2423
+ }
2424
+ if (processed && operationTerminal) {
2425
+ settleOperation(event.operationId);
2426
+ await dispatchPending(deviceId);
2427
+ }
2428
+ };
2429
+ const api = async (request, url) => {
2430
+ if (url.pathname === "/api/health" && request.method === "GET") {
2431
+ return json({
2432
+ ok: true,
2433
+ version,
2434
+ taskAttachments: true,
2435
+ taskProgress: true,
2436
+ taskClarification: true,
2437
+ taskDeadlines: true,
2438
+ taskIdempotency: true
2439
+ });
2440
+ }
2441
+ if (url.pathname === "/api/auth/pair" && request.method === "POST") {
2442
+ return run(Effect3.gen(function* () {
2443
+ const store = yield* exports_store.Service;
2444
+ const input = yield* body(request, decodeExchangePairingInput);
2445
+ return yield* store.exchangePairing(input.token);
2446
+ })).then((value) => json(value, 201)).catch(() => json({ error: "Pairing credential is invalid, expired, or already used" }, 401));
2447
+ }
2448
+ if (url.pathname === "/api/device/credential" && request.method === "GET") {
2449
+ const authorization = request.headers.get("authorization");
2450
+ const token = authorization?.startsWith("Bearer ") === true ? authorization.slice("Bearer ".length) : undefined;
2451
+ if (token === undefined || await authenticate(token, "device") === undefined) {
2452
+ return json({ error: "Unauthorized" }, 401);
2453
+ }
2454
+ return json({ ok: true });
2455
+ }
2456
+ const attachmentRoute = request.method === "GET" && /^\/api\/tasks\/[^/]+\/attachments(?:\/[^/]+)?$/.test(url.pathname);
2457
+ const progressRoute = request.method === "POST" && /^\/api\/tasks\/[^/]+\/progress$/.test(url.pathname);
2458
+ const inputRoute = request.method === "POST" && /^\/api\/tasks\/[^/]+\/input$/.test(url.pathname);
2459
+ const principal = await principalFor(request, attachmentRoute || progressRoute || inputRoute);
2460
+ if (principal === undefined) {
2461
+ return json({ error: "Unauthorized" }, 401);
2462
+ }
2463
+ const ownerOnly = url.pathname.startsWith("/api/auth/") || url.pathname.startsWith("/api/operations");
2464
+ if (ownerOnly && principal !== "owner") {
2465
+ return json({ error: "Owner token required" }, 403);
2466
+ }
2467
+ const sourceDeviceId = principal === "owner" ? undefined : principal.deviceId;
2468
+ const effect = Effect3.gen(function* () {
2469
+ const store = yield* exports_store.Service;
2470
+ if (url.pathname === "/api/auth/pairings" && request.method === "POST") {
2471
+ const input = yield* body(request, decodeCreatePairingInput);
2472
+ return json(yield* store.createPairing(input), 201);
2473
+ }
2474
+ if (url.pathname === "/api/auth/sessions" && request.method === "GET") {
2475
+ return json(yield* store.listAuthSessions());
2476
+ }
2477
+ const revoke = url.pathname.match(/^\/api\/auth\/sessions\/([^/]+)\/revoke$/);
2478
+ if (request.method === "POST" && revoke?.[1] !== undefined) {
2479
+ const id = yield* pathId(AuthSessionId, revoke[1]);
2480
+ const session = yield* store.revokeAuthSession(id);
2481
+ hub.closeSession(id);
2482
+ return json(session);
2483
+ }
2484
+ if (url.pathname === "/api/devices/overview" && request.method === "GET") {
2485
+ return json(yield* store.deviceOverview());
2486
+ }
2487
+ if (url.pathname === "/api/devices/page" && request.method === "GET") {
2488
+ const after = url.searchParams.get("after");
2489
+ return json(yield* store.listDevicePage(after === null ? undefined : yield* pathId(DeviceId, after)));
2490
+ }
2491
+ if (url.pathname === "/api/devices" && request.method === "GET") {
2492
+ return json(yield* store.listDevices());
2493
+ }
2494
+ if (url.pathname === "/api/usage" && request.method === "GET") {
2495
+ return json(yield* store.usage());
2496
+ }
2497
+ if (url.pathname === "/api/operations" && request.method === "GET") {
2498
+ return json(yield* store.listOperations());
2499
+ }
2500
+ if (url.pathname === "/api/operations/upgrades" && request.method === "POST") {
2501
+ const input = yield* body(request, decodeCreateUpgradeOperationsInput);
2502
+ const operations = yield* store.createUpgradeOperations(input);
2503
+ return json(yield* Effect3.tryPromise(() => Promise.all(operations.map(dispatchOperation))), 201);
2504
+ }
2505
+ const abandonOperation = url.pathname.match(/^\/api\/operations\/([^/]+)\/abandon$/);
2506
+ if (request.method === "POST" && abandonOperation?.[1] !== undefined) {
2507
+ const operation = yield* store.abandonOperation(yield* pathId(OperationId, abandonOperation[1]));
2508
+ hub.sendToDevice(operation.targetDeviceId, SocketEvent.make({ _tag: "OperationSettled", operationId: operation.id }));
2509
+ return json(operation);
2510
+ }
2511
+ const forgetDevice = url.pathname.match(/^\/api\/devices\/([^/]+)\/forget$/);
2512
+ if (request.method === "POST" && forgetDevice?.[1] !== undefined) {
2513
+ if (principal !== "owner") {
2514
+ return yield* new RequestError({ status: 403, message: "Owner token required" });
2515
+ }
2516
+ const id = yield* pathId(DeviceId, forgetDevice[1]);
2517
+ if (hub.hasDevice(id)) {
2518
+ return yield* new RequestError({
2519
+ status: 409,
2520
+ message: `Device ${id} must be offline before it can be forgotten`
2521
+ });
2522
+ }
2523
+ const forgotten = yield* store.forgetDevice(id);
2524
+ hub.closeDevice(id);
2525
+ return json(forgotten);
2526
+ }
2527
+ if (url.pathname === "/api/tasks" && request.method === "POST") {
2528
+ const requestedInput = yield* body(request, decodeCreateTaskInput);
2529
+ const existing = yield* store.findDelegation(requestedInput, principal);
2530
+ if (existing !== undefined)
2531
+ return json(existing);
2532
+ const { input, targetDeviceId: target } = yield* resolveDelegation(requestedInput, sourceDeviceId);
2533
+ const providerSessionId = input.threadId === undefined || input.provider === "grok-bot" ? undefined : yield* store.sessionFor(input.threadId, target, input.provider ?? "codex");
2534
+ const task2 = yield* store.createDelegation(input, target, principal, providerSessionId, requestedInput);
2535
+ return json(yield* Effect3.tryPromise(() => dispatch(task2)), 201);
2536
+ }
2537
+ if (url.pathname === "/api/inbox" && request.method === "GET") {
2538
+ return json(yield* store.inboxFor(principal));
2539
+ }
2540
+ const acknowledge = url.pathname.match(/^\/api\/inbox\/([^/]+)\/ack$/);
2541
+ if (request.method === "POST" && acknowledge?.[1] !== undefined) {
2542
+ return json(yield* store.acknowledgeCompletion(yield* pathId(TaskId, acknowledge[1]), principal));
2543
+ }
2544
+ const attachments = url.pathname.match(/^\/api\/tasks\/([^/]+)\/attachments$/);
2545
+ if (request.method === "GET" && attachments?.[1] !== undefined) {
2546
+ const id = yield* pathId(TaskId, attachments[1]);
2547
+ const task2 = yield* store.getTask(id);
2548
+ if (!canReadTaskAttachments(principal, task2)) {
2549
+ return yield* new RequestError({
2550
+ status: 403,
2551
+ message: "Device cannot read this task's attachments"
2552
+ });
2553
+ }
2554
+ return json(yield* store.listAttachments(id));
2555
+ }
2556
+ const attachment = url.pathname.match(/^\/api\/tasks\/([^/]+)\/attachments\/([^/]+)$/);
2557
+ if (attachment?.[1] !== undefined && attachment[2] !== undefined && request.method === "GET") {
2558
+ const id = yield* pathId(TaskId, attachment[1]);
2559
+ const name = yield* Effect3.try({
2560
+ try: () => decodeURIComponent(attachment[2]),
2561
+ catch: () => new RequestError({ status: 400, message: "Invalid attachment name" })
2562
+ }).pipe(Effect3.flatMap((value) => pathId(AttachmentName, value)));
2563
+ const task2 = yield* store.getTask(id);
2564
+ if (!canReadTaskAttachments(principal, task2)) {
2565
+ return yield* new RequestError({
2566
+ status: 403,
2567
+ message: "Device cannot read this task's attachments"
2568
+ });
2569
+ }
2570
+ const directionInput = url.searchParams.get("direction");
2571
+ const direction = directionInput === null ? undefined : yield* pathId(AttachmentDirection, directionInput);
2572
+ const data = yield* store.readAttachment(id, name, direction);
2573
+ return new Response(new Uint8Array(data), {
2574
+ headers: {
2575
+ "content-type": "application/octet-stream",
2576
+ "cache-control": "no-store",
2577
+ "x-content-type-options": "nosniff"
2578
+ }
2579
+ });
2580
+ }
2581
+ const task = url.pathname.match(/^\/api\/tasks\/([^/]+)$/);
2582
+ if (request.method === "GET" && task?.[1] !== undefined) {
2583
+ return json(yield* store.getTask(yield* pathId(TaskId, task[1])));
2584
+ }
2585
+ const trace = url.pathname.match(/^\/api\/tasks\/([^/]+)\/trace$/);
2586
+ if (request.method === "GET" && trace?.[1] !== undefined) {
2587
+ return json(yield* store.traceTask(yield* pathId(TaskId, trace[1])));
2588
+ }
2589
+ const progress = url.pathname.match(/^\/api\/tasks\/([^/]+)\/progress$/);
2590
+ if (request.method === "POST" && progress?.[1] !== undefined) {
2591
+ const id = yield* pathId(TaskId, progress[1]);
2592
+ const input = yield* body(request, decodeTaskProgressInput);
2593
+ const task2 = yield* store.getTask(id);
2594
+ const deviceId = principal === "owner" ? task2.targetDeviceId : principal.deviceId;
2595
+ if (deviceId === undefined) {
2596
+ return yield* new RequestError({
2597
+ status: 403,
2598
+ message: "Only the target device can report progress"
2599
+ });
2600
+ }
2601
+ return json(yield* store.reportTaskProgress(id, deviceId, input.note));
2602
+ }
2603
+ const cancel = url.pathname.match(/^\/api\/tasks\/([^/]+)\/cancel$/);
2604
+ const inputRequest = url.pathname.match(/^\/api\/tasks\/([^/]+)\/input$/);
2605
+ if (request.method === "POST" && inputRequest?.[1] !== undefined) {
2606
+ const id = yield* pathId(TaskId, inputRequest[1]);
2607
+ const input = yield* body(request, decodeRequestTaskInput);
2608
+ const task2 = yield* store.getTask(id);
2609
+ const deviceId = principal === "owner" ? task2.targetDeviceId : principal.deviceId;
2610
+ if (deviceId === undefined)
2611
+ return yield* new RequestError({
2612
+ status: 403,
2613
+ message: "Only the target device can request input"
2614
+ });
2615
+ return json(yield* store.requestTaskInput(id, deviceId, input));
2616
+ }
2617
+ const answer = url.pathname.match(/^\/api\/tasks\/([^/]+)\/answer$/);
2618
+ if (request.method === "POST" && answer?.[1] !== undefined) {
2619
+ const task2 = yield* store.answerTaskInput(yield* pathId(TaskId, answer[1]), principal, yield* body(request, decodeAnswerTaskInput));
2620
+ return json(yield* Effect3.tryPromise({
2621
+ try: () => dispatch(task2),
2622
+ catch: (cause) => new RequestError({
2623
+ status: 500,
2624
+ message: cause instanceof Error ? cause.message : String(cause)
2625
+ })
2626
+ }));
2627
+ }
2628
+ if (request.method === "POST" && cancel?.[1] !== undefined) {
2629
+ const id = yield* pathId(TaskId, cancel[1]);
2630
+ const updated = yield* store.requestCancellation(id);
2631
+ if (updated.status === "cancelling") {
2632
+ sendCancellation(updated);
2633
+ }
2634
+ return json(updated);
2635
+ }
2636
+ const thread = url.pathname.match(/^\/api\/threads\/([^/]+)$/);
2637
+ if (request.method === "GET" && thread?.[1] !== undefined) {
2638
+ return json(yield* store.threadContext(yield* pathId(ThreadId, thread[1])));
2639
+ }
2640
+ return yield* new RequestError({ status: 404, message: "Route not found" });
2641
+ }).pipe(Effect3.mapError((cause) => cause instanceof RequestError ? cause : cause._tag === "RelayStore.TaskProgressError" || cause._tag === "RelayStore.TaskInputError" || cause._tag === "RelayStore.TaskDeadlineError" || cause._tag === "RelayStore.TaskRequestError" ? new RequestError({ status: cause.status, message: cause.message }) : new RequestError({
2642
+ status: cause._tag !== "RelayStore.PersistenceError" ? 500 : cause.message.startsWith("Unknown") ? 404 : cause.message.includes("cannot cancel an individual Cohall request") ? 409 : cause.message.includes("outstanding task limit") ? 429 : cause.message.includes("must be offline") || cause.message.includes("still has outstanding tasks") || cause.message.includes("upgrade operation in progress") || cause.message === "No Cohall devices are registered" || cause.message.startsWith("All-device operations support") ? 409 : 500,
2643
+ message: cause.message
2644
+ })));
2645
+ return run(effect).catch((cause) => cause instanceof RequestError ? json({ error: cause.status === 500 ? "Relay request failed" : cause.message }, cause.status) : json({ error: "Relay request failed" }, 500));
2646
+ };
2647
+ const websocketServer = new WebSocketServer({
2648
+ noServer: true,
2649
+ maxPayload: maxSocketPayloadBytes,
2650
+ perMessageDeflate: false,
2651
+ allowSynchronousEvents: false
2652
+ });
2653
+ websocketServer.on("connection", (rawSocket) => {
2654
+ const socket = rawSocket;
2655
+ socket.on("error", () => socket.terminate());
2656
+ socket.data = {
2657
+ processing: Promise.resolve(),
2658
+ stageDeadline: undefined,
2659
+ preAuthFrameReceived: false,
2660
+ queuedMessages: 0,
2661
+ closed: false
2662
+ };
2663
+ connections += 1;
2664
+ socket.data.stageDeadline = setTimeout(() => {
2665
+ if (!hub.isAuthorized(socket)) {
2666
+ socket.close(4003, "Authentication timeout");
2667
+ }
2668
+ }, 5000);
2669
+ let alive = true;
2670
+ socket.on("pong", () => {
2671
+ alive = true;
2672
+ });
2673
+ const heartbeat = setInterval(() => {
2674
+ if (!hub.isAuthorized(socket)) {
2675
+ return;
2676
+ }
2677
+ if (!alive) {
2678
+ socket.terminate();
2679
+ return;
2680
+ }
2681
+ alive = false;
2682
+ socket.ping();
2683
+ }, 30000);
2684
+ heartbeat.unref();
2685
+ socket.on("message", (message) => {
2686
+ if (!hub.isAuthorized(socket)) {
2687
+ const size = Buffer.byteLength(socketText(message));
2688
+ if (socket.data.preAuthFrameReceived || size > maxAuthTokenBytes * 6 + 64) {
2689
+ socket.close(4003, "Only one authentication frame is allowed");
2690
+ return;
2691
+ }
2692
+ socket.data.preAuthFrameReceived = true;
2693
+ socket.data.processing = handleSocketEvent(socket, message).catch((cause) => {
2694
+ sendError(socket, "event_failed", cause instanceof Error ? cause.message : String(cause));
2695
+ });
2696
+ return;
2697
+ }
2698
+ if (socket.data.queuedMessages >= 8) {
2699
+ socket.close(4008, "Message queue limit reached");
2700
+ return;
2701
+ }
2702
+ socket.data.queuedMessages += 1;
2703
+ socket.data.processing = socket.data.processing.then(() => socket.data.closed ? undefined : handleSocketEvent(socket, message)).catch((cause) => {
2704
+ sendError(socket, "event_failed", cause instanceof Error ? cause.message : String(cause));
2705
+ if (cause instanceof exports_store.PersistenceError)
2706
+ socket.close(1011, "Could not persist device event");
2707
+ }).finally(() => {
2708
+ socket.data.queuedMessages = Math.max(0, socket.data.queuedMessages - 1);
2709
+ });
2710
+ });
2711
+ socket.once("close", () => {
2712
+ clearInterval(heartbeat);
2713
+ socket.data.closed = true;
2714
+ connections = Math.max(0, connections - 1);
2715
+ const deviceId = hub.detach(socket);
2716
+ if (deviceId === undefined) {
2717
+ return;
2718
+ }
2719
+ run(Effect3.gen(function* () {
2720
+ const store = yield* exports_store.Service;
2721
+ yield* store.requeueTasksFor(deviceId);
2722
+ yield* store.requeueOperationsFor(deviceId);
2723
+ yield* store.markDeviceOffline(deviceId);
2724
+ })).catch((cause) => console.error(cause));
2725
+ });
2726
+ });
2727
+ const server = createServer((incoming, outgoing) => {
2728
+ webRequest(incoming).then((request) => {
2729
+ const url = new URL(request.url);
2730
+ return url.pathname.startsWith("/api/") ? api(request, url) : json({ name: "Cohall relay", version, status: "running" });
2731
+ }).then((response) => sendResponse(outgoing, response)).catch((cause) => sendResponse(outgoing, json({ error: cause instanceof Error ? cause.message : "Invalid request" }, cause instanceof Error && cause.message.includes("Request body exceeded") ? 413 : 400)));
2732
+ });
2733
+ server.on("upgrade", (request, socket, head) => {
2734
+ const url = URL.parse(request.url ?? "/", "http://cohall.local");
2735
+ if (url === null) {
2736
+ rejectUpgrade(socket, 400, "Bad Request");
2737
+ return;
2738
+ }
2739
+ if (url.pathname !== "/ws/device") {
2740
+ rejectUpgrade(socket, 404, "Not Found");
2741
+ return;
2742
+ }
2743
+ if (connections >= 1024) {
2744
+ rejectUpgrade(socket, 503, "Service Unavailable");
2745
+ return;
2746
+ }
2747
+ websocketServer.handleUpgrade(request, socket, head, (websocket) => {
2748
+ websocketServer.emit("connection", websocket, request);
2749
+ });
2750
+ });
2751
+ await new Promise((resolve2, reject) => {
2752
+ server.once("error", reject);
2753
+ server.listen(relayListenOptions(configuration), () => {
2754
+ server.off("error", reject);
2755
+ resolve2();
2756
+ });
2757
+ });
2758
+ const address = server.address();
2759
+ const listener = typeof address === "string" ? address : address?.family === "IPv6" ? `[${address.address}]:${address.port}` : `${address?.address ?? configuration.host}:${address?.port ?? configuration.port}`;
2760
+ console.log(`Cohall relay listening on http://${listener}`);
2761
+ const deadlineController = new AbortController;
2762
+ const enforceDeadlines = Effect3.gen(function* () {
2763
+ const store = yield* exports_store.Service;
2764
+ const overdue = yield* store.expireTasks();
2765
+ for (const task of overdue)
2766
+ if (task.status === "cancelling")
2767
+ sendCancellation(task);
2768
+ }).pipe(Effect3.catch((cause) => Effect3.logError(cause)), Effect3.repeat({ schedule: Schedule.spaced("1 second") }));
2769
+ const deadlineWork = runtime.runPromise(enforceDeadlines, { signal: deadlineController.signal }).catch((cause) => {
2770
+ if (!deadlineController.signal.aborted)
2771
+ console.error(`Task deadline enforcement failed: ${cause instanceof Error ? cause.message : String(cause)}`);
2772
+ });
2773
+ let stopping = false;
2774
+ const shutdown = async () => {
2775
+ if (stopping) {
2776
+ return;
2777
+ }
2778
+ stopping = true;
2779
+ deadlineController.abort();
2780
+ await deadlineWork;
2781
+ for (const socket of websocketServer.clients) {
2782
+ socket.close(1001, "Relay shutting down");
2783
+ }
2784
+ await new Promise((resolve2) => server.close(() => resolve2()));
2785
+ websocketServer.close();
2786
+ await runtime.dispose();
2787
+ };
2788
+ process.once("SIGINT", () => void shutdown());
2789
+ process.once("SIGTERM", () => void shutdown());
2790
+ };
2791
+ if (false) {}
2792
+ export {
2793
+ runRelay,
2794
+ resolveDelegation,
2795
+ relayListenOptions,
2796
+ maxTaskRequestBodyBytes,
2797
+ canReadTaskAttachments,
2798
+ canDispatchTaskToDevice
2799
+ };
2800
+
2801
+ //# debugId=EDED4526FC76EFE964756E2164756E21