@clagentic/console 1.12.0-beta.2 → 1.12.0-beta.3

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 (127) hide show
  1. package/LICENSES/README.md +5 -0
  2. package/bin/cli.js +4 -2
  3. package/lib/agent-roster-ws.js +84 -0
  4. package/lib/agent-roster.js +312 -0
  5. package/lib/auth-required-notify.js +42 -0
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-notify.js +45 -0
  8. package/lib/build-update-offer.js +3 -4
  9. package/lib/build-update-standing.js +34 -14
  10. package/lib/cli/session-subcommands.js +26 -8
  11. package/lib/client-address.js +44 -0
  12. package/lib/daemon.js +25 -10
  13. package/lib/idle-compaction-setting.js +203 -0
  14. package/lib/mcp-bridge-credential.js +41 -0
  15. package/lib/notification-prefs.js +16 -22
  16. package/lib/notify/core.js +53 -18
  17. package/lib/notify/payload.js +2 -3
  18. package/lib/notify/type-registry.js +17 -0
  19. package/lib/notify/types.js +38 -1
  20. package/lib/outbound-access.js +12 -1
  21. package/lib/outbound-entry.js +8 -1
  22. package/lib/project-connection.js +9 -8
  23. package/lib/project-filesystem.js +23 -0
  24. package/lib/project-loop.js +16 -19
  25. package/lib/project-notifications.js +68 -7
  26. package/lib/project-sessions.js +9 -0
  27. package/lib/project-user-mention.js +22 -34
  28. package/lib/project-user-message.js +208 -4
  29. package/lib/project-user-shell.js +298 -0
  30. package/lib/project.js +26 -4
  31. package/lib/prompt-answer.js +145 -0
  32. package/lib/prompt-expiry.js +50 -0
  33. package/lib/prompt-registry.js +24 -1
  34. package/lib/prompt-source.js +16 -0
  35. package/lib/public/app.js +31 -2
  36. package/lib/public/css/agent-messages.css +96 -0
  37. package/lib/public/css/agent-roster.css +93 -0
  38. package/lib/public/css/diagnostics.css +1 -1
  39. package/lib/public/css/input.css +20 -141
  40. package/lib/public/css/login-panel.css +73 -0
  41. package/lib/public/css/menus.css +2 -2
  42. package/lib/public/css/sidebar.css +11 -0
  43. package/lib/public/css/team-panel.css +1 -6
  44. package/lib/public/css/team-view.css +101 -0
  45. package/lib/public/css/title-bar.css +10 -0
  46. package/lib/public/css/user-shell.css +144 -0
  47. package/lib/public/index.html +41 -7
  48. package/lib/public/modules/agent-avatar-picker.js +162 -0
  49. package/lib/public/modules/agent-avatar.js +153 -0
  50. package/lib/public/modules/agent-messages.js +285 -0
  51. package/lib/public/modules/agent-roster.js +157 -0
  52. package/lib/public/modules/app-connection.js +12 -0
  53. package/lib/public/modules/app-messages.js +55 -16
  54. package/lib/public/modules/app-notifications.js +59 -29
  55. package/lib/public/modules/app-panels.js +26 -3
  56. package/lib/public/modules/app-rate-limit.js +8 -165
  57. package/lib/public/modules/app-rendering.js +22 -7
  58. package/lib/public/modules/collapsible-text.js +33 -18
  59. package/lib/public/modules/compaction-state.js +34 -0
  60. package/lib/public/modules/custom-icons.js +23 -5
  61. package/lib/public/modules/diagnostics.js +52 -55
  62. package/lib/public/modules/injected-identity.js +24 -21
  63. package/lib/public/modules/input.js +176 -15
  64. package/lib/public/modules/login-panel.js +136 -0
  65. package/lib/public/modules/login-parser.js +73 -0
  66. package/lib/public/modules/login-tab.js +66 -0
  67. package/lib/public/modules/notifications.js +9 -1
  68. package/lib/public/modules/notify-client.js +114 -21
  69. package/lib/public/modules/pending-term-request.js +30 -0
  70. package/lib/public/modules/project-icon.js +22 -2
  71. package/lib/public/modules/queued-button.js +11 -0
  72. package/lib/public/modules/scheduled-input-actions.js +12 -4
  73. package/lib/public/modules/scheduled-outbox.js +230 -0
  74. package/lib/public/modules/send-now.js +200 -0
  75. package/lib/public/modules/server-settings.js +47 -1
  76. package/lib/public/modules/shell-card.js +76 -0
  77. package/lib/public/modules/shell-line.js +49 -0
  78. package/lib/public/modules/shell-queue.js +253 -0
  79. package/lib/public/modules/shell-settings-controls.js +76 -0
  80. package/lib/public/modules/sidebar-mobile.js +3 -3
  81. package/lib/public/modules/sidebar-sessions.js +8 -0
  82. package/lib/public/modules/sidebar-users.js +5 -7
  83. package/lib/public/modules/team-panel.js +30 -88
  84. package/lib/public/modules/team-view.js +211 -0
  85. package/lib/public/modules/terminal-links.js +18 -0
  86. package/lib/public/modules/terminal.js +65 -4
  87. package/lib/public/modules/tools.js +19 -0
  88. package/lib/public/modules/user-shell.js +824 -0
  89. package/lib/public/notify-sw-logic.js +35 -83
  90. package/lib/public/notify-target.js +70 -10
  91. package/lib/public/style.css +5 -0
  92. package/lib/public/sw.js +7 -3
  93. package/lib/queued-chat.js +392 -0
  94. package/lib/scheduled-input/ws.js +67 -9
  95. package/lib/sdk-bridge.js +122 -43
  96. package/lib/sdk-message-processor.js +46 -39
  97. package/lib/server-auth.js +6 -4
  98. package/lib/server-dm.js +11 -20
  99. package/lib/server-settings.js +39 -1
  100. package/lib/server.js +83 -19
  101. package/lib/session-directory.js +33 -8
  102. package/lib/session-end.js +97 -0
  103. package/lib/session-input-ipc.js +26 -0
  104. package/lib/session-input.js +176 -9
  105. package/lib/session-resume.js +1 -0
  106. package/lib/session-settings-file.js +53 -0
  107. package/lib/sessions.js +49 -5
  108. package/lib/team-traffic-ws.js +68 -0
  109. package/lib/team-traffic.js +318 -0
  110. package/lib/usage-store.js +7 -0
  111. package/lib/user-shell-settings.js +105 -0
  112. package/lib/ws-schema.js +27 -4
  113. package/lib/yoke/adapters/claude-capabilities.js +2 -0
  114. package/lib/yoke/adapters/claude-vendor.js +6 -0
  115. package/lib/yoke/adapters/claude-worker.js +39 -11
  116. package/lib/yoke/adapters/claude.js +218 -6
  117. package/lib/yoke/adapters/codex-capabilities.js +6 -1
  118. package/lib/yoke/adapters/codex-user-shell.js +265 -0
  119. package/lib/yoke/adapters/codex-vendor.js +7 -0
  120. package/lib/yoke/adapters/codex.js +186 -52
  121. package/lib/yoke/codex-app-server.js +8 -2
  122. package/lib/yoke/interface.js +54 -1
  123. package/lib/yoke/mcp-bridge-server.js +12 -8
  124. package/lib/yoke/registry.js +32 -0
  125. package/lib/yoke/user-shell.js +224 -0
  126. package/package.json +1 -1
  127. package/lib/public/modules/build-notice-gate.js +0 -73
