@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.2
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/client.js +646 -621
- package/dist/cli.js +32 -12
- package/dist/context.js +21 -9
- package/dist/cron.js +1 -1
- package/dist/desk.js +51 -24
- package/dist/engine.js +160 -77
- package/dist/fs-safe.js +1 -1
- package/dist/host.js +1 -0
- package/dist/http-plugin.js +6 -2
- package/dist/http.js +60 -22
- package/dist/inbox.js +10 -7
- package/dist/index.js +39 -24
- package/dist/live-diff.js +3 -1
- package/dist/live-snapshot.js +3 -1
- package/dist/provision.js +2 -0
- package/dist/runtime-registry.js +4 -4
- package/dist/session-files.js +1 -1
- package/dist/session-previews.js +5 -1
- package/dist/store.js +20 -5
- package/dist/tools.js +62 -26
- package/dist/triggers.js +83 -39
- package/dist/work-admit.js +10 -4
- package/dist/work-child.js +9 -6
- package/dist/work-http.js +4 -2
- package/dist/work-ledger.js +16 -14
- package/dist/work-mock-host.js +8 -6
- package/dist/work-mock.js +15 -18
- package/dist/work-tickets.js +156 -72
- package/dist/work-tools.js +2 -2
- package/dist/work-worker.js +117 -52
- package/package.json +8 -4
- package/public/assets/{index-ByU9a3Lh.js → index-D0tTt7E4.js} +37 -37
- package/public/assets/{index-Be82iGwe.css → index-PyqSrdBb.css} +1 -1
- package/public/index.html +2 -2
package/dist/tools.js
CHANGED
|
@@ -30,7 +30,8 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
|
|
|
30
30
|
},
|
|
31
31
|
required: ['query'],
|
|
32
32
|
}, async (args, hostId) => {
|
|
33
|
-
const
|
|
33
|
+
const requested = args.limit;
|
|
34
|
+
const limit = Math.min(20, Math.max(1, typeof requested === 'number' && Number.isInteger(requested) ? requested : 5));
|
|
34
35
|
if (typeof args.query !== 'string' || args.query.trim() === '')
|
|
35
36
|
return toolError('VALIDATION', 'query is required.');
|
|
36
37
|
const found = engine.recall(hostId, args.query.trim(), limit);
|
|
@@ -59,20 +60,24 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
|
|
|
59
60
|
const created = nowIso();
|
|
60
61
|
if (args.target === 'fact') {
|
|
61
62
|
const priority = Number.isInteger(args.priority) ? args.priority : 100;
|
|
62
|
-
const info = engine.store.db
|
|
63
|
+
const info = engine.store.db
|
|
64
|
+
.prepare(`
|
|
63
65
|
INSERT INTO facts (
|
|
64
66
|
session_id, kind, content, status, source_event_id, source_type, revision, priority, created_at, updated_at
|
|
65
67
|
) VALUES (?, 'user_fact', ?, 'active', ?, 'explicit_tool', 1, ?, ?, ?)
|
|
66
|
-
`)
|
|
68
|
+
`)
|
|
69
|
+
.run(hostId, args.content, args.sourceEventId ?? null, priority, created, created);
|
|
67
70
|
const id = Number(info.lastInsertRowid);
|
|
68
71
|
syncFactFts(engine.store.db, id, args.content, true);
|
|
69
72
|
return ok(revision(hostId), 1, { id, target: 'fact', revision: 1 });
|
|
70
73
|
}
|
|
71
|
-
const info = engine.store.db
|
|
74
|
+
const info = engine.store.db
|
|
75
|
+
.prepare(`
|
|
72
76
|
INSERT INTO memories (
|
|
73
77
|
session_id, title, content, status, source_event_id, source_type, revision, created_at, updated_at
|
|
74
78
|
) VALUES (?, ?, ?, 'active', ?, 'explicit_tool', 1, ?, ?)
|
|
75
|
-
`)
|
|
79
|
+
`)
|
|
80
|
+
.run(hostId, typeof args.title === 'string' ? args.title : null, args.content, args.sourceEventId ?? null, created, created);
|
|
76
81
|
const id = Number(info.lastInsertRowid);
|
|
77
82
|
syncMemoryFts(engine.store.db, id, typeof args.title === 'string' ? args.title : '', args.content, true);
|
|
78
83
|
return ok(revision(hostId), 1, { id, target: 'memory', revision: 1 });
|
|
@@ -138,7 +143,7 @@ export function toolDefinitions(engine, viewRevision = () => 0) {
|
|
|
138
143
|
* @param {string} name
|
|
139
144
|
* @param {string} description
|
|
140
145
|
* @param {Record<string, unknown>} parameters
|
|
141
|
-
* @param {(args: Record<string, unknown>, hostId: string) => Promise<
|
|
146
|
+
* @param {(args: Record<string, unknown>, hostId: string) => Promise<ToolPayload>} run
|
|
142
147
|
*/
|
|
143
148
|
function tool(name, description, parameters, run) {
|
|
144
149
|
return {
|
|
@@ -168,17 +173,18 @@ function tool(name, description, parameters, run) {
|
|
|
168
173
|
* @param {string} name
|
|
169
174
|
* @param {Record<string, unknown>} args
|
|
170
175
|
* @param {() => number} viewRevision
|
|
171
|
-
* @param {() =>
|
|
176
|
+
* @param {() => ToolPayload} apply
|
|
172
177
|
*/
|
|
173
178
|
async function write(engine, hostId, name, args, viewRevision, apply) {
|
|
174
179
|
const binding = engine.ensureSession(hostId);
|
|
175
180
|
if (binding.status === 'error')
|
|
176
181
|
return toolError('UNAVAILABLE', `Binding is ${binding.error_code ?? 'error'}.`);
|
|
177
|
-
|
|
182
|
+
const idempotencyKey = args.idempotencyKey;
|
|
183
|
+
if (typeof idempotencyKey !== 'string' || idempotencyKey.trim() === '') {
|
|
178
184
|
return toolError('VALIDATION', 'idempotencyKey is required.');
|
|
179
185
|
}
|
|
180
186
|
const payloadHash = createHash('sha256').update(stable(args)).digest('hex');
|
|
181
|
-
const result = await engine.store.write(hostId, () =>
|
|
187
|
+
const result = await engine.store.write(hostId, () => engine.mutate(hostId, idempotencyKey, payloadHash, name, args, apply, viewRevision()));
|
|
182
188
|
if (result.ok === true && result.outcome === 'applied') {
|
|
183
189
|
const exported = await engine.exportOne({ id: result.mutationId, session_id: hostId, attempts: 0 });
|
|
184
190
|
const final = {
|
|
@@ -186,7 +192,9 @@ async function write(engine, hostId, name, args, viewRevision, apply) {
|
|
|
186
192
|
export: exported.ok ? 'done' : 'failed',
|
|
187
193
|
...(exported.ok ? {} : { exportError: exported.error }),
|
|
188
194
|
};
|
|
189
|
-
engine.store.db
|
|
195
|
+
engine.store.db
|
|
196
|
+
.prepare('UPDATE mutations SET result_json = ? WHERE id = ?')
|
|
197
|
+
.run(JSON.stringify(final), result.mutationId);
|
|
190
198
|
return final;
|
|
191
199
|
}
|
|
192
200
|
return result;
|
|
@@ -213,7 +221,10 @@ function publish(result) {
|
|
|
213
221
|
* @param {Record<string, unknown>} args
|
|
214
222
|
*/
|
|
215
223
|
function correct(engine, hostId, args) {
|
|
216
|
-
if ((args.target !== 'fact' && args.target !== 'memory') ||
|
|
224
|
+
if ((args.target !== 'fact' && args.target !== 'memory') ||
|
|
225
|
+
typeof args.content !== 'string' ||
|
|
226
|
+
!Number.isInteger(args.id) ||
|
|
227
|
+
!Number.isInteger(args.expectedRevision)) {
|
|
217
228
|
return toolError('VALIDATION', 'correct arguments are incomplete.');
|
|
218
229
|
}
|
|
219
230
|
const table = args.target === 'fact' ? 'facts' : 'memories';
|
|
@@ -226,23 +237,31 @@ function correct(engine, hostId, args) {
|
|
|
226
237
|
const created = nowIso();
|
|
227
238
|
let inserted;
|
|
228
239
|
if (args.target === 'fact') {
|
|
229
|
-
inserted = engine.store.db
|
|
240
|
+
inserted = engine.store.db
|
|
241
|
+
.prepare(`
|
|
230
242
|
INSERT INTO facts (
|
|
231
243
|
session_id, kind, content, status, source_type, supersedes, revision, priority, created_at, updated_at
|
|
232
244
|
) VALUES (?, 'user_fact', ?, 'active', 'explicit_tool', ?, 1, ?, ?, ?)
|
|
233
|
-
`)
|
|
234
|
-
|
|
245
|
+
`)
|
|
246
|
+
.run(hostId, args.content, row.id, row.priority, created, created);
|
|
247
|
+
engine.store.db
|
|
248
|
+
.prepare(`UPDATE facts SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`)
|
|
249
|
+
.run(row.revision + 1, created, row.id);
|
|
235
250
|
syncFactFts(engine.store.db, row.id, row.content, false);
|
|
236
251
|
syncFactFts(engine.store.db, Number(inserted.lastInsertRowid), args.content, true);
|
|
237
252
|
}
|
|
238
253
|
else {
|
|
239
254
|
const title = typeof args.title === 'string' ? args.title : row.title;
|
|
240
|
-
inserted = engine.store.db
|
|
255
|
+
inserted = engine.store.db
|
|
256
|
+
.prepare(`
|
|
241
257
|
INSERT INTO memories (
|
|
242
258
|
session_id, title, content, status, source_type, supersedes, revision, created_at, updated_at
|
|
243
259
|
) VALUES (?, ?, ?, 'active', 'explicit_tool', ?, 1, ?, ?)
|
|
244
|
-
`)
|
|
245
|
-
|
|
260
|
+
`)
|
|
261
|
+
.run(hostId, title, args.content, row.id, created, created);
|
|
262
|
+
engine.store.db
|
|
263
|
+
.prepare(`UPDATE memories SET status = 'superseded', revision = ?, updated_at = ? WHERE id = ?`)
|
|
264
|
+
.run(row.revision + 1, created, row.id);
|
|
246
265
|
syncMemoryFts(engine.store.db, row.id, row.title, row.content, false);
|
|
247
266
|
syncMemoryFts(engine.store.db, Number(inserted.lastInsertRowid), title, args.content, true);
|
|
248
267
|
}
|
|
@@ -254,7 +273,9 @@ function correct(engine, hostId, args) {
|
|
|
254
273
|
* @param {Record<string, unknown>} args
|
|
255
274
|
*/
|
|
256
275
|
function forget(engine, hostId, args) {
|
|
257
|
-
if ((args.target !== 'fact' && args.target !== 'memory') ||
|
|
276
|
+
if ((args.target !== 'fact' && args.target !== 'memory') ||
|
|
277
|
+
!Number.isInteger(args.id) ||
|
|
278
|
+
!Number.isInteger(args.expectedRevision)) {
|
|
258
279
|
return toolError('VALIDATION', 'forget arguments are incomplete.');
|
|
259
280
|
}
|
|
260
281
|
const table = args.target === 'fact' ? 'facts' : 'memories';
|
|
@@ -264,7 +285,9 @@ function forget(engine, hostId, args) {
|
|
|
264
285
|
if (row.revision !== args.expectedRevision)
|
|
265
286
|
return toolError('CAS_CONFLICT', 'The revision has changed.', { actualRevision: row.revision });
|
|
266
287
|
const updated = nowIso();
|
|
267
|
-
engine.store.db
|
|
288
|
+
engine.store.db
|
|
289
|
+
.prepare(`UPDATE ${table} SET status = 'forgotten', revision = ?, updated_at = ? WHERE id = ?`)
|
|
290
|
+
.run(row.revision + 1, updated, row.id);
|
|
268
291
|
if (args.target === 'fact')
|
|
269
292
|
syncFactFts(engine.store.db, row.id, row.content, false);
|
|
270
293
|
else
|
|
@@ -277,7 +300,10 @@ function forget(engine, hostId, args) {
|
|
|
277
300
|
* @param {Record<string, unknown>} args
|
|
278
301
|
*/
|
|
279
302
|
function updateState(engine, hostId, args) {
|
|
280
|
-
if (!Number.isInteger(args.expectedRevision) ||
|
|
303
|
+
if (!Number.isInteger(args.expectedRevision) ||
|
|
304
|
+
args.patch == null ||
|
|
305
|
+
typeof args.patch !== 'object' ||
|
|
306
|
+
Array.isArray(args.patch)) {
|
|
281
307
|
return toolError('VALIDATION', 'state_update arguments are incomplete.');
|
|
282
308
|
}
|
|
283
309
|
const current = engine.statePayload(hostId);
|
|
@@ -314,14 +340,18 @@ function updateState(engine, hostId, args) {
|
|
|
314
340
|
const revision = current.revision + 1;
|
|
315
341
|
const updated = nowIso();
|
|
316
342
|
if (current.revision === 0) {
|
|
317
|
-
engine.store.db
|
|
343
|
+
engine.store.db
|
|
344
|
+
.prepare(`
|
|
318
345
|
INSERT INTO working_state (session_id, revision, payload_json, updated_at) VALUES (?, ?, ?, ?)
|
|
319
|
-
`)
|
|
346
|
+
`)
|
|
347
|
+
.run(hostId, revision, JSON.stringify(next), updated);
|
|
320
348
|
}
|
|
321
349
|
else {
|
|
322
|
-
engine.store.db
|
|
350
|
+
engine.store.db
|
|
351
|
+
.prepare(`
|
|
323
352
|
UPDATE working_state SET revision = ?, payload_json = ?, updated_at = ? WHERE session_id = ?
|
|
324
|
-
`)
|
|
353
|
+
`)
|
|
354
|
+
.run(revision, JSON.stringify(next), updated, hostId);
|
|
325
355
|
}
|
|
326
356
|
return ok(0, revision, { revision, payload: next });
|
|
327
357
|
}
|
|
@@ -339,11 +369,17 @@ function ok(viewRevision, storeRevision, data) {
|
|
|
339
369
|
function stable(value) {
|
|
340
370
|
if (Array.isArray(value))
|
|
341
371
|
return `[${value.map(item => stable(item)).join(',')}]`;
|
|
342
|
-
if (value
|
|
343
|
-
return `{${Object.keys(value)
|
|
372
|
+
if (isRecord(value)) {
|
|
373
|
+
return `{${Object.keys(value)
|
|
374
|
+
.sort()
|
|
375
|
+
.map(key => `${JSON.stringify(key)}:${stable(value[key])}`)
|
|
376
|
+
.join(',')}}`;
|
|
344
377
|
}
|
|
345
378
|
return JSON.stringify(value);
|
|
346
379
|
}
|
|
380
|
+
function isRecord(value) {
|
|
381
|
+
return value != null && typeof value === 'object' && !Array.isArray(value);
|
|
382
|
+
}
|
|
347
383
|
function nowIso() {
|
|
348
384
|
return new Date().toISOString();
|
|
349
385
|
}
|
package/dist/triggers.js
CHANGED
|
@@ -68,7 +68,9 @@ export function createTriggers(store, options) {
|
|
|
68
68
|
observeUserMessage,
|
|
69
69
|
observeTurnEnd,
|
|
70
70
|
hasOpen(sessionId) {
|
|
71
|
-
const row = db
|
|
71
|
+
const row = db
|
|
72
|
+
.prepare(`SELECT 1 AS ok FROM deliveries WHERE target_session_id = ? AND status IN ('intent','flushing','accepted','claimed','started') LIMIT 1`)
|
|
73
|
+
.get(sessionId);
|
|
72
74
|
return row != null;
|
|
73
75
|
},
|
|
74
76
|
};
|
|
@@ -111,10 +113,14 @@ export function createTriggers(store, options) {
|
|
|
111
113
|
* @param {string} senderSessionId
|
|
112
114
|
*/
|
|
113
115
|
function pairBlocked(targetSessionId, senderSessionId) {
|
|
114
|
-
return db
|
|
116
|
+
return (db
|
|
117
|
+
.prepare('SELECT 1 AS ok FROM delivery_block WHERE target_session_id = ? AND sender_session_id = ?')
|
|
118
|
+
.get(targetSessionId, senderSessionId) != null);
|
|
115
119
|
}
|
|
116
120
|
function listAcl() {
|
|
117
|
-
return db
|
|
121
|
+
return db
|
|
122
|
+
.prepare('SELECT target_session_id, sender_session_id, created_at FROM delivery_block ORDER BY created_at')
|
|
123
|
+
.all();
|
|
118
124
|
}
|
|
119
125
|
/**
|
|
120
126
|
* @param {string} senderSessionId host-bound sender
|
|
@@ -173,17 +179,21 @@ export function createTriggers(store, options) {
|
|
|
173
179
|
async function reply(senderSessionId, args) {
|
|
174
180
|
if (!checkSession(senderSessionId, true))
|
|
175
181
|
return toolError('VALIDATION', 'The sender session is invalid.');
|
|
176
|
-
if (typeof args.correlationId !== 'string' ||
|
|
182
|
+
if (typeof args.correlationId !== 'string' ||
|
|
183
|
+
typeof args.text !== 'string' ||
|
|
184
|
+
typeof args.idempotencyKey !== 'string') {
|
|
177
185
|
return toolError('VALIDATION', 'reply arguments are incomplete.');
|
|
178
186
|
}
|
|
179
187
|
const blocked = requireBot(senderSessionId);
|
|
180
188
|
if (blocked)
|
|
181
189
|
return blocked;
|
|
182
|
-
const prior = db
|
|
190
|
+
const prior = db
|
|
191
|
+
.prepare(`
|
|
183
192
|
SELECT * FROM deliveries
|
|
184
193
|
WHERE correlation_id = ? AND target_session_id = ? AND kind = 'message'
|
|
185
194
|
ORDER BY created_at DESC LIMIT 1
|
|
186
|
-
`)
|
|
195
|
+
`)
|
|
196
|
+
.get(args.correlationId, senderSessionId);
|
|
187
197
|
if (!prior)
|
|
188
198
|
return toolError('NOT_FOUND', 'No correlated message to this session was found.');
|
|
189
199
|
if (!checkSession(prior.sender_session_id, true))
|
|
@@ -214,19 +224,23 @@ export function createTriggers(store, options) {
|
|
|
214
224
|
*/
|
|
215
225
|
function listDeliveries(sessionId, correlationId) {
|
|
216
226
|
if (correlationId) {
|
|
217
|
-
return db
|
|
227
|
+
return db
|
|
228
|
+
.prepare(`
|
|
218
229
|
SELECT id, kind, sender_session_id, target_session_id, correlation_id, causation_id, hop, status,
|
|
219
230
|
splice_seq, turn_number, attempts, last_error, expires_at, created_at, updated_at
|
|
220
231
|
FROM deliveries WHERE correlation_id = ? ORDER BY created_at
|
|
221
|
-
`)
|
|
232
|
+
`)
|
|
233
|
+
.all(correlationId);
|
|
222
234
|
}
|
|
223
|
-
return db
|
|
235
|
+
return db
|
|
236
|
+
.prepare(`
|
|
224
237
|
SELECT id, kind, sender_session_id, target_session_id, correlation_id, causation_id, hop, status,
|
|
225
238
|
splice_seq, turn_number, attempts, last_error, expires_at, created_at, updated_at
|
|
226
239
|
FROM deliveries
|
|
227
240
|
WHERE target_session_id = ? OR sender_session_id = ?
|
|
228
241
|
ORDER BY created_at
|
|
229
|
-
`)
|
|
242
|
+
`)
|
|
243
|
+
.all(sessionId ?? '', sessionId ?? '');
|
|
230
244
|
}
|
|
231
245
|
/**
|
|
232
246
|
* @param {{ sessionId: string, kind: 'one-shot' | 'cron', cron?: string, runAt?: string, timezone?: string, note?: string }} input
|
|
@@ -271,10 +285,12 @@ export function createTriggers(store, options) {
|
|
|
271
285
|
return { ok: true, schedule: publicSchedule(id) };
|
|
272
286
|
}
|
|
273
287
|
function listSchedules() {
|
|
274
|
-
return db
|
|
288
|
+
return db
|
|
289
|
+
.prepare(`
|
|
275
290
|
SELECT id, session_id, kind, cron_expr, timezone, run_at, next_due, enabled, deleted, note, created_at, updated_at
|
|
276
291
|
FROM schedules WHERE deleted = 0 ORDER BY created_at
|
|
277
|
-
`)
|
|
292
|
+
`)
|
|
293
|
+
.all();
|
|
278
294
|
}
|
|
279
295
|
/**
|
|
280
296
|
* @param {string} id
|
|
@@ -325,9 +341,11 @@ export function createTriggers(store, options) {
|
|
|
325
341
|
return { ok: true };
|
|
326
342
|
}
|
|
327
343
|
function listWebhooks() {
|
|
328
|
-
return db
|
|
344
|
+
return db
|
|
345
|
+
.prepare(`
|
|
329
346
|
SELECT id, target_session_id, enabled, created_at, revoked_at FROM webhook_hooks ORDER BY created_at
|
|
330
|
-
`)
|
|
347
|
+
`)
|
|
348
|
+
.all();
|
|
331
349
|
}
|
|
332
350
|
/**
|
|
333
351
|
* @param {string} hookId
|
|
@@ -346,12 +364,16 @@ export function createTriggers(store, options) {
|
|
|
346
364
|
const verdict = verifyWebhook(hook.secret, raw, headers, now().getTime());
|
|
347
365
|
if (verdict.ok === false)
|
|
348
366
|
return { http: 401, body: verdict };
|
|
349
|
-
const recent = db
|
|
367
|
+
const recent = db
|
|
368
|
+
.prepare(`
|
|
350
369
|
SELECT COUNT(*) AS n FROM webhook_receipts WHERE hook_id = ? AND received_at > ?
|
|
351
|
-
`)
|
|
370
|
+
`)
|
|
371
|
+
.get(hookId, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
|
|
352
372
|
if (recent.n >= RATE_LIMIT)
|
|
353
373
|
return { http: 429, body: toolError('RATE_LIMIT', 'The webhook is firing too often.') };
|
|
354
|
-
const existing = db
|
|
374
|
+
const existing = db
|
|
375
|
+
.prepare('SELECT delivery_id FROM webhook_receipts WHERE hook_id = ? AND event_id = ?')
|
|
376
|
+
.get(hookId, headers.eventId);
|
|
355
377
|
if (existing)
|
|
356
378
|
return { http: 202, body: { ok: true, status: 'accepted', duplicate: true, deliveryId: existing.delivery_id } };
|
|
357
379
|
const body = raw.toString('utf8').slice(0, MAX_BODY);
|
|
@@ -375,9 +397,11 @@ export function createTriggers(store, options) {
|
|
|
375
397
|
return { http: 202, body: { ok: true, status: 'accepted', deliveryId: queued.deliveryId } };
|
|
376
398
|
}
|
|
377
399
|
async function tick() {
|
|
378
|
-
const due = db
|
|
400
|
+
const due = db
|
|
401
|
+
.prepare(`
|
|
379
402
|
SELECT * FROM schedules WHERE deleted = 0 AND enabled = 1 AND next_due IS NOT NULL AND next_due <= ? ORDER BY next_due
|
|
380
|
-
`)
|
|
403
|
+
`)
|
|
404
|
+
.all(iso());
|
|
381
405
|
for (const row of due) {
|
|
382
406
|
try {
|
|
383
407
|
await fireSchedule(row);
|
|
@@ -390,9 +414,11 @@ export function createTriggers(store, options) {
|
|
|
390
414
|
await reconcile();
|
|
391
415
|
}
|
|
392
416
|
async function reconcile() {
|
|
393
|
-
const rows = db
|
|
417
|
+
const rows = db
|
|
418
|
+
.prepare(`
|
|
394
419
|
SELECT * FROM deliveries WHERE status IN ('intent','flushing','ambiguous') AND attempts < ? ORDER BY created_at
|
|
395
|
-
`)
|
|
420
|
+
`)
|
|
421
|
+
.all(MAX_ATTEMPTS);
|
|
396
422
|
for (const row of rows) {
|
|
397
423
|
if (inflight.has(row.id))
|
|
398
424
|
continue;
|
|
@@ -474,9 +500,11 @@ export function createTriggers(store, options) {
|
|
|
474
500
|
if (obs.sessionId === sessionId && (obs.claimedTurn === turn || obs.startedTurn === turn))
|
|
475
501
|
notePending(id, { endKind: reasonKind });
|
|
476
502
|
}
|
|
477
|
-
const rows = db
|
|
503
|
+
const rows = db
|
|
504
|
+
.prepare(`
|
|
478
505
|
SELECT id, status FROM deliveries WHERE target_session_id = ? AND turn_number = ? AND status IN ('claimed','started')
|
|
479
|
-
`)
|
|
506
|
+
`)
|
|
507
|
+
.all(sessionId, turn);
|
|
480
508
|
for (const row of rows) {
|
|
481
509
|
if (row.status === 'started' && reasonKind === 'completed')
|
|
482
510
|
mark(row.id, 'completed', '');
|
|
@@ -491,10 +519,12 @@ export function createTriggers(store, options) {
|
|
|
491
519
|
*/
|
|
492
520
|
async function enqueueNew(input) {
|
|
493
521
|
const hash = sha(String(input.body));
|
|
494
|
-
const existing = db
|
|
522
|
+
const existing = db
|
|
523
|
+
.prepare(`
|
|
495
524
|
SELECT * FROM deliveries
|
|
496
525
|
WHERE kind = ? AND sender_session_id = ? AND target_session_id = ? AND idempotency_key = ?
|
|
497
|
-
`)
|
|
526
|
+
`)
|
|
527
|
+
.get(input.kind, input.sender, input.target, input.idempotencyKey);
|
|
498
528
|
if (existing) {
|
|
499
529
|
if (existing.body_hash !== hash)
|
|
500
530
|
return toolError('IDEMPOTENCY_KEY_REUSE', 'The same idempotency key was reused for different content.');
|
|
@@ -566,11 +596,13 @@ export function createTriggers(store, options) {
|
|
|
566
596
|
db.prepare('UPDATE schedules SET enabled = 0, updated_at = ? WHERE id = ?').run(iso(), row.id);
|
|
567
597
|
return;
|
|
568
598
|
}
|
|
569
|
-
const pending = db
|
|
599
|
+
const pending = db
|
|
600
|
+
.prepare(`
|
|
570
601
|
SELECT 1 AS ok FROM deliveries
|
|
571
602
|
WHERE target_session_id = ? AND kind = 'timer' AND status IN ('intent','flushing','accepted','claimed','started')
|
|
572
603
|
LIMIT 1
|
|
573
|
-
`)
|
|
604
|
+
`)
|
|
605
|
+
.get(row.session_id);
|
|
574
606
|
const slot = row.next_due;
|
|
575
607
|
const occurrence = `${row.id}:${slot}`;
|
|
576
608
|
let nextDue = null;
|
|
@@ -620,14 +652,18 @@ export function createTriggers(store, options) {
|
|
|
620
652
|
try {
|
|
621
653
|
db.exec('ROLLBACK');
|
|
622
654
|
}
|
|
623
|
-
catch {
|
|
655
|
+
catch {
|
|
656
|
+
/* closed by the failed statement */
|
|
657
|
+
}
|
|
624
658
|
throw error;
|
|
625
659
|
}
|
|
626
660
|
}
|
|
627
661
|
async function expirePending() {
|
|
628
|
-
const rows = db
|
|
662
|
+
const rows = db
|
|
663
|
+
.prepare(`
|
|
629
664
|
SELECT * FROM deliveries WHERE status = 'accepted' AND expires_at IS NOT NULL AND expires_at <= ?
|
|
630
|
-
`)
|
|
665
|
+
`)
|
|
666
|
+
.all(iso());
|
|
631
667
|
for (const row of rows) {
|
|
632
668
|
if (options.removePending) {
|
|
633
669
|
const removed = await options.removePending(row.target_session_id, row.id);
|
|
@@ -647,21 +683,25 @@ export function createTriggers(store, options) {
|
|
|
647
683
|
* @param {string} sessionId
|
|
648
684
|
*/
|
|
649
685
|
function activeInbound(sessionId) {
|
|
650
|
-
return db
|
|
686
|
+
return (db
|
|
687
|
+
.prepare(`
|
|
651
688
|
SELECT * FROM deliveries
|
|
652
689
|
WHERE target_session_id = ? AND kind = 'message' AND status IN ('claimed','started')
|
|
653
690
|
ORDER BY updated_at DESC LIMIT 1
|
|
654
|
-
`)
|
|
691
|
+
`)
|
|
692
|
+
.get(sessionId) ?? null);
|
|
655
693
|
}
|
|
656
694
|
/**
|
|
657
695
|
* @param {string} sessionId
|
|
658
696
|
* @param {string} correlationId
|
|
659
697
|
*/
|
|
660
698
|
function ownedCorrelation(sessionId, correlationId) {
|
|
661
|
-
const row = db
|
|
699
|
+
const row = db
|
|
700
|
+
.prepare(`
|
|
662
701
|
SELECT 1 AS ok FROM deliveries
|
|
663
702
|
WHERE correlation_id = ? AND (sender_session_id = ? OR target_session_id = ?)
|
|
664
|
-
`)
|
|
703
|
+
`)
|
|
704
|
+
.get(correlationId, sessionId, sessionId);
|
|
665
705
|
return row ? correlationId : null;
|
|
666
706
|
}
|
|
667
707
|
/**
|
|
@@ -669,10 +709,12 @@ export function createTriggers(store, options) {
|
|
|
669
709
|
* @param {string} target
|
|
670
710
|
*/
|
|
671
711
|
function rateLimited(sender, target) {
|
|
672
|
-
const row = db
|
|
712
|
+
const row = db
|
|
713
|
+
.prepare(`
|
|
673
714
|
SELECT COUNT(*) AS n FROM deliveries
|
|
674
715
|
WHERE sender_session_id = ? AND target_session_id = ? AND created_at > ? AND status != 'rejected'
|
|
675
|
-
`)
|
|
716
|
+
`)
|
|
717
|
+
.get(sender, target, new Date(now().getTime() - RATE_WINDOW_MS).toISOString());
|
|
676
718
|
return row.n >= RATE_LIMIT;
|
|
677
719
|
}
|
|
678
720
|
/**
|
|
@@ -771,7 +813,7 @@ export function createTriggers(store, options) {
|
|
|
771
813
|
*/
|
|
772
814
|
function publicSchedule(id) {
|
|
773
815
|
const row = schedule(id);
|
|
774
|
-
return row && {
|
|
816
|
+
return (row && {
|
|
775
817
|
id: row.id,
|
|
776
818
|
sessionId: row.session_id,
|
|
777
819
|
kind: row.kind,
|
|
@@ -781,7 +823,7 @@ export function createTriggers(store, options) {
|
|
|
781
823
|
nextDue: row.next_due,
|
|
782
824
|
enabled: row.enabled === 1,
|
|
783
825
|
note: row.note,
|
|
784
|
-
};
|
|
826
|
+
});
|
|
785
827
|
}
|
|
786
828
|
function iso() {
|
|
787
829
|
return now().toISOString();
|
|
@@ -835,7 +877,9 @@ export function verifyWebhook(secret, raw, headers, nowMs) {
|
|
|
835
877
|
const ts = Number(headers.timestamp) * 1000;
|
|
836
878
|
if (Math.abs(nowMs - ts) > 5 * 60 * 1000)
|
|
837
879
|
return toolError('TTL_EXPIRED', 'The timestamp is outside the 5 minute window.');
|
|
838
|
-
const expected = createHmac('sha256', secret)
|
|
880
|
+
const expected = createHmac('sha256', secret)
|
|
881
|
+
.update(`${headers.timestamp}.${raw.toString('utf8')}`)
|
|
882
|
+
.digest('hex');
|
|
839
883
|
const given = headers.signature ?? '';
|
|
840
884
|
const left = Buffer.from(expected);
|
|
841
885
|
const right = Buffer.from(given);
|
package/dist/work-admit.js
CHANGED
|
@@ -62,9 +62,11 @@ export function decideAdmission(input) {
|
|
|
62
62
|
* @returns {'steps' | 'wall' | 'tokens' | null}
|
|
63
63
|
*/
|
|
64
64
|
export function budgetTrip(input) {
|
|
65
|
-
|
|
65
|
+
const maxSteps = input.maxSteps;
|
|
66
|
+
const maxTokens = input.maxTokens;
|
|
67
|
+
if (maxSteps != null && Number.isFinite(maxSteps) && Number(input.steps) >= maxSteps)
|
|
66
68
|
return 'steps';
|
|
67
|
-
if (Number.isFinite(
|
|
69
|
+
if (maxTokens != null && Number.isFinite(maxTokens) && Number(input.tokens) >= maxTokens)
|
|
68
70
|
return 'tokens';
|
|
69
71
|
if (input.elapsedMs >= input.wallMs)
|
|
70
72
|
return 'wall';
|
|
@@ -116,12 +118,16 @@ export function childCreateOptions(sessionId, cwd, model, maxTokens) {
|
|
|
116
118
|
const options = { sessionId };
|
|
117
119
|
if (typeof cwd === 'string' && cwd !== '')
|
|
118
120
|
options.meta = { cwd };
|
|
119
|
-
if (model &&
|
|
121
|
+
if (model &&
|
|
122
|
+
typeof model.provider === 'string' &&
|
|
123
|
+
model.provider !== '' &&
|
|
124
|
+
typeof model.model === 'string' &&
|
|
125
|
+
model.model !== '') {
|
|
120
126
|
options.agentOptions = { provider: model.provider, model: model.model };
|
|
121
127
|
if (typeof model.reasoningEffort === 'string' && model.reasoningEffort !== '') {
|
|
122
128
|
options.agentOptions.reasoningEffort = model.reasoningEffort;
|
|
123
129
|
}
|
|
124
|
-
if (Number.isSafeInteger(maxTokens) && maxTokens > 0)
|
|
130
|
+
if (typeof maxTokens === 'number' && Number.isSafeInteger(maxTokens) && maxTokens > 0)
|
|
125
131
|
options.agentOptions.maxTokens = maxTokens;
|
|
126
132
|
}
|
|
127
133
|
return options;
|
package/dist/work-child.js
CHANGED
|
@@ -14,7 +14,9 @@ function presetsOf(ctx) {
|
|
|
14
14
|
if (typeof ctx.get === 'function')
|
|
15
15
|
return ctx.get('agentPresets') ?? null;
|
|
16
16
|
}
|
|
17
|
-
catch {
|
|
17
|
+
catch {
|
|
18
|
+
/* preset service is optional until a worker is created */
|
|
19
|
+
}
|
|
18
20
|
try {
|
|
19
21
|
return ctx.agentPresets ?? null;
|
|
20
22
|
}
|
|
@@ -31,7 +33,8 @@ export function ensureWorkerFilePreset(ctx) {
|
|
|
31
33
|
const presets = presetsOf(ctx);
|
|
32
34
|
if (!presets?.register || !presets?.mount)
|
|
33
35
|
return Promise.resolve(null);
|
|
34
|
-
return presets
|
|
36
|
+
return presets
|
|
37
|
+
.register({
|
|
35
38
|
id: WORKER_FILE_PRESET,
|
|
36
39
|
plugins: [
|
|
37
40
|
{
|
|
@@ -40,7 +43,9 @@ export function ensureWorkerFilePreset(ctx) {
|
|
|
40
43
|
config: { applyPatch: false, readImage: false },
|
|
41
44
|
},
|
|
42
45
|
],
|
|
43
|
-
})
|
|
46
|
+
})
|
|
47
|
+
.then(() => WORKER_FILE_PRESET)
|
|
48
|
+
.catch((error) => {
|
|
44
49
|
const message = error instanceof Error ? error.message : String(error);
|
|
45
50
|
if (message.includes('Duplicate'))
|
|
46
51
|
return WORKER_FILE_PRESET;
|
|
@@ -59,9 +64,7 @@ export function workerFileSetup(ctx, presetId) {
|
|
|
59
64
|
const presets = presetsOf(ctx);
|
|
60
65
|
if (!presets?.mount)
|
|
61
66
|
return;
|
|
62
|
-
const recorded = agent?.session && typeof presets.presetForSession === 'function'
|
|
63
|
-
? presets.presetForSession(agent.session)
|
|
64
|
-
: null;
|
|
67
|
+
const recorded = agent?.session && typeof presets.presetForSession === 'function' ? presets.presetForSession(agent.session) : null;
|
|
65
68
|
const id = presetId || recorded || presets.defaultId;
|
|
66
69
|
if (!id)
|
|
67
70
|
return;
|
package/dist/work-http.js
CHANGED
|
@@ -202,7 +202,9 @@ export function openPageLive(req, res, source) {
|
|
|
202
202
|
}
|
|
203
203
|
};
|
|
204
204
|
void pump();
|
|
205
|
-
timer = setInterval(() => {
|
|
205
|
+
timer = setInterval(() => {
|
|
206
|
+
void pump();
|
|
207
|
+
}, intervalMs);
|
|
206
208
|
timer.unref?.();
|
|
207
209
|
req.on('close', stop);
|
|
208
210
|
res.on('error', stop);
|
|
@@ -216,7 +218,7 @@ export function openPageLive(req, res, source) {
|
|
|
216
218
|
* @param {string} path
|
|
217
219
|
* @param {URL} url
|
|
218
220
|
* @param {Record<string, unknown>} body
|
|
219
|
-
* @param {ReturnType<import('./work-worker.js').createWorkRuntime> | null} work
|
|
221
|
+
* @param {ReturnType<typeof import('./work-worker.js').createWorkRuntime> | null} work
|
|
220
222
|
*/
|
|
221
223
|
export async function handleWorkApi(method, path, url, body, work) {
|
|
222
224
|
if (!path.startsWith('/session-foundations/api/work'))
|