@dsh-ray/assistant-delivery 0.2.4 → 0.3.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.
Files changed (79) hide show
  1. package/README.md +15 -2
  2. package/cordis.patch.yml +0 -2
  3. package/lib/agent-runtime.d.ts +15 -0
  4. package/lib/agent-runtime.d.ts.map +1 -1
  5. package/lib/agent-runtime.js +446 -51
  6. package/lib/agent-runtime.js.map +1 -1
  7. package/lib/attention-audit-store.d.ts +2 -1
  8. package/lib/attention-audit-store.d.ts.map +1 -1
  9. package/lib/attention-audit-store.js +3 -0
  10. package/lib/attention-audit-store.js.map +1 -1
  11. package/lib/coordinator.d.ts +21 -1
  12. package/lib/coordinator.d.ts.map +1 -1
  13. package/lib/coordinator.js +255 -68
  14. package/lib/coordinator.js.map +1 -1
  15. package/lib/feedback-command.d.ts +1 -0
  16. package/lib/feedback-command.d.ts.map +1 -1
  17. package/lib/feedback-command.js +1 -1
  18. package/lib/feedback-command.js.map +1 -1
  19. package/lib/index.d.ts +2 -1
  20. package/lib/index.d.ts.map +1 -1
  21. package/lib/index.js +1 -0
  22. package/lib/index.js.map +1 -1
  23. package/lib/interrupted-notices.d.ts +20 -5
  24. package/lib/interrupted-notices.d.ts.map +1 -1
  25. package/lib/interrupted-notices.js +238 -24
  26. package/lib/interrupted-notices.js.map +1 -1
  27. package/lib/learning-command.d.ts +2 -0
  28. package/lib/learning-command.d.ts.map +1 -1
  29. package/lib/learning-command.js +2 -0
  30. package/lib/learning-command.js.map +1 -1
  31. package/lib/native-web-owner.d.ts +12 -0
  32. package/lib/native-web-owner.d.ts.map +1 -1
  33. package/lib/native-web-owner.js +653 -80
  34. package/lib/native-web-owner.js.map +1 -1
  35. package/lib/operator-snapshot.d.ts +1 -1
  36. package/lib/operator-snapshot.d.ts.map +1 -1
  37. package/lib/operator-snapshot.js +6 -5
  38. package/lib/operator-snapshot.js.map +1 -1
  39. package/lib/ray-worker-runtime.d.ts +192 -0
  40. package/lib/ray-worker-runtime.d.ts.map +1 -0
  41. package/lib/ray-worker-runtime.js +1300 -0
  42. package/lib/ray-worker-runtime.js.map +1 -0
  43. package/lib/service.d.ts +286 -3
  44. package/lib/service.d.ts.map +1 -1
  45. package/lib/service.js +1608 -72
  46. package/lib/service.js.map +1 -1
  47. package/lib/session-commands.d.ts +6 -0
  48. package/lib/session-commands.d.ts.map +1 -1
  49. package/lib/session-commands.js +14 -0
  50. package/lib/session-commands.js.map +1 -1
  51. package/lib/session-lease-runtime.d.ts +31 -6
  52. package/lib/session-lease-runtime.d.ts.map +1 -1
  53. package/lib/session-lease-runtime.js +553 -43
  54. package/lib/session-lease-runtime.js.map +1 -1
  55. package/lib/sqlite.d.ts +1 -1
  56. package/lib/sqlite.d.ts.map +1 -1
  57. package/lib/sqlite.js +83 -3
  58. package/lib/sqlite.js.map +1 -1
  59. package/lib/store.d.ts +93 -2
  60. package/lib/store.d.ts.map +1 -1
  61. package/lib/store.js +695 -24
  62. package/lib/store.js.map +1 -1
  63. package/lib/tools.d.ts.map +1 -1
  64. package/lib/tools.js +319 -0
  65. package/lib/tools.js.map +1 -1
  66. package/lib/version-query.d.ts.map +1 -1
  67. package/lib/version-query.js +109 -20
  68. package/lib/version-query.js.map +1 -1
  69. package/lib/version.d.ts +1 -1
  70. package/lib/version.js +1 -1
  71. package/lib/work-item-feedback-store.d.ts +2 -1
  72. package/lib/work-item-feedback-store.d.ts.map +1 -1
  73. package/lib/work-item-feedback-store.js +1 -0
  74. package/lib/work-item-feedback-store.js.map +1 -1
  75. package/lib/work-item-replies-store.d.ts +2 -1
  76. package/lib/work-item-replies-store.d.ts.map +1 -1
  77. package/lib/work-item-replies-store.js +3 -0
  78. package/lib/work-item-replies-store.js.map +1 -1
  79. package/package.json +11 -11
