handmux 0.35.0 → 0.36.0

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 (77) hide show
  1. package/dist/build-meta.json +3 -3
  2. package/dist/package.json +7 -7
  3. package/dist/public/assets/{abnfDiagram-O67JEVCF-DslFDZId.js → abnfDiagram-O67JEVCF-77h2IIrd.js} +1 -1
  4. package/dist/public/assets/{arc-VHB0ANPU.js → arc-B1uiT5Hv.js} +1 -1
  5. package/dist/public/assets/{architectureDiagram-NJMV4G6O-CJcCA-5Z.js → architectureDiagram-NJMV4G6O-CIzN4Www.js} +1 -1
  6. package/dist/public/assets/{blockDiagram-BEXU5L5S-B01qZyZi.js → blockDiagram-BEXU5L5S-CFLMQR49.js} +1 -1
  7. package/dist/public/assets/{c4Diagram-YGBWAQC7-B3e2jVdt.js → c4Diagram-YGBWAQC7-De2rKPDq.js} +1 -1
  8. package/dist/public/assets/channel-DaUmhuF_.js +1 -0
  9. package/dist/public/assets/{chunk-2Q5K7J3B-CES4ihJ2.js → chunk-2Q5K7J3B-CLFF4J1f.js} +1 -1
  10. package/dist/public/assets/{chunk-3FUC2YCW-Dma2vRtQ.js → chunk-3FUC2YCW-QQVae1fu.js} +2 -2
  11. package/dist/public/assets/{chunk-5VM5RSS4-BlpNsgH-.js → chunk-5VM5RSS4-B5UjIFDk.js} +1 -1
  12. package/dist/public/assets/{chunk-GTNCS2PH-C2DhT6XM.js → chunk-GTNCS2PH-DcdDMr9j.js} +1 -1
  13. package/dist/public/assets/{chunk-GWA4HPMP-ye3iQ-a9.js → chunk-GWA4HPMP-CssmLYDR.js} +1 -1
  14. package/dist/public/assets/{chunk-JWPE2WC7-Cpju1Ogm.js → chunk-JWPE2WC7-BizFpeWo.js} +1 -1
  15. package/dist/public/assets/{chunk-NETBCI7D-oNkGN9hx.js → chunk-NETBCI7D-DWSxWS3y.js} +1 -1
  16. package/dist/public/assets/{chunk-WEXAMYUT-Bz2dLsEF.js → chunk-WEXAMYUT-BKN16NsC.js} +1 -1
  17. package/dist/public/assets/{chunk-XXDRQBXY-CfnAOHJH.js → chunk-XXDRQBXY-By-Uw-Aj.js} +1 -1
  18. package/dist/public/assets/{classDiagram-v2-NBCMYWYE-CtEVnXTP.js → classDiagram-v2-NBCMYWYE-DqoFIYb9.js} +1 -1
  19. package/dist/public/assets/{cose-bilkent-JH36ORCC-CZI_xbWv.js → cose-bilkent-JH36ORCC-HmH4VsKR.js} +1 -1
  20. package/dist/public/assets/{cynefin-OW5HDTMX-jKUkt7bh.js → cynefin-OW5HDTMX-DYD9YRjp.js} +1 -1
  21. package/dist/public/assets/{cynefinDiagram-VND7K2PF-DpOr06tv.js → cynefinDiagram-VND7K2PF-C9RjJJ0d.js} +1 -1
  22. package/dist/public/assets/{dagre-6A5THRUB-Cp42nnjs.js → dagre-6A5THRUB-COdxco8b.js} +1 -1
  23. package/dist/public/assets/{diagram-22UHCM2B-B4vh59kK.js → diagram-22UHCM2B-BV5ehlp3.js} +1 -1
  24. package/dist/public/assets/{diagram-3UASUU5V-BrySHBW5.js → diagram-3UASUU5V-CEc6OJqR.js} +1 -1
  25. package/dist/public/assets/{diagram-ATOU4E4O-CRDLRjJK.js → diagram-ATOU4E4O-DOhyTrVD.js} +1 -1
  26. package/dist/public/assets/{diagram-CDSNMT55-D_zXyS0J.js → diagram-CDSNMT55-C8NBEqvd.js} +1 -1
  27. package/dist/public/assets/{diagram-MLGK6HIB-D9Q6Ol7F.js → diagram-MLGK6HIB-CWaQF3Ld.js} +1 -1
  28. package/dist/public/assets/{diagram-MPIPVDR6-D_L7q2cj.js → diagram-MPIPVDR6-D6hkQ7gd.js} +1 -1
  29. package/dist/public/assets/{ebnfDiagram-ZINNZB2B-C9AymNC4.js → ebnfDiagram-ZINNZB2B-sLsnAmFD.js} +1 -1
  30. package/dist/public/assets/{elk-276RUBZZ-qj6gPVW5.js → elk-276RUBZZ-DVtwkYol.js} +1 -1
  31. package/dist/public/assets/{erDiagram-OPXOYQCR-DXHbm2-3.js → erDiagram-OPXOYQCR-xdeqkZd4.js} +1 -1
  32. package/dist/public/assets/{flowDiagram-KWPJA3E3-CytiY7My.js → flowDiagram-KWPJA3E3-CZl1CKuP.js} +1 -1
  33. package/dist/public/assets/{ganttDiagram-FUAMR5RP-XIXk3178.js → ganttDiagram-FUAMR5RP-DnkdTY3-.js} +1 -1
  34. package/dist/public/assets/{gitGraphDiagram-X574FWY7-2-Iaumi6.js → gitGraphDiagram-X574FWY7-DQNG42Tn.js} +1 -1
  35. package/dist/public/assets/index-BOQmZzyT.js +363 -0
  36. package/dist/public/assets/index-DPZqWW1u.css +32 -0
  37. package/dist/public/assets/{infoDiagram-VRGFBTTK-rDrzVo_U.js → infoDiagram-VRGFBTTK-BeYpU1R5.js} +1 -1
  38. package/dist/public/assets/{ishikawaDiagram-OU5B5YK6-D59KH_M6.js → ishikawaDiagram-OU5B5YK6-mEgC8PlA.js} +1 -1
  39. package/dist/public/assets/{journeyDiagram-ZHPQQLJL-15Csh4-7.js → journeyDiagram-ZHPQQLJL-C5mSuQmo.js} +1 -1
  40. package/dist/public/assets/{kanban-definition-PNTS6WVX-DJt5zKPb.js → kanban-definition-PNTS6WVX-A1k2Vl-J.js} +1 -1
  41. package/dist/public/assets/{linear-C_7B3tLp.js → linear-DSYqxhOx.js} +1 -1
  42. package/dist/public/assets/{mermaid.core-CUCURRF9.js → mermaid.core-Bl8C4fSx.js} +4 -4
  43. package/dist/public/assets/{mindmap-definition-NLK3R4M7-DgHHfDE2.js → mindmap-definition-NLK3R4M7-F2PHGXa5.js} +1 -1
  44. package/dist/public/assets/{pegDiagram-GJSIUBJH-Co8vXpQN.js → pegDiagram-GJSIUBJH-lS3dgdwe.js} +1 -1
  45. package/dist/public/assets/{pieDiagram-5QR66LMP-D2-jPmQz.js → pieDiagram-5QR66LMP-DjyOARJR.js} +1 -1
  46. package/dist/public/assets/{quadrantDiagram-O4NWA36T-C01SNg0F.js → quadrantDiagram-O4NWA36T-Drm_KOLr.js} +1 -1
  47. package/dist/public/assets/{railroadDiagram-XR7U4H2S-CpOHUJjS.js → railroadDiagram-XR7U4H2S-D7snifLU.js} +1 -1
  48. package/dist/public/assets/{requirementDiagram-PLB6GJNP-MnTTEaJ8.js → requirementDiagram-PLB6GJNP-C-7BjXZm.js} +1 -1
  49. package/dist/public/assets/{sankeyDiagram-IPEJSGJF-Drj8CpKl.js → sankeyDiagram-IPEJSGJF-DUE0QpYN.js} +1 -1
  50. package/dist/public/assets/{sequenceDiagram-PO4LG4MO-BKIZBej_.js → sequenceDiagram-PO4LG4MO--fgXhSUK.js} +1 -1
  51. package/dist/public/assets/{sizeCapture-INFHLROL-CA7QSTT6.js → sizeCapture-INFHLROL-J042wM-E.js} +1 -1
  52. package/dist/public/assets/{stateDiagram-v2-GCMORJYK-B5YaO32m.js → stateDiagram-v2-GCMORJYK-DBEgADBU.js} +1 -1
  53. package/dist/public/assets/{swimlanes-2SLR337P-Dp--9D-W.js → swimlanes-2SLR337P-n1MMMryz.js} +1 -1
  54. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-BxouFZW9.js +8 -0
  55. package/dist/public/assets/{timeline-definition-EJHVYXUP-DxFkKZze.js → timeline-definition-EJHVYXUP-Ch4oAOvy.js} +1 -1
  56. package/dist/public/assets/{usecaseDiagram-POWQR4AR-wUt5OSw0.js → usecaseDiagram-POWQR4AR-DFs_6tJM.js} +1 -1
  57. package/dist/public/assets/{vennDiagram-UO4OBE2U-DrXq2XMh.js → vennDiagram-UO4OBE2U-cJ5Rpp6V.js} +1 -1
  58. package/dist/public/assets/{wardleyDiagram-VNRHLVJA-DWqL4bqf.js → wardleyDiagram-VNRHLVJA-CFe6IjhY.js} +1 -1
  59. package/dist/public/assets/{xychartDiagram-PMCCYNJV-BkZqHOc6.js → xychartDiagram-PMCCYNJV-DVqkUPUP.js} +1 -1
  60. package/dist/public/index.html +2 -2
  61. package/dist/src/agent-runtime/conversation.js +20 -1
  62. package/dist/src/agent-runtime/conversationValidation.js +8 -1
  63. package/dist/src/agent-runtime/runtime.js +105 -0
  64. package/dist/src/agent-runtime/scheduledMessages.js +549 -0
  65. package/dist/src/agents/codexConversation.js +4 -2
  66. package/dist/src/agents/codexUsageLimitRecovery.js +97 -0
  67. package/dist/src/cli/authCmd.js +1 -1
  68. package/dist/src/cli/i18n/en.js +1 -0
  69. package/dist/src/cli/i18n/zh.js +1 -0
  70. package/dist/src/codexTranscriptParse.js +3 -0
  71. package/dist/src/deviceAuth/service.js +2 -2
  72. package/dist/src/routes/agents.js +46 -0
  73. package/package.json +3 -3
  74. package/dist/public/assets/channel-YqF13omZ.js +0 -1
  75. package/dist/public/assets/index-B02FNbyq.css +0 -32
  76. package/dist/public/assets/index-BQp0V5lU.js +0 -363
  77. package/dist/public/assets/swimlanesDiagram-TC7HE7FX-Du4bBHEh.js +0 -8
