@max10240/opencode-plugin-delayed-queue 0.0.0-stage → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,591 @@
1
+ const MAX_DELIVERY_FAILURES = 3;
2
+ /**
3
+ * Owns the delayed queue per Session. The runner's `experimental.idle` hook is the
4
+ * authoritative boundary; the controller never waits inside that hook. It either
5
+ * admits the next item, or returns and lets a wake or a recheck run again.
6
+ */
7
+ export class DelayedQueueController {
8
+ options;
9
+ states = new Map();
10
+ jobs = new Map();
11
+ timers = new Map();
12
+ locks = new Map();
13
+ parents = new Map();
14
+ now;
15
+ scheduleTimer;
16
+ cancelTimer;
17
+ waitKinds;
18
+ disposed = false;
19
+ constructor(options) {
20
+ this.options = options;
21
+ this.now = options.now;
22
+ this.scheduleTimer = options.timers?.setTimeout ?? ((run, delay) => setTimeout(run, delay));
23
+ this.cancelTimer =
24
+ options.timers?.clearTimeout ?? ((timer) => clearTimeout(timer));
25
+ this.waitKinds = new Set(options.waitKinds);
26
+ }
27
+ hydrate(sessionID, stored) {
28
+ if (this.disposed)
29
+ return;
30
+ const paused = stored.boot !== this.options.boot ? true : stored.paused;
31
+ const pauseReason = stored.boot !== this.options.boot ? "restart" : paused ? stored.pauseReason : undefined;
32
+ this.states.set(sessionID, {
33
+ sessionID,
34
+ boot: this.options.boot,
35
+ paused,
36
+ ...(pauseReason === undefined ? {} : { pauseReason }),
37
+ items: stored.items.map((item) => ({ id: item.id, text: item.text, createdAt: item.createdAt })),
38
+ updatedAt: stored.updatedAt,
39
+ observed: false,
40
+ delivering: false,
41
+ failures: 0,
42
+ });
43
+ }
44
+ status(sessionID) {
45
+ const state = this.states.get(sessionID);
46
+ if (!state)
47
+ return this.emptyStatus(sessionID);
48
+ return this.snapshot(state);
49
+ }
50
+ async enqueue(sessionID, text, jobs) {
51
+ return this.withLock(sessionID, async () => {
52
+ const state = this.state(sessionID);
53
+ const value = text.trim();
54
+ if (!value)
55
+ return this.snapshot(state);
56
+ state.items.push({ id: messageID(this.now()), text: value, createdAt: this.now() });
57
+ state.updatedAt = this.now();
58
+ if (jobs !== undefined) {
59
+ state.observed = true;
60
+ await this.replaceJobs(sessionID, jobs);
61
+ }
62
+ await this.changed(state);
63
+ await this.kickLocked(state);
64
+ return this.snapshot(state);
65
+ });
66
+ }
67
+ async syncJobs(sessionID, jobs) {
68
+ return this.withLock(sessionID, async () => {
69
+ const state = this.state(sessionID);
70
+ const first = !state.observed;
71
+ state.observed = true;
72
+ state.updatedAt = this.now();
73
+ await this.replaceJobs(sessionID, jobs);
74
+ if (first)
75
+ await this.changed(state);
76
+ else
77
+ this.options.onChange(this.snapshot(state));
78
+ await this.kickLocked(state);
79
+ return this.snapshot(state);
80
+ });
81
+ }
82
+ async remove(sessionID, ids) {
83
+ return this.withLock(sessionID, async () => {
84
+ const state = this.states.get(sessionID);
85
+ if (!state)
86
+ return this.emptyStatus(sessionID);
87
+ const drop = new Set(ids);
88
+ state.items = state.items.filter((item) => !drop.has(item.id));
89
+ state.updatedAt = this.now();
90
+ if (state.items.length === 0)
91
+ this.cancelRecheck(sessionID);
92
+ await this.changed(state);
93
+ return this.snapshot(state);
94
+ });
95
+ }
96
+ async clear(sessionID) {
97
+ return this.withLock(sessionID, async () => {
98
+ const state = this.states.get(sessionID);
99
+ if (!state)
100
+ return this.emptyStatus(sessionID);
101
+ state.items = [];
102
+ state.updatedAt = this.now();
103
+ this.cancelRecheck(sessionID);
104
+ await this.changed(state);
105
+ return this.snapshot(state);
106
+ });
107
+ }
108
+ async pause(sessionID, reason) {
109
+ return this.withLock(sessionID, async () => {
110
+ const state = this.state(sessionID);
111
+ state.paused = true;
112
+ state.pauseReason = reason;
113
+ state.updatedAt = this.now();
114
+ this.cancelRecheck(sessionID);
115
+ await this.changed(state);
116
+ return this.snapshot(state);
117
+ });
118
+ }
119
+ async resume(sessionID) {
120
+ return this.withLock(sessionID, async () => {
121
+ const state = this.state(sessionID);
122
+ state.paused = false;
123
+ state.pauseReason = undefined;
124
+ state.failures = 0;
125
+ state.lastError = undefined;
126
+ state.observed = true;
127
+ state.updatedAt = this.now();
128
+ await this.changed(state);
129
+ await this.kickLocked(state);
130
+ return this.snapshot(state);
131
+ });
132
+ }
133
+ async deliverNow(sessionID, id) {
134
+ return this.withLock(sessionID, async () => {
135
+ const state = this.states.get(sessionID);
136
+ if (!state)
137
+ return this.emptyStatus(sessionID);
138
+ const item = state.items.find((entry) => entry.id === id);
139
+ if (!item || state.delivering)
140
+ return this.snapshot(state);
141
+ await this.deliverLocked(state, item, true);
142
+ return this.snapshot(state);
143
+ });
144
+ }
145
+ /** Runs at the runner's idle boundary. Never awaits background work. */
146
+ async onIdle(sessionID, background) {
147
+ await this.withLock(sessionID, async () => {
148
+ const state = this.state(sessionID);
149
+ state.observed = true;
150
+ state.background = background.map((work) => ({ ...work }));
151
+ state.updatedAt = this.now();
152
+ this.cancelRecheck(sessionID);
153
+ for (const other of this.states.values()) {
154
+ if (other.sessionID === sessionID || other.items.length === 0 || other.paused)
155
+ continue;
156
+ this.scheduleRecheck(other.sessionID);
157
+ }
158
+ if (state.paused || state.items.length === 0 || state.delivering) {
159
+ await this.changed(state);
160
+ return;
161
+ }
162
+ const relevant = this.relevantBackground(state, background);
163
+ if (relevant.some((work) => work.sessionID === sessionID)) {
164
+ // The Session's own work normally wakes it. A recheck covers a missed notice, a
165
+ // recovered notice admitted with resume:false, and a client that reconnects late.
166
+ await this.changed(state);
167
+ this.scheduleRecheck(sessionID);
168
+ return;
169
+ }
170
+ if (relevant.length > 0) {
171
+ // Descendant-owned work wakes that descendant, not this Session. Recheck.
172
+ await this.changed(state);
173
+ this.scheduleRecheck(sessionID);
174
+ return;
175
+ }
176
+ await this.deliverLocked(state, state.items[0], true);
177
+ });
178
+ }
179
+ /** A non-plugin prompt is a fresh user turn and releases an interrupt/failure pause. */
180
+ async onPrompt(sessionID, own) {
181
+ if (own)
182
+ return;
183
+ await this.withLock(sessionID, async () => {
184
+ const state = this.states.get(sessionID);
185
+ if (!state || !state.paused)
186
+ return;
187
+ state.paused = false;
188
+ state.pauseReason = undefined;
189
+ state.failures = 0;
190
+ state.lastError = undefined;
191
+ state.updatedAt = this.now();
192
+ await this.changed(state);
193
+ });
194
+ }
195
+ async onExecutionInterrupted(sessionID, reason) {
196
+ if (reason === "user" && this.options.pauseOnInterrupt) {
197
+ await this.pauseIfWaiting(sessionID, "interrupted");
198
+ return;
199
+ }
200
+ if (reason === "shutdown")
201
+ await this.pauseIfWaiting(sessionID, "restart");
202
+ }
203
+ async onExecutionFailed(sessionID) {
204
+ if (this.options.pauseOnFailure)
205
+ await this.pauseIfWaiting(sessionID, "failed");
206
+ }
207
+ async pauseIfWaiting(sessionID, reason) {
208
+ const state = this.states.get(sessionID);
209
+ if (!state || state.items.length === 0)
210
+ return;
211
+ await this.pause(sessionID, reason);
212
+ }
213
+ onExecutionStarted(sessionID) {
214
+ this.cancelRecheck(sessionID);
215
+ }
216
+ onJob(info) {
217
+ if (this.disposed)
218
+ return;
219
+ if (info.status === "running")
220
+ this.jobs.set(info.id, { ...info });
221
+ else
222
+ this.jobs.delete(info.id);
223
+ for (const state of this.states.values()) {
224
+ if (state.items.length === 0)
225
+ continue;
226
+ state.observed = true;
227
+ if (!state.paused)
228
+ this.scheduleRecheck(state.sessionID);
229
+ }
230
+ for (const state of this.states.values())
231
+ this.options.onChange(this.snapshot(state));
232
+ }
233
+ async onSessionDeleted(sessionID) {
234
+ await this.withLock(sessionID, async () => {
235
+ this.cancelRecheck(sessionID);
236
+ this.states.delete(sessionID);
237
+ for (const [id, job] of this.jobs) {
238
+ if (job.sessionID === sessionID || job.childSessionID === sessionID)
239
+ this.jobs.delete(id);
240
+ }
241
+ this.parents.delete(sessionID);
242
+ });
243
+ }
244
+ async replaceJobs(sessionID, jobs) {
245
+ for (const [id, job] of this.jobs) {
246
+ if (job.sessionID === sessionID || job.childSessionID === sessionID) {
247
+ this.jobs.delete(id);
248
+ continue;
249
+ }
250
+ if (!this.options.waitDescendants)
251
+ continue;
252
+ if ((await this.isDescendant(job.sessionID, sessionID)) ||
253
+ (job.childSessionID !== undefined && (await this.isDescendant(job.childSessionID, sessionID))))
254
+ this.jobs.delete(id);
255
+ }
256
+ this.seedJobs(sessionID, jobs);
257
+ }
258
+ seedJobs(sessionID, jobs) {
259
+ const state = this.states.get(sessionID);
260
+ if (state)
261
+ state.observed = true;
262
+ for (const job of jobs) {
263
+ if (job.status === "running")
264
+ this.jobs.set(job.id, { ...job });
265
+ else
266
+ this.jobs.delete(job.id);
267
+ }
268
+ }
269
+ dispose() {
270
+ this.disposed = true;
271
+ for (const sessionID of this.timers.keys())
272
+ this.cancelRecheck(sessionID);
273
+ this.states.clear();
274
+ this.jobs.clear();
275
+ this.parents.clear();
276
+ }
277
+ state(sessionID) {
278
+ const existing = this.states.get(sessionID);
279
+ if (existing)
280
+ return existing;
281
+ const created = {
282
+ sessionID,
283
+ boot: this.options.boot,
284
+ paused: false,
285
+ items: [],
286
+ updatedAt: this.now(),
287
+ observed: false,
288
+ delivering: false,
289
+ failures: 0,
290
+ };
291
+ this.states.set(sessionID, created);
292
+ return created;
293
+ }
294
+ emptyStatus(sessionID) {
295
+ return {
296
+ sessionID,
297
+ paused: false,
298
+ items: [],
299
+ waitingFor: [],
300
+ observed: false,
301
+ delivering: false,
302
+ updatedAt: this.now(),
303
+ };
304
+ }
305
+ snapshot(state) {
306
+ return {
307
+ sessionID: state.sessionID,
308
+ paused: state.paused,
309
+ ...(state.pauseReason === undefined ? {} : { pauseReason: state.pauseReason }),
310
+ items: state.items.map((item) => ({ ...item })),
311
+ waitingFor: this.waitingFor(state),
312
+ observed: state.observed,
313
+ delivering: state.delivering,
314
+ ...(state.lastError === undefined ? {} : { lastError: state.lastError }),
315
+ updatedAt: state.updatedAt,
316
+ };
317
+ }
318
+ waitingFor(state) {
319
+ const jobs = [...this.jobs.values()].filter((job) => job.status === "running" && this.waitKinds.has(job.kind));
320
+ const relevant = jobs.filter((job) => job.sessionID === state.sessionID ||
321
+ (this.options.waitDescendants && this.knownDescendant(job.sessionID, state.sessionID)));
322
+ if (relevant.length > 0) {
323
+ return relevant.map((job) => ({
324
+ kind: job.kind,
325
+ sessionID: job.sessionID,
326
+ ...(jobLabel(job) === undefined ? {} : { label: jobLabel(job) }),
327
+ jobID: job.id,
328
+ ...(job.shellID === undefined ? {} : { shellID: job.shellID }),
329
+ ...(job.command === undefined ? {} : { command: job.command }),
330
+ ...(job.childSessionID === undefined ? {} : { childSessionID: job.childSessionID }),
331
+ ...(job.description === undefined ? {} : { description: job.description }),
332
+ ...(job.path === undefined ? {} : { path: job.path }),
333
+ }));
334
+ }
335
+ return state.background === undefined ? [] : this.relevantBackground(state, state.background);
336
+ }
337
+ /** Snapshot-only descendant test. Deep parent chains refresh through `isDescendant`. */
338
+ knownDescendant(owner, ancestor) {
339
+ let current = this.parents.get(owner);
340
+ if (current === undefined)
341
+ return false;
342
+ const seen = new Set();
343
+ while (current !== null && !seen.has(current)) {
344
+ if (current === ancestor)
345
+ return true;
346
+ seen.add(current);
347
+ current = this.parents.get(current) ?? null;
348
+ }
349
+ return false;
350
+ }
351
+ relevantBackground(state, background) {
352
+ return background.filter((work) => {
353
+ if (!this.waitKinds.has(work.kind))
354
+ return false;
355
+ if (work.sessionID === state.sessionID)
356
+ return true;
357
+ return this.options.waitDescendants;
358
+ });
359
+ }
360
+ async kickLocked(state) {
361
+ if (this.disposed || state.paused || state.items.length === 0 || state.delivering)
362
+ return;
363
+ if (await this.safeBusy(state.sessionID)) {
364
+ this.scheduleRecheck(state.sessionID);
365
+ return;
366
+ }
367
+ if (await this.hasRelevantJobs(state.sessionID) || (await this.backgroundBlocks(state))) {
368
+ this.scheduleRecheck(state.sessionID);
369
+ return;
370
+ }
371
+ if (!state.observed) {
372
+ this.scheduleRecheck(state.sessionID);
373
+ return;
374
+ }
375
+ await this.deliverLocked(state, state.items[0]);
376
+ }
377
+ async deliverLocked(state, item, atIdle = false) {
378
+ if (this.disposed || state.delivering)
379
+ return;
380
+ if (!atIdle && (await this.safeBusy(state.sessionID))) {
381
+ this.scheduleRecheck(state.sessionID);
382
+ return;
383
+ }
384
+ state.delivering = true;
385
+ try {
386
+ await this.options.deliver(state.sessionID, item);
387
+ state.items = state.items.filter((entry) => entry.id !== item.id);
388
+ state.failures = 0;
389
+ state.lastError = undefined;
390
+ state.updatedAt = this.now();
391
+ await this.changed(state);
392
+ }
393
+ catch (error) {
394
+ state.failures += 1;
395
+ state.lastError = error instanceof Error ? error.message : String(error);
396
+ state.updatedAt = this.now();
397
+ this.options.onError(error, state.sessionID);
398
+ if (state.failures >= MAX_DELIVERY_FAILURES) {
399
+ state.paused = true;
400
+ state.pauseReason = "delivery";
401
+ }
402
+ else {
403
+ this.scheduleRecheck(state.sessionID);
404
+ }
405
+ await this.changed(state);
406
+ }
407
+ finally {
408
+ state.delivering = false;
409
+ }
410
+ }
411
+ scheduleRecheck(sessionID) {
412
+ if (this.disposed || this.timers.has(sessionID))
413
+ return;
414
+ const handle = this.scheduleTimer(() => {
415
+ this.timers.delete(sessionID);
416
+ void this.recheck(sessionID);
417
+ }, this.options.recheckMs);
418
+ this.timers.set(sessionID, handle);
419
+ }
420
+ cancelRecheck(sessionID) {
421
+ const handle = this.timers.get(sessionID);
422
+ if (handle === undefined)
423
+ return;
424
+ this.cancelTimer(handle);
425
+ this.timers.delete(sessionID);
426
+ }
427
+ async recheck(sessionID) {
428
+ await this.withLock(sessionID, async () => {
429
+ const state = this.states.get(sessionID);
430
+ if (this.disposed || !state || state.paused || state.items.length === 0 || state.delivering)
431
+ return;
432
+ if (await this.safeBusy(sessionID)) {
433
+ this.scheduleRecheck(sessionID);
434
+ return;
435
+ }
436
+ if (await this.hasRelevantJobs(sessionID)) {
437
+ this.scheduleRecheck(sessionID);
438
+ return;
439
+ }
440
+ const background = state.background;
441
+ if (background) {
442
+ for (const work of this.relevantBackground(state, background)) {
443
+ if (work.sessionID === sessionID) {
444
+ // Own work wakes this Session and re-runs the idle hook. A recheck must not
445
+ // deliver ahead of that wake while the snapshot still lists it.
446
+ if (await this.jobRunning(work)) {
447
+ this.scheduleRecheck(sessionID);
448
+ return;
449
+ }
450
+ continue;
451
+ }
452
+ const owner = this.states.get(work.sessionID);
453
+ if (owner?.background === undefined || owner.background.length > 0) {
454
+ this.scheduleRecheck(sessionID);
455
+ return;
456
+ }
457
+ if (await this.safeBusy(work.sessionID)) {
458
+ this.scheduleRecheck(sessionID);
459
+ return;
460
+ }
461
+ }
462
+ }
463
+ // No idle hook has run for this Session yet. If no watched job is running and
464
+ // the Session is idle, the recheck is the confirmation and delivery can proceed.
465
+ await this.deliverLocked(state, state.items[0]);
466
+ });
467
+ }
468
+ async hasRelevantJobs(sessionID) {
469
+ for (const job of this.jobs.values()) {
470
+ if (job.status !== "running" || !this.waitKinds.has(job.kind))
471
+ continue;
472
+ if (job.sessionID === sessionID)
473
+ return true;
474
+ if (!this.options.waitDescendants)
475
+ continue;
476
+ if (await this.isDescendant(job.sessionID, sessionID))
477
+ return true;
478
+ if (job.childSessionID && (await this.isDescendant(job.childSessionID, sessionID)))
479
+ return true;
480
+ }
481
+ return false;
482
+ }
483
+ async jobRunning(work) {
484
+ for (const job of this.jobs.values()) {
485
+ if (job.status !== "running" || job.kind !== work.kind)
486
+ continue;
487
+ if (work.kind === "shell" && job.shellID === work.shellID)
488
+ return true;
489
+ if (work.kind === "subagent" && job.childSessionID === work.childSessionID)
490
+ return true;
491
+ if ((work.kind === "image" || work.kind === "video") && job.path === work.path)
492
+ return true;
493
+ if (work.kind === "codemode" && job.id === work.jobID)
494
+ return true;
495
+ }
496
+ return false;
497
+ }
498
+ async backgroundBlocks(state) {
499
+ if (!state.background)
500
+ return false;
501
+ for (const work of this.relevantBackground(state, state.background)) {
502
+ if (work.sessionID === state.sessionID)
503
+ return true;
504
+ const owner = this.states.get(work.sessionID);
505
+ if (owner?.background === undefined || owner.background.length > 0)
506
+ return true;
507
+ if (await this.safeBusy(work.sessionID))
508
+ return true;
509
+ }
510
+ return false;
511
+ }
512
+ async isDescendant(owner, ancestor) {
513
+ if (owner === ancestor)
514
+ return true;
515
+ const seen = new Set();
516
+ let current = owner;
517
+ while (current !== undefined && !seen.has(current)) {
518
+ if (current === ancestor)
519
+ return true;
520
+ seen.add(current);
521
+ const cached = this.parents.get(current);
522
+ if (cached !== undefined) {
523
+ current = cached ?? undefined;
524
+ continue;
525
+ }
526
+ try {
527
+ const parent = await this.options.parentOf(current);
528
+ this.parents.set(current, parent ?? null);
529
+ current = parent;
530
+ }
531
+ catch (error) {
532
+ this.options.onError(error, owner);
533
+ return false;
534
+ }
535
+ }
536
+ return false;
537
+ }
538
+ async safeBusy(sessionID) {
539
+ try {
540
+ return await this.options.isBusy(sessionID);
541
+ }
542
+ catch (error) {
543
+ this.options.onError(error, sessionID);
544
+ return true;
545
+ }
546
+ }
547
+ async changed(state) {
548
+ const persisted = {
549
+ version: 1,
550
+ boot: state.boot,
551
+ paused: state.paused,
552
+ ...(state.pauseReason === undefined ? {} : { pauseReason: state.pauseReason }),
553
+ items: state.items.map((item) => ({ ...item })),
554
+ updatedAt: state.updatedAt,
555
+ };
556
+ try {
557
+ await this.options.save(state.sessionID, persisted);
558
+ }
559
+ catch (error) {
560
+ this.options.onError(error, state.sessionID);
561
+ }
562
+ this.options.onChange(this.snapshot(state));
563
+ }
564
+ async withLock(sessionID, run) {
565
+ const previous = this.locks.get(sessionID) ?? Promise.resolve();
566
+ const next = previous.then(run, run);
567
+ this.locks.set(sessionID, next);
568
+ const cleanup = () => {
569
+ if (this.locks.get(sessionID) === next)
570
+ this.locks.delete(sessionID);
571
+ };
572
+ void next.then(cleanup, cleanup);
573
+ return next;
574
+ }
575
+ }
576
+ function messageID(now) {
577
+ const time = now.toString(16).padStart(12, "0");
578
+ const random = crypto.randomUUID().replaceAll("-", "").slice(0, 14);
579
+ return `msg_${time}${random}`;
580
+ }
581
+ function jobLabel(job) {
582
+ if (job.kind === "shell")
583
+ return job.command;
584
+ if (job.kind === "subagent")
585
+ return job.description ?? job.title;
586
+ if (job.kind === "image" || job.kind === "video")
587
+ return job.path;
588
+ if (job.kind === "codemode")
589
+ return "Code Mode script";
590
+ return job.title;
591
+ }