@@ -0,0 +1,1300 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { dirname } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { installModelSelection } from '@deepseek-ai/dsh-agent';
6
+ import { createUserMessage, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
7
+ import { SessionId } from '@deepseek-ai/dsh-session';
8
+ import { externalPrincipalId } from './canonical.js';
9
+ const MAX_SUMMARY_CHARS = 1200;
10
+ function clipText(value, maxChars = MAX_SUMMARY_CHARS) {
11
+ const clean = value.trim();
12
+ if (clean.length <= maxChars)
13
+ return clean;
14
+ return `${clean.slice(0, maxChars - 1)}…`;
15
+ }
16
+ function isSubagentHeader(header) {
17
+ if (header === undefined)
18
+ return false;
19
+ if (header.origin === 'subagent')
20
+ return true;
21
+ const depth = header.delegationDepth;
22
+ if (depth === undefined)
23
+ return false;
24
+ return typeof depth !== 'number' || !Number.isSafeInteger(depth) || depth !== 0;
25
+ }
26
+ function rowToSnapshot(row) {
27
+ return Object.freeze({
28
+ ticketId: row.ticket_id,
29
+ sessionId: row.session_id,
30
+ title: row.title,
31
+ objective: row.objective,
32
+ scopeSummary: row.scope_summary,
33
+ status: row.status,
34
+ lane: row.lane === 'free' ? 'free' : 'owner',
35
+ handbackCount: Number.isFinite(row.handback_count) ? Math.max(0, Math.trunc(row.handback_count)) : 0,
36
+ revision: Number.isFinite(row.revision) ? Math.max(1, Math.trunc(row.revision)) : 1,
37
+ ...(row.source_binding_id === null ? {} : { sourceBindingId: row.source_binding_id }),
38
+ ...(row.source_channel === null ? {} : { sourceChannel: row.source_channel }),
39
+ ...(row.source_account === null ? {} : { sourceAccount: row.source_account }),
40
+ ...(row.source_chat === null ? {} : { sourceChat: row.source_chat }),
41
+ principalId: row.principal_id,
42
+ workspace: row.workspace,
43
+ agentPreset: row.agent_preset,
44
+ provider: row.provider,
45
+ model: row.model,
46
+ ...(row.reasoning_effort === null ? {} : { reasoningEffort: row.reasoning_effort }),
47
+ ...(row.token_budget === null ? {} : { tokenBudget: row.token_budget }),
48
+ usedTokens: row.used_tokens,
49
+ ...(row.result_summary === null ? {} : { resultSummary: row.result_summary }),
50
+ ...(row.handback_reason === null ? {} : { handbackReason: row.handback_reason }),
51
+ ...(row.error_message === null ? {} : { errorMessage: row.error_message }),
52
+ ...(row.narration_text === null ? {} : { narrationText: row.narration_text }),
53
+ narrationSent: row.narration_sent === 1,
54
+ frontNarrated: row.front_narrated === 1,
55
+ createdAt: row.created_at,
56
+ updatedAt: row.updated_at,
57
+ ...(row.completed_at === null ? {} : { completedAt: row.completed_at }),
58
+ });
59
+ }
60
+ function extractUsageTokens(events) {
61
+ let total = 0;
62
+ for (const event of events) {
63
+ if (event.type !== 'assistant/message')
64
+ continue;
65
+ const rawData = event.data;
66
+ if (rawData === null || rawData === undefined || typeof rawData !== 'object')
67
+ continue;
68
+ const data = rawData;
69
+ const usage = data.usage ?? data.message?.usage;
70
+ if (usage === undefined || typeof usage !== 'object' || usage === null)
71
+ continue;
72
+ if (typeof usage.totalTokens === 'number' && Number.isFinite(usage.totalTokens)) {
73
+ total += Math.max(0, Math.floor(usage.totalTokens));
74
+ }
75
+ else {
76
+ const inp = typeof usage.inputTokens === 'number' && Number.isFinite(usage.inputTokens) ? usage.inputTokens : 0;
77
+ const out = typeof usage.outputTokens === 'number' && Number.isFinite(usage.outputTokens) ? usage.outputTokens : 0;
78
+ total += Math.max(0, Math.floor(inp + out));
79
+ }
80
+ }
81
+ return total;
82
+ }
83
+ function extractLastAssistantText(agent) {
84
+ const messages = agent.session.deriveMessages();
85
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
86
+ const msg = messages[i];
87
+ if (msg?.role !== 'assistant')
88
+ continue;
89
+ const text = msg.content
90
+ .filter((block) => block.type === 'text' && typeof block.text === 'string')
91
+ .map(block => block.text)
92
+ .join('')
93
+ .trim();
94
+ if (text !== '')
95
+ return text;
96
+ }
97
+ return '';
98
+ }
99
+ function inspectTurnState(events) {
100
+ let lastUserSeq = -1;
101
+ let lastTurnStartSeq = -1;
102
+ let lastTurnEnd;
103
+ for (const event of events) {
104
+ if (event.type === 'user/message')
105
+ lastUserSeq = Number(event.seq);
106
+ if (event.type === 'turn/start')
107
+ lastTurnStartSeq = Number(event.seq);
108
+ if (event.type === 'turn/end')
109
+ lastTurnEnd = event;
110
+ }
111
+ if (lastTurnEnd === undefined || Number(lastTurnEnd.seq) < lastTurnStartSeq || Number(lastTurnEnd.seq) < lastUserSeq) {
112
+ return { settledCompleted: false };
113
+ }
114
+ const reason = lastTurnEnd.data.reason;
115
+ const turnEndKind = typeof reason?.kind === 'string' ? reason.kind : undefined;
116
+ const errorMessage = typeof reason?.error?.message === 'string' ? reason.error.message : undefined;
117
+ return {
118
+ settledCompleted: turnEndKind === 'completed' || turnEndKind === 'max-tokens',
119
+ ...(turnEndKind === undefined ? {} : { turnEndKind }),
120
+ ...(errorMessage === undefined ? {} : { errorMessage }),
121
+ };
122
+ }
123
+ function buildNaturalNarration(snapshot) {
124
+ if (snapshot.status === 'completed') {
125
+ const summary = snapshot.resultSummary?.trim();
126
+ return summary && summary !== ''
127
+ ? `后台任务「${snapshot.title}」已完成:${clipText(summary, 500)}`
128
+ : `后台任务「${snapshot.title}」(${snapshot.ticketId})已完成。`;
129
+ }
130
+ if (snapshot.status === 'handed_back') {
131
+ const reason = snapshot.handbackReason ?? '超出当前任务边界或需要你的进一步确认';
132
+ const summary = snapshot.resultSummary ? `(进展:${clipText(snapshot.resultSummary, 300)})` : '';
133
+ return `后台任务「${snapshot.title}」已交回前台协调:${reason}${summary}`;
134
+ }
135
+ if (snapshot.status === 'failed') {
136
+ const detail = snapshot.errorMessage ? `(${clipText(snapshot.errorMessage, 240)})` : '';
137
+ return `后台任务「${snapshot.title}」未顺利完成${detail},可以随时告诉我是否重试或调整目标。`;
138
+ }
139
+ return `后台任务「${snapshot.title}」正在进行中。`;
140
+ }
141
+ function toModelSelection(route) {
142
+ return {
143
+ provider: route.provider,
144
+ model: route.model,
145
+ ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: ReasoningEffortId(route.reasoningEffort) }),
146
+ };
147
+ }
148
+ export class RayWorkerTicketRuntime {
149
+ options;
150
+ databasePath;
151
+ db;
152
+ runtimeCtx;
153
+ runtimeDisposers = [];
154
+ parentSessionByChild = new Map();
155
+ activeWorkers = new Map();
156
+ revivingTickets = new Map();
157
+ recoveringPromise;
158
+ disposing = false;
159
+ closed = false;
160
+ constructor(options) {
161
+ this.options = options;
162
+ this.databasePath = `${options.rayHome.replace(/\/+$/u, '')}/state/tickets.sqlite`;
163
+ this.openDb();
164
+ try {
165
+ this.options.getRaySelf()?.registerDatabase?.('assistant-delivery/worker-tickets', this.databasePath);
166
+ }
167
+ catch {
168
+ // Registration metadata is best-effort if Ray Home has not opened manifest yet.
169
+ }
170
+ }
171
+ openDb() {
172
+ mkdirSync(dirname(this.databasePath), { recursive: true, mode: 0o700 });
173
+ const db = new DatabaseSync(this.databasePath);
174
+ db.exec('PRAGMA busy_timeout = 5000;');
175
+ db.exec('PRAGMA journal_mode = WAL;');
176
+ db.exec('PRAGMA synchronous = NORMAL;');
177
+ db.exec(`
178
+ CREATE TABLE IF NOT EXISTS ray_tickets (
179
+ ticket_id TEXT PRIMARY KEY,
180
+ session_id TEXT NOT NULL UNIQUE,
181
+ title TEXT NOT NULL,
182
+ objective TEXT NOT NULL,
183
+ scope_summary TEXT NOT NULL,
184
+ status TEXT NOT NULL,
185
+ lane TEXT NOT NULL DEFAULT 'owner',
186
+ handback_count INTEGER NOT NULL DEFAULT 0,
187
+ revision INTEGER NOT NULL DEFAULT 1,
188
+ source_binding_id TEXT,
189
+ source_channel TEXT,
190
+ source_account TEXT,
191
+ source_chat TEXT,
192
+ principal_id TEXT NOT NULL,
193
+ workspace TEXT NOT NULL,
194
+ agent_preset TEXT NOT NULL,
195
+ provider TEXT NOT NULL,
196
+ model TEXT NOT NULL,
197
+ reasoning_effort TEXT,
198
+ token_budget INTEGER,
199
+ used_tokens INTEGER NOT NULL DEFAULT 0,
200
+ result_summary TEXT,
201
+ handback_reason TEXT,
202
+ error_message TEXT,
203
+ narration_text TEXT,
204
+ narration_sent INTEGER NOT NULL DEFAULT 0,
205
+ front_narrated INTEGER NOT NULL DEFAULT 0,
206
+ created_at INTEGER NOT NULL,
207
+ updated_at INTEGER NOT NULL,
208
+ completed_at INTEGER
209
+ );
210
+ CREATE INDEX IF NOT EXISTS idx_ray_tickets_status ON ray_tickets(status, updated_at);
211
+ CREATE INDEX IF NOT EXISTS idx_ray_tickets_updated ON ray_tickets(updated_at DESC, ticket_id DESC);
212
+ CREATE TABLE IF NOT EXISTS ray_ticket_events (
213
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
214
+ ticket_id TEXT NOT NULL,
215
+ kind TEXT NOT NULL,
216
+ payload_json TEXT NOT NULL,
217
+ created_at INTEGER NOT NULL
218
+ );
219
+ CREATE INDEX IF NOT EXISTS idx_ray_ticket_events_ticket ON ray_ticket_events(ticket_id, id);
220
+ CREATE TABLE IF NOT EXISTS ray_ticket_session_usage (
221
+ ticket_id TEXT NOT NULL,
222
+ session_id TEXT NOT NULL,
223
+ used_tokens INTEGER NOT NULL DEFAULT 0,
224
+ updated_at INTEGER NOT NULL,
225
+ PRIMARY KEY (ticket_id, session_id)
226
+ );
227
+ `);
228
+ const cols = db.prepare('PRAGMA table_info(ray_tickets)').all();
229
+ if (!cols.some(c => c.name === 'lane')) {
230
+ db.exec("ALTER TABLE ray_tickets ADD COLUMN lane TEXT NOT NULL DEFAULT 'owner';");
231
+ }
232
+ if (!cols.some(c => c.name === 'handback_count')) {
233
+ db.exec('ALTER TABLE ray_tickets ADD COLUMN handback_count INTEGER NOT NULL DEFAULT 0;');
234
+ }
235
+ if (!cols.some(c => c.name === 'revision')) {
236
+ db.exec('ALTER TABLE ray_tickets ADD COLUMN revision INTEGER NOT NULL DEFAULT 1;');
237
+ }
238
+ this.db = db;
239
+ this.hydratePersistedSessionRoles();
240
+ }
241
+ hydratePersistedSessionRoles(targetRaySelf) {
242
+ if (this.closed || this.db === undefined)
243
+ return 0;
244
+ const raySelf = targetRaySelf ?? this.options.getRaySelf();
245
+ if (typeof raySelf?.setSessionRole !== 'function')
246
+ return 0;
247
+ const rows = this.db.prepare('SELECT session_id, lane FROM ray_tickets').all();
248
+ let hydrated = 0;
249
+ for (const row of rows) {
250
+ const clean = typeof row.session_id === 'string' ? row.session_id.trim() : '';
251
+ if (clean === '')
252
+ continue;
253
+ raySelf.setSessionRole(clean, row.lane === 'free' ? 'worker-free' : 'worker');
254
+ hydrated += 1;
255
+ }
256
+ return hydrated;
257
+ }
258
+ checkpoint() {
259
+ if (this.closed || this.db === undefined)
260
+ return;
261
+ try {
262
+ this.db.exec('PRAGMA wal_checkpoint(TRUNCATE);');
263
+ }
264
+ catch { }
265
+ }
266
+ closeForReload() {
267
+ if (this.closed)
268
+ return;
269
+ const workers = [...this.activeWorkers.values()];
270
+ this.activeWorkers.clear();
271
+ for (const worker of workers) {
272
+ worker.cleanup();
273
+ try {
274
+ void worker.handle.dispose();
275
+ }
276
+ catch { }
277
+ }
278
+ try {
279
+ this.db?.close();
280
+ }
281
+ catch { }
282
+ this.db = undefined;
283
+ }
284
+ reopen() {
285
+ if (this.closed)
286
+ return;
287
+ this.closeForReload();
288
+ this.openDb();
289
+ if (this.runtimeCtx !== undefined) {
290
+ void this.recoverUnfinishedTickets().catch(() => { });
291
+ }
292
+ }
293
+ clearRuntimeListeners() {
294
+ while (this.runtimeDisposers.length > 0) {
295
+ const fn = this.runtimeDisposers.pop();
296
+ try {
297
+ fn();
298
+ }
299
+ catch { }
300
+ }
301
+ }
302
+ recordParentSession(childId, parentId) {
303
+ if (childId === '' || parentId === '' || childId === parentId)
304
+ return;
305
+ if (this.parentSessionByChild.size >= 10_000 && !this.parentSessionByChild.has(childId)) {
306
+ const oldest = this.parentSessionByChild.keys().next().value;
307
+ if (oldest !== undefined)
308
+ this.parentSessionByChild.delete(oldest);
309
+ }
310
+ this.parentSessionByChild.set(childId, parentId);
311
+ }
312
+ resolveTicketByDescendantSession(sessionId, directParent) {
313
+ if (this.closed || this.db === undefined)
314
+ return undefined;
315
+ const clean = sessionId.trim();
316
+ if (clean === '')
317
+ return undefined;
318
+ const direct = this.getTicketRowBySession(clean);
319
+ if (direct !== undefined)
320
+ return direct;
321
+ const visited = new Set([clean]);
322
+ let current = directParent ?? this.parentSessionByChild.get(clean);
323
+ for (let depth = 0; depth < 16 && current !== undefined && current !== ''; depth += 1) {
324
+ if (visited.has(current))
325
+ break;
326
+ visited.add(current);
327
+ const ticket = this.getTicketRowBySession(current);
328
+ if (ticket !== undefined)
329
+ return ticket;
330
+ current = this.parentSessionByChild.get(current);
331
+ }
332
+ return undefined;
333
+ }
334
+ attachRuntime(ctx) {
335
+ if (this.closed || this.disposing)
336
+ return;
337
+ this.hydratePersistedSessionRoles();
338
+ if (this.runtimeCtx === ctx)
339
+ return;
340
+ this.clearRuntimeListeners();
341
+ this.runtimeCtx = ctx;
342
+ const on = ctx.on;
343
+ if (typeof on !== 'function')
344
+ return;
345
+ const currentInitiatorSessionId = () => {
346
+ try {
347
+ const sid = ctx.get('agents')?.currentInitiator?.()?.session?.id;
348
+ return typeof sid === 'string' && sid.trim() !== '' ? sid.trim() : undefined;
349
+ }
350
+ catch {
351
+ return undefined;
352
+ }
353
+ };
354
+ const unsubSessionCreated = on('session/created', rawSession => {
355
+ if (this.closed || this.disposing)
356
+ return;
357
+ const session = rawSession;
358
+ const childId = typeof session?.id === 'string' ? session.id.trim() : '';
359
+ const parentId = typeof session?.header?.parentSession === 'string' && session.header.parentSession.trim() !== ''
360
+ ? session.header.parentSession.trim()
361
+ : (currentInitiatorSessionId() ?? '');
362
+ this.recordParentSession(childId, parentId);
363
+ });
364
+ if (typeof unsubSessionCreated === 'function')
365
+ this.runtimeDisposers.push(unsubSessionCreated);
366
+ const unsubAgentCreated = on('agent/created', rawPayload => {
367
+ if (this.closed || this.disposing)
368
+ return;
369
+ const payload = rawPayload;
370
+ const agent = payload?.agent;
371
+ const childId = typeof agent?.session?.id === 'string' ? agent.session.id.trim() : '';
372
+ const parentId = typeof agent?.session?.header?.parentSession === 'string' && agent.session.header.parentSession.trim() !== ''
373
+ ? agent.session.header.parentSession.trim()
374
+ : (currentInitiatorSessionId() ?? '');
375
+ this.recordParentSession(childId, parentId);
376
+ });
377
+ if (typeof unsubAgentCreated === 'function')
378
+ this.runtimeDisposers.push(unsubAgentCreated);
379
+ const unsubSubagentStart = on('subagent/start', rawInfo => {
380
+ if (this.closed || this.disposing)
381
+ return;
382
+ const info = rawInfo;
383
+ const childId = typeof info?.id === 'string' ? info.id.trim() : '';
384
+ const parentId = typeof info?.parentSessionId === 'string' ? info.parentSessionId.trim() : '';
385
+ this.recordParentSession(childId, parentId);
386
+ });
387
+ if (typeof unsubSubagentStart === 'function')
388
+ this.runtimeDisposers.push(unsubSubagentStart);
389
+ const unsubSessionEvent = on('session/event', (rawSession, rawEvent) => {
390
+ if (this.closed || this.disposing || this.db === undefined)
391
+ return;
392
+ const ev = rawEvent;
393
+ if (ev?.type !== 'assistant/message' && ev?.type !== 'turn/end')
394
+ return;
395
+ const session = rawSession;
396
+ if (typeof session?.id !== 'string' || typeof session.snapshotEvents !== 'function')
397
+ return;
398
+ const isSubagent = isSubagentHeader(session.header);
399
+ if (!isSubagent)
400
+ return;
401
+ const directParent = typeof session.header?.parentSession === 'string' && session.header.parentSession.trim() !== ''
402
+ ? session.header.parentSession.trim()
403
+ : undefined;
404
+ const ticketRow = this.resolveTicketByDescendantSession(session.id, directParent);
405
+ if (ticketRow === undefined)
406
+ return;
407
+ this.syncSessionTokenUsage(ticketRow.ticket_id, session.id, session.snapshotEvents());
408
+ });
409
+ if (typeof unsubSessionEvent === 'function')
410
+ this.runtimeDisposers.push(unsubSessionEvent);
411
+ }
412
+ detachRuntime(ctx) {
413
+ if (this.runtimeCtx === ctx) {
414
+ this.clearRuntimeListeners();
415
+ this.runtimeCtx = undefined;
416
+ }
417
+ }
418
+ assertOpen() {
419
+ if (this.closed || this.db === undefined) {
420
+ throw new Error('assistant-delivery: worker ticket runtime is closed');
421
+ }
422
+ return this.db;
423
+ }
424
+ withWriteTransaction(operation) {
425
+ const db = this.assertOpen();
426
+ db.exec('BEGIN IMMEDIATE;');
427
+ try {
428
+ const result = operation(db);
429
+ db.exec('COMMIT;');
430
+ return result;
431
+ }
432
+ catch (error) {
433
+ try {
434
+ db.exec('ROLLBACK;');
435
+ }
436
+ catch { }
437
+ throw error;
438
+ }
439
+ }
440
+ getTicketRow(ticketId) {
441
+ const db = this.assertOpen();
442
+ return db.prepare('SELECT * FROM ray_tickets WHERE ticket_id = ?').get(ticketId);
443
+ }
444
+ getTicketRowBySession(sessionId) {
445
+ const db = this.assertOpen();
446
+ return db.prepare('SELECT * FROM ray_tickets WHERE session_id = ?').get(sessionId);
447
+ }
448
+ appendEvent(ticketId, kind, payload, now = Date.now()) {
449
+ const db = this.assertOpen();
450
+ db.prepare('INSERT INTO ray_ticket_events (ticket_id, kind, payload_json, created_at) VALUES (?, ?, ?, ?)')
451
+ .run(ticketId, kind, JSON.stringify(payload), now);
452
+ }
453
+ ownsWorkerSession(sessionId) {
454
+ if (this.closed || this.db === undefined)
455
+ return false;
456
+ const clean = sessionId.trim();
457
+ if (clean === '')
458
+ return false;
459
+ return this.getTicketRowBySession(clean) !== undefined;
460
+ }
461
+ ownsOwnerWorkerSession(sessionId) {
462
+ if (this.closed || this.db === undefined)
463
+ return false;
464
+ const clean = sessionId.trim();
465
+ if (clean === '')
466
+ return false;
467
+ const row = this.getTicketRowBySession(clean);
468
+ return row !== undefined && row.lane !== 'free';
469
+ }
470
+ getTicketBySession(sessionId) {
471
+ if (this.closed || this.db === undefined)
472
+ return undefined;
473
+ const clean = sessionId.trim();
474
+ if (clean === '')
475
+ return undefined;
476
+ const row = this.getTicketRowBySession(clean);
477
+ return row === undefined ? undefined : rowToSnapshot(row);
478
+ }
479
+ hasTickets() {
480
+ if (this.closed || this.db === undefined)
481
+ return false;
482
+ const row = this.db.prepare('SELECT 1 AS found FROM ray_tickets LIMIT 1').get();
483
+ return row?.found === 1;
484
+ }
485
+ listTickets(input = {}) {
486
+ if (this.closed || this.db === undefined)
487
+ return [];
488
+ const limit = Math.max(1, Math.min(100, Math.floor(input.limit ?? 20)));
489
+ const rows = input.status === undefined
490
+ ? this.db.prepare('SELECT * FROM ray_tickets ORDER BY updated_at DESC LIMIT ?').all(limit)
491
+ : this.db.prepare('SELECT * FROM ray_tickets WHERE status = ? ORDER BY updated_at DESC LIMIT ?').all(input.status, limit);
492
+ return rows.map(rowToSnapshot);
493
+ }
494
+ *iterateTickets(batchSize = 200) {
495
+ if (this.closed || this.db === undefined)
496
+ return;
497
+ const limit = Math.max(1, Math.min(500, Math.floor(batchSize)));
498
+ let cursorUpdatedAt;
499
+ let cursorTicketId;
500
+ while (!this.closed && this.db !== undefined) {
501
+ const rows = cursorUpdatedAt === undefined
502
+ ? this.db.prepare('SELECT * FROM ray_tickets ORDER BY updated_at DESC, ticket_id DESC LIMIT ?')
503
+ .all(limit)
504
+ : this.db.prepare(`
505
+ SELECT * FROM ray_tickets
506
+ WHERE updated_at < ? OR (updated_at = ? AND ticket_id < ?)
507
+ ORDER BY updated_at DESC, ticket_id DESC LIMIT ?
508
+ `).all(cursorUpdatedAt, cursorUpdatedAt, cursorTicketId, limit);
509
+ if (rows.length === 0)
510
+ break;
511
+ for (const row of rows)
512
+ yield rowToSnapshot(row);
513
+ if (rows.length < limit)
514
+ break;
515
+ const last = rows[rows.length - 1];
516
+ cursorUpdatedAt = last.updated_at;
517
+ cursorTicketId = last.ticket_id;
518
+ }
519
+ }
520
+ getTicket(ticketId) {
521
+ if (this.closed || this.db === undefined)
522
+ return undefined;
523
+ const row = this.getTicketRow(ticketId);
524
+ return row === undefined ? undefined : rowToSnapshot(row);
525
+ }
526
+ listTicketEvents(ticketId, limit = 50) {
527
+ const db = this.assertOpen();
528
+ const rows = db.prepare('SELECT * FROM ray_ticket_events WHERE ticket_id = ? ORDER BY id DESC LIMIT ?')
529
+ .all(ticketId, Math.max(1, Math.min(200, Math.floor(limit))));
530
+ return rows.map(row => ({
531
+ id: row.id,
532
+ ticketId: row.ticket_id,
533
+ kind: row.kind,
534
+ payload: JSON.parse(row.payload_json),
535
+ createdAt: row.created_at,
536
+ }));
537
+ }
538
+ resolveFrozenRoute(frontAgent, binding) {
539
+ const headerEvent = frontAgent.session.snapshotEvents().findLast(event => event.type === 'request/header');
540
+ const headerConfig = headerEvent?.type === 'request/header' ? headerEvent.data.header.config : undefined;
541
+ if (headerConfig?.provider && headerConfig.model) {
542
+ return {
543
+ provider: headerConfig.provider,
544
+ model: headerConfig.model,
545
+ ...(headerConfig.reasoningEffort === undefined ? {} : { reasoningEffort: String(headerConfig.reasoningEffort) }),
546
+ };
547
+ }
548
+ const stored = this.options.getModelSelection(binding.conversation);
549
+ if (stored !== undefined)
550
+ return stored;
551
+ return { provider: this.options.defaultProvider, model: this.options.defaultModel };
552
+ }
553
+ async setupWorkerAgent(agentCtx, preparedAgent, ticket, presetId, agentPresets) {
554
+ if (preparedAgent === undefined) {
555
+ throw new Error('assistant-delivery: worker Agent identity is missing');
556
+ }
557
+ const unbindInitiator = this.options.policy.bindInitiator(preparedAgent, 'external', ticket.principalId);
558
+ agentCtx.effect(() => unbindInitiator, 'assistant-delivery.ray-worker-initiator');
559
+ this.options.getRaySelf()?.setSessionRole?.(ticket.sessionId, ticket.lane === 'free' ? 'worker-free' : 'worker');
560
+ installModelSelection(agentCtx);
561
+ preparedAgent.model.select(toModelSelection({
562
+ provider: ticket.provider,
563
+ model: ticket.model,
564
+ ...(ticket.reasoningEffort === undefined ? {} : { reasoningEffort: ticket.reasoningEffort }),
565
+ }));
566
+ agentCtx.inject(['systemPrompt'], promptCtx => promptCtx.systemPrompt.context({
567
+ name: 'ray:worker-ticket-scope',
568
+ order: 245,
569
+ text: () => {
570
+ const latest = this.getTicket(ticket.ticketId) ?? ticket;
571
+ return [
572
+ '[Ray Persistent Worker Ticket]',
573
+ `- ticketId: ${latest.ticketId}`,
574
+ `- title: ${latest.title}`,
575
+ `- objective: ${latest.objective}`,
576
+ `- scope: ${latest.scopeSummary}`,
577
+ ...(latest.tokenBudget === undefined ? [] : [`- tokenBudget: ${latest.tokenBudget} (used ${latest.usedTokens})`]),
578
+ '- instructions: You are an independent persistent background worker for Ray running concurrently with the front consciousness. Focus strictly on your ticket objective and scope. If the owner sends a steering/follow-up note, adapt in place without discarding progress. If requirements grow out of scope or hit an unresolvable blocker requiring owner coordination, call `ticket_handback` with a clear `reason` and `summary`.',
579
+ ].join('\n');
580
+ },
581
+ }));
582
+ await agentPresets?.mount(agentCtx, presetId);
583
+ }
584
+ observeWorkerHandle(ticketId, handle) {
585
+ const existing = this.activeWorkers.get(ticketId);
586
+ if (existing !== undefined) {
587
+ if (existing.handle === handle)
588
+ return existing;
589
+ existing.cleanup();
590
+ }
591
+ const runtimeCtx = this.runtimeCtx;
592
+ const disposers = [];
593
+ if (runtimeCtx !== undefined) {
594
+ disposers.push(runtimeCtx.on('session/event', (session, event) => {
595
+ if (session !== handle.agent.session)
596
+ return;
597
+ if (event.type === 'turn/end' || event.type === 'assistant/message') {
598
+ this.syncTokenUsage(ticketId, handle.agent);
599
+ }
600
+ if (event.type === 'turn/end') {
601
+ void this.reconcileWorkerSettlement(ticketId, handle.agent);
602
+ }
603
+ }));
604
+ disposers.push(runtimeCtx.on('agent/status', ({ agent, status }) => {
605
+ if (agent !== handle.agent || status !== 'idle')
606
+ return;
607
+ void this.reconcileWorkerSettlement(ticketId, handle.agent);
608
+ }));
609
+ }
610
+ const tracked = {
611
+ ticketId,
612
+ handle,
613
+ pendingFollowups: 0,
614
+ cleanup: () => {
615
+ for (const dispose of disposers) {
616
+ try {
617
+ dispose();
618
+ }
619
+ catch { }
620
+ }
621
+ },
622
+ };
623
+ this.activeWorkers.set(ticketId, tracked);
624
+ return tracked;
625
+ }
626
+ syncSessionTokenUsage(ticketId, sessionId, events) {
627
+ if (this.closed || this.db === undefined)
628
+ return 0;
629
+ const sessionTokens = extractUsageTokens(events);
630
+ if (sessionTokens <= 0) {
631
+ const existing = this.getTicketRow(ticketId);
632
+ return existing?.used_tokens ?? 0;
633
+ }
634
+ const now = Date.now();
635
+ this.db.prepare(`
636
+ INSERT INTO ray_ticket_session_usage (ticket_id, session_id, used_tokens, updated_at)
637
+ VALUES (?, ?, ?, ?)
638
+ ON CONFLICT(ticket_id, session_id) DO UPDATE SET
639
+ used_tokens = MAX(used_tokens, excluded.used_tokens),
640
+ updated_at = excluded.updated_at
641
+ `).run(ticketId, sessionId, sessionTokens, now);
642
+ const sumRow = this.db.prepare('SELECT COALESCE(SUM(used_tokens), 0) AS total FROM ray_ticket_session_usage WHERE ticket_id = ?')
643
+ .get(ticketId);
644
+ const totalUsed = Math.max(0, Math.trunc(sumRow?.total ?? sessionTokens));
645
+ this.db.prepare('UPDATE ray_tickets SET used_tokens = MAX(used_tokens, ?), updated_at = ? WHERE ticket_id = ?')
646
+ .run(totalUsed, now, ticketId);
647
+ return Math.max(totalUsed, this.getTicketRow(ticketId)?.used_tokens ?? 0);
648
+ }
649
+ syncTokenUsage(ticketId, agent) {
650
+ this.syncSessionTokenUsage(ticketId, String(agent.session.id), agent.session.snapshotEvents());
651
+ }
652
+ async reconcileWorkerSettlement(ticketId, agent) {
653
+ if (this.closed || this.disposing || this.db === undefined)
654
+ return;
655
+ const tracked = this.activeWorkers.get(ticketId);
656
+ const row = this.getTicketRow(ticketId);
657
+ if (row === undefined || row.status !== 'running')
658
+ return;
659
+ if (tracked !== undefined && tracked.pendingFollowups > 0)
660
+ return;
661
+ if (agent.status !== 'idle' || agent.inbox.nextTurn.length > 0 || agent.inbox.nextStep.length > 0)
662
+ return;
663
+ const events = agent.session.snapshotEvents();
664
+ const turnState = inspectTurnState(events);
665
+ if (!turnState.settledCompleted && turnState.turnEndKind === undefined)
666
+ return;
667
+ const now = Date.now();
668
+ const usedTokens = Math.max(row.used_tokens, this.syncSessionTokenUsage(ticketId, String(agent.session.id), events));
669
+ const assistantText = extractLastAssistantText(agent);
670
+ const nextStatus = turnState.settledCompleted ? 'completed' : 'failed';
671
+ const resultSummary = assistantText !== '' ? clipText(assistantText) : row.result_summary;
672
+ const errorMessage = nextStatus === 'failed'
673
+ ? (turnState.errorMessage ?? `turn ended with ${turnState.turnEndKind ?? 'unknown'}`)
674
+ : null;
675
+ const draft = rowToSnapshot({
676
+ ...row,
677
+ status: nextStatus,
678
+ revision: row.revision + 1,
679
+ used_tokens: usedTokens,
680
+ result_summary: resultSummary ?? null,
681
+ error_message: errorMessage,
682
+ updated_at: now,
683
+ completed_at: now,
684
+ });
685
+ const narration = buildNaturalNarration(draft);
686
+ const updated = this.db.prepare(`
687
+ UPDATE ray_tickets
688
+ SET status = ?, revision = revision + 1, used_tokens = ?, result_summary = ?, error_message = ?, narration_text = ?, updated_at = ?, completed_at = ?
689
+ WHERE ticket_id = ? AND status = 'running'
690
+ `).run(nextStatus, usedTokens, resultSummary ?? null, errorMessage, narration, now, now, ticketId);
691
+ if (Number(updated.changes) === 0)
692
+ return;
693
+ this.appendEvent(ticketId, nextStatus === 'completed' ? 'completed' : 'failed', {
694
+ usedTokens,
695
+ ...(turnState.turnEndKind === undefined ? {} : { turnEndKind: turnState.turnEndKind }),
696
+ ...(errorMessage === null ? {} : { errorMessage }),
697
+ }, now);
698
+ const finalized = this.getTicket(ticketId);
699
+ if (finalized !== undefined) {
700
+ try {
701
+ const raySelf = this.options.getRaySelf();
702
+ if (raySelf?.recordGrowthEvent) {
703
+ const elapsedMs = Math.max(1, now - row.created_at);
704
+ raySelf.recordGrowthEvent({
705
+ category: 'owner-task',
706
+ metricKey: 'worker-ticket',
707
+ subjectId: ticketId,
708
+ detail: { status: nextStatus },
709
+ });
710
+ raySelf.recordGrowthEvent({
711
+ category: 'latency-ms',
712
+ metricKey: 'worker-ticket',
713
+ value: elapsedMs,
714
+ subjectId: ticketId,
715
+ });
716
+ }
717
+ }
718
+ catch { /* ignore */ }
719
+ this.options.onTicketUpdated?.(finalized);
720
+ await this.tryPublishNarration(finalized);
721
+ }
722
+ }
723
+ async tryPublishNarration(ticket) {
724
+ if (this.closed || this.disposing || this.db === undefined || ticket.narrationSent || !ticket.narrationText)
725
+ return;
726
+ let sent = false;
727
+ try {
728
+ sent = await this.options.publishNarration(ticket);
729
+ }
730
+ catch {
731
+ sent = false;
732
+ }
733
+ if (sent && !this.closed && this.db !== undefined) {
734
+ const now = Date.now();
735
+ this.db.prepare('UPDATE ray_tickets SET narration_sent = 1, updated_at = ? WHERE ticket_id = ?')
736
+ .run(now, ticket.ticketId);
737
+ this.appendEvent(ticket.ticketId, 'narrated', { channel: ticket.sourceChannel ?? 'unknown' }, now);
738
+ const latest = this.getTicket(ticket.ticketId);
739
+ if (latest !== undefined)
740
+ this.options.onTicketUpdated?.(latest);
741
+ }
742
+ }
743
+ assertDispatchCapacityAndBudget(lane, tokenBudget) {
744
+ const db = this.assertOpen();
745
+ const raySelf = this.options.getRaySelf();
746
+ const snap = raySelf?.energySnapshot?.();
747
+ const maxWorkers = Math.max(1, Math.trunc(snap?.maxConcurrentWorkers ?? 4));
748
+ const runningCount = db.prepare("SELECT COUNT(*) AS c FROM ray_tickets WHERE status = 'running'").get().c;
749
+ if (runningCount >= maxWorkers) {
750
+ throw new Error(`assistant-delivery: maxConcurrentWorkers (${maxWorkers}) reached with ${runningCount} active workers`);
751
+ }
752
+ const requestedTokens = Math.max(1, tokenBudget ?? 1);
753
+ if (lane === 'free') {
754
+ const freeCheck = raySelf?.checkFreeEnergyBudget?.(requestedTokens);
755
+ if (freeCheck !== undefined && !freeCheck.allowed) {
756
+ throw new Error(`assistant-delivery: free energy budget exhausted (${freeCheck.reason})`);
757
+ }
758
+ return;
759
+ }
760
+ const ownerCheck = raySelf?.checkOwnerEnergyBudget?.(requestedTokens);
761
+ if (ownerCheck !== undefined && (!ownerCheck.allowed || ownerCheck.remainingDailyTokens <= 0)) {
762
+ throw new Error(`assistant-delivery: owner energy budget exhausted (${ownerCheck.reason})`);
763
+ }
764
+ }
765
+ async dispatchTicket(frontAgent, input) {
766
+ this.assertOpen();
767
+ if (!this.options.isOwnerSessionAgent(frontAgent) || frontAgent === undefined) {
768
+ throw new Error('assistant-delivery: ticket_dispatch requires an authenticated owner front session');
769
+ }
770
+ if (this.disposing) {
771
+ throw new Error('assistant-delivery: worker ticket runtime is stopping');
772
+ }
773
+ if (input.tokenBudget !== undefined && (!Number.isSafeInteger(input.tokenBudget) || input.tokenBudget <= 0)) {
774
+ throw new Error('assistant-delivery: ticket tokenBudget must be a positive safe integer');
775
+ }
776
+ const title = clipText(input.title, 200);
777
+ const objective = input.objective.trim();
778
+ const scopeSummary = input.scopeSummary?.trim() || title;
779
+ if (title === '' || objective === '') {
780
+ throw new Error('assistant-delivery: ticket title and objective are required');
781
+ }
782
+ const tokenBudget = input.tokenBudget ?? null;
783
+ const lane = input.lane === 'free' ? 'free' : 'owner';
784
+ const ctx = this.runtimeCtx;
785
+ const agents = ctx?.get('agents');
786
+ const sessions = ctx?.get('sessions');
787
+ if (ctx === undefined || agents === undefined || sessions === undefined) {
788
+ throw new Error('assistant-delivery: agent runtime is unavailable for persistent worker dispatch');
789
+ }
790
+ const frontSessionId = String(frontAgent.session.id);
791
+ const binding = this.options.deliveryStore.getBindingBySession(frontSessionId);
792
+ if (binding === undefined || binding.status !== 'active') {
793
+ throw new Error('assistant-delivery: active conversation binding not found for front session');
794
+ }
795
+ const route = this.resolveFrozenRoute(frontAgent, binding);
796
+ const now = Date.now();
797
+ const ticketId = `tkt_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
798
+ const sessionId = `ray_worker_${randomUUID()}`;
799
+ let initial = this.withWriteTransaction(txDb => {
800
+ this.assertDispatchCapacityAndBudget(lane, tokenBudget);
801
+ txDb.prepare(`
802
+ INSERT INTO ray_tickets (
803
+ ticket_id, session_id, title, objective, scope_summary, status, lane,
804
+ handback_count, revision, source_binding_id, source_channel, source_account, source_chat,
805
+ principal_id, workspace, agent_preset, provider, model, reasoning_effort,
806
+ token_budget, used_tokens, created_at, updated_at
807
+ ) VALUES (?, ?, ?, ?, ?, 'running', ?, 0, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
808
+ `).run(ticketId, sessionId, title, objective, scopeSummary, lane, binding.id, binding.conversation.channel, binding.conversation.account, binding.conversation.chat, externalPrincipalId(binding.principal), binding.workspace, binding.agentPreset, route.provider, route.model, route.reasoningEffort ?? null, tokenBudget, now, now);
809
+ this.appendEvent(ticketId, 'dispatched', {
810
+ sourceBindingId: binding.id,
811
+ sourceChannel: binding.conversation.channel,
812
+ provider: route.provider,
813
+ model: route.model,
814
+ lane,
815
+ }, now);
816
+ return this.getTicket(ticketId);
817
+ });
818
+ try {
819
+ const agentPresets = this.options.getAgentPresets();
820
+ const presetId = agentPresets === undefined
821
+ ? binding.agentPreset
822
+ : (await agentPresets.resolve(binding.agentPreset)).id;
823
+ if (presetId !== binding.agentPreset) {
824
+ this.withWriteTransaction(txDb => {
825
+ txDb.prepare('UPDATE ray_tickets SET agent_preset = ? WHERE ticket_id = ?').run(presetId, ticketId);
826
+ });
827
+ initial = this.getTicket(ticketId) ?? initial;
828
+ }
829
+ const handle = await agents.create({
830
+ sessionId: SessionId(sessionId),
831
+ meta: {
832
+ cwd: binding.workspace,
833
+ agentPreset: presetId,
834
+ },
835
+ agentOptions: {
836
+ provider: route.provider,
837
+ model: route.model,
838
+ maxTokens: this.options.maxOutputTokens,
839
+ },
840
+ setup: async (agentCtx, preparedAgent) => {
841
+ await this.setupWorkerAgent(agentCtx, preparedAgent, initial, presetId, agentPresets);
842
+ },
843
+ });
844
+ const tracked = this.observeWorkerHandle(ticketId, handle);
845
+ await sessions.flush(handle.agent.session);
846
+ const promptText = [
847
+ `请作为文鳐的持久后台 Worker 执行以下工单(${ticketId}):`,
848
+ `标题:${title}`,
849
+ `目标:${objective}`,
850
+ `范围边界:${scopeSummary}`,
851
+ '请独立完成并给出清晰可向主人转述的最终结论;如果发现范围明显超出或需主人重新决策,请调用 ticket_handback。',
852
+ ].join('\n');
853
+ tracked.pendingFollowups += 1;
854
+ try {
855
+ handle.agent.followup(createUserMessage({
856
+ content: [{ type: 'text', text: promptText }],
857
+ source: { kind: 'ray-worker', ticketId, action: 'dispatch' },
858
+ }));
859
+ }
860
+ finally {
861
+ tracked.pendingFollowups = Math.max(0, tracked.pendingFollowups - 1);
862
+ }
863
+ this.options.onTicketUpdated?.(initial);
864
+ return initial;
865
+ }
866
+ catch (error) {
867
+ const failedAt = Date.now();
868
+ const msg = error instanceof Error ? error.message : String(error);
869
+ try {
870
+ this.withWriteTransaction(txDb => {
871
+ txDb.prepare(`
872
+ UPDATE ray_tickets
873
+ SET status = 'failed', revision = revision + 1, error_message = ?, updated_at = ?, completed_at = ?
874
+ WHERE ticket_id = ? AND status = 'running'
875
+ `).run(msg, failedAt, failedAt, ticketId);
876
+ this.appendEvent(ticketId, 'failed', { errorMessage: msg }, failedAt);
877
+ });
878
+ }
879
+ catch {
880
+ // Best-effort cleanup if runtime closed concurrently.
881
+ }
882
+ throw error;
883
+ }
884
+ }
885
+ async followupTicket(frontAgent, input) {
886
+ this.assertOpen();
887
+ if (!this.options.isOwnerSessionAgent(frontAgent) || frontAgent === undefined) {
888
+ throw new Error('assistant-delivery: ticket_followup requires an authenticated owner front session');
889
+ }
890
+ const cleanTicketId = input.ticketId.trim();
891
+ const messageText = input.message.trim();
892
+ if (messageText === '') {
893
+ throw new Error('assistant-delivery: follow-up message cannot be empty');
894
+ }
895
+ const ctx = this.runtimeCtx;
896
+ const agents = ctx?.get('agents');
897
+ if (ctx === undefined || agents === undefined) {
898
+ throw new Error('assistant-delivery: agent runtime is unavailable for worker follow-up');
899
+ }
900
+ while (this.activeWorkers.get(cleanTicketId) === undefined) {
901
+ const inFlightRevival = this.revivingTickets.get(cleanTicketId);
902
+ if (inFlightRevival === undefined)
903
+ break;
904
+ await inFlightRevival.catch(() => { });
905
+ }
906
+ const now = Date.now();
907
+ const frontBinding = this.options.deliveryStore.getBindingBySession(String(frontAgent.session.id));
908
+ let row;
909
+ let priorRow;
910
+ let wasRunning = false;
911
+ let ticketLane = 'owner';
912
+ let tracked = this.activeWorkers.get(cleanTicketId);
913
+ this.withWriteTransaction(txDb => {
914
+ const current = this.getTicketRow(cleanTicketId);
915
+ if (current === undefined) {
916
+ throw new Error(`assistant-delivery: unknown worker ticket ${input.ticketId}`);
917
+ }
918
+ row = current;
919
+ priorRow = { ...current };
920
+ wasRunning = current.status === 'running';
921
+ ticketLane = current.lane === 'free' ? 'free' : 'owner';
922
+ if (!wasRunning) {
923
+ this.assertDispatchCapacityAndBudget(ticketLane, current.token_budget);
924
+ const updated = txDb.prepare(`
925
+ UPDATE ray_tickets
926
+ SET status = 'running', revision = revision + 1, handback_reason = NULL, error_message = NULL,
927
+ narration_sent = 0, front_narrated = 0, completed_at = NULL, updated_at = ?,
928
+ source_binding_id = COALESCE(?, source_binding_id),
929
+ source_channel = COALESCE(?, source_channel),
930
+ source_account = COALESCE(?, source_account),
931
+ source_chat = COALESCE(?, source_chat)
932
+ WHERE ticket_id = ? AND status != 'running'
933
+ `).run(now, frontBinding?.id ?? null, frontBinding?.conversation.channel ?? null, frontBinding?.conversation.account ?? null, frontBinding?.conversation.chat ?? null, current.ticket_id);
934
+ if (Number(updated.changes) !== 1) {
935
+ throw new Error(`assistant-delivery: concurrent worker state transition on ${current.ticket_id}`);
936
+ }
937
+ }
938
+ else if (frontBinding !== undefined) {
939
+ // Allow owner interruptions from any surface to also update the latest narration target.
940
+ txDb.prepare(`
941
+ UPDATE ray_tickets
942
+ SET source_binding_id = ?, source_channel = ?, source_account = ?, source_chat = ?, updated_at = ?
943
+ WHERE ticket_id = ?
944
+ `).run(frontBinding.id, frontBinding.conversation.channel, frontBinding.conversation.account, frontBinding.conversation.chat, now, current.ticket_id);
945
+ }
946
+ if (tracked === undefined) {
947
+ const existingAgent = agents.get(SessionId(current.session_id));
948
+ if (existingAgent !== undefined) {
949
+ this.options.getRaySelf()?.setSessionRole?.(current.session_id, ticketLane === 'free' ? 'worker-free' : 'worker');
950
+ tracked = this.observeWorkerHandle(current.ticket_id, {
951
+ agent: existingAgent,
952
+ dispose: async () => { },
953
+ });
954
+ }
955
+ }
956
+ });
957
+ if (tracked === undefined) {
958
+ const snapshot = rowToSnapshot(this.getTicketRow(row.ticket_id) ?? row);
959
+ const revivePromise = (async () => {
960
+ const agentPresets = this.options.getAgentPresets();
961
+ const presetId = agentPresets === undefined
962
+ ? row.agent_preset
963
+ : (await agentPresets.resolve(row.agent_preset)).id;
964
+ const handle = await agents.resume({
965
+ resumeSessionId: SessionId(row.session_id),
966
+ agentOptions: {
967
+ provider: row.provider,
968
+ model: row.model,
969
+ maxTokens: this.options.maxOutputTokens,
970
+ },
971
+ setup: async (agentCtx, preparedAgent) => {
972
+ await this.setupWorkerAgent(agentCtx, preparedAgent, snapshot, presetId, agentPresets);
973
+ },
974
+ });
975
+ return this.observeWorkerHandle(row.ticket_id, handle);
976
+ })();
977
+ this.revivingTickets.set(row.ticket_id, revivePromise);
978
+ try {
979
+ tracked = await revivePromise;
980
+ }
981
+ catch (error) {
982
+ if (!wasRunning) {
983
+ try {
984
+ this.withWriteTransaction(txDb => {
985
+ txDb.prepare(`
986
+ UPDATE ray_tickets
987
+ SET status = ?, revision = ?, handback_reason = ?, error_message = ?,
988
+ narration_sent = ?, front_narrated = ?, completed_at = ?, updated_at = ?,
989
+ source_binding_id = ?, source_channel = ?, source_account = ?, source_chat = ?
990
+ WHERE ticket_id = ? AND status = 'running'
991
+ `).run(priorRow.status, priorRow.revision, priorRow.handback_reason, priorRow.error_message, priorRow.narration_sent, priorRow.front_narrated, priorRow.completed_at, priorRow.updated_at, priorRow.source_binding_id, priorRow.source_channel, priorRow.source_account, priorRow.source_chat, row.ticket_id);
992
+ });
993
+ }
994
+ catch {
995
+ // Best-effort rollback if DB closed concurrently.
996
+ }
997
+ }
998
+ throw error;
999
+ }
1000
+ finally {
1001
+ if (this.revivingTickets.get(row.ticket_id) === revivePromise) {
1002
+ this.revivingTickets.delete(row.ticket_id);
1003
+ }
1004
+ }
1005
+ }
1006
+ const agent = tracked.handle.agent;
1007
+ const deliveryMode = input.mode === 'followup'
1008
+ ? 'followup'
1009
+ : input.mode === 'steer'
1010
+ ? 'steer'
1011
+ : agent.status === 'idle'
1012
+ ? 'followup'
1013
+ : 'steer';
1014
+ const payloadMsg = createUserMessage({
1015
+ content: [{
1016
+ type: 'text',
1017
+ text: `[主人补充/插话 - ${deliveryMode === 'steer' ? '不中断实时调整' : '追加指令'}] ${messageText}`,
1018
+ }],
1019
+ source: { kind: 'ray-worker', ticketId: row.ticket_id, action: deliveryMode },
1020
+ });
1021
+ tracked.pendingFollowups += 1;
1022
+ try {
1023
+ this.appendEvent(row.ticket_id, deliveryMode, { message: clipText(messageText, 400) }, now);
1024
+ if (deliveryMode === 'steer') {
1025
+ agent.steer(payloadMsg);
1026
+ }
1027
+ else {
1028
+ agent.followup(payloadMsg);
1029
+ }
1030
+ }
1031
+ finally {
1032
+ tracked.pendingFollowups = Math.max(0, tracked.pendingFollowups - 1);
1033
+ }
1034
+ const updated = this.getTicket(row.ticket_id);
1035
+ this.options.onTicketUpdated?.(updated);
1036
+ return { ticket: updated, deliveryMode };
1037
+ }
1038
+ async handbackTicket(workerAgent, input) {
1039
+ const db = this.assertOpen();
1040
+ if (workerAgent === undefined) {
1041
+ throw new Error('assistant-delivery: ticket_handback requires a worker session');
1042
+ }
1043
+ const sessionId = String(workerAgent.session.id);
1044
+ const row = this.getTicketRowBySession(sessionId);
1045
+ if (row === undefined) {
1046
+ throw new Error('assistant-delivery: ticket_handback is restricted to active persistent worker sessions');
1047
+ }
1048
+ const reason = input.reason.trim();
1049
+ const summary = input.summary.trim();
1050
+ if (reason === '' || summary === '') {
1051
+ throw new Error('assistant-delivery: handback reason and summary are required');
1052
+ }
1053
+ const now = Date.now();
1054
+ const usedTokens = Math.max(row.used_tokens, this.syncSessionTokenUsage(row.ticket_id, String(workerAgent.session.id), workerAgent.session.snapshotEvents()));
1055
+ const fullSummary = input.suggestedNextStep?.trim()
1056
+ ? `${summary}\n建议下一步:${input.suggestedNextStep.trim()}`
1057
+ : summary;
1058
+ const draft = rowToSnapshot({
1059
+ ...row,
1060
+ status: 'handed_back',
1061
+ handback_count: row.handback_count + 1,
1062
+ revision: row.revision + 1,
1063
+ used_tokens: usedTokens,
1064
+ handback_reason: reason,
1065
+ result_summary: fullSummary,
1066
+ error_message: null,
1067
+ updated_at: now,
1068
+ completed_at: now,
1069
+ });
1070
+ const narration = buildNaturalNarration(draft);
1071
+ db.prepare(`
1072
+ UPDATE ray_tickets
1073
+ SET status = 'handed_back', handback_count = handback_count + 1, revision = revision + 1,
1074
+ used_tokens = ?, handback_reason = ?, result_summary = ?,
1075
+ error_message = NULL, narration_text = ?, narration_sent = 0, front_narrated = 0,
1076
+ updated_at = ?, completed_at = ?
1077
+ WHERE ticket_id = ?
1078
+ `).run(usedTokens, reason, fullSummary, narration, now, now, row.ticket_id);
1079
+ this.appendEvent(row.ticket_id, 'handed_back', {
1080
+ reason: clipText(reason, 300),
1081
+ summary: clipText(fullSummary, 400),
1082
+ }, now);
1083
+ const updated = this.getTicket(row.ticket_id);
1084
+ try {
1085
+ const raySelf = this.options.getRaySelf();
1086
+ if (raySelf?.recordGrowthEvent) {
1087
+ const elapsedMs = Math.max(1, now - row.created_at);
1088
+ raySelf.recordGrowthEvent({
1089
+ category: 'owner-task',
1090
+ metricKey: 'worker-ticket',
1091
+ subjectId: row.ticket_id,
1092
+ detail: { status: 'handed_back' },
1093
+ });
1094
+ raySelf.recordGrowthEvent({
1095
+ category: 'latency-ms',
1096
+ metricKey: 'worker-ticket',
1097
+ value: elapsedMs,
1098
+ subjectId: row.ticket_id,
1099
+ });
1100
+ }
1101
+ }
1102
+ catch { /* ignore */ }
1103
+ this.options.onTicketUpdated?.(updated);
1104
+ try {
1105
+ this.options.wakeFrontOnHandback?.(updated);
1106
+ }
1107
+ catch (error) {
1108
+ this.options.warn?.(`assistant-delivery: failed to schedule handback front wakeup for ${updated.ticketId}: ${error instanceof Error ? error.message : String(error)}`);
1109
+ }
1110
+ await this.tryPublishNarration(updated);
1111
+ return this.getTicket(row.ticket_id) ?? updated;
1112
+ }
1113
+ async recoverUnfinishedTickets() {
1114
+ if (this.closed || this.disposing || this.db === undefined)
1115
+ return 0;
1116
+ if (this.recoveringPromise !== undefined)
1117
+ return this.recoveringPromise;
1118
+ const flight = this.recoverUnfinishedTicketsInternal().finally(() => {
1119
+ if (this.recoveringPromise === flight)
1120
+ this.recoveringPromise = undefined;
1121
+ });
1122
+ this.recoveringPromise = flight;
1123
+ return flight;
1124
+ }
1125
+ async recoverUnfinishedTicketsInternal() {
1126
+ const db = this.assertOpen();
1127
+ const ctx = this.runtimeCtx;
1128
+ const agents = ctx?.get('agents');
1129
+ const sessions = ctx?.get('sessions');
1130
+ if (ctx === undefined || agents === undefined || sessions === undefined)
1131
+ return 0;
1132
+ const pendingRows = db.prepare('SELECT * FROM ray_tickets WHERE status = ? ORDER BY created_at ASC')
1133
+ .all('running');
1134
+ let recovered = 0;
1135
+ const agentPresets = this.options.getAgentPresets();
1136
+ for (const row of pendingRows) {
1137
+ if (this.closed || this.disposing)
1138
+ break;
1139
+ if (this.activeWorkers.has(row.ticket_id) || this.revivingTickets.has(row.ticket_id))
1140
+ continue;
1141
+ try {
1142
+ const snapshot = rowToSnapshot(row);
1143
+ const presetId = agentPresets === undefined
1144
+ ? row.agent_preset
1145
+ : (await agentPresets.resolve(row.agent_preset)).id;
1146
+ const handle = await agents.resume({
1147
+ resumeSessionId: SessionId(row.session_id),
1148
+ agentOptions: {
1149
+ provider: row.provider,
1150
+ model: row.model,
1151
+ maxTokens: this.options.maxOutputTokens,
1152
+ },
1153
+ setup: async (agentCtx, preparedAgent) => {
1154
+ await this.setupWorkerAgent(agentCtx, preparedAgent, snapshot, presetId, agentPresets);
1155
+ },
1156
+ });
1157
+ const tracked = this.observeWorkerHandle(row.ticket_id, handle);
1158
+ const now = Date.now();
1159
+ this.appendEvent(row.ticket_id, 'resumed', { sessionId: row.session_id }, now);
1160
+ const turnState = inspectTurnState(handle.agent.session.snapshotEvents());
1161
+ const assistantText = extractLastAssistantText(handle.agent);
1162
+ if (turnState.settledCompleted && assistantText !== '' && handle.agent.status === 'idle') {
1163
+ await this.reconcileWorkerSettlement(row.ticket_id, handle.agent);
1164
+ }
1165
+ else if (handle.agent.status === 'idle' && handle.agent.inbox.nextTurn.length === 0) {
1166
+ tracked.pendingFollowups += 1;
1167
+ try {
1168
+ handle.agent.followup(createUserMessage({
1169
+ content: [{
1170
+ type: 'text',
1171
+ text: `宿主刚刚重启恢复。请从上次进度继续完成工单「${row.title}」(${row.ticket_id});如果任务已不再适用或超出边界,请调用 ticket_handback。`,
1172
+ }],
1173
+ source: { kind: 'ray-worker', ticketId: row.ticket_id, action: 'resume' },
1174
+ }));
1175
+ }
1176
+ finally {
1177
+ tracked.pendingFollowups = Math.max(0, tracked.pendingFollowups - 1);
1178
+ }
1179
+ }
1180
+ const latest = this.getTicket(row.ticket_id);
1181
+ if (latest !== undefined)
1182
+ this.options.onTicketUpdated?.(latest);
1183
+ recovered += 1;
1184
+ }
1185
+ catch (error) {
1186
+ this.options.warn?.(`assistant-delivery: failed to recover worker ticket ${row.ticket_id}: ${error instanceof Error ? error.message : String(error)}`);
1187
+ }
1188
+ }
1189
+ return recovered;
1190
+ }
1191
+ markFrontNarrated(ticketIds) {
1192
+ if (this.closed || this.db === undefined || ticketIds.length === 0)
1193
+ return;
1194
+ const now = Date.now();
1195
+ const stmt = this.db.prepare('UPDATE ray_tickets SET front_narrated = 1, updated_at = ? WHERE ticket_id = ?');
1196
+ for (const ticketId of ticketIds) {
1197
+ stmt.run(now, ticketId);
1198
+ }
1199
+ }
1200
+ pendingFrontNarrationIds() {
1201
+ if (this.closed || this.db === undefined)
1202
+ return [];
1203
+ const rows = this.db.prepare(`
1204
+ SELECT ticket_id FROM ray_tickets
1205
+ WHERE status IN ('completed', 'handed_back', 'failed') AND front_narrated = 0
1206
+ ORDER BY updated_at ASC LIMIT 10
1207
+ `).all();
1208
+ return rows.map(row => row.ticket_id);
1209
+ }
1210
+ renderFrontPromptContext() {
1211
+ if (this.closed || this.db === undefined)
1212
+ return '';
1213
+ const running = this.listTickets({ status: 'running', limit: 8 });
1214
+ const pendingNarration = this.db.prepare(`
1215
+ SELECT * FROM ray_tickets
1216
+ WHERE status IN ('completed', 'handed_back', 'failed') AND front_narrated = 0
1217
+ ORDER BY updated_at DESC LIMIT 6
1218
+ `).all();
1219
+ const recentTerminal = pendingNarration.length > 0
1220
+ ? pendingNarration.map(rowToSnapshot)
1221
+ : this.listTickets({ limit: 4 }).filter(t => t.status !== 'running');
1222
+ const lines = [
1223
+ '## 前台意识与持久 Worker 协作策略',
1224
+ '- 对需要多步调研、长耗时执行或可独立推进的工作,优先用 `ticket_dispatch` 派发持久后台 Worker 并立即自然回应主人,保持对话随时可插话。',
1225
+ '- 当主人中途插话补充需求、修改方向或纠正细节时,不要取消原工单,优先用 `ticket_followup`(`steer` 或 `followup`)把调整路由给对应 Worker;用 `ticket_list` 查看当前进度。',
1226
+ ];
1227
+ if (running.length > 0) {
1228
+ lines.push('', '### 正在进行的持久 Worker 工单');
1229
+ for (const t of running) {
1230
+ lines.push(`- ${t.ticketId} | ${t.title} | 状态: running | 已用 tokens: ${t.usedTokens}${t.tokenBudget ? `/${t.tokenBudget}` : ''}`);
1231
+ }
1232
+ }
1233
+ if (pendingNarration.length > 0) {
1234
+ lines.push('', '### 待自然转述给主人的 Worker 结果(请在本轮回复中用自然语言主动同步关键结果,不要直接贴原始 JSON)');
1235
+ for (const row of pendingNarration) {
1236
+ const snap = rowToSnapshot(row);
1237
+ lines.push(`- ${snap.ticketId} | ${snap.title} | ${snap.status}: ${snap.narrationText ?? snap.resultSummary ?? snap.handbackReason ?? snap.errorMessage ?? ''}`);
1238
+ }
1239
+ }
1240
+ else if (recentTerminal.length > 0) {
1241
+ lines.push('', '### 近期已结算工单');
1242
+ for (const t of recentTerminal) {
1243
+ lines.push(`- ${t.ticketId} | ${t.title} | ${t.status}: ${clipText(t.narrationText ?? t.resultSummary ?? t.handbackReason ?? '', 180)}`);
1244
+ }
1245
+ }
1246
+ return lines.join('\n');
1247
+ }
1248
+ formatTicketsCommandReply() {
1249
+ const tickets = this.listTickets({ limit: 12 });
1250
+ if (tickets.length === 0) {
1251
+ return '当前没有进行中或近期的持久 Worker 工单。';
1252
+ }
1253
+ const statusLabel = (s) => s === 'running' ? '运行中'
1254
+ : s === 'completed' ? '已完成'
1255
+ : s === 'handed_back' ? '已交回前台'
1256
+ : '失败';
1257
+ const lines = ['文鳐持久 Worker 工单:'];
1258
+ for (const t of tickets) {
1259
+ const detail = t.status === 'handed_back'
1260
+ ? t.handbackReason ?? t.resultSummary ?? ''
1261
+ : t.status === 'completed'
1262
+ ? t.resultSummary ?? ''
1263
+ : t.status === 'failed'
1264
+ ? t.errorMessage ?? ''
1265
+ : t.objective;
1266
+ lines.push(`- [${statusLabel(t.status)}] ${t.ticketId} · ${t.title}${detail ? `:${clipText(detail, 120)}` : ''}`);
1267
+ }
1268
+ return lines.join('\n');
1269
+ }
1270
+ async dispose() {
1271
+ if (this.closed)
1272
+ return;
1273
+ this.disposing = true;
1274
+ const workers = [...this.activeWorkers.values()];
1275
+ this.activeWorkers.clear();
1276
+ for (const worker of workers) {
1277
+ worker.cleanup();
1278
+ try {
1279
+ await worker.handle.dispose();
1280
+ }
1281
+ catch { }
1282
+ }
1283
+ if (this.recoveringPromise !== undefined) {
1284
+ try {
1285
+ await this.recoveringPromise;
1286
+ }
1287
+ catch { }
1288
+ }
1289
+ this.clearRuntimeListeners();
1290
+ this.parentSessionByChild.clear();
1291
+ this.runtimeCtx = undefined;
1292
+ this.closed = true;
1293
+ try {
1294
+ this.db?.close();
1295
+ }
1296
+ catch { }
1297
+ this.db = undefined;
1298
+ }
1299
+ }
1300
+ //# sourceMappingURL=ray-worker-runtime.js.map