@clagentic/console 1.10.0 → 1.11.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +14 -1
  2. package/bin/cli.js +38 -16
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/arg-validation.js +50 -0
  11. package/lib/cli/daemon-launch.js +5 -4
  12. package/lib/cli/menus.js +2 -2
  13. package/lib/cli/schedule-input-subcommands.js +327 -0
  14. package/lib/cli/session-subcommands.js +101 -17
  15. package/lib/client-build-id.js +56 -0
  16. package/lib/daemon.js +38 -6
  17. package/lib/identity/index.js +9 -4
  18. package/lib/injected-sender.js +225 -0
  19. package/lib/message-sender-record.js +133 -0
  20. package/lib/pending-prompts.js +55 -0
  21. package/lib/permission-mode-policy.js +63 -0
  22. package/lib/permission-settings.js +96 -0
  23. package/lib/permission-summary.js +67 -0
  24. package/lib/project-connection.js +10 -11
  25. package/lib/project-external-trigger.js +9 -1
  26. package/lib/project-loop.js +50 -23
  27. package/lib/project-permission-settings.js +59 -0
  28. package/lib/project-prompt-responses.js +25 -15
  29. package/lib/project-sessions.js +164 -60
  30. package/lib/project-user-message.js +18 -47
  31. package/lib/project.js +46 -74
  32. package/lib/public/app.js +4 -7
  33. package/lib/public/css/channel-layout.css +20 -0
  34. package/lib/public/css/diagnostics.css +7 -0
  35. package/lib/public/css/input.css +78 -0
  36. package/lib/public/css/menus.css +17 -0
  37. package/lib/public/css/overlays.css +0 -3
  38. package/lib/public/css/scheduler-modal.css +5 -0
  39. package/lib/public/index.html +44 -8
  40. package/lib/public/modules/app-connection.js +18 -1
  41. package/lib/public/modules/app-loop-ui.js +11 -1
  42. package/lib/public/modules/app-messages.js +23 -30
  43. package/lib/public/modules/app-panels.js +10 -3
  44. package/lib/public/modules/app-rate-limit.js +64 -88
  45. package/lib/public/modules/app-rendering.js +37 -6
  46. package/lib/public/modules/approve-tools-toggle.js +33 -0
  47. package/lib/public/modules/at-agents.js +8 -0
  48. package/lib/public/modules/build-guard.js +61 -0
  49. package/lib/public/modules/build-update-detail.js +1 -4
  50. package/lib/public/modules/diagnostics.js +98 -9
  51. package/lib/public/modules/injected-identity.js +78 -0
  52. package/lib/public/modules/injected-label.js +62 -0
  53. package/lib/public/modules/input.js +64 -114
  54. package/lib/public/modules/loop-hooks-warning.js +20 -0
  55. package/lib/public/modules/mode-options.js +35 -16
  56. package/lib/public/modules/permission-settings.js +56 -0
  57. package/lib/public/modules/project-settings.js +3 -0
  58. package/lib/public/modules/rate-limit-state.js +47 -22
  59. package/lib/public/modules/schedule-panel.js +234 -0
  60. package/lib/public/modules/schedule-time.js +193 -0
  61. package/lib/public/modules/scheduled-input-actions.js +19 -0
  62. package/lib/public/modules/scheduler-config.js +12 -0
  63. package/lib/public/modules/scheduler.js +8 -0
  64. package/lib/public/modules/server-settings.js +5 -9
  65. package/lib/public/modules/settings-defaults.js +18 -4
  66. package/lib/runtime-env.js +4 -0
  67. package/lib/scheduled-input/ipc.js +92 -0
  68. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  69. package/lib/scheduled-input/records.js +350 -0
  70. package/lib/scheduled-input/service.js +743 -0
  71. package/lib/scheduled-input/store.js +132 -0
  72. package/lib/scheduled-input/ws.js +194 -0
  73. package/lib/scheduler.js +4 -0
  74. package/lib/sdk-bridge.js +194 -175
  75. package/lib/sdk-message-processor.js +13 -5
  76. package/lib/sdk-skill-discovery.js +17 -0
  77. package/lib/sender-ref.js +109 -0
  78. package/lib/server.js +37 -11
  79. package/lib/session-directory.js +224 -0
  80. package/lib/session-file-scan.js +55 -0
  81. package/lib/session-input-ipc.js +21 -0
  82. package/lib/session-input.js +396 -23
  83. package/lib/session-name-holder.js +82 -0
  84. package/lib/session-resume.js +3 -0
  85. package/lib/sessions.js +111 -2
  86. package/lib/turn-initiator.js +6 -2
  87. package/lib/updater.js +8 -2
  88. package/lib/ws-schema.js +20 -9
  89. package/lib/yoke/adapters/claude-worker.js +3 -1
  90. package/lib/yoke/adapters/claude.js +13 -17
  91. package/lib/yoke/adapters/codex.js +18 -5
  92. package/lib/yoke/adapters/permission-relay.js +9 -0
  93. package/lib/yoke/interface.js +7 -1
  94. package/package.json +1 -1
  95. package/scripts/check-test-count.js +1 -1
  96. package/scripts/install-local-test.js +45 -1
  97. package/scripts/postinstall.js +1 -0