@@ -0,0 +1,549 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ // Apply the rolling limit only when accepting a rule, never while loading persisted tasks.
5
+ function validateCutoffLimit(rule, now) {
6
+ if (rule.frequency !== 'once' && Date.parse(rule.endsAt) > now + 365 * 86400000)
7
+ throw new ScheduledError('Choose an end time within the next 365 days');
8
+ }
9
+ function requiredScope(scope) {
10
+ if (!scope || typeof scope.tmuxSession !== 'string' || !scope.tmuxSession.trim() || typeof scope.paneId !== 'string' || !scope.paneId.trim())
11
+ throw new ScheduledError('Choose a tmux session and pane');
12
+ return scope;
13
+ }
14
+ function inScope(target, scope) { return target.tmuxSession === scope.tmuxSession && target.paneId === scope.paneId; }
15
+ export class MemoryScheduledStore {
16
+ value;
17
+ load() { return structuredClone(this.value); }
18
+ save(state) { this.value = structuredClone(state); }
19
+ }
20
+ export class FileScheduledStore {
21
+ file;
22
+ constructor(file) {
23
+ this.file = file;
24
+ }
25
+ load() { try {
26
+ return JSON.parse(fs.readFileSync(this.file, 'utf8'));
27
+ }
28
+ catch (e) {
29
+ if (e.code === 'ENOENT')
30
+ return undefined;
31
+ throw e;
32
+ } }
33
+ save(state) {
34
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
35
+ const temporary = `${this.file}.${randomUUID()}.tmp`;
36
+ try {
37
+ fs.writeFileSync(temporary, JSON.stringify(state), { mode: 0o600, flag: 'wx', flush: true });
38
+ fs.renameSync(temporary, this.file);
39
+ }
40
+ finally {
41
+ fs.rmSync(temporary, { force: true });
42
+ }
43
+ }
44
+ }
45
+ export class ScheduledError extends Error {
46
+ code;
47
+ constructor(message, code = 'invalid_request') {
48
+ super(message);
49
+ this.code = code;
50
+ }
51
+ }
52
+ function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
53
+ function invalid() { throw new ScheduledError('Invalid scheduled message rule'); }
54
+ const formatters = new Map();
55
+ function parts(at, zone) {
56
+ let formatter = formatters.get(zone);
57
+ if (!formatter) {
58
+ formatter = new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
59
+ formatters.set(zone, formatter);
60
+ }
61
+ const p = Object.fromEntries(formatter.formatToParts(at).map(({ type, value }) => [type, value]));
62
+ const date = `${p.year}-${p.month}-${p.day}`;
63
+ const time = `${p.hour}:${p.minute}`;
64
+ const wall = Date.parse(`${date}T${time}:00Z`);
65
+ return { date, time, minute: Number(p.minute), weekday: new Date(`${date}T00:00:00Z`).getUTCDay(), wall };
66
+ }
67
+ function instants(date, time, zone) {
68
+ const wall = Date.parse(`${date}T${time}:00Z`);
69
+ const offsets = new Set([-86400000, 0, 86400000].map((delta) => {
70
+ const sample = wall + delta;
71
+ return parts(sample, zone).wall - sample;
72
+ }));
73
+ const candidates = [...offsets].map((offset) => wall - offset);
74
+ const exact = candidates.filter((at) => { const p = parts(at, zone); return p.date === date && p.time === time; }).sort((a, b) => a - b);
75
+ if (exact.length)
76
+ return exact.slice(0, 1);
77
+ // Spring-forward gap: preserve the intended minute by moving forward by the offset change.
78
+ return candidates.filter((at) => { const p = parts(at, zone); return p.date === date && p.wall > wall; }).sort((a, b) => a - b).slice(0, 1);
79
+ }
80
+ export function validateRule(raw, zone) {
81
+ try {
82
+ parts(Date.now(), zone);
83
+ }
84
+ catch {
85
+ invalid();
86
+ }
87
+ const value = object(raw);
88
+ if (!Array.isArray(value.slots) || !value.slots.length || value.slots.length > 64)
89
+ invalid();
90
+ if (typeof value.endsAtLocal === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value.endsAtLocal)) {
91
+ const [date, time] = value.endsAtLocal.split('T');
92
+ const at = instants(date, time, zone)[0];
93
+ if (at !== undefined)
94
+ value.endsAt = new Date(at).toISOString();
95
+ }
96
+ const frequency = value.frequency;
97
+ if (!['once', 'hourly', 'daily', 'weekly'].includes(String(frequency)))
98
+ invalid();
99
+ const slots = value.slots.map((rawSlot) => {
100
+ const slot = object(rawSlot);
101
+ if (frequency === 'hourly') {
102
+ if (!Number.isInteger(slot.minute) || Number(slot.minute) < 0 || Number(slot.minute) > 59)
103
+ invalid();
104
+ return { minute: slot.minute };
105
+ }
106
+ if (typeof slot.time !== 'string' || !/^([01]\d|2[0-3]):[0-5]\d$/.test(slot.time))
107
+ invalid();
108
+ if (frequency === 'once') {
109
+ if (typeof slot.date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(slot.date) || !Number.isFinite(Date.parse(`${slot.date}T00:00:00Z`)) || new Date(`${slot.date}T00:00:00Z`).toISOString().slice(0, 10) !== slot.date || !instants(slot.date, slot.time, zone).length)
110
+ invalid();
111
+ return { date: slot.date, time: slot.time };
112
+ }
113
+ if (frequency === 'weekly') {
114
+ if (!Number.isInteger(slot.weekday) || Number(slot.weekday) < 1 || Number(slot.weekday) > 7)
115
+ invalid();
116
+ return { weekday: slot.weekday, time: slot.time };
117
+ }
118
+ return { time: slot.time };
119
+ });
120
+ if (new Set(slots.map((slot) => JSON.stringify(slot))).size !== slots.length)
121
+ invalid();
122
+ if (frequency !== 'once' && (typeof value.endsAt !== 'string' || !/Z$|[+-]\d\d:\d\d$/.test(value.endsAt) || !Number.isFinite(Date.parse(value.endsAt))))
123
+ invalid();
124
+ return { frequency, slots, ...(frequency === 'once' ? {} : { endsAt: new Date(value.endsAt).toISOString() }) };
125
+ }
126
+ /** Calendar based local slots; DST gaps move forward, repeated wall times fire once (earliest instant). */
127
+ export function nextOccurrence(rule, zone, after) {
128
+ const cutoff = rule.frequency === 'once' ? Infinity : Date.parse(rule.endsAt);
129
+ if (after >= cutoff)
130
+ return null;
131
+ let candidates = [];
132
+ if (rule.frequency === 'once')
133
+ candidates = rule.slots.flatMap((slot) => instants(slot.date, slot.time, zone));
134
+ else if (rule.frequency === 'hourly') {
135
+ for (let at = Math.floor(after / 60000) * 60000 + 60000; at < cutoff && at <= after + 3 * 3600000; at += 60000) {
136
+ const p = parts(at, zone);
137
+ if (rule.slots.some((slot) => slot.minute === p.minute) && instants(p.date, p.time, zone)[0] === at)
138
+ return at;
139
+ }
140
+ }
141
+ else {
142
+ const date = parts(after, zone).date;
143
+ for (let day = 0; day < 9; day++) {
144
+ const localDate = new Date(Date.parse(`${date}T00:00:00Z`) + day * 86400000).toISOString().slice(0, 10);
145
+ const weekday = new Date(`${localDate}T00:00:00Z`).getUTCDay() || 7;
146
+ candidates.push(...rule.slots.filter((slot) => rule.frequency !== 'weekly' || ('weekday' in slot && slot.weekday === weekday)).flatMap((slot) => instants(localDate, slot.time, zone)));
147
+ }
148
+ }
149
+ return candidates.filter((at) => at > after && at < cutoff).sort((a, b) => a - b)[0] ?? null;
150
+ }
151
+ export class ScheduledMessagesService {
152
+ #state;
153
+ #running;
154
+ #closed = false;
155
+ #manual = new Set();
156
+ #store;
157
+ #now;
158
+ timeZone;
159
+ #reconcile;
160
+ #deliver;
161
+ constructor(options) {
162
+ this.#store = options.store;
163
+ this.#now = options.now ?? Date.now;
164
+ this.timeZone = options.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
165
+ this.#deliver = options.deliver;
166
+ this.#reconcile = options.reconcile;
167
+ const loaded = options.store.load();
168
+ const parsed = object(loaded);
169
+ if (loaded !== undefined && (parsed.version !== 1 || !Array.isArray(parsed.tasks) || !Array.isArray(parsed.exceptions)))
170
+ throw new Error('Corrupt scheduled message state');
171
+ this.#state = loaded === undefined ? { version: 1, tasks: [], exceptions: [] } : loaded;
172
+ for (const task of this.#state.tasks) {
173
+ validateRule(task.rule, task.timeZone);
174
+ if (!task.id || !task.target?.sessionId || !task.target.tmuxSession || typeof task.text !== 'string' || !Number.isFinite(task.cursor) || !Number.isSafeInteger(task.revision))
175
+ throw new Error('Corrupt scheduled message task');
176
+ if (task.endedReason !== undefined && (task.endedReason !== 'terminated' || task.state !== 'ended' || task.enabled || task.nextAt !== null || !Number.isFinite(task.endedAt)))
177
+ throw new Error('Corrupt scheduled message termination');
178
+ if (task.claim) {
179
+ this.#exception(task, task.claim.at, 'delivery_unconfirmed', true, task.claim.text);
180
+ task.blocked = true;
181
+ task.blockedAt = task.claim.at;
182
+ task.lastAt = task.claim.at;
183
+ task.lastResult = 'delivery_unconfirmed';
184
+ if (task.endedReason !== 'terminated' && task.rule.frequency === 'once' && task.nextAt === null)
185
+ task.state = 'exception';
186
+ task.enabled = false;
187
+ delete task.claim;
188
+ }
189
+ }
190
+ if (loaded !== undefined)
191
+ this.#store.save(this.#state);
192
+ }
193
+ activeTargets() { return this.#state.tasks.filter((task) => (task.state === 'active' && task.enabled) || task.blocked).map((task) => structuredClone(task.target)); }
194
+ paneIds() {
195
+ return new Set([...this.#state.tasks.map((task) => task.target.paneId), ...this.#state.exceptions.map((item) => item.target.paneId)]);
196
+ }
197
+ /** Only call with a successful, complete tmux topology; failed reads are not deletion evidence. */
198
+ reconcilePanes(livePaneIds, candidatePaneIds = this.paneIds()) {
199
+ const keep = (target) => !candidatePaneIds.has(target.paneId) || livePaneIds.has(target.paneId);
200
+ const tasks = this.#state.tasks.filter((task) => keep(task.target));
201
+ const exceptions = this.#state.exceptions.filter((item) => keep(item.target));
202
+ if (tasks.length === this.#state.tasks.length && exceptions.length === this.#state.exceptions.length)
203
+ return;
204
+ this.#transaction(() => { this.#state.tasks = tasks; this.#state.exceptions = exceptions; });
205
+ }
206
+ snapshot(scope) {
207
+ requiredScope(scope);
208
+ const serverNow = this.#now();
209
+ const tasks = this.#state.tasks.filter(task => inScope(task.target, scope)).map(task => {
210
+ if (task.state !== 'active' || task.enabled)
211
+ return task;
212
+ const future = nextOccurrence(task.rule, task.timeZone, serverNow);
213
+ return { ...task, nextAt: future ?? (task.rule.frequency === 'once' ? task.nextAt : null), expired: task.rule.frequency === 'once' && !task.blocked && future === null };
214
+ });
215
+ return structuredClone({ serverNow, timeZone: this.timeZone, tasks, exceptions: this.#state.exceptions.filter(item => inScope(item.target, scope)) });
216
+ }
217
+ preview(raw, zone = this.timeZone) { const now = this.#now(); const rule = validateRule(raw, zone); validateCutoffLimit(rule, now); return { serverNow: now, timeZone: zone, nextAt: nextOccurrence(rule, zone, now) }; }
218
+ #transaction(operation) { const before = structuredClone(this.#state); try {
219
+ const result = operation();
220
+ this.#store.save(this.#state);
221
+ return structuredClone(result);
222
+ }
223
+ catch (error) {
224
+ this.#state = before;
225
+ throw error;
226
+ } }
227
+ #newTask(target, raw, zone = this.timeZone) {
228
+ const value = object(raw);
229
+ const rule = validateRule(value, zone);
230
+ if (typeof value.text !== 'string' || !value.text.trim() || value.text.length > 256 * 1024)
231
+ throw new ScheduledError('Message text is required');
232
+ const now = this.#now();
233
+ validateCutoffLimit(rule, now);
234
+ const nextAt = nextOccurrence(rule, zone, now);
235
+ if (nextAt === null)
236
+ throw new ScheduledError('Choose a future scheduled time and cutoff');
237
+ const task = { id: randomUUID(), revision: 1, target: structuredClone(target), text: value.text.trim(), rule, timeZone: zone, enabled: true, state: 'active', createdAt: now, cursor: now, nextAt };
238
+ this.#state.tasks.push(task);
239
+ return task;
240
+ }
241
+ create(target, raw) { return this.#transaction(() => this.#newTask(target, raw)); }
242
+ #task(scope, id, revision) { requiredScope(scope); const task = this.#state.tasks.find((item) => item.id === id && inScope(item.target, scope)); if (!task)
243
+ throw new ScheduledError('Scheduled message no longer exists', 'not_found'); if (task.revision !== revision)
244
+ throw new ScheduledError('Changed on another client. Reload the list.', 'conflict'); return task; }
245
+ update(scope, id, revision, raw) {
246
+ return this.#transaction(() => {
247
+ const task = this.#task(scope, id, revision);
248
+ const value = object(raw);
249
+ const now = this.#now();
250
+ if (task.state !== 'active' || task.claim)
251
+ throw new ScheduledError('This occurrence is being submitted or has ended', 'conflict');
252
+ if (value.frequency !== undefined) {
253
+ task.rule = validateRule(value, task.timeZone);
254
+ validateCutoffLimit(task.rule, now);
255
+ task.cursor = now;
256
+ task.nextAt = nextOccurrence(task.rule, task.timeZone, task.cursor);
257
+ if (task.nextAt === null)
258
+ throw new ScheduledError('Choose a future scheduled time and cutoff');
259
+ }
260
+ if (value.text !== undefined) {
261
+ if (typeof value.text !== 'string' || !value.text.trim() || value.text.length > 256 * 1024)
262
+ throw new ScheduledError('Message text is required');
263
+ task.text = value.text.trim();
264
+ }
265
+ if (value.enabled !== undefined) {
266
+ if (typeof value.enabled !== 'boolean')
267
+ invalid();
268
+ if (task.blocked && value.enabled)
269
+ throw new ScheduledError('Resolve uncertain delivery in Queue before creating another schedule', 'conflict');
270
+ if (value.enabled && !task.enabled) {
271
+ task.cursor = now;
272
+ task.nextAt = nextOccurrence(task.rule, task.timeZone, task.cursor);
273
+ if (task.nextAt === null && task.rule.frequency === 'once')
274
+ throw new ScheduledError('This scheduled message has expired. Edit it to choose a future time before resuming.', 'conflict');
275
+ if (task.nextAt === null && task.rule.frequency !== 'once' && now >= Date.parse(task.rule.endsAt)) {
276
+ task.state = 'ended';
277
+ task.endedAt = now;
278
+ }
279
+ }
280
+ task.enabled = value.enabled;
281
+ }
282
+ task.revision++;
283
+ return task;
284
+ });
285
+ }
286
+ terminate(scope, id, revision) {
287
+ return this.#transaction(() => {
288
+ const task = this.#task(scope, id, revision);
289
+ if (task.state !== 'active' || task.claim)
290
+ throw new ScheduledError('This occurrence is being submitted or has ended. Reload the list.', 'conflict');
291
+ task.state = 'ended';
292
+ task.endedReason = 'terminated';
293
+ task.endedAt = this.#now();
294
+ task.enabled = false;
295
+ task.nextAt = null;
296
+ task.revision++;
297
+ return task;
298
+ });
299
+ }
300
+ trigger(scope, id, revision) {
301
+ const operation = (async () => {
302
+ if (this.#closed)
303
+ throw new ScheduledError('Scheduled messages are stopping', 'conflict');
304
+ const task = this.#transaction(() => {
305
+ const task = this.#task(scope, id, revision);
306
+ if (task.state !== 'active' || task.claim || task.blocked)
307
+ throw new ScheduledError('This task is submitting, uncertain or has ended. Reload the list.', 'conflict');
308
+ const at = Math.max(this.#now(), (task.manualCursor ?? -Infinity) + 1);
309
+ task.manualCursor = at;
310
+ task.immediateAt = at;
311
+ task.lastAt = at;
312
+ task.claim = { at, text: task.text, target: structuredClone(task.target) };
313
+ task.revision++;
314
+ return task;
315
+ });
316
+ const receipt = await this.#submitClaim(task);
317
+ if (!receipt || !['queued', 'accepted'].includes(receipt.status))
318
+ throw new ScheduledError(receipt?.status === 'unknown' ? 'Delivery is uncertain. Check conversation and Queue before trying again.'
319
+ : receipt?.reason === 'queue_full' ? 'Queue is full. Free a slot and try again.'
320
+ : receipt?.reason === 'target_changed' ? 'The target session changed. Check the conversation before trying again.'
321
+ : 'Message was not submitted. Check the conversation and try again.', 'conflict');
322
+ return { status: 'submitted' };
323
+ })();
324
+ this.#manual.add(operation);
325
+ void operation.finally(() => { this.#manual.delete(operation); }).catch(() => { });
326
+ return operation;
327
+ }
328
+ remove(scope, id, revision) { return this.#transaction(() => { const task = this.#task(scope, id, revision); this.#state.tasks = this.#state.tasks.filter((item) => item !== task); return { ok: true }; }); }
329
+ resolveException(scope, id, revision, raw) {
330
+ requiredScope(scope);
331
+ return this.#transaction(() => {
332
+ const item = this.#state.exceptions.find((candidate) => candidate.id === id && inScope(candidate.target, scope));
333
+ if (!item || item.revision !== revision)
334
+ throw new ScheduledError('Exception already changed. Reload the list.', 'conflict');
335
+ const value = object(raw);
336
+ if (value.action === 'reschedule') {
337
+ if (item.unknown)
338
+ throw new ScheduledError('Delivery is uncertain. Check conversation and Queue; automatic resend is disabled.', 'conflict');
339
+ const rule = object(value.rule);
340
+ if (rule.frequency !== 'once')
341
+ invalid();
342
+ this.#newTask(item.target, { ...rule, text: item.text }, item.timeZone);
343
+ }
344
+ else if (value.action !== 'discard')
345
+ invalid();
346
+ this.#state.exceptions = this.#state.exceptions.filter((candidate) => candidate !== item);
347
+ this.#state.tasks = this.#state.tasks.filter((task) => task.id !== item.taskId || task.rule.frequency !== 'once' || task.state !== 'exception' || task.nextAt !== null || task.blocked === true);
348
+ return { ok: true };
349
+ });
350
+ }
351
+ #exception(task, at, reason, unknown = false, text = task.text, count) {
352
+ const id = `${task.id}:${task.immediateAt === at ? 'immediate:' : ''}${at}`;
353
+ if (!this.#state.exceptions.some((item) => item.id === id))
354
+ this.#state.exceptions.push({ id, revision: 1, taskId: task.id, target: structuredClone(task.target), text, timeZone: task.timeZone, scheduledAt: at, reason, unknown, ...(count ? { count } : {}) });
355
+ }
356
+ tick() { if (this.#closed)
357
+ return Promise.resolve(); if (this.#running)
358
+ return this.#running; const operation = this.#tick(); this.#running = operation; return operation.finally(() => { if (this.#running === operation)
359
+ this.#running = undefined; }); }
360
+ async close() { this.#closed = true; await Promise.allSettled([this.#running, ...this.#manual]); }
361
+ async #tick() {
362
+ for (const id of this.#state.tasks.map((task) => task.id)) {
363
+ if (this.#closed)
364
+ return;
365
+ const existing = this.#state.tasks.find((item) => item.id === id);
366
+ if (!existing)
367
+ continue;
368
+ let task = existing;
369
+ if (task.blocked && task.blockedAt !== undefined && this.#reconcile) {
370
+ const exceptionId = `${task.id}:${task.immediateAt === task.blockedAt ? 'immediate:' : ''}${task.blockedAt}`;
371
+ let receipt = null;
372
+ try {
373
+ receipt = await this.#reconcile(task.target, `scheduled:${exceptionId}`);
374
+ }
375
+ catch { /* uncertainty remains visible */ }
376
+ // A concurrent failed transaction can replace the state while reconciliation awaits.
377
+ const current = this.#state.tasks.find((item) => item.id === id);
378
+ if (current)
379
+ task = current;
380
+ if (receipt && ['accepted', 'queued'].includes(receipt.status)) {
381
+ this.#transaction(() => {
382
+ this.#state.exceptions = this.#state.exceptions.filter((item) => item.id !== exceptionId);
383
+ if (!current)
384
+ return;
385
+ const manual = task.immediateAt === task.blockedAt;
386
+ delete task.blocked;
387
+ delete task.blockedAt;
388
+ task.lastResult = 'submitted';
389
+ if (task.endedReason !== 'terminated' && task.rule.frequency === 'once')
390
+ task.state = task.nextAt !== null ? 'active' : this.#state.exceptions.some((item) => item.taskId === task.id) ? 'exception' : 'ended';
391
+ if (task.endedReason !== 'terminated' && manual && task.rule.frequency === 'once') {
392
+ task.state = 'ended';
393
+ task.nextAt = null;
394
+ task.endedAt = this.#now();
395
+ }
396
+ delete task.immediateAt;
397
+ task.revision++;
398
+ });
399
+ }
400
+ if (!current)
401
+ continue;
402
+ }
403
+ // Older versions could persist the cutoff itself as the next occurrence. It is not a missed send.
404
+ if (task.state === 'active' && !task.claim && task.rule.frequency !== 'once' && task.nextAt !== null && task.nextAt >= Date.parse(task.rule.endsAt)) {
405
+ this.#transaction(() => { task.nextAt = null; task.revision++; });
406
+ }
407
+ if (task.state === 'active' && task.rule.frequency !== 'once' && this.#now() >= Date.parse(task.rule.endsAt) && (!task.enabled || task.nextAt === null)) {
408
+ this.#transaction(() => { task.state = 'ended'; task.nextAt = null; task.endedAt = this.#now(); task.revision++; });
409
+ }
410
+ if (task.state !== 'active' || !task.enabled || task.claim || task.nextAt === null)
411
+ continue;
412
+ const now = this.#now();
413
+ if (task.nextAt > now)
414
+ continue;
415
+ if (task.rule.frequency === 'once') {
416
+ // Each absolute slot is independent: a recovery window may contain several intentional sends.
417
+ while (this.#state.tasks.includes(task) && task.nextAt !== null && task.nextAt <= now && task.enabled && !task.blocked) {
418
+ const scheduledAt = task.nextAt;
419
+ this.#transaction(() => {
420
+ task.cursor = scheduledAt;
421
+ task.lastAt = scheduledAt;
422
+ task.nextAt = nextOccurrence(task.rule, task.timeZone, scheduledAt);
423
+ task.revision++;
424
+ if (now - scheduledAt > 600000) {
425
+ this.#exception(task, scheduledAt, 'missed');
426
+ task.lastResult = 'missed';
427
+ }
428
+ else
429
+ task.claim = { at: scheduledAt, text: task.text, target: structuredClone(task.target) };
430
+ });
431
+ if (task.claim)
432
+ await this.#submitClaim(task);
433
+ // Delivery may overlap a rollback or deletion; only finalize the current stored task.
434
+ const current = this.#state.tasks.find((item) => item.id === id);
435
+ if (!current)
436
+ break;
437
+ task = current;
438
+ this.#transaction(() => {
439
+ if (task.endedReason === 'terminated')
440
+ return;
441
+ if (task.nextAt !== null)
442
+ task.state = 'active';
443
+ else {
444
+ task.state = this.#state.exceptions.some((item) => item.taskId === task.id) ? 'exception' : 'ended';
445
+ task.endedAt = this.#now();
446
+ }
447
+ });
448
+ }
449
+ continue;
450
+ }
451
+ const due = [];
452
+ let at = task.nextAt;
453
+ let range;
454
+ while (at !== null && at <= now) {
455
+ due.push(at);
456
+ const next = nextOccurrence(task.rule, task.timeZone, at);
457
+ if (due.length >= 256 && next !== null && next <= now - 600000) {
458
+ range = { from: task.nextAt, through: now - 600001 };
459
+ due.length = 0;
460
+ at = nextOccurrence(task.rule, task.timeZone, now - 600001);
461
+ }
462
+ else
463
+ at = next;
464
+ }
465
+ // A long outage may have no eligible recent slot; the range still records all old misses.
466
+ const latest = due.at(-1) ?? range?.through ?? task.nextAt;
467
+ const cutoff = Date.parse(task.rule.endsAt);
468
+ const cutoffPassed = now >= cutoff;
469
+ this.#transaction(() => {
470
+ if (range) {
471
+ this.#exception(task, range.from, 'missed');
472
+ this.#state.exceptions.find((item) => item.id === `${task.id}:${range.from}`).missedThroughAt = range.through;
473
+ }
474
+ for (const missed of due.slice(0, -1))
475
+ this.#exception(task, missed, 'missed');
476
+ task.cursor = latest;
477
+ task.nextAt = at;
478
+ task.lastAt = latest;
479
+ task.revision++;
480
+ if (!due.length || now - latest > 600000 || cutoffPassed) {
481
+ if (due.length)
482
+ this.#exception(task, latest, 'missed');
483
+ task.lastResult = 'missed';
484
+ }
485
+ else {
486
+ task.claim = { at: latest, text: task.text, target: structuredClone(task.target) };
487
+ }
488
+ if (now >= cutoff) {
489
+ task.state = 'ended';
490
+ task.endedAt = now;
491
+ }
492
+ });
493
+ await this.#submitClaim(task);
494
+ }
495
+ }
496
+ async #submitClaim(task) {
497
+ const claim = structuredClone(task.claim);
498
+ if (!claim)
499
+ return;
500
+ const manual = task.immediateAt === claim.at;
501
+ let receipt;
502
+ try {
503
+ let timer;
504
+ try {
505
+ receipt = await Promise.race([this.#deliver(claim.target, claim.text, `scheduled:${task.id}:${manual ? 'immediate:' : ''}${claim.at}`, !manual && task.rule.frequency !== 'once'), new Promise((resolve) => { timer = setTimeout(() => resolve({ status: 'unknown', reason: 'delivery_unconfirmed' }), 25_000); timer.unref?.(); })]);
506
+ }
507
+ finally {
508
+ if (timer)
509
+ clearTimeout(timer);
510
+ }
511
+ }
512
+ catch {
513
+ receipt = { status: 'unknown', reason: 'delivery_unconfirmed' };
514
+ }
515
+ // Core still owns the claimed effect, but a late result must not recreate deleted scheduled data.
516
+ const current = this.#state.tasks.find((item) => item.id === task.id);
517
+ if (!current)
518
+ return receipt;
519
+ this.#transaction(() => {
520
+ task = current;
521
+ const successful = receipt.status === 'accepted' || receipt.status === 'queued';
522
+ const skipped = !manual && task.rule.frequency !== 'once' && ['duplicate_queued', 'queue_full'].includes(receipt.reason ?? '');
523
+ task.lastResult = successful ? 'submitted' : skipped ? receipt.reason : receipt.reason ?? receipt.status;
524
+ if (!successful && !skipped) {
525
+ this.#exception(task, claim.at, receipt.reason ?? receipt.status, receipt.status === 'unknown', claim.text);
526
+ if (task.endedReason !== 'terminated' && task.rule.frequency === 'once' && task.nextAt === null)
527
+ task.state = 'exception';
528
+ }
529
+ if (receipt.status === 'unknown') {
530
+ task.blocked = true;
531
+ task.blockedAt = claim.at;
532
+ task.enabled = false;
533
+ }
534
+ if (receipt.reason === 'target_changed')
535
+ task.enabled = false;
536
+ if (task.endedReason !== 'terminated' && manual && successful && task.rule.frequency === 'once') {
537
+ task.state = 'ended';
538
+ task.enabled = false;
539
+ task.nextAt = null;
540
+ task.endedAt = this.#now();
541
+ }
542
+ if (manual && receipt.status !== 'unknown')
543
+ delete task.immediateAt;
544
+ delete task.claim;
545
+ task.revision++;
546
+ });
547
+ return receipt;
548
+ }
549
+ }
@@ -1,3 +1,4 @@
1
+ import { codexUsageLimitRecovery } from './codexUsageLimitRecovery.js';
1
2
  import { createHash } from 'node:crypto';