@@ -0,0 +1,392 @@
1
+ // queued-chat.js - chat pushed into a running turn that the agent has not yet
2
+ // taken in. The message is already with the agent (native timing: it is folded
3
+ // in at the agent's next step), so the console only tracks it, by the message id
4
+ // the page minted, until the agent reports it consumed it (delivered) or the
5
+ // sender withdraws it (cancelled). Exactly one of the two ever happens for an
6
+ // id: whichever the session sees first removes the entry, and the other finds
7
+ // nothing and changes nothing.
8
+ //
9
+ // A message the agent has not taken stays tracked across turns: the agent's
10
+ // queue keeps it and runs it as a later turn (as the native CLI does), so a
11
+ // turn ending with it still waiting is not a drop. It is dropped only when the
12
+ // query that held it is closed (dropAll), because then nothing will ever take it.
13
+ //
14
+ // One exception: a cancel the SDK answers false to. The SDK's cancel_async_message
15
+ // answer is only `response.cancelled` (a boolean; sdk.mjs cancelAsyncMessage), and
16
+ // false does not say whether the message runs: it also covers the representative
17
+ // of a coalesced batch (the whole batch is dropped) and a held-back uuid (dropped
18
+ // later by the drain), see the SDKControlInterruptResponse notes in sdk.d.ts.
19
+ // Such a message stays tracked as unconfirmed. An unconfirmed message ends in one
20
+ // of three ways only: taken (delivered), dropped "not_taken" by the idle grace
21
+ // settle (settleIdle, which never fires while a turn runs), or dropped "closed"
22
+ // with its query. The end of a turn settles nothing: a turn that ends with the
23
+ // message untaken does not say the agent will not run it as the next turn.
24
+ //
25
+ // Send now (requestSendNow) interrupts the running turn so a tracked message runs
26
+ // as the next input; it does not end the message. It still ends delivered, unless
27
+ // the interrupt receipt says the agent no longer holds it (dropped, send_now_missed).
28
+ //
29
+ // No I/O here: what delivery and a drop do (record the message, tell the page)
30
+ // is passed in by the caller that registered the message.
31
+
32
+ var STATE_KEY = "_queuedChat";
33
+ // Registration counter, and its value when the last turn ended: a message
34
+ // registered before that point was waiting for the next turn's batch (used only
35
+ // to choose which waiting messages a representative cancel puts in doubt).
36
+ var SEQ_KEY = "_queuedChatSeq";
37
+ var BOUNDARY_KEY = "_queuedChatBoundary";
38
+ // Messages that ended send_now_missed, kept only so a later delivery report for one
39
+ // of them is not lost (see consume). Not tracked, so never listed, saved or settled.
40
+ var MISSED_KEY = "_queuedChatMissed";
41
+
42
+ // The id is handed to the agent as the message's uuid, so it must be a uuid.
43
+ var UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
44
+
45
+ /** Whether a value from a page is usable as a message id. */
46
+ function isMessageId(value) {
47
+ return typeof value === "string" && UUID_SHAPE.test(value);
48
+ }
49
+
50
+ function table(session) {
51
+ if (!session[STATE_KEY]) session[STATE_KEY] = new Map();
52
+ return session[STATE_KEY];
53
+ }
54
+
55
+ /**
56
+ * Starts tracking a pushed message.
57
+ * @param {object} session
58
+ * @param {string} messageId
59
+ * @param {{onDelivered: function(): void, onDropped: function(string): void, onUnconfirmed: (function(): void)|undefined}} hooks
60
+ * onDelivered runs once when the agent takes the message; onDropped runs once
61
+ * with the cause when the message is never taken and never cancelled:
62
+ * "closed" (its query closed) or "not_taken" (a cancel the agent answered false
63
+ * to was followed by the idle grace with no turn running and no delivery);
64
+ * onUnconfirmed runs when a
65
+ * cancel of another message puts this one in doubt, so its page can say so.
66
+ * @param {{text: string, pastes: string[], imageCount: number}} [restore] what
67
+ * the page needs to hand the message back to its sender when it can no longer
68
+ * find its own queued item (a switched session, a reload)
69
+ */
70
+ function register(session, messageId, hooks, restore, owner) {
71
+ var seq = (session[SEQ_KEY] || 0) + 1;
72
+ session[SEQ_KEY] = seq;
73
+ table(session).set(messageId, { hooks: hooks, restore: restore || null, owner: owner || null, cancelling: null, seq: seq, unconfirmed: false, sendNow: null });
74
+ }
75
+
76
+ function restoreRecord(messageId, restore) {
77
+ return { messageId: messageId, text: restore.text, pastes: restore.pastes.slice(), imageCount: restore.imageCount };
78
+ }
79
+
80
+ /**
81
+ * The messages still tracked as queued, with what the page needs to draw each
82
+ * one again (a reload, a second tab). Messages registered without restore data
83
+ * are not listed: there is nothing to draw.
84
+ * sendNow is present (true) only for a message Send now was pressed on: a page
85
+ * draws it as sending, never as queued again.
86
+ * @returns {Array<{messageId: string, text: string, pastes: string[], imageCount: number, unconfirmed: boolean, sendNow?: boolean}>}
87
+ */
88
+ function pending(session) {
89
+ var tracked = session[STATE_KEY];
90
+ if (!tracked) return [];
91
+ var out = [];
92
+ tracked.forEach(function (entry, id) {
93
+ if (!entry.restore) return;
94
+ var record = Object.assign(restoreRecord(id, entry.restore), { unconfirmed: entry.unconfirmed });
95
+ if (entry.sendNow) record.sendNow = true;
96
+ out.push(record);
97
+ });
98
+ return out;
99
+ }
100
+
101
+ // Text of messages that will never run (their query closed with nobody viewing
102
+ // the session, or the daemon restarted) and that no page has been handed yet. It
103
+ // lives with the session, so a restart does not lose it, and goes out once, on
104
+ // the next time the session is shown. Each record is {messageId, text, pastes,
105
+ // imageCount, cause}; cause is "closed" in this process and "restart" once read
106
+ // back from the session file.
107
+ var PARKED_KEY = "_queuedChatParked";
108
+
109
+ /** Keeps a dropped message's text for the next page that shows the session. */
110
+ function park(session, messageId, restore, cause) {
111
+ if (!restore) return;
112
+ if (!session[PARKED_KEY]) session[PARKED_KEY] = [];
113
+ session[PARKED_KEY].push(Object.assign(restoreRecord(messageId, restore), { cause: cause }));
114
+ }
115
+
116
+ /** Returns the parked messages and forgets them: each is handed back once. */
117
+ function takeParked(session) {
118
+ var parked = session[PARKED_KEY] || [];
119
+ session[PARKED_KEY] = [];
120
+ return parked;
121
+ }
122
+
123
+ /**
124
+ * What survives a restart: the tracked messages and the parked ones, as plain
125
+ * records for the session file. After a restart none of them is tracked any more
126
+ * (the agent that held them is gone), so they all come back as parked.
127
+ */
128
+ function durable(session) {
129
+ var records = pending(session).map(function (p) { return { messageId: p.messageId, text: p.text, pastes: p.pastes, imageCount: p.imageCount }; });
130
+ (session[PARKED_KEY] || []).forEach(function (p) {
131
+ records.push({ messageId: p.messageId, text: p.text, pastes: p.pastes, imageCount: p.imageCount });
132
+ });
133
+ return records;
134
+ }
135
+
136
+ /** Reads records from a session file back as parked messages; anything malformed is skipped. */
137
+ function loadParked(session, records) {
138
+ if (!Array.isArray(records)) return;
139
+ records.forEach(function (r) {
140
+ if (!r || !isMessageId(r.messageId) || typeof r.text !== "string") return;
141
+ var pastes = Array.isArray(r.pastes) ? r.pastes.filter(function (p) { return typeof p === "string"; }) : [];
142
+ var imageCount = Number.isInteger(r.imageCount) && r.imageCount > 0 ? r.imageCount : 0;
143
+ park(session, r.messageId, { text: r.text, pastes: pastes, imageCount: imageCount }, "restart");
144
+ });
145
+ }
146
+
147
+ /** The text of a tracked message, as registered, or null when it is not tracked. */
148
+ function restoreOf(session, messageId) {
149
+ var entry = session[STATE_KEY] && session[STATE_KEY].get(messageId);
150
+ return entry ? entry.restore : null;
151
+ }
152
+
153
+ function has(session, messageId) {
154
+ return !!session[STATE_KEY] && session[STATE_KEY].has(messageId);
155
+ }
156
+
157
+ /**
158
+ * The agent reports these message ids as consumed. Each tracked id is delivered
159
+ * once; an id that is not tracked (already delivered, cancelled, or never
160
+ * queued) is ignored.
161
+ * @param {object} session
162
+ * @param {string[]} ids
163
+ * @returns {string[]} the ids that were delivered by this call
164
+ */
165
+ function consume(session, ids) {
166
+ var tracked = session[STATE_KEY];
167
+ var missed = session[MISSED_KEY];
168
+ if (!Array.isArray(ids) || ((!tracked || tracked.size === 0) && (!missed || missed.size === 0))) return [];
169
+ var delivered = [];
170
+ ids.forEach(function (id) {
171
+ var entry = tracked && tracked.get(id);
172
+ if (entry) {
173
+ tracked.delete(id);
174
+ } else if (missed && missed.has(id)) {
175
+ // Ended send_now_missed, then the agent reported it consumed after all: the
176
+ // receipt raced the SDK taking it into the interrupted turn. It ran, so it is
177
+ // recorded once and the page is told; the page was already handed the text.
178
+ entry = missed.get(id);
179
+ missed.delete(id);
180
+ } else {
181
+ return;
182
+ }
183
+ delivered.push(id);
184
+ entry.hooks.onDelivered();
185
+ });
186
+ return delivered;
187
+ }
188
+
189
+ /**
190
+ * Withdraws a tracked message.
191
+ * @param {object} session
192
+ * @param {string} messageId
193
+ * @param {function(string): Promise<boolean>} cancelFn asks the agent; true
194
+ * only when the agent still held the message and dropped it
195
+ * @returns {Promise<"cancelled"|"already_delivered"|"pending">} already_delivered
196
+ * covers a message already consumed, one cancelled before, and an unknown id:
197
+ * in each the page must not expect the message back. pending: the agent did
198
+ * not drop it from its queue, which does not say whether it runs; it stays
199
+ * tracked and ends delivered or dropped (see settleIdle, dropAll). Rejects when the
200
+ * agent could not answer; the message is then still tracked. An unconfirmed
201
+ * message is asked about again: until it is delivered or dropped the agent may
202
+ * still hold it, and a cancel the builder made must reach the agent.
203
+ */
204
+ function cancel(session, messageId, cancelFn) {
205
+ var tracked = session[STATE_KEY];
206
+ var entry = tracked && tracked.get(messageId);
207
+ if (!entry) return Promise.resolve("already_delivered");
208
+ if (entry.cancelling) return entry.cancelling;
209
+ var asked = Promise.resolve().then(function () { return cancelFn(messageId); }).then(function (withdrawn) {
210
+ entry.cancelling = null;
211
+ // A delivery that was processed while the agent was answering already
212
+ // removed the entry; it wins, whatever the agent said.
213
+ if (tracked.get(messageId) !== entry) return "already_delivered";
214
+ if (withdrawn === true) {
215
+ tracked.delete(messageId);
216
+ return "cancelled";
217
+ }
218
+ // The SDK's answer is a bare boolean (see the file header). false covers a
219
+ // message that runs (taken already, a non-representative member of a
220
+ // coalesced batch), one that is dropped (the batch representative drops the
221
+ // whole batch; a held-back message is dropped by the drain later) and an
222
+ // unknown id, with no field telling them apart. The message therefore stays
223
+ // tracked: its delivery still delivers it; if nothing takes it and no turn
224
+ // runs for the grace period, settleIdle drops it with its text.
225
+ suspect(session, entry);
226
+ return "pending";
227
+ }, function (err) {
228
+ entry.cancelling = null;
229
+ throw err;
230
+ });
231
+ entry.cancelling = asked;
232
+ return asked;
233
+ }
234
+
235
+ /**
236
+ * Send now on a message that is already with the agent: the running turn is
237
+ * interrupted (the agent's queue is kept) so the message runs as the next input
238
+ * at once. The message is never pushed again; the interrupt receipt says whether
239
+ * the agent still holds it.
240
+ *
241
+ * The agent's receipt lists the uuids that survive the interrupt and WILL run
242
+ * unless cancelled. A uuid in the list: the message is marked send-now (it is
243
+ * never drawn queued again) and still ends as delivered. A uuid absent while the
244
+ * message was not delivered meanwhile: nothing holds it any more, so it is dropped
245
+ * "send_now_missed" with its text. A receipt that is absent (an agent too old to
246
+ * send one) cannot say either way, so the message stays marked and tracked: a
247
+ * restore could run it twice. A second request for a message already marked asks
248
+ * the agent nothing and answers the first request's outcome.
249
+ * @param {object} session
250
+ * @param {string} messageId
251
+ * @param {{turnRunning: boolean, liveOwner: *, interrupt: function(): Promise<{stillQueued: (string[]|null)}>}} how
252
+ * liveOwner is the session's current query, the one interrupt() reaches
253
+ * @returns {Promise<"requested"|"missed"|"already_delivered"|"no_turn">} already_delivered
254
+ * covers a message delivered, cancelled or never tracked; no_turn: nothing was
255
+ * interrupted because no turn runs, or the message was pushed into a query that
256
+ * is no longer the live one. Rejects when the agent could not interrupt;
257
+ * the message is then unmarked and can be asked again.
258
+ */
259
+ function requestSendNow(session, messageId, how) {
260
+ var tracked = session[STATE_KEY];
261
+ var entry = tracked && tracked.get(messageId);
262
+ if (!entry) return Promise.resolve("already_delivered");
263
+ if (entry.sendNow) return entry.sendNow;
264
+ if (!how.turnRunning) return Promise.resolve("no_turn");
265
+ // The interrupt reaches the session's live query. An entry pushed into an older
266
+ // query that is still unwinding is not in it: interrupting would cut off an
267
+ // unrelated turn. Nothing is interrupted; the old query's close drops the entry.
268
+ if (entry.owner !== null && entry.owner !== how.liveOwner) return Promise.resolve("no_turn");
269
+ var asked = Promise.resolve().then(function () { return how.interrupt(); }).then(function (receipt) {
270
+ // A delivery processed while the agent was answering already removed the
271
+ // entry; it wins, and the text reached the agent once.
272
+ if (tracked.get(messageId) !== entry) return "already_delivered";
273
+ var kept = receipt && Array.isArray(receipt.stillQueued) ? receipt.stillQueued : null;
274
+ if (kept === null || kept.indexOf(messageId) !== -1) {
275
+ entry.sendNow = Promise.resolve("requested");
276
+ return "requested";
277
+ }
278
+ dropEntries(session, [[messageId, entry]], "send_now_missed");
279
+ if (!session[MISSED_KEY]) session[MISSED_KEY] = new Map();
280
+ session[MISSED_KEY].set(messageId, entry);
281
+ return "missed";
282
+ }, function (err) {
283
+ entry.sendNow = null;
284
+ throw err;
285
+ });
286
+ entry.sendNow = asked;
287
+ return asked;
288
+ }
289
+
290
+ // Marks the cancelled message, and the messages that were waiting with it for
291
+ // the same turn's batch (registered before the last turn ended), as unconfirmed,
292
+ // and tells the page of each member newly put in doubt.
293
+ //
294
+ // Which messages a representative cancel drops: sdk.d.ts:4890 (0.3.318, and the
295
+ // batch wording of 0.3.295 at sdk.d.ts:4638) says "once a batch is dequeued and
296
+ // coalesced into one turn, ... cancelling the batch-representative uuid drops the
297
+ // WHOLE coalesced batch". The batch is what was in the queue when the turn was
298
+ // dequeued, i.e. the messages registered before the previous turn's result. A
299
+ // message registered after that result was pushed while this turn runs: it was
300
+ // not in the queue at dequeue, so it is not in the dropped batch; it is taken
301
+ // by a fold-in of this turn or waits for the next batch, and stays correctly
302
+ // queued (a held-back uuid's cancel-pending mark names only its own uuid). A
303
+ // message registered between the result and the dequeue (milliseconds) is
304
+ // treated as outside the batch too; if the SDK did drop it, the idle settle
305
+ // still returns its text, never a loss.
306
+ function suspect(session, entry) {
307
+ var boundary = session[BOUNDARY_KEY] || 0;
308
+ entry.unconfirmed = true;
309
+ table(session).forEach(function (other) {
310
+ if (other === entry || other.unconfirmed || other.seq > boundary) return;
311
+ other.unconfirmed = true;
312
+ if (typeof other.hooks.onUnconfirmed === "function") other.hooks.onUnconfirmed();
313
+ });
314
+ }
315
+
316
+ function dropEntries(session, picked, cause) {
317
+ var tracked = session[STATE_KEY];
318
+ var ids = [];
319
+ picked.forEach(function (pair) {
320
+ tracked.delete(pair[0]);
321
+ ids.push(pair[0]);
322
+ });
323
+ picked.forEach(function (pair) { pair[1].hooks.onDropped(cause); });
324
+ return ids;
325
+ }
326
+
327
+ function unconfirmedPairs(session) {
328
+ var tracked = session[STATE_KEY];
329
+ if (!tracked) return [];
330
+ // A message Send now was pressed on is excluded: the interrupt receipt names it
331
+ // as still held by the agent (or the agent sent no receipt), so the idle grace,
332
+ // which guesses, must not hand its text back while it may still run.
333
+ return Array.from(tracked.entries()).filter(function (pair) { return pair[1].unconfirmed && !pair[1].sendNow; });
334
+ }
335
+
336
+ /**
337
+ * A turn ended (its result frame). Records the registration count so a later
338
+ * representative cancel can tell the batch dequeued for the next turn from
339
+ * messages pushed after it. It neither delivers nor drops anything.
340
+ * @param {object} session
341
+ */
342
+ function markTurnEnd(session) {
343
+ session[BOUNDARY_KEY] = session[SEQ_KEY] || 0;
344
+ }
345
+
346
+ /** Whether any message is waiting for the outcome of a cancel the agent answered false to. */
347
+ function hasUnconfirmed(session) {
348
+ return unconfirmedPairs(session).length > 0;
349
+ }
350
+
351
+ /**
352
+ * Called some time after a cancel answered false. With no turn running nothing
353
+ * is left that could take the message, so each unconfirmed message is dropped
354
+ * now; with a turn running it is left alone (the agent may still take it, or run
355
+ * it as the next turn) and the caller asks again later.
356
+ * @returns {string[]} the dropped ids
357
+ */
358
+ function settleIdle(session, turnRunning) {
359
+ if (turnRunning) return [];
360
+ return dropEntries(session, unconfirmedPairs(session), "not_taken");
361
+ }
362
+
363
+ /**
364
+ * The query was closed and these messages were never taken: nothing will
365
+ * deliver them now, so each is dropped once. Not for the end of a turn: the
366
+ * agent runs a message still waiting then as its next turn.
367
+ * @param {object} session
368
+ * @param {object} [owner] the query that closed. A rewind can replace the query
369
+ * while the old one is still unwinding, so a message pushed into the new query
370
+ * must survive the old one's close: only messages pushed into this query (or
371
+ * registered with no query to name, which a close cannot tell apart) are
372
+ * dropped. Omitted: every tracked message.
373
+ * @returns {string[]} the dropped ids
374
+ */
375
+ function dropAll(session, owner) {
376
+ var missed = session[MISSED_KEY];
377
+ if (missed) {
378
+ Array.from(missed.entries()).forEach(function (pair) {
379
+ if (owner === undefined || pair[1].owner === owner || pair[1].owner === null) missed.delete(pair[0]);
380
+ });
381
+ }
382
+ var tracked = session[STATE_KEY];
383
+ if (!tracked || tracked.size === 0) return [];
384
+ var entries = Array.from(tracked.entries()).filter(function (pair) {
385
+ return owner === undefined || pair[1].owner === owner || pair[1].owner === null;
386
+ });
387
+ entries.forEach(function (pair) { tracked.delete(pair[0]); });
388
+ entries.forEach(function (pair) { pair[1].hooks.onDropped("closed"); });
389
+ return entries.map(function (pair) { return pair[0]; });
390
+ }
391
+
392
+ module.exports = { isMessageId: isMessageId, register: register, has: has, restoreOf: restoreOf, consume: consume, cancel: cancel, requestSendNow: requestSendNow, markTurnEnd: markTurnEnd, settleIdle: settleIdle, hasUnconfirmed: hasUnconfirmed, dropAll: dropAll, pending: pending, park: park, takeParked: takeParked, durable: durable, loadParked: loadParked };
@@ -6,10 +6,16 @@
6
6
  // schedule_message arm an input on the session on screen