@@ -0,0 +1,743 @@
1
+ // service.js - scheduled input: text the console sends into a session at a
2
+ // later time, once or on a repeat that always has an end. For people (the clock
3
+ // button) and for agents and scripts (the schedule-input CLI) alike.
4
+ //
5
+ // One service per daemon:
6
+ // - one persisted list of records per project (store.js), shared by every way
7
+ // of making, listing and deleting a record;
8
+ // - one timer, set for the earliest time any armed record is due, re-armed
9
+ // whenever a record is created, fired, skipped, deleted or ended;
10
+ // - one firing path: session-input fireScheduled(), which delivers through
11
+ // deliver(), the path send-input uses.
12
+ //
13
+ // Lifecycle: a record ends (state "ended") when its session is closed or
14
+ // deleted, and is done when it ran its course. A session whose runtime was
15
+ // reaped is not ended; the firing resumes it by id. Nothing here moves a record
16
+ // to another session. Missed firings are not made up: a once record that came
17
+ // due while the daemon was down fires once at startup, and a recurring record
18
+ // fires at most once and then continues from that delivery. Delivery is at most
19
+ // once: a record is advanced and saved before its text is delivered, and when
20
+ // the list cannot be saved nothing is delivered (see fire() and commit()).
21
+ //
22
+ // Memory always equals the disk. Every change to a record or to the list is made
23
+ // inside commit(), which saves it and, when the save fails, puts everything back
24
+ // as it was last saved. There is no other write path in this file.
25
+ //
26
+ // One owner while a delivery is in flight: from the moment fire() starts the
27
+ // delivery until settle() has run, only settle() changes that record. A daemon-made
28
+ // transition with no caller (a session ending, a vendor-id upgrade) records what
29
+ // it wants as an op in `pending`, and settle() applies its own outcome and then
30
+ // those ops, in order, in one commit(). An operation with a caller is never held:
31
+ // deleting a record that is being sent is refused as busy, and arming a resume
32
+ // creates its record durably at once (settle() ends the older resume if both
33
+ // would be armed).
34
+
35
+ var path = require("path");
36
+
37
+ var sessionResume = require("../session-resume");
38
+ var { encodeCwd } = require("../utils");
39
+ var { INITIATORS } = require("../turn-initiator");
40
+ var records = require("./records");
41
+ var { createStore } = require("./store");
42
+
43
+ var KIND = records.KIND;
44
+ var STATE = records.STATE;
45
+
46
+ // A firing skipped because the session was mid-turn retries after this long.
47
+ // Short and bounded (never over 30 s) rather than at full timer precision.
48
+ var RETRY_BUSY_MS = 15 * 1000;
49
+ var RETRY_ERROR_MS = 30 * 1000;
50
+ var MAX_FAILURES = 10;
51
+ // Sessions and runtimes are settling when a project is attached at startup.
52
+ var STARTUP_GRACE_MS = 5 * 1000;
53
+ // The timer never sleeps longer than this, so a clock change is noticed.
54
+ var MAX_WAIT_MS = 30 * 60 * 1000;
55
+
56
+ // A browser's bubble shows the start of a long text; the record keeps it whole.
57
+ var BUBBLE_TEXT_CHARS = 2000;
58
+
59
+ // What a record was made for, kept in createdBy for the rate-limit resume (the
60
+ // only record the daemon makes by itself).
61
+ var CREATED_BY_RATE_LIMIT = "rate-limit";
62
+
63
+ function messageOf(err) {
64
+ return err && err.message ? err.message : String(err);
65
+ }
66
+
67
+ function fail(result, reason) {
68
+ return { ok: false, result: result, reason: reason };
69
+ }
70
+
71
+ // deps:
72
+ // dir directory the per-project files live in
73
+ // getProject(slug) -> project context | null
74
+ // sessionInput the createSessionInput() instance (fireScheduled)
75
+ // publish(event) optional; { type, slug, record, session }
76
+ // now() / setTimer(fn, ms) / clearTimer(handle) optional, for tests
77
+ function createScheduledInputService(deps) {
78
+ var now = deps.now || Date.now;
79
+ var setTimer = deps.setTimer || function (fn, ms) {
80
+ var handle = setTimeout(fn, ms);
81
+ if (handle && typeof handle.unref === "function") handle.unref();
82
+ return handle;
83
+ };
84
+ var clearTimer = deps.clearTimer || clearTimeout;
85
+ var projects = new Map(); // slug -> { store }
86
+ var inFlight = new Set(); // record ids being delivered
87
+ // In-flight record id -> ops to apply once settle() has run. Only transitions
88
+ // the daemon makes by itself with no caller to tell (sessionEnded,
89
+ // upgradeTargets, endUnstableTargets) are ever held here. Each heals after a
90
+ // crash: a closed session's record fires, gets not-found and ends; an upgrade
91
+ // is redone on the next tick or list; a console-keyed record is ended again at
92
+ // attach. A caller-facing operation (remove, armResume) is never held, because
93
+ // its caller would be told it happened before it is saved.
94
+ var pending = new Map();
95
+ var notBefore = new Map(); // record id -> earliest next attempt (ms)
96
+ var timer = null;
97
+ var stopped = false;
98
+
99
+ function publish(type, slug, record, session) {
100
+ if (typeof deps.publish !== "function") return;
101
+ try { deps.publish({ type: type, slug: slug, record: record, session: session || null }); }
102
+ catch (e) { console.error("[scheduled-input] publish failed:", messageOf(e)); }
103
+ }
104
+
105
+ // --- the timer ---
106
+
107
+ function dueAt(record) {
108
+ return Math.max(record.nextAt, notBefore.get(record.id) || 0);
109
+ }
110
+
111
+ // --- saving ---
112
+ //
113
+ // Every write of a project's list goes through commit(). A write that fails
114
+ // marks the project unhealthy: nothing of it is delivered until a write
115
+ // succeeds, because a delivery that cannot be recorded would be made again
116
+ // after a restart. A read-only store (see store.js) never recovers on its own.
117
+
118
+ // Saves the list and keeps the project's health. Called only by commit() and
119
+ // by mayFire()'s retry of a save (which changes nothing).
120
+ function persist(slug, entry) {
121
+ if (entry.store.save()) {
122
+ if (entry.unhealthy) {
123
+ console.error("[scheduled-input] " + slug + ": the list saved again; firing resumes");
124
+ entry.unhealthy = null;
125
+ }
126
+ return true;
127
+ }
128
+ var health = entry.store.health();
129
+ if (!entry.unhealthy) console.error("[scheduled-input] " + slug + ": the list cannot be saved; nothing is delivered until a save succeeds");
130
+ entry.unhealthy = {
131
+ readOnly: health.readOnly,
132
+ error: health.error || "the list could not be written",
133
+ retryAt: now() + RETRY_ERROR_MS,
134
+ };
135
+ return false;
136
+ }
137
+
138
+ // The one way a record or the list changes. mutate() makes the change; the list
139
+ // is then saved. If the save fails, every record is put back (in place, so
140
+ // references held elsewhere stay valid) to the state that was last saved, the
141
+ // project is marked unhealthy by persist(), and false is answered. A change is
142
+ // never kept in memory unsaved. mutate() changes records and the list only.
143
+ function commit(slug, entry, mutate) {
144
+ var snap = entry.store.all().map(function (r) {
145
+ return { record: r, copy: JSON.parse(JSON.stringify(r)) };
146
+ });
147
+ try {
148
+ mutate();
149
+ } catch (err) {
150
+ rollback(entry, snap);
151
+ throw err;
152
+ }
153
+ if (persist(slug, entry)) return true;
154
+ rollback(entry, snap);
155
+ // The project is unhealthy now; make sure a retry of the save is waited for.
156
+ rearm();
157
+ return false;
158
+ }
159
+
160
+ function rollback(entry, snap) {
161
+ entry.store.all().slice().forEach(function (r) { entry.store.remove(r.id); });
162
+ snap.forEach(function (s) {
163
+ Object.keys(s.record).forEach(function (k) { delete s.record[k]; });
164
+ Object.assign(s.record, s.copy);
165
+ entry.store.add(s.record);
166
+ });
167
+ }
168
+
169
+ // True when the project may fire: it is healthy, or a retried save worked.
170
+ function mayFire(slug, entry) {
171
+ if (!entry.unhealthy) return true;
172
+ if (entry.unhealthy.readOnly || now() < entry.unhealthy.retryAt) return false;
173
+ return persist(slug, entry);
174
+ }
175
+
176
+ // --- operations on a record that is being delivered ---
177
+
178
+ // Remembers what an operation wanted done to an in-flight record. Upgrading and
179
+ // ending are idempotent, so the first one held is enough.
180
+ function holdOp(id, op) {
181
+ var ops = pending.get(id);
182
+ if (!ops) { ops = []; pending.set(id, ops); }
183
+ if ((op.type === "upgrade" || op.type === "ended") && ops.some(function (o) { return o.type === op.type; })) return;
184
+ ops.push(op);
185
+ }
186
+
187
+ // Applies held ops in the order they came, each as the operation itself would
188
+ // have on the record as it stands. Called inside commit() only. Answers the
189
+ // events to publish once the commit succeeded and the ids of moved resumes.
190
+ function applyOps(record, ops, t) {
191
+ var out = { events: [], moved: [] };
192
+ ops.forEach(function (op) {
193
+ if (op.type === "upgrade") {
194
+ if (records.isArmed(record) && record.sessionIdKind === records.ID_KIND.CONSOLE) {
195
+ record.sessionId = op.id;
196
+ record.sessionIdKind = records.ID_KIND.VENDOR;
197
+ }
198
+ } else if (op.type === "ended") {
199
+ if (records.isArmed(record)) {
200
+ records.sessionGone(record, t, op.reason);
201
+ // Not given the session: it is gone (see sessionEnded()).
202
+ out.events.push({ type: "ended", record: record, session: null });
203
+ }
204
+ }
205
+ });
206
+ return out;
207
+ }
208
+
209
+ // A delivery that did not happen puts a resume record back to armed. If the
210
+ // session has a newer armed resume meanwhile (armResume() created it while this
211
+ // one was being delivered), the older one ends: a session never has two armed
212
+ // resumes and the newer wins. Called inside commit() only.
213
+ function endIfReplaced(entry, record, t, out) {
214
+ if (record.createdBy !== CREATED_BY_RATE_LIMIT || !records.isArmed(record)) return;
215
+ var newer = entry.store.all().some(function (r) {
216
+ return r !== record && r.createdBy === CREATED_BY_RATE_LIMIT && records.isArmed(r) && records.sameTarget(r, record);
217
+ });
218
+ if (!newer) return;
219
+ records.sessionGone(record, t, "replaced by a newer resume");
220
+ out.events.push({ type: "ended", record: record, session: null });
221
+ }
222
+
223
+ // One commit for a record's own change (step, optional) and the ops held for
224
+ // it. The held ops are dropped only when the commit succeeded; otherwise
225
+ // drainHeld() applies them at the next tick.
226
+ function commitHeld(slug, entry, record, step) {
227
+ var ops = pending.get(record.id) || null;
228
+ var applied = null;
229
+ var kept = commit(slug, entry, function () {
230
+ var t = now();
231
+ if (step) step();
232
+ applied = ops ? applyOps(record, ops, t) : { events: [], moved: [] };
233
+ endIfReplaced(entry, record, t, applied);
234
+ });
235
+ if (kept) pending.delete(record.id);
236
+ return { kept: kept, applied: applied };
237
+ }
238
+
239
+ function publishApplied(slug, applied) {
240
+ if (!applied) return;
241
+ applied.moved.forEach(function (id) { notBefore.delete(id); });
242
+ applied.events.forEach(function (e) { publish(e.type, slug, e.record, e.session); });
243
+ }
244
+
245
+ // Ops held for a record whose settle() could not save them.
246
+ function drainHeld(slug, entry) {
247
+ entry.store.all().slice().forEach(function (r) {
248
+ if (entry.unhealthy || !pending.has(r.id) || inFlight.has(r.id)) return;
249
+ var done = commitHeld(slug, entry, r, null);
250
+ if (done.kept) publishApplied(slug, done.applied);
251
+ });
252
+ }
253
+
254
+ function rearm() {
255
+ if (timer !== null) { clearTimer(timer); timer = null; }
256
+ if (stopped) return;
257
+ var earliest = null;
258
+ projects.forEach(function (entry) {
259
+ if (entry.unhealthy) {
260
+ // Only a retry of the save is waited for, not the records themselves.
261
+ if (!entry.unhealthy.readOnly && (earliest === null || entry.unhealthy.retryAt < earliest)) earliest = entry.unhealthy.retryAt;
262
+ return;
263
+ }
264
+ entry.store.all().forEach(function (r) {
265
+ if (!records.isArmed(r) || inFlight.has(r.id)) return;
266
+ var at = dueAt(r);
267
+ if (earliest === null || at < earliest) earliest = at;
268
+ });
269
+ });
270
+ if (earliest === null) return;
271
+ var wait = Math.min(Math.max(0, earliest - now()), MAX_WAIT_MS);
272
+ timer = setTimer(tick, wait);
273
+ }
274
+
275
+ function tick() {
276
+ timer = null;
277
+ if (stopped) return;
278
+ var t = now();
279
+ projects.forEach(function (entry, slug) {
280
+ if (!mayFire(slug, entry)) return;
281
+ drainHeld(slug, entry);
282
+ endUnstableTargets(slug, entry);
283
+ upgradeTargets(slug, entry);
284
+ entry.store.all().slice().forEach(function (r) {
285
+ if (entry.unhealthy || !records.isArmed(r) || inFlight.has(r.id) || dueAt(r) > t) return;
286
+ if (records.pastItsEnd(r, t)) {
287
+ if (commit(slug, entry, function () { records.endReached(r, t); })) publish("ended", slug, r, null);
288
+ return;
289
+ }
290
+ fire(slug, r, { initiator: INITIATORS.SCHEDULED, force: false });
291
+ });
292
+ });
293
+ rearm();
294
+ }
295
+
296
+ // --- firing ---
297
+
298
+ // Delivers a record's text now. Answers (as a Promise) the firing's result.
299
+ //
300
+ // At most once: the record is advanced (nextAt, firedCount, state) and saved
301
+ // BEFORE the text is delivered, so a crash or a restart after a delivery
302
+ // cannot make it again. If that save fails nothing is delivered. A delivery
303
+ // that then does not happen (busy session, error) puts the record back as it
304
+ // was, saves that, and tries again shortly.
305
+ function fire(slug, record, how) {
306
+ var entry = projects.get(slug);
307
+ if (!entry || !mayFire(slug, entry)) {
308
+ return Promise.resolve({ ok: false, result: "error", reason: "not delivered: the scheduled inputs of this project cannot be saved" + (entry && entry.unhealthy ? " (" + entry.unhealthy.error + ")" : "") });
309
+ }
310
+ var before = records.snapshot(record);
311
+ if (!commit(slug, entry, function () { records.afterDelivery(record, now(), "sending"); })) {
312
+ return Promise.resolve({ ok: false, result: "error", reason: "not delivered: the schedule could not be saved first (" + entry.unhealthy.error + ")" });
313
+ }
314
+ inFlight.add(record.id);
315
+ // Started in this turn, not after a microtask: a person's "send now" is
316
+ // delivered before the next thing they do, in order.
317
+ var started;
318
+ try {
319
+ started = deps.sessionInput.fireScheduled({
320
+ projectSlug: slug,
321
+ sessionId: record.sessionId,
322
+ prompt: record.text,
323
+ note: record.note,
324
+ initiator: how.initiator,
325
+ force: how.force,
326
+ });
327
+ } catch (err) {
328
+ started = { ok: false, result: "error", retryable: true, reason: "firing failed: " + messageOf(err) };
329
+ }
330
+ return Promise.resolve(started).catch(function (err) {
331
+ return { ok: false, result: "error", retryable: true, reason: "firing failed: " + messageOf(err) };
332
+ }).then(function (res) {
333
+ inFlight.delete(record.id);
334
+ if (!entry || projects.get(slug) !== entry || entry.store.get(record.id) !== record) return res;
335
+ settle(slug, entry, record, res, how, before);
336
+ rearm();
337
+ return res;
338
+ });
339
+ }
340
+
341
+ // The record was advanced and saved as "sending" before delivery (see fire).
342
+ // Each branch is one commit. A save that fails leaves the record as last saved:
343
+ // - a delivered text keeps "sending" (it was delivered, once, and is not
344
+ // delivered again);
345
+ // - a failed delivery whose put-back cannot be saved stays advanced, so the
346
+ // text is not delivered at all, which at-most-once accepts.
347
+ //
348
+ // The record is owned by this function while it is in flight (see the top of
349
+ // the file), so the outcome is always applied to what fire() saved: there is no
350
+ // comparison with a snapshot. The ops other operations held meanwhile are
351
+ // applied in the same commit, after the outcome.
352
+ function settle(slug, entry, record, res, how, before) {
353
+ var t = now();
354
+ var step;
355
+ var retryMs = 0;
356
+ var event = null;
357
+ if (res.ok) {
358
+ step = function () { record.lastOutcome = res.result; };
359
+ event = "sent";
360
+ } else if (res.result === "busy") {
361
+ // Skipped, not failed: the same record is tried again soon.
362
+ step = function () {
363
+ records.restore(record, before);
364
+ record.lastOutcome = "skipped: the session was mid-turn";
365
+ };
366
+ retryMs = RETRY_BUSY_MS;
367
+ } else if (res.result === "not-found") {
368
+ step = function () {
369
+ records.restore(record, before);
370
+ records.sessionGone(record, t, "the session no longer exists");
371
+ };
372
+ event = "ended";
373
+ } else if (how.force) {
374
+ // A person's "send now" that failed is reported to them; the schedule goes on.
375
+ step = function () { records.restore(record, before); };
376
+ } else {
377
+ var reason = String(res.reason || res.result).slice(0, 200);
378
+ step = function () {
379
+ records.restore(record, before);
380
+ record.failures += 1;
381
+ record.lastOutcome = "error: " + reason;
382
+ event = "changed";
383
+ if (record.failures >= MAX_FAILURES) {
384
+ records.sessionGone(record, t, "delivery kept failing: " + reason);
385
+ event = "ended";
386
+ }
387
+ };
388
+ retryMs = RETRY_ERROR_MS;
389
+ }
390
+ notBefore.delete(record.id);
391
+ var done = commitHeld(slug, entry, record, step);
392
+ if (!done.kept) {
393
+ // Whatever was last saved stands: a delivered text stays "sending" (it is
394
+ // not delivered again); a failed delivery stays advanced (it is not
395
+ // delivered at all), which at-most-once accepts. Held ops are applied at
396
+ // the next tick.
397
+ console.error("[scheduled-input] " + slug + ": " + record.id + (res.ok
398
+ ? " was delivered but its outcome could not be saved; it stays recorded as sending"
399
+ : " could not be put back after a delivery that did not happen; it stays as last saved and the text is not delivered"));
400
+ return;
401
+ }
402
+ var stillHere = entry.store.get(record.id) === record;
403
+ if (stillHere && retryMs && records.isArmed(record)) notBefore.set(record.id, t + retryMs);
404
+ if (stillHere && event) publish(event, slug, record, null);
405
+ publishApplied(slug, done.applied);
406
+ }
407
+
408
+ // --- projects ---
409
+
410
+ function storeFile(project) {
411
+ return path.join(deps.dir, encodeCwd(project.cwd) + ".json");
412
+ }
413
+
414
+ // A record bound by console id when the project was attached belongs to a
415
+ // session that had not run a turn; a restart numbers sessions anew, so it can
416
+ // no longer be trusted to name the same one and ends. If that cannot be saved
417
+ // the ids stay in entry.stale and the end is made again at the next tick.
418
+ function endUnstableTargets(slug, entry) {
419
+ if (!entry.stale.size || entry.unhealthy) return;
420
+ var t = now();
421
+ var reason = "the session had not started when the daemon restarted";
422
+ var stale = entry.store.all().filter(function (r) {
423
+ return entry.stale.has(r.id) && r.sessionIdKind === records.ID_KIND.CONSOLE && (inFlight.has(r.id) || records.isArmed(r));
424
+ });
425
+ // An in-flight record is changed by settle() only; it is ended there, and
426
+ // stays listed here until then.
427
+ var free = stale.filter(function (r) { return !inFlight.has(r.id); });
428
+ stale.forEach(function (r) { if (inFlight.has(r.id)) holdOp(r.id, { type: "ended", reason: reason }); });
429
+ if (free.length && !commit(slug, entry, function () {
430
+ free.forEach(function (r) { records.sessionGone(r, t, reason); });
431
+ })) return;
432
+ entry.stale.forEach(function (id) { if (!inFlight.has(id)) entry.stale.delete(id); });
433
+ }
434
+
435
+ // A record made before its session had a vendor id takes it once it has one.
436
+ function upgradeTargets(slug, entry) {
437
+ if (entry.unhealthy) return;
438
+ var project = deps.getProject(slug);
439
+ if (!project || !project.sm) return;
440
+ var upgrades = [];
441
+ entry.store.all().forEach(function (r) {
442
+ var delivering = inFlight.has(r.id);
443
+ if ((!delivering && !records.isArmed(r)) || r.sessionIdKind !== records.ID_KIND.CONSOLE || entry.stale.has(r.id)) return;
444
+ var session = records.liveSessionOf(project.sm, r);
445
+ if (!session || !session.cliSessionId) return;
446
+ // An in-flight record is changed by settle() only.
447
+ if (delivering) holdOp(r.id, { type: "upgrade", id: session.cliSessionId });
448
+ else upgrades.push({ record: r, id: session.cliSessionId });
449
+ });
450
+ if (!upgrades.length) return;
451
+ commit(slug, entry, function () {
452
+ upgrades.forEach(function (u) {
453
+ u.record.sessionId = u.id;
454
+ u.record.sessionIdKind = records.ID_KIND.VENDOR;
455
+ });
456
+ });
457
+ }
458
+
459
+ function attachProject(slug) {
460
+ var project = deps.getProject(slug);
461
+ if (!project) return false;
462
+ var store = createStore({ file: storeFile(project) });
463
+ store.load();
464
+ var entry = { store: store, unhealthy: null, stale: new Set() };
465
+ store.all().forEach(function (r) {
466
+ if (records.isArmed(r) && r.sessionIdKind === records.ID_KIND.CONSOLE) entry.stale.add(r.id);
467
+ });
468
+ var health = store.health();
469
+ if (health.readOnly) entry.unhealthy = { readOnly: true, error: health.error, retryAt: Infinity };
470
+ projects.set(slug, entry);
471
+ endUnstableTargets(slug, entry);
472
+ var t = now();
473
+ store.all().forEach(function (r) {
474
+ if (records.isArmed(r) && dueAt(r) <= t) notBefore.set(r.id, t + STARTUP_GRACE_MS);
475
+ });
476
+ rearm();
477
+ return true;
478
+ }
479
+
480
+ function detachProject(slug) {
481
+ var entry = projects.get(slug);
482
+ if (!entry) return;
483
+ entry.store.all().forEach(function (r) { notBefore.delete(r.id); inFlight.delete(r.id); pending.delete(r.id); });
484
+ projects.delete(slug);
485
+ rearm();
486
+ }
487
+
488
+ function entryFor(slug) {
489
+ var entry = projects.get(slug);
490
+ return entry || null;
491
+ }
492
+
493
+ // --- reads ---
494
+
495
+ function armedFor(entry, session) {
496
+ return entry.store.all().filter(function (r) { return records.isArmed(r) && records.recordIsFor(r, session); });
497
+ }
498
+
499
+ // The armed records of a live session as its browser lists them: the summary
500
+ // plus the text, cut to what a bubble shows.
501
+ function armedForSession(slug, session) {
502
+ var entry = entryFor(slug);
503
+ if (!entry) return [];
504
+ upgradeTargets(slug, entry);
505
+ return armedFor(entry, session).map(function (r) {
506
+ return Object.assign(records.summarize(r), { text: r.text.slice(0, BUBBLE_TEXT_CHARS) });
507
+ });
508
+ }
509
+
510
+ // filter: { sessionId?, state? } state is armed (default), done, ended or any.
511
+ function list(slug, filter) {
512
+ var entry = entryFor(slug);
513
+ if (!entry) return fail("refused", "unknown project " + JSON.stringify(String(slug).slice(0, 64)));
514
+ upgradeTargets(slug, entry);
515
+ filter = filter || {};
516
+ var state = filter.state || STATE.ARMED;
517
+ if (state !== "any" && state !== STATE.ARMED && state !== STATE.DONE && state !== STATE.ENDED) {
518
+ return fail("refused", "unknown state " + JSON.stringify(String(state).slice(0, 32)) + " (use armed, done, ended or any)");
519
+ }
520
+ var project = deps.getProject(slug);
521
+ var live = null;
522
+ if (filter.sessionId) live = records.liveSessionById(project.sm, filter.sessionId);
523
+ var found = entry.store.all().filter(function (r) {
524
+ if (state !== "any" && r.state !== state) return false;
525
+ if (!filter.sessionId) return true;
526
+ return live ? records.recordIsFor(r, live) : r.sessionId === filter.sessionId;
527
+ });
528
+ var listed = { ok: true, result: "listed", count: found.length, inputs: found.map(records.summarize) };
529
+ // A project whose list cannot be saved says so: nothing of it is delivered.
530
+ if (entry.unhealthy) {
531
+ listed.store = { state: entry.unhealthy.readOnly ? "read-only" : "unhealthy", error: entry.unhealthy.error };
532
+ }
533
+ return listed;
534
+ }
535
+
536
+ // --- writes ---
537
+
538
+ // Resolves the session an id names to the stable target a record keeps.
539
+ // Answers a Promise of { target, session? } or a failure result.
540
+ function resolveTarget(slug, rawId) {
541
+ var project = deps.getProject(slug);
542
+ if (!project || !project.sm) return Promise.resolve(fail("refused", "unknown project " + JSON.stringify(String(slug).slice(0, 64))));
543
+ if (typeof rawId !== "string" || !rawId) return Promise.resolve(fail("refused", "a session id is required"));
544
+ if (!sessionResume.isSafeSessionId(rawId)) return Promise.resolve(fail("refused", "unsafe session id " + JSON.stringify(rawId.slice(0, 64)) + " refused"));
545
+ var live = records.liveSessionById(project.sm, rawId);
546
+ if (live) return Promise.resolve({ ok: true, target: records.targetOf(live), session: live });
547
+ return sessionResume.sessionExistsInStore(project.sm, rawId).then(function (exists) {
548
+ if (!exists) return fail("not-found", "no session " + JSON.stringify(rawId.slice(0, 64)) + " in project " + JSON.stringify(String(slug).slice(0, 64)));
549
+ return { ok: true, target: { sessionId: rawId, sessionIdKind: records.ID_KIND.VENDOR }, session: null };
550
+ }).catch(function (err) {
551
+ return fail("error", "could not look up the session: " + messageOf(err));
552
+ });
553
+ }
554
+
555
+ // input: { target, session?, kind, text, note?, createdBy, at?, every?,
556
+ // until?, count?, exemptFromCap? }
557
+ // target and session come from resolveTarget (or targetOf for a live session).
558
+ function create(slug, input) {
559
+ var entry = entryFor(slug);
560
+ if (!entry) return fail("refused", "unknown project " + JSON.stringify(String(slug).slice(0, 64)));
561
+ var armedHere = entry.store.all().filter(function (r) {
562
+ if (!records.isArmed(r)) return false;
563
+ return input.session ? records.recordIsFor(r, input.session) : records.sameTarget(r, input.target);
564
+ }).length;
565
+ var built = records.buildRecord({
566
+ sessionId: input.target.sessionId,
567
+ sessionIdKind: input.target.sessionIdKind,
568
+ kind: input.kind,
569
+ text: input.text,
570
+ note: input.note,
571
+ createdBy: input.createdBy,
572
+ at: input.at,
573
+ every: input.every,
574
+ until: input.until,
575
+ count: input.count,
576
+ }, { now: now(), armedForSession: armedHere, exemptFromCap: !!input.exemptFromCap });
577
+ if (built.error) return fail("refused", built.error);
578
+ if (!commit(slug, entry, function () { entry.store.add(built.record); })) {
579
+ return fail("error", "could not save the scheduled input" + (entry.unhealthy && entry.unhealthy.readOnly ? ": " + entry.unhealthy.error : ""));
580
+ }
581
+ rearm();
582
+ publish("queued", slug, built.record, input.session || null);
583
+ return { ok: true, result: "scheduled", record: records.summarize(built.record) };
584
+ }
585
+
586
+ // session, when given, is the live session the caller is acting for: a record
587
+ // of another session is not found for it.
588
+ function findFor(slug, id, session) {
589
+ var entry = entryFor(slug);
590
+ if (!entry) return { failure: fail("refused", "unknown project " + JSON.stringify(String(slug).slice(0, 64))) };
591
+ var record = entry.store.get(id);
592
+ if (!record || (session && !records.recordIsFor(record, session))) {
593
+ return { failure: fail("not-found", "no scheduled input " + JSON.stringify(String(id).slice(0, 64))) };
594
+ }
595
+ return { entry: entry, record: record };
596
+ }
597
+
598
+ function remove(slug, id, session) {
599
+ var found = findFor(slug, id, session);
600
+ if (found.failure) return found.failure;
601
+ // Refused, not held: a deletion held in memory would be answered as done
602
+ // before it is saved, and a crash would bring the record back.
603
+ if (inFlight.has(id)) return fail("busy", "that scheduled input is being sent; try again in a moment");
604
+ var wasArmed = records.isArmed(found.record);
605
+ // A deletion that did not reach the disk would come back after a restart and
606
+ // fire a schedule the person cancelled, so it is refused instead.
607
+ if (!commit(slug, found.entry, function () { found.entry.store.remove(id); })) {
608
+ return fail("error", "could not save the deletion of " + JSON.stringify(String(id).slice(0, 64)));
609
+ }
610
+ notBefore.delete(id);
611
+ rearm();
612
+ if (wasArmed) publish("cancelled", slug, found.record, session || null);
613
+ return { ok: true, result: "deleted", record: records.summarize(found.record) };
614
+ }
615
+
616
+ // A person pressed "send now": the record is delivered at once as
617
+ // scheduled-now, even into a running turn.
618
+ function sendNow(slug, id, session) {
619
+ var found = findFor(slug, id, session);
620
+ if (found.failure) return Promise.resolve(found.failure);
621
+ if (!records.isArmed(found.record)) return Promise.resolve(fail("refused", "that scheduled input is no longer armed"));
622
+ if (inFlight.has(id)) return Promise.resolve(fail("refused", "that scheduled input is being sent"));
623
+ return fire(slug, found.record, { initiator: INITIATORS.SCHEDULED_NOW, force: true }).then(function (res) {
624
+ if (res.ok) return { ok: true, result: "sent", record: records.summarize(found.record) };
625
+ return { ok: false, result: res.result, reason: res.reason };
626
+ });
627
+ }
628
+
629
+ // The session was closed or deleted (the session object as it was).
630
+ function sessionEnded(slug, session) {
631
+ var entry = entryFor(slug);
632
+ if (!entry || !session) return;
633
+ var t = now();
634
+ var reason = "the session was closed or deleted";
635
+ var every = entry.store.all().filter(function (r) { return (inFlight.has(r.id) || records.isArmed(r)) && records.recordIsFor(r, session); });
636
+ // An in-flight record is changed by settle() only; it is ended there if it is
637
+ // still armed once the delivery's outcome is applied.
638
+ every.forEach(function (r) { if (inFlight.has(r.id)) holdOp(r.id, { type: "ended", reason: reason }); });
639
+ var mine = every.filter(function (r) { return !inFlight.has(r.id); });
640
+ if (!mine.length) return;
641
+ // If this cannot be saved the records stay armed; their next firing finds no
642
+ // session and ends them (see settle()).
643
+ if (!commit(slug, entry, function () {
644
+ mine.forEach(function (r) { records.sessionGone(r, t, reason); });
645
+ })) return;
646
+ mine.forEach(function (r) {
647
+ notBefore.delete(r.id);
648
+ // Not given the session: it is gone, and writing an event into its
649
+ // history would recreate the file the deletion removed.
650
+ publish("ended", slug, r, null);
651
+ });
652
+ rearm();
653
+ }
654
+
655
+ // --- the rate-limit resume ---
656
+ // The one record the daemon makes by itself. A session has at most one armed;
657
+ // arming again moves it. It is exempt from the per-session limit (it still
658
+ // counts toward it) so a person's own schedules can never make a rate-limited
659
+ // session lose its resume.
660
+
661
+ function armedResume(entry, session) {
662
+ return armedFor(entry, session).filter(function (r) { return r.createdBy === CREATED_BY_RATE_LIMIT && !inFlight.has(r.id); })[0] || null;
663
+ }
664
+
665
+ function hasArmedResume(slug, session) {
666
+ var entry = entryFor(slug);
667
+ return !!(entry && armedResume(entry, session));
668
+ }
669
+
670
+ function moveResume(record, spec) {
671
+ record.at = spec.at;
672
+ record.nextAt = Math.max(spec.at, spec.armedAt);
673
+ record.text = spec.text;
674
+ record.note = spec.note;
675
+ }
676
+
677
+ function armResume(slug, session, spec) {
678
+ var entry = entryFor(slug);
679
+ if (!entry) return fail("refused", "unknown project " + JSON.stringify(String(slug).slice(0, 64)));
680
+ var existing = armedResume(entry, session);
681
+ // Never held and never refused: while a resume is being delivered it is not
682
+ // armed (it was advanced and saved first), so the new one is created durably
683
+ // here, before the answer. If the delivery then fails and the old record would
684
+ // be armed again, settle() ends it in favour of this one.
685
+ if (existing) {
686
+ if (!commit(slug, entry, function () {
687
+ moveResume(existing, { at: spec.at, armedAt: now(), text: spec.text, note: spec.note });
688
+ })) {
689
+ return fail("error", "could not save the scheduled input");
690
+ }
691
+ notBefore.delete(existing.id);
692
+ rearm();
693
+ publish("queued", slug, existing, session);
694
+ return { ok: true, result: "scheduled", record: records.summarize(existing) };
695
+ }
696
+ return create(slug, {
697
+ target: records.targetOf(session),
698
+ session: session,
699
+ kind: KIND.ONCE,
700
+ text: spec.text,
701
+ note: spec.note,
702
+ createdBy: CREATED_BY_RATE_LIMIT,
703
+ at: spec.at,
704
+ exemptFromCap: true,
705
+ });
706
+ }
707
+
708
+ function projectSlugs() {
709
+ return Array.from(projects.keys());
710
+ }
711
+
712
+ function stop() {
713
+ stopped = true;
714
+ if (timer !== null) { clearTimer(timer); timer = null; }
715
+ }
716
+
717
+ return {
718
+ attachProject: attachProject,
719
+ detachProject: detachProject,
720
+ projectSlugs: projectSlugs,
721
+ resolveTarget: resolveTarget,
722
+ create: create,
723
+ list: list,
724
+ armedForSession: armedForSession,
725
+ remove: remove,
726
+ sendNow: sendNow,
727
+ sessionEnded: sessionEnded,
728
+ armResume: armResume,
729
+ hasArmedResume: hasArmedResume,
730
+ tick: tick,
731
+ stop: stop,
732
+ CREATED_BY_RATE_LIMIT: CREATED_BY_RATE_LIMIT,
733
+ };
734
+ }
735
+
736
+ module.exports = {
737
+ createScheduledInputService: createScheduledInputService,
738
+ RETRY_BUSY_MS: RETRY_BUSY_MS,
739
+ RETRY_ERROR_MS: RETRY_ERROR_MS,
740
+ MAX_FAILURES: MAX_FAILURES,
741
+ STARTUP_GRACE_MS: STARTUP_GRACE_MS,
742
+ CREATED_BY_RATE_LIMIT: CREATED_BY_RATE_LIMIT,
743
+ };