2
3
  import { homedir } from 'node:os';
3
4
  import { resolve } from 'node:path';
@@ -361,7 +362,7 @@ function projectDurableMessage(message, sessionId, suppressedCompactorItems) {
361
362
  }
362
363
  if (message.type === 'notice' && typeof message.text === 'string') {
363
364
  return [{ ...itemBase(message, sessionId), kind: 'notice', level: message.noticeLevel || 'info',
364
- code: 'provider_error', message: clipConversationText(message.text).text }];
365
+ code: 'provider_error', message: clipConversationText(message.text).text, ...(message.recovery ? { recovery: message.recovery } : {}) }];
365
366
  }
366
367
  if (message.type === 'thinking' && typeof message.text === 'string') {
367
368
  // Codex rollout stores the provider's public reasoning summary, not hidden reasoning content.
@@ -975,8 +976,9 @@ export function createCodexConversationAdapter({ app, sessionsRoot = sessionsDir
975
976
  if (event.type === 'cursorReset' || event.type === 'disconnected' || event.type === 'error') {
976
977
  if (event.type === 'error' && event.message.trim()) {
977
978
  const provisionalId = `codex-stream-error:${sessionId}:${live.sourceSequence + 1}`;
979
+ const recovery = codexUsageLimitRecovery(event, typeof event.timestamp === 'string' ? Date.parse(event.timestamp) : undefined);
978
980
  const draft = {
979
- kind: 'notice', level: 'warning', code: 'provider_error', message: event.message.trim(),
981
+ kind: 'notice', level: 'warning', code: 'provider_error', message: event.message.trim(), ...(recovery ? { recovery } : {}),
980
982
  };
981
983
  await emit({ type: 'item.opened', provisionalId, draft });
982
984
  await emit({ type: 'item.settled', provisionalId,