7
7
  // { text, resetsAt } once (the original shape)
8
8
  // { text, kind: "recurring", every, until | count }
9
- // cancel_scheduled_message { id? } delete one of its inputs
10
- // send_scheduled_now { id? } deliver one now
9
+ // cancel_scheduled_message { id?, requestId? } delete one of its inputs
10
+ // send_scheduled_now { id?, requestId? } deliver one now
11
11
  // scheduled_input_list_request answer the session's armed inputs
12
12
  //
13
+ // A requestId is optional and opaque to the server. When one is sent, the
14
+ // answer to that request carries it back: scheduled_request_result { requestId,
15
+ // id, ok: true } when it was done, or the error frame with requestId added when
16
+ // it was refused, so a page can tell which of its requests an answer is for.
17
+ // Without one the messages behave as they always did.
18
+ //
13
19
  // An id names the record. A browser still running the client from before
14
20
  // records had ids sends none, and gets the input that fires first. A browser
15
21
  // only ever acts on the session it has on screen; the CLI is the path that can
@@ -71,6 +77,23 @@ function createWsHandlers(deps) {
71
77
  deps.sendTo(ws, { type: "error", text: "Clagentic: Console could not schedule that: " + reason });
72
78
  }
73
79
 
80
+ // The requestId a browser sent, if it is a usable string; else undefined.
81
+ function requestIdOf(msg) {
82
+ return typeof msg.requestId === "string" && msg.requestId && msg.requestId.length <= 64 ? msg.requestId : undefined;
83
+ }
84
+
85
+ // An error naming the request it answers, when the request had an id.
86
+ function refuseRequest(ws, requestId, text) {
87
+ var frame = { type: "error", text: text };
88
+ if (requestId !== undefined) frame.requestId = requestId;
89
+ deps.sendTo(ws, frame);
90
+ }
91
+
92
+ function confirmRequest(ws, requestId, id) {
93
+ if (requestId === undefined) return;
94
+ deps.sendTo(ws, { type: "scheduled_request_result", requestId: requestId, id: id, ok: true });
95
+ }
96
+
74
97
  function kindOf(msg) {
75
98
  if (msg.kind === undefined || msg.kind === KIND.ONCE) return KIND.ONCE;
76
99
  if (msg.kind === KIND.RECURRING) return KIND.RECURRING;
@@ -105,9 +128,17 @@ function createWsHandlers(deps) {
105
128
  function handle(ws, msg) {
106
129
  if (!msg || !HANDLED.has(msg.type)) return false;
107
130
  var session = deps.getSessionForWs(ws);
108
- if (!session) return true;
131
+ // Only the two request-shaped messages are answered by id; the others
132
+ // behave as they always did.
133
+ var asked = msg.type === "cancel_scheduled_message" || msg.type === "send_scheduled_now"
134
+ ? requestIdOf(msg) : undefined;
135
+ if (!session) {
136
+ if (asked !== undefined) refuseRequest(ws, asked, "Clagentic: Console could not find a session to act on");
137
+ return true;
138
+ }
109
139
  if (!service) {
110
- refuse(ws, "scheduling is not available here");
140
+ if (asked !== undefined) refuseRequest(ws, asked, "Clagentic: Console could not schedule that: scheduling is not available here");
141
+ else refuse(ws, "scheduling is not available here");
111
142
  return true;
112
143
  }
113
144
  if (msg.type === "scheduled_input_list_request") {
@@ -118,20 +149,47 @@ function createWsHandlers(deps) {
118
149
  schedule(ws, session, msg);
119
150
  return true;
120
151
  }
152
+ var requestId = requestIdOf(msg);
121
153
  var id = idFor(session, msg);
122
- if (!id) return true;
154
+ if (!id) {
155
+ // Silent for a caller without a request id, as before; one with an id is told.
156
+ if (requestId !== undefined) refuseRequest(ws, requestId, "Clagentic: Console could not find a scheduled input to act on");
157
+ return true;
158
+ }
123
159
  if (msg.type === "cancel_scheduled_message") {
124
160
  var removed = service.remove(slug, id, session);
125
161
  // Refused while the text is being sent: the person is told, and the bubble
126
162
  // stays because nothing changed.
127
- if (!removed.ok && removed.result === "busy") {
128
- deps.sendTo(ws, { type: "error", text: "Clagentic: Console could not cancel that: " + removed.reason });
163
+ // Any other refusal was silent; a request with an id is told, so its row is freed.
164
+ if (!removed.ok && (removed.result === "busy" || requestId !== undefined)) {
165
+ refuseRequest(ws, requestId, "Clagentic: Console could not cancel that: " + removed.reason);
166
+ } else if (removed.ok) {
167
+ confirmRequest(ws, requestId, id);
129
168
  }
130
169
  return true;
131
170
  }
132
171
  // send_scheduled_now: a person forced it, so it joins a running turn.
133
- service.sendNow(slug, id, session).then(function (res) {
134
- if (!res.ok) deps.sendTo(ws, { type: "error", text: "Clagentic: Console could not send that now: " + res.reason });
172
+ var pending;
173
+ try {
174
+ pending = Promise.resolve(service.sendNow(slug, id, session));
175
+ } catch (e) {
176
+ pending = Promise.reject(e);
177
+ }
178
+ pending.then(function (res) {
179
+ // Anything but an object is a failure of the service, answered like a rejection.
180
+ if (res === null || typeof res !== "object") {
181
+ throw new Error("send now resolved to " + (res === null ? "null" : typeof res));
182
+ }
183
+ return res;
184
+ }).then(function (res) {
185
+ if (!res.ok) refuseRequest(ws, requestId, "Clagentic: Console could not send that now: " + res.reason);
186
+ else confirmRequest(ws, requestId, id);
187
+ }, function (e) {
188
+ // The detail stays in the log; the client gets a reason that names nothing internal.
189
+ // The id may be the browser's own string, so it is capped and stripped before logging.
190
+ var loggedId = String(id).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 64);
191
+ console.error("[scheduled-input] " + slug + ": send now failed for " + loggedId + ":", e && e.message ? e.message : String(e));
192
+ if (requestId !== undefined) refuseRequest(ws, requestId, "Clagentic: Console could not send that now");
135
193
  });
136
194
  return true;
137
195
  }