@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.1
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.
- package/LICENSE +21 -0
- package/README.md +45 -2
- package/client.js +646 -0
- package/dist/cdc.js +73 -0
- package/dist/cli.js +352 -0
- package/dist/context.js +262 -0
- package/dist/cron.js +98 -0
- package/dist/desk-ledger.js +91 -0
- package/dist/desk.js +518 -0
- package/dist/engine.js +733 -0
- package/dist/errors.js +46 -0
- package/dist/fs-safe.js +100 -0
- package/dist/http-plugin.js +33 -0
- package/dist/http.js +593 -0
- package/dist/inbox.js +194 -0
- package/dist/index.js +411 -0
- package/dist/live-diff.js +188 -0
- package/dist/live-snapshot.js +152 -0
- package/dist/provision.js +44 -0
- package/dist/router-plugin.js +14 -0
- package/dist/runtime-registry.js +36 -0
- package/dist/session-files.js +111 -0
- package/dist/session-previews.js +111 -0
- package/dist/store.js +598 -0
- package/dist/tools.js +357 -0
- package/dist/triggers.js +874 -0
- package/dist/work-admit.js +128 -0
- package/dist/work-child.js +73 -0
- package/dist/work-durable.js +53 -0
- package/dist/work-http.js +287 -0
- package/dist/work-ledger.js +217 -0
- package/dist/work-mock-host.js +187 -0
- package/dist/work-mock.js +131 -0
- package/dist/work-tickets.js +1042 -0
- package/dist/work-tools.js +150 -0
- package/dist/work-worker.js +1108 -0
- package/fixtures/mock-llm.mjs +267 -0
- package/package.json +54 -4
- package/public/assets/index-Be82iGwe.css +1 -0
- package/public/assets/index-ByU9a3Lh.js +61 -0
- package/public/index.html +14 -0
|
@@ -0,0 +1,1042 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { sha256 } from "./fs-safe.js";
|
|
5
|
+
export const ACTIVE_TICKET = Object.freeze(['accepted', 'enqueued', 'started', 'needs_user']);
|
|
6
|
+
const TERMINAL_KIND = new Set(['question', 'result', 'failure']);
|
|
7
|
+
const OPEN_NOTICE_FLUSH = new Set(['intent', 'flushing', 'ambiguous']);
|
|
8
|
+
/**
|
|
9
|
+
* Ticket protocol tables. Callers own transactions when they need several statements together.
|
|
10
|
+
* This module does not call a model and does not touch the native inbox.
|
|
11
|
+
* @param {import('node:sqlite').DatabaseSync} db
|
|
12
|
+
* @param {string} root
|
|
13
|
+
* @param {() => Date} [now]
|
|
14
|
+
*/
|
|
15
|
+
export function createTicketBook(db, root, now = () => new Date()) {
|
|
16
|
+
const iso = () => now().toISOString();
|
|
17
|
+
return {
|
|
18
|
+
iso,
|
|
19
|
+
countActive,
|
|
20
|
+
countGlobal,
|
|
21
|
+
ticket: (id) => row('SELECT * FROM work_tickets WHERE id = ?', id),
|
|
22
|
+
attempt: (id) => row('SELECT * FROM work_attempts WHERE id = ?', id),
|
|
23
|
+
byIdempotency,
|
|
24
|
+
attemptForChild,
|
|
25
|
+
input: (id) => row('SELECT * FROM work_inputs WHERE id = ?', id),
|
|
26
|
+
inputByNative,
|
|
27
|
+
currentInput,
|
|
28
|
+
event: (id) => row('SELECT * FROM work_events WHERE event_id = ?', id),
|
|
29
|
+
writeBriefing,
|
|
30
|
+
readBriefing,
|
|
31
|
+
insertAccepted,
|
|
32
|
+
setChildIfEmpty,
|
|
33
|
+
insertInput,
|
|
34
|
+
markEnqueued,
|
|
35
|
+
markStarted,
|
|
36
|
+
advanceGeneration,
|
|
37
|
+
markCancelled,
|
|
38
|
+
insertRetry,
|
|
39
|
+
insertEvent,
|
|
40
|
+
applyTerminal,
|
|
41
|
+
touchLease,
|
|
42
|
+
markExtensionOpen,
|
|
43
|
+
extendBudget,
|
|
44
|
+
failRunning,
|
|
45
|
+
expireQuiet,
|
|
46
|
+
insertDelivery,
|
|
47
|
+
deliveryForEvent,
|
|
48
|
+
abandonOpenDeliveries,
|
|
49
|
+
setReview,
|
|
50
|
+
bindDelivery,
|
|
51
|
+
summaries,
|
|
52
|
+
detail,
|
|
53
|
+
liveStamp,
|
|
54
|
+
liveBoard,
|
|
55
|
+
liveBoardAll,
|
|
56
|
+
pendingWake,
|
|
57
|
+
openNotice,
|
|
58
|
+
openDelivery,
|
|
59
|
+
backgroundIds,
|
|
60
|
+
latestNoticeAt,
|
|
61
|
+
flushInputs,
|
|
62
|
+
flushNotices,
|
|
63
|
+
markInputFlush,
|
|
64
|
+
markNoticeGroup,
|
|
65
|
+
noteInputAccepted,
|
|
66
|
+
setNoticeObserve,
|
|
67
|
+
intentsFor,
|
|
68
|
+
noticeIds,
|
|
69
|
+
eventsWithoutNotice,
|
|
70
|
+
insertNotices,
|
|
71
|
+
attemptsOf,
|
|
72
|
+
ownerIds,
|
|
73
|
+
childIds,
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* @param {string} sql
|
|
77
|
+
* @param {unknown} arg
|
|
78
|
+
*/
|
|
79
|
+
function row(sql, arg) {
|
|
80
|
+
return db.prepare(sql).get(arg) ?? null;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* @param {string} owner
|
|
84
|
+
*/
|
|
85
|
+
function countActive(owner) {
|
|
86
|
+
return db.prepare(`
|
|
87
|
+
SELECT COUNT(*) AS n FROM work_tickets
|
|
88
|
+
WHERE owner_session_id = ? AND status IN ('accepted','enqueued','started','needs_user')
|
|
89
|
+
`).get(owner).n;
|
|
90
|
+
}
|
|
91
|
+
function countGlobal() {
|
|
92
|
+
return db.prepare(`
|
|
93
|
+
SELECT COUNT(*) AS n FROM work_tickets
|
|
94
|
+
WHERE status IN ('accepted','enqueued','started','needs_user')
|
|
95
|
+
`).get().n;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* @param {string} owner
|
|
99
|
+
* @param {string | null} key
|
|
100
|
+
*/
|
|
101
|
+
function byIdempotency(owner, key) {
|
|
102
|
+
if (key == null)
|
|
103
|
+
return null;
|
|
104
|
+
return db.prepare(`
|
|
105
|
+
SELECT * FROM work_tickets WHERE owner_session_id = ? AND idempotency_key = ?
|
|
106
|
+
`).get(owner, key) ?? null;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* @param {string} sessionId
|
|
110
|
+
*/
|
|
111
|
+
function attemptForChild(sessionId) {
|
|
112
|
+
return db.prepare(`
|
|
113
|
+
SELECT * FROM work_attempts WHERE child_session_id = ? ORDER BY fencing_token DESC LIMIT 1
|
|
114
|
+
`).get(sessionId) ?? null;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* @param {string} nativeId
|
|
118
|
+
*/
|
|
119
|
+
function inputByNative(nativeId) {
|
|
120
|
+
return db.prepare('SELECT * FROM work_inputs WHERE native_message_id = ?').get(nativeId) ?? null;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* @param {{ current_input_id?: string | null }} attempt
|
|
124
|
+
*/
|
|
125
|
+
function currentInput(attempt) {
|
|
126
|
+
if (!attempt?.current_input_id)
|
|
127
|
+
return null;
|
|
128
|
+
return row('SELECT * FROM work_inputs WHERE id = ?', attempt.current_input_id);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* @param {string} text
|
|
132
|
+
*/
|
|
133
|
+
function writeBriefing(text) {
|
|
134
|
+
const hash = sha256(text);
|
|
135
|
+
const dir = join(root, 'blobs', 'work');
|
|
136
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
137
|
+
const file = join(dir, `${hash}.txt`);
|
|
138
|
+
if (!existsSync(file))
|
|
139
|
+
writeFileSync(file, text, { mode: 0o600 });
|
|
140
|
+
return hash;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* @param {string} hash
|
|
144
|
+
*/
|
|
145
|
+
function readBriefing(hash) {
|
|
146
|
+
const file = join(root, 'blobs', 'work', `${hash}.txt`);
|
|
147
|
+
if (!existsSync(file))
|
|
148
|
+
return '';
|
|
149
|
+
return readFileSync(file, 'utf8');
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* @param {{
|
|
153
|
+
* owner: string,
|
|
154
|
+
* briefing: string,
|
|
155
|
+
* idempotencyKey: string | null,
|
|
156
|
+
* correlationId: string,
|
|
157
|
+
* budget: Record<string, number>,
|
|
158
|
+
* }} input
|
|
159
|
+
*/
|
|
160
|
+
function insertAccepted(input) {
|
|
161
|
+
const ticketId = randomUUID();
|
|
162
|
+
const attemptId = randomUUID();
|
|
163
|
+
const stamp = iso();
|
|
164
|
+
const hash = writeBriefing(input.briefing);
|
|
165
|
+
db.prepare(`
|
|
166
|
+
INSERT INTO work_attempts (
|
|
167
|
+
id, ticket_id, child_session_id, fencing_token, briefing_revision, current_input_id, status,
|
|
168
|
+
lease_until, lease_observed_seq, started_at, ended_at
|
|
169
|
+
) VALUES (?, ?, NULL, 1, 1, NULL, 'starting', NULL, NULL, NULL, NULL)
|
|
170
|
+
`).run(attemptId, ticketId);
|
|
171
|
+
db.prepare(`
|
|
172
|
+
INSERT INTO work_tickets (
|
|
173
|
+
id, owner_session_id, child_session_id, revision, briefing_revision, status, review_status,
|
|
174
|
+
active_attempt_id, briefing_hash, correlation_id, idempotency_key, parent_ticket_id, budget_json,
|
|
175
|
+
cancel_requested_revision, created_at, updated_at
|
|
176
|
+
) VALUES (?, ?, NULL, 1, 1, 'accepted', 'none', ?, ?, ?, ?, NULL, ?, NULL, ?, ?)
|
|
177
|
+
`).run(ticketId, input.owner, attemptId, hash, input.correlationId ?? '', input.idempotencyKey, JSON.stringify(input.budget), stamp, stamp);
|
|
178
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId) };
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* @param {string} ticketId
|
|
182
|
+
* @param {string} childSessionId
|
|
183
|
+
*/
|
|
184
|
+
function setChildIfEmpty(ticketId, childSessionId) {
|
|
185
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
186
|
+
if (!ticket || ticket.child_session_id)
|
|
187
|
+
return ticket;
|
|
188
|
+
db.prepare(`
|
|
189
|
+
UPDATE work_tickets SET child_session_id = ?, updated_at = ? WHERE id = ? AND child_session_id IS NULL
|
|
190
|
+
`).run(childSessionId, iso(), ticketId);
|
|
191
|
+
db.prepare(`
|
|
192
|
+
UPDATE work_attempts SET child_session_id = ? WHERE id = ? AND child_session_id IS NULL
|
|
193
|
+
`).run(childSessionId, ticket.active_attempt_id);
|
|
194
|
+
return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* @param {{
|
|
198
|
+
* ticketId: string,
|
|
199
|
+
* attemptId: string,
|
|
200
|
+
* revision: number,
|
|
201
|
+
* kind: 'briefing' | 'supply' | 'redirect' | 'cancel_note',
|
|
202
|
+
* text: string,
|
|
203
|
+
* }} input
|
|
204
|
+
*/
|
|
205
|
+
function insertInput(input) {
|
|
206
|
+
const id = randomUUID();
|
|
207
|
+
const native = randomUUID();
|
|
208
|
+
const stamp = iso();
|
|
209
|
+
const hash = sha256(input.text);
|
|
210
|
+
writeBriefing(input.text);
|
|
211
|
+
db.prepare(`
|
|
212
|
+
INSERT INTO work_inputs (
|
|
213
|
+
id, ticket_id, attempt_id, briefing_revision, kind, native_message_id, payload_hash,
|
|
214
|
+
flush_status, flush_pid, flush_attempts, last_error, log_seq, created_at, updated_at
|
|
215
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, 'intent', NULL, 0, '', NULL, ?, ?)
|
|
216
|
+
`).run(id, input.ticketId, input.attemptId, input.revision, input.kind, native, hash, stamp, stamp);
|
|
217
|
+
db.prepare(`
|
|
218
|
+
UPDATE work_attempts SET current_input_id = ?, briefing_revision = ? WHERE id = ?
|
|
219
|
+
`).run(id, input.revision, input.attemptId);
|
|
220
|
+
return row('SELECT * FROM work_inputs WHERE id = ?', id);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Flush of the current input confirmed. Status becomes enqueued. Revision is not a command.
|
|
224
|
+
* @param {string} ticketId
|
|
225
|
+
*/
|
|
226
|
+
function markEnqueued(ticketId) {
|
|
227
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
228
|
+
if (!ticket || ticket.status === 'cancelled' || ticket.status === 'failed' || ticket.status === 'delivered')
|
|
229
|
+
return ticket;
|
|
230
|
+
db.prepare(`UPDATE work_tickets SET status = 'enqueued', updated_at = ? WHERE id = ?`).run(iso(), ticketId);
|
|
231
|
+
db.prepare(`
|
|
232
|
+
UPDATE work_attempts
|
|
233
|
+
SET status = 'enqueued', started_at = NULL, ended_at = NULL
|
|
234
|
+
WHERE id = ? AND status IN ('starting','enqueued','started','succeeded')
|
|
235
|
+
`).run(ticket.active_attempt_id);
|
|
236
|
+
return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* @param {string} ticketId
|
|
240
|
+
* @param {string} nativeMessageId
|
|
241
|
+
*/
|
|
242
|
+
function markStarted(ticketId, nativeMessageId) {
|
|
243
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
244
|
+
const attempt = ticket ? row('SELECT * FROM work_attempts WHERE id = ?', ticket.active_attempt_id) : null;
|
|
245
|
+
const input = attempt ? currentInput(attempt) : null;
|
|
246
|
+
if (!ticket || !attempt || !input)
|
|
247
|
+
return null;
|
|
248
|
+
if (input.native_message_id !== nativeMessageId)
|
|
249
|
+
return ticket;
|
|
250
|
+
if (input.briefing_revision !== ticket.briefing_revision)
|
|
251
|
+
return ticket;
|
|
252
|
+
if (ticket.status !== 'accepted' && ticket.status !== 'enqueued' && ticket.status !== 'started')
|
|
253
|
+
return ticket;
|
|
254
|
+
const stamp = iso();
|
|
255
|
+
if (ticket.status !== 'started') {
|
|
256
|
+
db.prepare(`UPDATE work_tickets SET status = 'started', updated_at = ? WHERE id = ?`).run(stamp, ticketId);
|
|
257
|
+
}
|
|
258
|
+
db.prepare(`
|
|
259
|
+
UPDATE work_attempts
|
|
260
|
+
SET status = 'started', started_at = COALESCE(started_at, ?)
|
|
261
|
+
WHERE id = ?
|
|
262
|
+
`).run(stamp, attempt.id);
|
|
263
|
+
return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* redirect or supply. Revision and briefing_revision both increment before flush.
|
|
267
|
+
* Ticket status stays until flush confirms. Returns null on CAS conflict.
|
|
268
|
+
* @param {string} ticketId
|
|
269
|
+
* @param {number | null} expectedRevision
|
|
270
|
+
* @param {'supply' | 'redirect'} kind
|
|
271
|
+
* @param {string} text
|
|
272
|
+
*/
|
|
273
|
+
function advanceGeneration(ticketId, expectedRevision, kind, text) {
|
|
274
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
275
|
+
if (!ticket)
|
|
276
|
+
return { error: 'NOT_FOUND' };
|
|
277
|
+
const allowed = kind === 'supply'
|
|
278
|
+
? ticket.status === 'needs_user' || ticket.status === 'enqueued'
|
|
279
|
+
: ticket.status === 'accepted' || ticket.status === 'enqueued' || ticket.status === 'started' || ticket.status === 'needs_user' || ticket.status === 'ready';
|
|
280
|
+
if (!allowed)
|
|
281
|
+
return { error: 'VALIDATION', message: `Ticket status ${ticket.status} cannot ${kind === 'supply' ? 'supply' : 'redirect'}.` };
|
|
282
|
+
if (!ticket.child_session_id)
|
|
283
|
+
return { error: 'VALIDATION', message: 'The worker session does not exist yet, so this generation cannot be changed.' };
|
|
284
|
+
const expected = expectedRevision == null ? ticket.revision : expectedRevision;
|
|
285
|
+
if (expected !== ticket.revision)
|
|
286
|
+
return { error: 'CAS_CONFLICT' };
|
|
287
|
+
const nextRevision = ticket.revision + 1;
|
|
288
|
+
const nextBrief = ticket.briefing_revision + 1;
|
|
289
|
+
const hash = writeBriefing(text);
|
|
290
|
+
const info = db.prepare(`
|
|
291
|
+
UPDATE work_tickets
|
|
292
|
+
SET revision = ?, briefing_revision = ?, briefing_hash = ?, review_status = 'none', updated_at = ?
|
|
293
|
+
WHERE id = ? AND revision = ?
|
|
294
|
+
`).run(nextRevision, nextBrief, hash, iso(), ticketId, expected);
|
|
295
|
+
if (info.changes !== 1)
|
|
296
|
+
return { error: 'CAS_CONFLICT' };
|
|
297
|
+
abandonOpenDeliveries(ticketId, nextBrief);
|
|
298
|
+
const input = insertInput({
|
|
299
|
+
ticketId,
|
|
300
|
+
attemptId: ticket.active_attempt_id,
|
|
301
|
+
revision: nextBrief,
|
|
302
|
+
kind,
|
|
303
|
+
text,
|
|
304
|
+
});
|
|
305
|
+
db.prepare(`
|
|
306
|
+
UPDATE work_events SET apply_status = 'stale'
|
|
307
|
+
WHERE ticket_id = ? AND briefing_revision < ? AND apply_status != 'stale'
|
|
308
|
+
`).run(ticketId, nextBrief);
|
|
309
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), input };
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* @param {string} ticketId
|
|
313
|
+
* @param {number | null} expectedRevision
|
|
314
|
+
* @param {string} [note]
|
|
315
|
+
*/
|
|
316
|
+
function markCancelled(ticketId, expectedRevision, note) {
|
|
317
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
318
|
+
if (!ticket)
|
|
319
|
+
return { error: 'NOT_FOUND' };
|
|
320
|
+
if (ticket.status === 'delivered')
|
|
321
|
+
return { error: 'VALIDATION', message: 'A delivered ticket cannot be cancelled.' };
|
|
322
|
+
if (ticket.status === 'cancelled')
|
|
323
|
+
return { ticket, input: null, already: true };
|
|
324
|
+
const expected = expectedRevision == null ? ticket.revision : expectedRevision;
|
|
325
|
+
if (expected !== ticket.revision)
|
|
326
|
+
return { error: 'CAS_CONFLICT' };
|
|
327
|
+
const next = ticket.revision + 1;
|
|
328
|
+
const info = db.prepare(`
|
|
329
|
+
UPDATE work_tickets
|
|
330
|
+
SET revision = ?, status = 'cancelled', cancel_requested_revision = ?, updated_at = ?
|
|
331
|
+
WHERE id = ? AND revision = ?
|
|
332
|
+
`).run(next, next, iso(), ticketId, expected);
|
|
333
|
+
if (info.changes !== 1)
|
|
334
|
+
return { error: 'CAS_CONFLICT' };
|
|
335
|
+
db.prepare(`
|
|
336
|
+
UPDATE work_attempts SET status = 'cancelled', ended_at = ? WHERE id = ? AND status != 'superseded'
|
|
337
|
+
`).run(iso(), ticket.active_attempt_id);
|
|
338
|
+
db.prepare(`
|
|
339
|
+
UPDATE work_events SET apply_status = 'stale'
|
|
340
|
+
WHERE ticket_id = ? AND apply_status != 'stale'
|
|
341
|
+
`).run(ticketId);
|
|
342
|
+
abandonOpenDeliveries(ticketId, 1_000_000);
|
|
343
|
+
let input = null;
|
|
344
|
+
if (typeof note === 'string' && note.trim() !== '' && ticket.child_session_id) {
|
|
345
|
+
input = insertInput({
|
|
346
|
+
ticketId,
|
|
347
|
+
attemptId: ticket.active_attempt_id,
|
|
348
|
+
revision: ticket.briefing_revision,
|
|
349
|
+
kind: 'cancel_note',
|
|
350
|
+
text: note,
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), input, already: false };
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Explicit retry from failed or cancelled. Same child id, new fencing token.
|
|
357
|
+
* @param {string} ticketId
|
|
358
|
+
* @param {number | null} expectedRevision
|
|
359
|
+
*/
|
|
360
|
+
function insertRetry(ticketId, expectedRevision) {
|
|
361
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
362
|
+
if (!ticket)
|
|
363
|
+
return { error: 'NOT_FOUND' };
|
|
364
|
+
if (ticket.status !== 'failed' && ticket.status !== 'cancelled') {
|
|
365
|
+
return { error: 'VALIDATION', message: 'Only a failed or cancelled ticket can be retried.' };
|
|
366
|
+
}
|
|
367
|
+
const expected = expectedRevision == null ? ticket.revision : expectedRevision;
|
|
368
|
+
if (expected !== ticket.revision)
|
|
369
|
+
return { error: 'CAS_CONFLICT' };
|
|
370
|
+
const previous = row('SELECT * FROM work_attempts WHERE id = ?', ticket.active_attempt_id);
|
|
371
|
+
const token = (previous?.fencing_token ?? 0) + 1;
|
|
372
|
+
const attemptId = randomUUID();
|
|
373
|
+
const next = ticket.revision + 1;
|
|
374
|
+
const info = db.prepare(`
|
|
375
|
+
UPDATE work_tickets
|
|
376
|
+
SET revision = ?, briefing_revision = 1, status = 'accepted', review_status = 'none',
|
|
377
|
+
active_attempt_id = ?, cancel_requested_revision = NULL, updated_at = ?
|
|
378
|
+
WHERE id = ? AND revision = ?
|
|
379
|
+
`).run(next, attemptId, iso(), ticketId, expected);
|
|
380
|
+
if (info.changes !== 1)
|
|
381
|
+
return { error: 'CAS_CONFLICT' };
|
|
382
|
+
if (previous) {
|
|
383
|
+
db.prepare(`UPDATE work_attempts SET status = 'superseded', ended_at = COALESCE(ended_at, ?) WHERE id = ?`).run(iso(), previous.id);
|
|
384
|
+
}
|
|
385
|
+
db.prepare(`
|
|
386
|
+
INSERT INTO work_attempts (
|
|
387
|
+
id, ticket_id, child_session_id, fencing_token, briefing_revision, current_input_id, status,
|
|
388
|
+
lease_until, lease_observed_seq, started_at, ended_at
|
|
389
|
+
) VALUES (?, ?, ?, ?, 1, NULL, 'starting', NULL, NULL, NULL, NULL)
|
|
390
|
+
`).run(attemptId, ticketId, ticket.child_session_id, token);
|
|
391
|
+
const briefing = readBriefing(ticket.briefing_hash);
|
|
392
|
+
const input = insertInput({
|
|
393
|
+
ticketId,
|
|
394
|
+
attemptId,
|
|
395
|
+
revision: 1,
|
|
396
|
+
kind: 'briefing',
|
|
397
|
+
text: briefing,
|
|
398
|
+
});
|
|
399
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), attempt: row('SELECT * FROM work_attempts WHERE id = ?', attemptId), input };
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* @param {{
|
|
403
|
+
* ticketId: string,
|
|
404
|
+
* attemptId: string,
|
|
405
|
+
* fencingToken: number,
|
|
406
|
+
* briefingRevision: number,
|
|
407
|
+
* kind: string,
|
|
408
|
+
* text: string,
|
|
409
|
+
* applyStatus: 'pending_completion' | 'applied' | 'stale',
|
|
410
|
+
* }} input
|
|
411
|
+
*/
|
|
412
|
+
function insertEvent(input) {
|
|
413
|
+
const eventId = randomUUID();
|
|
414
|
+
const hash = writeBriefing(input.text);
|
|
415
|
+
try {
|
|
416
|
+
db.prepare(`
|
|
417
|
+
INSERT INTO work_events (
|
|
418
|
+
event_id, ticket_id, attempt_id, fencing_token, briefing_revision, kind, apply_status,
|
|
419
|
+
turn_end_reason, payload_hash, notice_id, created_at
|
|
420
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, NULL, ?)
|
|
421
|
+
`).run(eventId, input.ticketId, input.attemptId, input.fencingToken, input.briefingRevision, input.kind, input.applyStatus, hash, iso());
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
425
|
+
if (message.includes('UNIQUE') || message.includes('PRIMARY'))
|
|
426
|
+
return { duplicate: true, event: null };
|
|
427
|
+
throw error;
|
|
428
|
+
}
|
|
429
|
+
return { duplicate: false, event: row('SELECT * FROM work_events WHERE event_id = ?', eventId) };
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* @param {string} eventId
|
|
433
|
+
* @param {string} reasonKind
|
|
434
|
+
*/
|
|
435
|
+
function applyTerminal(eventId, reasonKind) {
|
|
436
|
+
const found = row('SELECT * FROM work_events WHERE event_id = ?', eventId);
|
|
437
|
+
if (!found || !TERMINAL_KIND.has(found.kind))
|
|
438
|
+
return null;
|
|
439
|
+
if (found.apply_status === 'stale') {
|
|
440
|
+
db.prepare(`UPDATE work_events SET turn_end_reason = ? WHERE event_id = ?`).run(reasonKind, eventId);
|
|
441
|
+
return row('SELECT * FROM work_events WHERE event_id = ?', eventId);
|
|
442
|
+
}
|
|
443
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', found.ticket_id);
|
|
444
|
+
const attempt = row('SELECT * FROM work_attempts WHERE id = ?', found.attempt_id);
|
|
445
|
+
const matches = Boolean(ticket && attempt
|
|
446
|
+
&& ticket.active_attempt_id === found.attempt_id
|
|
447
|
+
&& attempt.fencing_token === found.fencing_token
|
|
448
|
+
&& ticket.briefing_revision === found.briefing_revision
|
|
449
|
+
&& ticket.status !== 'cancelled'
|
|
450
|
+
&& ticket.status !== 'failed'
|
|
451
|
+
&& ticket.status !== 'delivered');
|
|
452
|
+
if (!matches || reasonKind !== 'completed') {
|
|
453
|
+
db.prepare(`UPDATE work_events SET apply_status = 'stale', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind || '', eventId);
|
|
454
|
+
return row('SELECT * FROM work_events WHERE event_id = ?', eventId);
|
|
455
|
+
}
|
|
456
|
+
db.prepare(`UPDATE work_events SET apply_status = 'applied', turn_end_reason = ? WHERE event_id = ?`).run(reasonKind, eventId);
|
|
457
|
+
const stamp = iso();
|
|
458
|
+
if (found.kind === 'question') {
|
|
459
|
+
db.prepare(`UPDATE work_tickets SET status = 'needs_user', updated_at = ? WHERE id = ?`).run(stamp, ticket.id);
|
|
460
|
+
}
|
|
461
|
+
else if (found.kind === 'result') {
|
|
462
|
+
const review = ticket.review_status === 'rejected' ? 'rejected' : 'candidate';
|
|
463
|
+
db.prepare(`
|
|
464
|
+
UPDATE work_tickets SET status = 'ready', review_status = ?, updated_at = ? WHERE id = ?
|
|
465
|
+
`).run(review, stamp, ticket.id);
|
|
466
|
+
db.prepare(`UPDATE work_attempts SET status = 'succeeded', ended_at = ? WHERE id = ?`).run(stamp, attempt.id);
|
|
467
|
+
}
|
|
468
|
+
else if (found.kind === 'failure') {
|
|
469
|
+
db.prepare(`UPDATE work_tickets SET status = 'failed', updated_at = ? WHERE id = ?`).run(stamp, ticket.id);
|
|
470
|
+
db.prepare(`UPDATE work_attempts SET status = 'failed', ended_at = ? WHERE id = ?`).run(stamp, attempt.id);
|
|
471
|
+
}
|
|
472
|
+
return row('SELECT * FROM work_events WHERE event_id = ?', eventId);
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* @param {string} attemptId
|
|
476
|
+
* @param {string} until
|
|
477
|
+
* @param {number | null} seq
|
|
478
|
+
*/
|
|
479
|
+
function touchLease(attemptId, until, seq) {
|
|
480
|
+
db.prepare(`
|
|
481
|
+
UPDATE work_attempts
|
|
482
|
+
SET lease_until = ?, lease_observed_seq = COALESCE(?, lease_observed_seq)
|
|
483
|
+
WHERE id = ?
|
|
484
|
+
`).run(until, seq, attemptId);
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* One open extension request per ticket. A second ask does not insert another notice.
|
|
488
|
+
* @param {string} ticketId
|
|
489
|
+
*/
|
|
490
|
+
function markExtensionOpen(ticketId) {
|
|
491
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
492
|
+
if (!ticket)
|
|
493
|
+
return null;
|
|
494
|
+
const budget = budgetObject(ticket);
|
|
495
|
+
if (budget.extension === 'open')
|
|
496
|
+
return { ticket, already: true };
|
|
497
|
+
budget.extension = 'open';
|
|
498
|
+
db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(budget), iso(), ticketId);
|
|
499
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), already: false };
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Add granted runtime or tokens, capped by the host ceiling, and close the request.
|
|
503
|
+
* @param {string} ticketId
|
|
504
|
+
* @param {{ wallMs?: number, maxTokens?: number }} add
|
|
505
|
+
* @param {{ wallMs: number, maxTokens: number }} ceilings
|
|
506
|
+
*/
|
|
507
|
+
function extendBudget(ticketId, add, ceilings) {
|
|
508
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
509
|
+
if (!ticket)
|
|
510
|
+
return { error: 'NOT_FOUND', message: 'No such ticket.' };
|
|
511
|
+
if (ticket.status === 'failed' || ticket.status === 'cancelled' || ticket.status === 'delivered') {
|
|
512
|
+
return { error: 'VALIDATION', message: 'This ticket has finished and cannot be granted more budget.' };
|
|
513
|
+
}
|
|
514
|
+
const budget = budgetObject(ticket);
|
|
515
|
+
const beforeWall = Number(budget.wallMs) || ceilings.wallMs;
|
|
516
|
+
const beforeTokens = Number(budget.maxTokens) || ceilings.maxTokens;
|
|
517
|
+
const wallAdd = Number(add.wallMs);
|
|
518
|
+
const tokenAdd = Number(add.maxTokens);
|
|
519
|
+
const wallMs = Number.isFinite(wallAdd) && wallAdd > 0
|
|
520
|
+
? Math.min(ceilings.wallMs, beforeWall + Math.floor(wallAdd))
|
|
521
|
+
: beforeWall;
|
|
522
|
+
const maxTokens = Number.isFinite(tokenAdd) && tokenAdd > 0
|
|
523
|
+
? Math.min(ceilings.maxTokens, beforeTokens + Math.floor(tokenAdd))
|
|
524
|
+
: beforeTokens;
|
|
525
|
+
if (wallMs === beforeWall && maxTokens === beforeTokens) {
|
|
526
|
+
return { error: 'VALIDATION', message: 'Nothing more can be granted. The host ceiling is already used.' };
|
|
527
|
+
}
|
|
528
|
+
const next = { ...budget, wallMs, maxTokens, extension: null };
|
|
529
|
+
db.prepare(`UPDATE work_tickets SET budget_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(next), iso(), ticketId);
|
|
530
|
+
return { ticket: row('SELECT * FROM work_tickets WHERE id = ?', ticketId), budget: next };
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* @param {{ budget_json?: string }} ticket
|
|
534
|
+
*/
|
|
535
|
+
function budgetObject(ticket) {
|
|
536
|
+
try {
|
|
537
|
+
const parsed = JSON.parse(ticket.budget_json ?? '');
|
|
538
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return {};
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Lease or enqueue-wall or step budget. Does not open another attempt.
|
|
546
|
+
* @param {string} ticketId
|
|
547
|
+
* @param {string} reason
|
|
548
|
+
*/
|
|
549
|
+
function failRunning(ticketId, reason) {
|
|
550
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
551
|
+
if (!ticket)
|
|
552
|
+
return null;
|
|
553
|
+
if (ticket.status === 'delivered' || ticket.status === 'cancelled' || ticket.status === 'failed')
|
|
554
|
+
return ticket;
|
|
555
|
+
const stamp = iso();
|
|
556
|
+
db.prepare(`UPDATE work_tickets SET status = 'failed', updated_at = ? WHERE id = ?`).run(stamp, ticketId);
|
|
557
|
+
db.prepare(`
|
|
558
|
+
UPDATE work_attempts SET status = 'failed', ended_at = ? WHERE id = ? AND status != 'superseded'
|
|
559
|
+
`).run(stamp, ticket.active_attempt_id);
|
|
560
|
+
db.prepare(`
|
|
561
|
+
UPDATE work_events SET apply_status = 'stale'
|
|
562
|
+
WHERE ticket_id = ? AND apply_status = 'pending_completion'
|
|
563
|
+
`).run(ticketId);
|
|
564
|
+
const attempt = row('SELECT * FROM work_attempts WHERE id = ?', ticket.active_attempt_id);
|
|
565
|
+
if (attempt) {
|
|
566
|
+
insertEvent({
|
|
567
|
+
ticketId,
|
|
568
|
+
attemptId: attempt.id,
|
|
569
|
+
fencingToken: attempt.fencing_token,
|
|
570
|
+
briefingRevision: ticket.briefing_revision,
|
|
571
|
+
kind: 'failure',
|
|
572
|
+
text: hostFailureText(reason),
|
|
573
|
+
applyStatus: 'applied',
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
577
|
+
}
|
|
578
|
+
function expireQuiet() {
|
|
579
|
+
const failed = [];
|
|
580
|
+
const running = db.prepare(`
|
|
581
|
+
SELECT t.id AS ticket_id, t.budget_json, t.status AS ticket_status, a.id AS attempt_id, a.status AS attempt_status,
|
|
582
|
+
a.lease_until, a.current_input_id
|
|
583
|
+
FROM work_tickets t
|
|
584
|
+
JOIN work_attempts a ON a.id = t.active_attempt_id
|
|
585
|
+
WHERE t.status IN ('enqueued','started')
|
|
586
|
+
`).all();
|
|
587
|
+
for (const item of running) {
|
|
588
|
+
if (item.ticket_status === 'started' && item.attempt_status === 'started' && item.lease_until && Date.parse(item.lease_until) <= now().getTime()) {
|
|
589
|
+
failRunning(item.ticket_id, 'lease');
|
|
590
|
+
failed.push(item.ticket_id);
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
if (item.ticket_status === 'enqueued' && item.attempt_status === 'enqueued' && item.current_input_id) {
|
|
594
|
+
const input = row('SELECT * FROM work_inputs WHERE id = ?', item.current_input_id);
|
|
595
|
+
let wall = 10 * 60 * 1000;
|
|
596
|
+
try {
|
|
597
|
+
wall = JSON.parse(item.budget_json).wallMs ?? wall;
|
|
598
|
+
}
|
|
599
|
+
catch { /* host default */ }
|
|
600
|
+
if (input && input.flush_status === 'accepted' && Date.parse(input.updated_at) + wall <= now().getTime()) {
|
|
601
|
+
failRunning(item.ticket_id, 'enqueue-wall');
|
|
602
|
+
failed.push(item.ticket_id);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return failed;
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* @param {{
|
|
610
|
+
* ticketId: string,
|
|
611
|
+
* eventId: string,
|
|
612
|
+
* owner: string,
|
|
613
|
+
* attemptId: string,
|
|
614
|
+
* fencingToken: number,
|
|
615
|
+
* briefingRevision: number,
|
|
616
|
+
* text: string,
|
|
617
|
+
* turn: string | null,
|
|
618
|
+
* }} input
|
|
619
|
+
*/
|
|
620
|
+
function insertDelivery(input) {
|
|
621
|
+
const existing = db.prepare(`
|
|
622
|
+
SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
|
|
623
|
+
`).get(input.ticketId, input.eventId);
|
|
624
|
+
if (existing)
|
|
625
|
+
return { row: existing, already: true };
|
|
626
|
+
const id = randomUUID();
|
|
627
|
+
db.prepare(`
|
|
628
|
+
INSERT INTO user_deliveries (
|
|
629
|
+
publish_id, ticket_id, result_event_id, owner_session_id, attempt_id, fencing_token, briefing_revision,
|
|
630
|
+
text_hash, status, assistant_seq, turn_native_id, client_ack_at, created_at
|
|
631
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'intent', NULL, ?, NULL, ?)
|
|
632
|
+
`).run(id, input.ticketId, input.eventId, input.owner, input.attemptId, input.fencingToken, input.briefingRevision, sha256(input.text), input.turn, iso());
|
|
633
|
+
return { row: db.prepare('SELECT * FROM user_deliveries WHERE publish_id = ?').get(id), already: false };
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* @param {string} ticketId
|
|
637
|
+
* @param {string} eventId
|
|
638
|
+
*/
|
|
639
|
+
function deliveryForEvent(ticketId, eventId) {
|
|
640
|
+
return db.prepare(`
|
|
641
|
+
SELECT * FROM user_deliveries WHERE ticket_id = ? AND result_event_id = ?
|
|
642
|
+
`).get(ticketId, eventId) ?? null;
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* @param {string} ticketId
|
|
646
|
+
* @param {number} briefingRevision
|
|
647
|
+
*/
|
|
648
|
+
function abandonOpenDeliveries(ticketId, briefingRevision) {
|
|
649
|
+
db.prepare(`
|
|
650
|
+
UPDATE user_deliveries SET status = 'abandoned'
|
|
651
|
+
WHERE ticket_id = ? AND status = 'intent' AND briefing_revision < ?
|
|
652
|
+
`).run(ticketId, briefingRevision);
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* @param {string} ticketId
|
|
656
|
+
* @param {'none' | 'candidate' | 'rejected'} review
|
|
657
|
+
*/
|
|
658
|
+
function setReview(ticketId, review) {
|
|
659
|
+
db.prepare(`UPDATE work_tickets SET review_status = ?, updated_at = ? WHERE id = ?`).run(review, iso(), ticketId);
|
|
660
|
+
return row('SELECT * FROM work_tickets WHERE id = ?', ticketId);
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* @param {string} publishId
|
|
664
|
+
* @param {number} seq
|
|
665
|
+
*/
|
|
666
|
+
function bindDelivery(publishId, seq) {
|
|
667
|
+
const delivery = db.prepare('SELECT * FROM user_deliveries WHERE publish_id = ?').get(publishId);
|
|
668
|
+
if (!delivery || delivery.status !== 'intent')
|
|
669
|
+
return delivery;
|
|
670
|
+
db.prepare(`
|
|
671
|
+
UPDATE user_deliveries SET status = 'log_bound', assistant_seq = ? WHERE publish_id = ? AND status = 'intent'
|
|
672
|
+
`).run(seq, publishId);
|
|
673
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', delivery.ticket_id);
|
|
674
|
+
if (ticket && ticket.status === 'ready' && ticket.briefing_revision === delivery.briefing_revision) {
|
|
675
|
+
db.prepare(`UPDATE work_tickets SET status = 'delivered', updated_at = ? WHERE id = ? AND status = 'ready'`).run(iso(), ticket.id);
|
|
676
|
+
}
|
|
677
|
+
return db.prepare('SELECT * FROM user_deliveries WHERE publish_id = ?').get(publishId);
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* @param {string} owner
|
|
681
|
+
*/
|
|
682
|
+
function visibleTickets(owner) {
|
|
683
|
+
const rows = db.prepare(`
|
|
684
|
+
SELECT * FROM work_tickets WHERE owner_session_id = ? ORDER BY updated_at DESC
|
|
685
|
+
`).all(owner);
|
|
686
|
+
const open = rows.filter(item => item.status !== 'delivered' && item.status !== 'cancelled' && item.status !== 'failed');
|
|
687
|
+
const closed = rows.filter(item => !open.includes(item)).slice(0, 8);
|
|
688
|
+
return [...open, ...closed];
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* @param {string} owner
|
|
692
|
+
*/
|
|
693
|
+
function summaries(owner) {
|
|
694
|
+
return visibleTickets(owner).map(item => ({
|
|
695
|
+
id: item.id,
|
|
696
|
+
status: item.status,
|
|
697
|
+
briefing_revision: item.briefing_revision,
|
|
698
|
+
child_session_id: item.child_session_id,
|
|
699
|
+
summary: readBriefing(item.briefing_hash).replace(/\s+/g, ' ').trim().slice(0, 80),
|
|
700
|
+
}));
|
|
701
|
+
}
|
|
702
|
+
/** Stable across unchanged rows. Lease touches are not part of it. */
|
|
703
|
+
function liveStamp() {
|
|
704
|
+
const tickets = db.prepare(`
|
|
705
|
+
SELECT id, status, briefing_revision, IFNULL(child_session_id, '') AS child_session_id,
|
|
706
|
+
IFNULL(active_attempt_id, '') AS active_attempt_id, briefing_hash, updated_at
|
|
707
|
+
FROM work_tickets ORDER BY id
|
|
708
|
+
`).all();
|
|
709
|
+
const events = db.prepare(`
|
|
710
|
+
SELECT event_id, apply_status, payload_hash FROM work_events ORDER BY event_id
|
|
711
|
+
`).all();
|
|
712
|
+
const attempts = db.prepare(`
|
|
713
|
+
SELECT id, IFNULL(started_at, '') AS started_at FROM work_attempts ORDER BY id
|
|
714
|
+
`).all();
|
|
715
|
+
return JSON.stringify([tickets, events, attempts]);
|
|
716
|
+
}
|
|
717
|
+
/** Delivered and cancelled tickets do not light a bot, so they stay out of signals. */
|
|
718
|
+
function signalMap() {
|
|
719
|
+
const rows = db.prepare(`
|
|
720
|
+
SELECT owner_session_id, status FROM work_tickets
|
|
721
|
+
WHERE status != 'delivered' AND status != 'cancelled'
|
|
722
|
+
ORDER BY updated_at DESC
|
|
723
|
+
`).all();
|
|
724
|
+
/** @type {Record<string, string[]>} */
|
|
725
|
+
const signals = {};
|
|
726
|
+
for (const item of rows) {
|
|
727
|
+
const owner = item.owner_session_id;
|
|
728
|
+
const list = signals[owner] ?? [];
|
|
729
|
+
list.push(item.status);
|
|
730
|
+
signals[owner] = list;
|
|
731
|
+
}
|
|
732
|
+
return signals;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Sidebar statuses for every owner, plus card bodies for one session.
|
|
736
|
+
* Delivered and cancelled tickets do not light a bot, so they stay out of signals.
|
|
737
|
+
* @param {string} sessionId
|
|
738
|
+
*/
|
|
739
|
+
function liveBoard(sessionId) {
|
|
740
|
+
return {
|
|
741
|
+
ok: true,
|
|
742
|
+
sessionId,
|
|
743
|
+
signals: signalMap(),
|
|
744
|
+
cards: sessionId === '' ? [] : cardBodies(sessionId),
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
/** Cards for every owner, so one stream can follow a session switch. */
|
|
748
|
+
function liveBoardAll() {
|
|
749
|
+
const owners = db.prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`).all();
|
|
750
|
+
/** @type {Record<string, ReturnType<typeof cardBodies>>} */
|
|
751
|
+
const cards = {};
|
|
752
|
+
for (const owner of owners)
|
|
753
|
+
cards[owner.id] = cardBodies(owner.id);
|
|
754
|
+
return { signals: signalMap(), cards };
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* The same rows the ticket list shows, with the fields a card reads.
|
|
758
|
+
* @param {string} owner
|
|
759
|
+
*/
|
|
760
|
+
function cardBodies(owner) {
|
|
761
|
+
const picked = visibleTickets(owner);
|
|
762
|
+
if (picked.length === 0)
|
|
763
|
+
return [];
|
|
764
|
+
const ids = picked.map(item => item.id);
|
|
765
|
+
const marks = ids.map(() => '?').join(',');
|
|
766
|
+
const attempts = db.prepare(`
|
|
767
|
+
SELECT id, ticket_id, started_at FROM work_attempts WHERE ticket_id IN (${marks})
|
|
768
|
+
`).all(...ids);
|
|
769
|
+
const events = db.prepare(`
|
|
770
|
+
SELECT * FROM work_events WHERE ticket_id IN (${marks}) ORDER BY created_at
|
|
771
|
+
`).all(...ids);
|
|
772
|
+
/** @type {Map<string, Array<{ id: string, started_at: string | null }>>} */
|
|
773
|
+
const byAttempt = new Map();
|
|
774
|
+
for (const attempt of attempts) {
|
|
775
|
+
const list = byAttempt.get(attempt.ticket_id) ?? [];
|
|
776
|
+
list.push({ id: attempt.id, started_at: attempt.started_at ?? null });
|
|
777
|
+
byAttempt.set(attempt.ticket_id, list);
|
|
778
|
+
}
|
|
779
|
+
/** @type {Map<string, Array<Record<string, unknown>>>} */
|
|
780
|
+
const byEvent = new Map();
|
|
781
|
+
for (const event of events) {
|
|
782
|
+
const list = byEvent.get(event.ticket_id) ?? [];
|
|
783
|
+
list.push({
|
|
784
|
+
event_id: event.event_id,
|
|
785
|
+
kind: event.kind,
|
|
786
|
+
apply_status: event.apply_status,
|
|
787
|
+
briefing_revision: event.briefing_revision,
|
|
788
|
+
text: readBriefing(event.payload_hash),
|
|
789
|
+
});
|
|
790
|
+
byEvent.set(event.ticket_id, list);
|
|
791
|
+
}
|
|
792
|
+
return picked.map(item => ({
|
|
793
|
+
summary: readBriefing(item.briefing_hash).replace(/\s+/g, ' ').trim().slice(0, 80),
|
|
794
|
+
ticket: {
|
|
795
|
+
id: item.id,
|
|
796
|
+
status: item.status,
|
|
797
|
+
briefing_revision: item.briefing_revision,
|
|
798
|
+
child_session_id: item.child_session_id,
|
|
799
|
+
active_attempt_id: item.active_attempt_id,
|
|
800
|
+
},
|
|
801
|
+
attempts: byAttempt.get(item.id) ?? [],
|
|
802
|
+
events: byEvent.get(item.id) ?? [],
|
|
803
|
+
}));
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* @param {string} id
|
|
807
|
+
*/
|
|
808
|
+
function detail(id) {
|
|
809
|
+
const found = row('SELECT * FROM work_tickets WHERE id = ?', id);
|
|
810
|
+
if (!found)
|
|
811
|
+
return null;
|
|
812
|
+
return {
|
|
813
|
+
ticket: found,
|
|
814
|
+
attempts: db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(id),
|
|
815
|
+
inputs: db.prepare('SELECT * FROM work_inputs WHERE ticket_id = ? ORDER BY created_at').all(id),
|
|
816
|
+
events: db.prepare('SELECT * FROM work_events WHERE ticket_id = ? ORDER BY created_at').all(id).map(event => ({
|
|
817
|
+
...event,
|
|
818
|
+
text: readBriefing(event.payload_hash),
|
|
819
|
+
})),
|
|
820
|
+
notices: db.prepare('SELECT * FROM work_notices WHERE ticket_id = ? ORDER BY created_at').all(id),
|
|
821
|
+
deliveries: db.prepare('SELECT * FROM user_deliveries WHERE ticket_id = ? ORDER BY created_at').all(id),
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* @param {string} owner
|
|
826
|
+
*/
|
|
827
|
+
function eventsWithoutNotice(owner) {
|
|
828
|
+
return db.prepare(`
|
|
829
|
+
SELECT e.* FROM work_events e
|
|
830
|
+
JOIN work_tickets t ON t.id = e.ticket_id
|
|
831
|
+
WHERE t.owner_session_id = ? AND e.notice_id IS NULL AND e.apply_status != 'stale'
|
|
832
|
+
ORDER BY e.created_at
|
|
833
|
+
`).all(owner);
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* @param {string} owner
|
|
837
|
+
*/
|
|
838
|
+
function pendingWake(owner) {
|
|
839
|
+
const events = eventsWithoutNotice(owner);
|
|
840
|
+
const cancels = db.prepare(`
|
|
841
|
+
SELECT * FROM work_tickets t
|
|
842
|
+
WHERE t.owner_session_id = ? AND t.status = 'cancelled' AND t.cancel_requested_revision IS NOT NULL
|
|
843
|
+
AND NOT EXISTS (
|
|
844
|
+
SELECT 1 FROM work_notices n
|
|
845
|
+
WHERE n.ticket_id = t.id AND n.event_id = 'cancel:' || t.cancel_requested_revision
|
|
846
|
+
)
|
|
847
|
+
`).all(owner);
|
|
848
|
+
return { events, cancels };
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* @param {string} owner
|
|
852
|
+
*/
|
|
853
|
+
function openNotice(owner) {
|
|
854
|
+
const rows = db.prepare(`SELECT flush_status, observe_status FROM work_notices WHERE owner_session_id = ?`).all(owner);
|
|
855
|
+
return rows.some(item => OPEN_NOTICE_FLUSH.has(item.flush_status) || (item.flush_status === 'accepted' && item.observe_status !== 'completed'));
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* @param {string} owner
|
|
859
|
+
*/
|
|
860
|
+
function openDelivery(owner) {
|
|
861
|
+
const found = db.prepare(`
|
|
862
|
+
SELECT 1 AS ok FROM deliveries
|
|
863
|
+
WHERE target_session_id = ? AND kind IN ('message','timer','webhook')
|
|
864
|
+
AND status IN ('intent','flushing','accepted','claimed','started')
|
|
865
|
+
LIMIT 1
|
|
866
|
+
`).get(owner);
|
|
867
|
+
return found != null;
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* @param {string} owner
|
|
871
|
+
*/
|
|
872
|
+
function backgroundIds(owner) {
|
|
873
|
+
const notices = db.prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`).all(owner);
|
|
874
|
+
const deliveries = db.prepare(`SELECT id FROM deliveries WHERE target_session_id = ?`).all(owner);
|
|
875
|
+
return [...notices.map(item => item.native_message_id), ...deliveries.map(item => item.id)];
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* @param {string} owner
|
|
879
|
+
*/
|
|
880
|
+
function latestNoticeAt(owner) {
|
|
881
|
+
const found = db.prepare(`
|
|
882
|
+
SELECT created_at FROM work_notices WHERE owner_session_id = ? ORDER BY created_at DESC LIMIT 1
|
|
883
|
+
`).get(owner);
|
|
884
|
+
return found ? Date.parse(found.created_at) : null;
|
|
885
|
+
}
|
|
886
|
+
function flushInputs() {
|
|
887
|
+
return db.prepare(`
|
|
888
|
+
SELECT * FROM work_inputs WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
|
|
889
|
+
`).all();
|
|
890
|
+
}
|
|
891
|
+
function flushNotices() {
|
|
892
|
+
return db.prepare(`
|
|
893
|
+
SELECT * FROM work_notices WHERE flush_status IN ('intent','flushing','ambiguous') ORDER BY created_at
|
|
894
|
+
`).all();
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* @param {string} id
|
|
898
|
+
* @param {string} status
|
|
899
|
+
* @param {number | null} pid
|
|
900
|
+
* @param {string} error
|
|
901
|
+
* @param {number | null} seq
|
|
902
|
+
* @param {boolean} bump
|
|
903
|
+
*/
|
|
904
|
+
function markInputFlush(id, status, pid, error, seq, bump) {
|
|
905
|
+
if (bump) {
|
|
906
|
+
db.prepare(`
|
|
907
|
+
UPDATE work_inputs
|
|
908
|
+
SET flush_status = ?, flush_pid = ?, flush_attempts = flush_attempts + 1, last_error = ?, log_seq = COALESCE(?, log_seq), updated_at = ?
|
|
909
|
+
WHERE id = ?
|
|
910
|
+
`).run(status, pid, error, seq, iso(), id);
|
|
911
|
+
}
|
|
912
|
+
else {
|
|
913
|
+
db.prepare(`
|
|
914
|
+
UPDATE work_inputs
|
|
915
|
+
SET flush_status = ?, flush_pid = COALESCE(?, flush_pid), last_error = ?, log_seq = COALESCE(?, log_seq), updated_at = ?
|
|
916
|
+
WHERE id = ?
|
|
917
|
+
`).run(status, pid, error, seq, iso(), id);
|
|
918
|
+
}
|
|
919
|
+
return row('SELECT * FROM work_inputs WHERE id = ?', id);
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* @param {string} nativeId
|
|
923
|
+
* @param {string} status
|
|
924
|
+
* @param {number | null} pid
|
|
925
|
+
* @param {string} error
|
|
926
|
+
* @param {number | null} seq
|
|
927
|
+
* @param {boolean} bump
|
|
928
|
+
*/
|
|
929
|
+
function markNoticeGroup(nativeId, status, pid, error, seq, bump) {
|
|
930
|
+
if (bump) {
|
|
931
|
+
db.prepare(`
|
|
932
|
+
UPDATE work_notices
|
|
933
|
+
SET flush_status = ?, flush_pid = ?, flush_attempts = flush_attempts + 1, last_error = ?, log_seq = COALESCE(?, log_seq), updated_at = ?
|
|
934
|
+
WHERE native_message_id = ?
|
|
935
|
+
`).run(status, pid, error, seq, iso(), nativeId);
|
|
936
|
+
}
|
|
937
|
+
else {
|
|
938
|
+
db.prepare(`
|
|
939
|
+
UPDATE work_notices
|
|
940
|
+
SET flush_status = ?, flush_pid = COALESCE(?, flush_pid), last_error = ?, log_seq = COALESCE(?, log_seq), updated_at = ?
|
|
941
|
+
WHERE native_message_id = ?
|
|
942
|
+
`).run(status, pid, error, seq, iso(), nativeId);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* @param {import('node:sqlite').StatementResultRow} input
|
|
947
|
+
* @param {number | null} seq
|
|
948
|
+
*/
|
|
949
|
+
function noteInputAccepted(input, seq) {
|
|
950
|
+
markInputFlush(input.id, 'accepted', input.flush_pid ?? null, '', seq, false);
|
|
951
|
+
const ticket = row('SELECT * FROM work_tickets WHERE id = ?', input.ticket_id);
|
|
952
|
+
if (!ticket || ticket.active_attempt_id !== input.attempt_id)
|
|
953
|
+
return;
|
|
954
|
+
if (ticket.briefing_revision !== input.briefing_revision)
|
|
955
|
+
return;
|
|
956
|
+
if (input.kind === 'cancel_note')
|
|
957
|
+
return;
|
|
958
|
+
markEnqueued(ticket.id);
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* @param {string} nativeId
|
|
962
|
+
* @param {'claimed' | 'started' | 'completed'} status
|
|
963
|
+
*/
|
|
964
|
+
function setNoticeObserve(nativeId, status) {
|
|
965
|
+
const rank = { none: 0, claimed: 1, started: 2, completed: 3 };
|
|
966
|
+
const rows = db.prepare(`SELECT id, observe_status FROM work_notices WHERE native_message_id = ?`).all(nativeId);
|
|
967
|
+
for (const item of rows) {
|
|
968
|
+
if ((rank[item.observe_status] ?? 0) >= rank[status])
|
|
969
|
+
continue;
|
|
970
|
+
db.prepare(`UPDATE work_notices SET observe_status = ?, updated_at = ? WHERE id = ?`).run(status, iso(), item.id);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* @param {string} owner
|
|
975
|
+
*/
|
|
976
|
+
function intentsFor(owner) {
|
|
977
|
+
return db.prepare(`
|
|
978
|
+
SELECT * FROM user_deliveries WHERE owner_session_id = ? AND status = 'intent' ORDER BY created_at
|
|
979
|
+
`).all(owner);
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* One native wake id shared by every event in the merged notice.
|
|
983
|
+
* @param {string} nativeId
|
|
984
|
+
* @param {string} owner
|
|
985
|
+
* @param {Array<{ ticketId: string, eventId: string }>} items
|
|
986
|
+
*/
|
|
987
|
+
function insertNotices(nativeId, owner, items) {
|
|
988
|
+
const stamp = iso();
|
|
989
|
+
/** @type {string[]} */
|
|
990
|
+
const ids = [];
|
|
991
|
+
for (const item of items) {
|
|
992
|
+
const id = randomUUID();
|
|
993
|
+
db.prepare(`
|
|
994
|
+
INSERT INTO work_notices (
|
|
995
|
+
id, ticket_id, event_id, owner_session_id, native_message_id, flush_status, flush_pid,
|
|
996
|
+
flush_attempts, last_error, log_seq, observe_status, created_at, updated_at
|
|
997
|
+
) VALUES (?, ?, ?, ?, ?, 'intent', NULL, 0, '', NULL, 'none', ?, ?)
|
|
998
|
+
`).run(id, item.ticketId, item.eventId, owner, nativeId, stamp, stamp);
|
|
999
|
+
if (!item.eventId.startsWith('cancel:')) {
|
|
1000
|
+
db.prepare(`UPDATE work_events SET notice_id = ? WHERE event_id = ? AND notice_id IS NULL`).run(id, item.eventId);
|
|
1001
|
+
}
|
|
1002
|
+
ids.push(id);
|
|
1003
|
+
}
|
|
1004
|
+
return ids;
|
|
1005
|
+
}
|
|
1006
|
+
function attemptsOf(ticketId) {
|
|
1007
|
+
return db.prepare('SELECT * FROM work_attempts WHERE ticket_id = ? ORDER BY fencing_token').all(ticketId);
|
|
1008
|
+
}
|
|
1009
|
+
function ownerIds() {
|
|
1010
|
+
return db.prepare(`SELECT DISTINCT owner_session_id AS id FROM work_tickets`).all().map(item => item.id);
|
|
1011
|
+
}
|
|
1012
|
+
function childIds() {
|
|
1013
|
+
return db.prepare(`
|
|
1014
|
+
SELECT DISTINCT child_session_id AS id FROM work_attempts
|
|
1015
|
+
WHERE child_session_id IS NOT NULL
|
|
1016
|
+
`).all().map(item => item.id);
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* @param {string} owner
|
|
1020
|
+
*/
|
|
1021
|
+
function noticeIds(owner) {
|
|
1022
|
+
return new Set(db.prepare(`SELECT native_message_id FROM work_notices WHERE owner_session_id = ?`).all(owner).map(item => item.native_message_id));
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* @param {string} reason
|
|
1027
|
+
*/
|
|
1028
|
+
function hostFailureText(reason) {
|
|
1029
|
+
if (reason === 'wall')
|
|
1030
|
+
return 'The worker hit its time limit and this round has stopped.';
|
|
1031
|
+
if (reason === 'tokens')
|
|
1032
|
+
return 'The worker hit its token limit and this round has stopped.';
|
|
1033
|
+
if (reason === 'grant-denied')
|
|
1034
|
+
return 'The main session refused more budget and this round has stopped.';
|
|
1035
|
+
if (reason === 'lease')
|
|
1036
|
+
return 'The worker lease expired and this round has stopped.';
|
|
1037
|
+
if (reason === 'enqueue-wall')
|
|
1038
|
+
return 'The task entered the queue and did not start before the time limit.';
|
|
1039
|
+
if (reason === 'steps')
|
|
1040
|
+
return 'The worker hit its step limit and this round has stopped.';
|
|
1041
|
+
return 'The worker has stopped.';
|
|
1042
|
+
}
|