@clagentic/console 1.10.0-beta.4 → 1.11.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +14 -0
  2. package/bin/cli.js +15 -3
  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/schedule-input-subcommands.js +327 -0
  11. package/lib/cli/session-subcommands.js +100 -17
  12. package/lib/client-build-id.js +56 -0
  13. package/lib/daemon.js +20 -5
  14. package/lib/injected-sender.js +225 -0
  15. package/lib/message-sender-record.js +133 -0
  16. package/lib/pending-prompts.js +55 -0
  17. package/lib/permission-mode-policy.js +63 -0
  18. package/lib/permission-summary.js +67 -0
  19. package/lib/project-connection.js +2 -1
  20. package/lib/project-external-trigger.js +9 -1
  21. package/lib/project-loop.js +26 -20
  22. package/lib/project-prompt-responses.js +20 -14
  23. package/lib/project-sessions.js +73 -21
  24. package/lib/project-user-message.js +18 -47
  25. package/lib/project.js +36 -62
  26. package/lib/public/app.js +3 -5
  27. package/lib/public/css/channel-layout.css +20 -0
  28. package/lib/public/css/diagnostics.css +7 -0
  29. package/lib/public/css/input.css +78 -0
  30. package/lib/public/css/menus.css +17 -0
  31. package/lib/public/modules/app-connection.js +18 -1
  32. package/lib/public/modules/app-messages.js +19 -17
  33. package/lib/public/modules/app-panels.js +9 -2
  34. package/lib/public/modules/app-rate-limit.js +63 -87
  35. package/lib/public/modules/app-rendering.js +37 -6
  36. package/lib/public/modules/at-agents.js +8 -0
  37. package/lib/public/modules/build-guard.js +61 -0
  38. package/lib/public/modules/build-update-detail.js +1 -4
  39. package/lib/public/modules/diagnostics.js +98 -9
  40. package/lib/public/modules/injected-identity.js +78 -0
  41. package/lib/public/modules/injected-label.js +62 -0
  42. package/lib/public/modules/input.js +64 -114
  43. package/lib/public/modules/mode-options.js +19 -16
  44. package/lib/public/modules/rate-limit-state.js +47 -22
  45. package/lib/public/modules/schedule-panel.js +234 -0
  46. package/lib/public/modules/schedule-time.js +193 -0
  47. package/lib/public/modules/scheduled-input-actions.js +19 -0
  48. package/lib/runtime-env.js +4 -0
  49. package/lib/scheduled-input/ipc.js +92 -0
  50. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  51. package/lib/scheduled-input/records.js +350 -0
  52. package/lib/scheduled-input/service.js +743 -0
  53. package/lib/scheduled-input/store.js +132 -0
  54. package/lib/scheduled-input/ws.js +194 -0
  55. package/lib/sdk-bridge.js +137 -152
  56. package/lib/sdk-message-processor.js +13 -5
  57. package/lib/sdk-skill-discovery.js +17 -0
  58. package/lib/sender-ref.js +109 -0
  59. package/lib/server.js +28 -8
  60. package/lib/session-directory.js +224 -0
  61. package/lib/session-file-scan.js +55 -0
  62. package/lib/session-input-ipc.js +20 -0
  63. package/lib/session-input.js +355 -19
  64. package/lib/session-name-holder.js +82 -0
  65. package/lib/session-resume.js +1 -0
  66. package/lib/sessions.js +44 -0
  67. package/lib/turn-initiator.js +6 -2
  68. package/lib/ws-schema.js +15 -7
  69. package/lib/yoke/adapters/claude-worker.js +3 -1
  70. package/lib/yoke/adapters/claude.js +13 -7
  71. package/lib/yoke/adapters/codex.js +18 -5
  72. package/lib/yoke/adapters/permission-relay.js +9 -0
  73. package/lib/yoke/interface.js +7 -1
  74. package/package.json +1 -1
  75. package/scripts/check-test-count.js +1 -1
  76. package/scripts/install-local-test.js +45 -1
  77. package/scripts/postinstall.js +1 -0
@@ -0,0 +1,327 @@
1
+ // lib/cli/schedule-input-subcommands.js
2
+ //
3
+ // `clagentic-console schedule-input create | list | delete`: schedule text to be
4
+ // sent into a console session later, once or on a repeat that always has an end,
5
+ // through the running daemon's IPC socket. The same scheduled input the clock
6
+ // button in the browser makes: a record made here shows in that list, and the
7
+ // reverse. Each verb prints the daemon's result as JSON on stdout.
8
+ //
9
+ // Flag/value pairs only, so each command shape can be allow-listed:
10
+ //
11
+ // schedule-input create --session <id> [--project <slug>]
12
+ // (--in <dur> | --at <time> | --every <dur> (--until <time> | --count <n>))
13
+ // (--prompt <text|-> | --prompt-file <path>)
14
+ // schedule-input list [--session <id>] [--project <slug>] [--state armed|done|ended|any]
15
+ // schedule-input delete --id <id> [--project <slug>]
16
+ //
17
+ // <dur> is a number of minutes or a run of s, m, h and d parts (90, 10m, 1h30m).
18
+ // <time> is a local HH:MM, or a local YYYY-MM-DDTHH:MM; an HH:MM already past
19
+ // today means tomorrow. The times are resolved here, in the caller's own time
20
+ // zone, and the daemon is sent absolute times.
21
+ //
22
+ // Exit codes (the same pattern as open-session and send-input):
23
+ // 0 done (scheduled, listed, deleted)
24
+ // 1 refused, error, or not found
25
+
26
+ var fs = require("fs");
27
+
28
+ var senderRef = require("../sender-ref");
29
+ var { LIMITS, isCount } = require("../scheduled-input/records");
30
+ var { requestDaemon, withSenderRef, EXIT } = require("./session-subcommands");
31
+
32
+ // --- The time inputs: a duration ("10m", "1h30m"), a local clock time ("20:01")
33
+ // and a local date-time ("2026-03-01T20:01"). Pure: each takes the current time
34
+ // as an argument. The browser client carries a small mirror of resolveClockTime
35
+ // (lib/public/modules/schedule-time.js) because it cannot load this CommonJS
36
+ // file; test/scheduled-input-client.test.js feeds both the same cases.
37
+
38
+ var UNIT_MS = Object.freeze({ s: 1000, m: 60000, h: 3600000, d: 86400000 });
39
+
40
+ var DURATION_RE = /^(?:\d+[smhd])+$/;
41
+ var DURATION_PART_RE = /(\d+)([smhd])/g;
42
+ var CLOCK_RE = /^(\d{1,2}):(\d{2})$/;
43
+ var DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})$/;
44
+
45
+ // A bare number is minutes, the unit the person's own field uses.
46
+ // Returns { ms } or { error }.
47
+ function parseDuration(raw) {
48
+ var text = typeof raw === "string" ? raw.trim().toLowerCase() : "";
49
+ if (/^\d+$/.test(text)) text += "m";
50
+ if (!DURATION_RE.test(text)) {
51
+ return { error: "not a duration: " + JSON.stringify(String(raw).slice(0, 32)) + " (use for example 90, 10m, 2h, 1h30m)" };
52
+ }
53
+ var total = 0;
54
+ var part;
55
+ DURATION_PART_RE.lastIndex = 0;
56
+ while ((part = DURATION_PART_RE.exec(text)) !== null) {
57
+ total += parseInt(part[1], 10) * UNIT_MS[part[2]];
58
+ }
59
+ if (!Number.isSafeInteger(total) || total <= 0) return { error: "a duration must be longer than zero" };
60
+ return { ms: total };
61
+ }
62
+
63
+ function validClock(hours, minutes) {
64
+ return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59;
65
+ }
66
+
67
+ // A local clock time resolves to its next occurrence strictly after `now`: a
68
+ // time that has passed today means tomorrow. A full local date-time is taken as
69
+ // given and must lie in the future. Returns { ms, tomorrow } or { error }.
70
+ function resolveClockTime(raw, now) {
71
+ var text = typeof raw === "string" ? raw.trim() : "";
72
+ var clock = CLOCK_RE.exec(text);
73
+ if (clock) {
74
+ var h = parseInt(clock[1], 10);
75
+ var m = parseInt(clock[2], 10);
76
+ if (!validClock(h, m)) return { error: "not a time of day: " + JSON.stringify(text) + " (use HH:MM, 00:00 to 23:59)" };
77
+ var candidate = new Date(now);
78
+ candidate.setHours(h, m, 0, 0);
79
+ var tomorrow = false;
80
+ if (candidate.getTime() <= now) {
81
+ // setDate keeps the wall-clock time across a daylight-saving change.
82
+ candidate.setDate(candidate.getDate() + 1);
83
+ tomorrow = true;
84
+ }
85
+ return { ms: candidate.getTime(), tomorrow: tomorrow };
86
+ }
87
+ var full = DATE_TIME_RE.exec(text);
88
+ if (full) {
89
+ var y = parseInt(full[1], 10);
90
+ var mo = parseInt(full[2], 10);
91
+ var d = parseInt(full[3], 10);
92
+ var hh = parseInt(full[4], 10);
93
+ var mm = parseInt(full[5], 10);
94
+ // The fields are checked as typed: Date() carries an out-of-range minute or
95
+ // hour into the next hour or day, so a check after construction cannot tell
96
+ // 20:99 from 21:39.
97
+ if (!validClock(hh, mm)) return { error: "not a date and time: " + JSON.stringify(text) + " (the time of day must be 00:00 to 23:59)" };
98
+ var when = new Date(y, mo - 1, d, hh, mm, 0, 0);
99
+ // Every field must come back unchanged, which also refuses a day the month
100
+ // lacks and a wall-clock time that a daylight-saving change skips.
101
+ var roundTrips = when.getFullYear() === y && when.getMonth() === mo - 1 && when.getDate() === d
102
+ && when.getHours() === hh && when.getMinutes() === mm;
103
+ if (!roundTrips) return { error: "not a date and time: " + JSON.stringify(text) };
104
+ if (when.getTime() <= now) return { error: "that date and time has already passed: " + JSON.stringify(text) };
105
+ return { ms: when.getTime(), tomorrow: false };
106
+ }
107
+ return { error: "not a time: " + JSON.stringify(text.slice(0, 32)) + " (use HH:MM, or YYYY-MM-DDTHH:MM, local time)" };
108
+ }
109
+
110
+ function pad2(n) {
111
+ return (n < 10 ? "0" : "") + n;
112
+ }
113
+
114
+ // "2026-03-01 20:01" in the host's local time: the unambiguous absolute form
115
+ // printed beside every resolved time.
116
+ function formatLocal(ms) {
117
+ var d = new Date(ms);
118
+ return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate()) + " " + pad2(d.getHours()) + ":" + pad2(d.getMinutes());
119
+ }
120
+
121
+ var SUBCOMMANDS = Object.freeze(["create", "list", "delete"]);
122
+
123
+ var FLAGS = {
124
+ "--session": "sessionId",
125
+ "--project": "projectSlug",
126
+ "--in": "in",
127
+ "--at": "at",
128
+ "--every": "every",
129
+ "--until": "until",
130
+ "--count": "count",
131
+ "--prompt": "prompt",
132
+ "--prompt-file": "promptFile",
133
+ "--id": "id",
134
+ "--state": "state",
135
+ };
136
+
137
+ var ALLOWED = {
138
+ create: ["sessionId", "projectSlug", "in", "at", "every", "until", "count", "prompt", "promptFile"],
139
+ list: ["sessionId", "projectSlug", "state"],
140
+ delete: ["id", "projectSlug"],
141
+ };
142
+
143
+ var USAGE = {
144
+ create: "Usage: clagentic-console schedule-input create --session <id> [--project <slug>] (--in <dur> | --at <time> | --every <dur> (--until <time> | --count <n>)) (--prompt <text|-> | --prompt-file <path>)",
145
+ list: "Usage: clagentic-console schedule-input list [--session <id>] [--project <slug>] [--state armed|done|ended|any]",
146
+ delete: "Usage: clagentic-console schedule-input delete --id <id> [--project <slug>]",
147
+ };
148
+
149
+ var IPC_COMMAND = {
150
+ create: "schedule_input_create",
151
+ list: "schedule_input_list",
152
+ delete: "schedule_input_delete",
153
+ };
154
+
155
+ var COUNT_RE = /^\d+$/;
156
+
157
+ function has(obj, key) {
158
+ return Object.prototype.hasOwnProperty.call(obj, key);
159
+ }
160
+
161
+ function given(parsed, key) {
162
+ return parsed[key] !== undefined;
163
+ }
164
+
165
+ // The timing flags of create, resolved against `now` (ms). Returns
166
+ // { fields, resolved } or { error }: fields go to the daemon, resolved says what
167
+ // the times came to (absolute, local, and whether a clock time rolled to
168
+ // tomorrow).
169
+ function resolveTiming(parsed, now) {
170
+ var shapes = ["in", "at", "every"].filter(function (k) { return given(parsed, k); });
171
+ if (shapes.length !== 1) return { error: "Give exactly one of --in, --at or --every" };
172
+ var shape = shapes[0];
173
+ var resolved = {};
174
+
175
+ if (shape !== "every") {
176
+ if (given(parsed, "until") || given(parsed, "count")) return { error: "--until and --count belong to --every" };
177
+ if (shape === "in") {
178
+ var dur = parseDuration(parsed.in);
179
+ if (dur.error) return { error: "--in: " + dur.error };
180
+ resolved.at = now + dur.ms;
181
+ } else {
182
+ var when = resolveClockTime(parsed.at, now);
183
+ if (when.error) return { error: "--at: " + when.error };
184
+ resolved.at = when.ms;
185
+ resolved.tomorrow = when.tomorrow;
186
+ }
187
+ return { fields: { at: resolved.at }, resolved: { at: resolved.at, atLocal: formatLocal(resolved.at), tomorrow: !!resolved.tomorrow } };
188
+ }
189
+
190
+ var every = parseDuration(parsed.every);
191
+ if (every.error) return { error: "--every: " + every.error };
192
+ if (given(parsed, "until") === given(parsed, "count")) {
193
+ return { error: "A repeat needs an end: give exactly one of --until or --count" };
194
+ }
195
+ var fields = { every: every.ms };
196
+ var out = { every: every.ms, firstAt: now + every.ms, firstAtLocal: formatLocal(now + every.ms) };
197
+ if (given(parsed, "until")) {
198
+ var until = resolveClockTime(parsed.until, now);
199
+ if (until.error) return { error: "--until: " + until.error };
200
+ fields.until = until.ms;
201
+ out.until = until.ms;
202
+ out.untilLocal = formatLocal(until.ms);
203
+ out.tomorrow = until.tomorrow;
204
+ } else {
205
+ var count = COUNT_RE.test(parsed.count) ? Number(parsed.count) : NaN;
206
+ if (!isCount(count)) return { error: "--count must be a whole number from 1 to " + LIMITS.MAX_COUNT };
207
+ fields.count = count;
208
+ out.count = fields.count;
209
+ }
210
+ return { fields: fields, resolved: out };
211
+ }
212
+
213
+ // Parses the arguments after the subcommand. Returns { request, resolved } or
214
+ // { error }. Pure: reading a "-" prompt from stdin or a --prompt-file is the
215
+ // handler's job. env supplies the calling session's project as the default.
216
+ function parseScheduleArgs(sub, args, now, env) {
217
+ if (!has(ALLOWED, sub)) return { error: "Unknown schedule-input command: " + sub };
218
+ var allowed = ALLOWED[sub];
219
+ var parsed = {};
220
+ for (var i = 0; i < args.length; i++) {
221
+ var key = has(FLAGS, args[i]) ? FLAGS[args[i]] : null;
222
+ if (!key || allowed.indexOf(key) === -1) return { error: "Unknown option for schedule-input " + sub + ": " + args[i] };
223
+ if (i + 1 >= args.length) return { error: "Missing value for " + args[i] };
224
+ if (given(parsed, key)) return { error: "Option given twice: " + args[i] };
225
+ parsed[key] = args[++i];
226
+ }
227
+
228
+ var request = { cmd: IPC_COMMAND[sub] };
229
+ if (given(parsed, "projectSlug")) request.projectSlug = parsed.projectSlug;
230
+
231
+ if (sub === "delete") {
232
+ if (!given(parsed, "id")) return { error: "Missing required option --id" };
233
+ request.id = parsed.id;
234
+ return { request: request };
235
+ }
236
+
237
+ if (sub === "list") {
238
+ if (given(parsed, "sessionId")) request.sessionId = parsed.sessionId;
239
+ if (given(parsed, "state")) request.state = parsed.state;
240
+ return { request: request };
241
+ }
242
+
243
+ if (!given(parsed, "sessionId")) return { error: "Missing required option --session" };
244
+ request.sessionId = parsed.sessionId;
245
+ // The session's own project when the caller is a console session and names none.
246
+ if (!request.projectSlug) {
247
+ var ref = senderRef.fromEnv(env);
248
+ if (ref) request.projectSlug = ref.project;
249
+ }
250
+ if (!request.projectSlug) return { error: "Missing required option --project (this shell is not inside a console session)" };
251
+ if (given(parsed, "prompt") === given(parsed, "promptFile")) {
252
+ return { error: "Give the text one way only: --prompt <text|-> or --prompt-file <path>" };
253
+ }
254
+ if (given(parsed, "prompt")) request.prompt = parsed.prompt;
255
+ else request.promptFile = parsed.promptFile;
256
+ var timing = resolveTiming(parsed, now);
257
+ if (timing.error) return { error: timing.error };
258
+ Object.assign(request, timing.fields);
259
+ return { request: request, resolved: timing.resolved };
260
+ }
261
+
262
+ // Reads a "-" prompt from stdin and a --prompt-file from disk, as the verbs of
263
+ // session-subcommands read their prompt. Returns an error string or null.
264
+ function loadPrompt(request, readStdin, readFile) {
265
+ if (request.promptFile !== undefined) {
266
+ try { request.prompt = readFile(request.promptFile).replace(/\n$/, ""); }
267
+ catch (e) { return "Cannot read --prompt-file " + request.promptFile + ": " + (e && e.message ? e.message : String(e)); }
268
+ delete request.promptFile;
269
+ } else if (request.prompt === "-") {
270
+ request.prompt = readStdin().replace(/\n$/, "");
271
+ }
272
+ return null;
273
+ }
274
+
275
+ // Says, beside the daemon's answer, what the times came to in the caller's own
276
+ // local time, so a clock time that rolled to tomorrow is plain to see.
277
+ function withResolved(res, resolved) {
278
+ if (res && res.ok && resolved) res.resolved = resolved;
279
+ return res;
280
+ }
281
+
282
+ function exitCodeFor(res) {
283
+ return res && res.ok ? EXIT.OK : EXIT.FAILED;
284
+ }
285
+
286
+ function fail(message) {
287
+ console.error(message);
288
+ process.exit(1);
289
+ }
290
+
291
+ function runScheduleInput(args) {
292
+ var sub = args[0];
293
+ if (SUBCOMMANDS.indexOf(sub) === -1) {
294
+ console.error("Unknown schedule-input command: " + String(sub));
295
+ fail("Usage: clagentic-console schedule-input (" + SUBCOMMANDS.join(" | ") + ") ...");
296
+ return;
297
+ }
298
+ var parsed = parseScheduleArgs(sub, args.slice(1), Date.now(), process.env);
299
+ if (parsed.error) {
300
+ console.error(parsed.error);
301
+ fail(USAGE[sub]);
302
+ return;
303
+ }
304
+ var request = parsed.request;
305
+ if (sub === "create") {
306
+ var promptError = loadPrompt(request, function () { return fs.readFileSync(0, "utf8"); }, function (p) { return fs.readFileSync(p, "utf8"); });
307
+ if (promptError) { fail(promptError); return; }
308
+ withSenderRef(request, process.env);
309
+ }
310
+ requestDaemon(request).then(function (res) {
311
+ console.log(JSON.stringify(withResolved(res, parsed.resolved), null, 2));
312
+ // Not process.exit: on a pipe it can cut the JSON off before stdout drains.
313
+ process.exitCode = exitCodeFor(res);
314
+ });
315
+ }
316
+
317
+ module.exports = {
318
+ parseDuration: parseDuration,
319
+ resolveClockTime: resolveClockTime,
320
+ formatLocal: formatLocal,
321
+ parseScheduleArgs: parseScheduleArgs,
322
+ loadPrompt: loadPrompt,
323
+ withResolved: withResolved,
324
+ exitCodeFor: exitCodeFor,
325
+ runScheduleInput: runScheduleInput,
326
+ USAGE: USAGE,
327
+ };
@@ -1,69 +1,125 @@
1
1
  // lib/cli/session-subcommands.js
2
2
  //
3
- // `clagentic-console open-session` and `clagentic-console send-input`: open a
4
- // session in a project, or send input to one, through the running daemon's IPC
5
- // socket. Both print the daemon's result as JSON on stdout and exit 0 when the
6
- // request was acted on (opened, delivered, resumed-and-delivered), 1 otherwise
7
- // (not-found, refused, error), so a script can branch on either.
3
+ // `clagentic-console open-session`, `send-input` and `list-sessions`: open a
4
+ // session in a project, send input to one, or list the sessions, through the
5
+ // running daemon's IPC socket. Each prints the daemon's result as JSON on stdout.
6
+ //
7
+ // Exit codes (documented in docs/guides/AGENT-GUIDE.md):
8
+ // 0 the request was acted on (opened, delivered, resumed-and-delivered, listed)
9
+ // 1 refused, error, or not-found for a request that named a session id
10
+ // 3 ambiguous: an address named several sessions; the candidates are in the JSON
11
+ // 4 not-found for a request that gave an address (--to) or --reply
8
12
 
9
13
  var fs = require("fs");
10
14
 
11
15
  var { loadConfig, socketPath, isDaemonAliveAsync } = require("../config");
12
16
  var { sendIPCCommand } = require("../ipc");
17
+ var senderRef = require("../sender-ref");
13
18
 
14
19
  // A resumed session starts a runtime before the call answers: longer than the
15
20
  // IPC default.
16
21
  var IPC_TIMEOUT_MS = 30000;
17
22
 
23
+ var EXIT = Object.freeze({ OK: 0, FAILED: 1, AMBIGUOUS: 3, NOT_FOUND_BY_ADDRESS: 4 });
24
+
18
25
  var FLAGS = {
19
26
  "--project": "projectSlug",
20
27
  "--session": "sessionId",
28
+ "--to": "to",
21
29
  "--prompt": "prompt",
22
30
  "--vendor": "vendor",
23
31
  "--agent": "agentName",
32
+ "--name": "sessionName",
33
+ "--state": "state",
24
34
  "--visibility": "sessionVisibility",
25
35
  "--initiator": "initiator",
26
36
  "--context-note": "contextNote",
37
+ "--from": "from",
38
+ "--from-session": "fromSession",
39
+ };
40
+
41
+ // Kept apart from FLAGS because the parser reads a value after every FLAGS
42
+ // entry; a flag listed there would swallow the next argument.
43
+ var SWITCHES = {
44
+ "--reply": "reply",
27
45
  };
28
46
 
29
47
  var USAGE = {
30
- "open-session": "Usage: clagentic-console open-session --project <slug> --prompt <text|-> [--vendor <id>] [--agent <name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>]",
31
- "send-input": "Usage: clagentic-console send-input --project <slug> --session <id> --prompt <text|-> [--initiator <kind>] [--context-note <text>]",
48
+ "open-session": "Usage: clagentic-console open-session (--project <slug> | --to <address>) --prompt <text|-> [--vendor <id>] [--agent <name>] [--name <session-name>] [--visibility shared|private] [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
49
+ "send-input": "Usage: clagentic-console send-input (--project <slug> --session <id> | --to <address> | --reply) --prompt <text|-> [--initiator <kind>] [--context-note <text>] [--from <name>] [--from-session <id>]",
50
+ "list-sessions": "Usage: clagentic-console list-sessions [--project <slug>] [--agent <name>] [--vendor <id>] [--state live|idle|reaped|any]",
32
51
  };
33
52
 
34
53
  var ALLOWED = {
35
- "open-session": ["projectSlug", "prompt", "vendor", "agentName", "sessionVisibility", "initiator", "contextNote"],
36
- "send-input": ["projectSlug", "sessionId", "prompt", "initiator", "contextNote"],
54
+ "open-session": ["projectSlug", "to", "prompt", "vendor", "agentName", "sessionName", "sessionVisibility", "initiator", "contextNote", "from", "fromSession"],
55
+ "send-input": ["projectSlug", "sessionId", "to", "reply", "prompt", "initiator", "contextNote", "from", "fromSession"],
56
+ "list-sessions": ["projectSlug", "agentName", "vendor", "state"],
37
57
  };
38
58
 
39
59
  var REQUIRED = {
40
- "open-session": ["projectSlug", "prompt"],
41
- "send-input": ["projectSlug", "sessionId", "prompt"],
60
+ "open-session": ["prompt"],
61
+ "send-input": ["prompt"],
62
+ "list-sessions": [],
63
+ };
64
+
65
+ var TARGET_HINT = {
66
+ "open-session": "--project, or --to",
67
+ "send-input": "--session (with --project), or --to, or --reply",
42
68
  };
43
69
 
44
70
  var IPC_COMMAND = {
45
71
  "open-session": "open_session",
46
72
  "send-input": "send_session_input",
73
+ "list-sessions": "list_sessions",
47
74
  };
48
75
 
76
+ function flagOf(key) {
77
+ var all = Object.keys(FLAGS).concat(Object.keys(SWITCHES));
78
+ return all.filter(function (f) { return FLAGS[f] === key || SWITCHES[f] === key; })[0];
79
+ }
80
+
81
+ function has(obj, key) {
82
+ return Object.prototype.hasOwnProperty.call(obj, key);
83
+ }
84
+
85
+ // Checks how the target is named: a project (and for send-input a session id),
86
+ // or an address (--to, which may be given beside the project it names), or for
87
+ // send-input --reply. One way only. Returns an error string or null.
88
+ function checkTarget(verb, request) {
89
+ if (!TARGET_HINT[verb]) return null;
90
+ var conflict = "Give the target one way only: " + TARGET_HINT[verb];
91
+ var given = function (k) { return request[k] !== undefined; };
92
+ if (given("to")) return given("sessionId") || given("reply") ? conflict : null;
93
+ if (given("reply")) return given("projectSlug") || given("sessionId") ? conflict : null;
94
+ if (!given("projectSlug") && !given("sessionId")) return "Missing the target: " + TARGET_HINT[verb];
95
+ if (!given("projectSlug")) return "Missing required option --project";
96
+ if (verb === "send-input" && !given("sessionId")) return "Missing required option --session";
97
+ return null;
98
+ }
99
+
49
100
  // Parses the arguments after the verb. Returns { request } or { error }.
50
101
  // Pure: reading a "-" prompt from stdin is the handler's job.
51
102
  function parseSessionArgs(verb, args) {
52
103
  var allowed = ALLOWED[verb];
53
104
  var request = {};
54
105
  for (var i = 0; i < args.length; i++) {
55
- var key = Object.prototype.hasOwnProperty.call(FLAGS, args[i]) ? FLAGS[args[i]] : null;
106
+ if (has(SWITCHES, args[i])) {
107
+ var switchKey = SWITCHES[args[i]];
108
+ if (allowed.indexOf(switchKey) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
109
+ request[switchKey] = true;
110
+ continue;
111
+ }
112
+ var key = has(FLAGS, args[i]) ? FLAGS[args[i]] : null;
56
113
  if (!key || allowed.indexOf(key) === -1) return { error: "Unknown option for " + verb + ": " + args[i] };
57
114
  if (i + 1 >= args.length) return { error: "Missing value for " + args[i] };
58
115
  request[key] = args[++i];
59
116
  }
60
117
  var required = REQUIRED[verb];
61
118
  for (var r = 0; r < required.length; r++) {
62
- if (!request[required[r]]) {
63
- var flag = Object.keys(FLAGS).filter(function (f) { return FLAGS[f] === required[r]; })[0];
64
- return { error: "Missing required option " + flag };
65
- }
119
+ if (!request[required[r]]) return { error: "Missing required option " + flagOf(required[r]) };
66
120
  }
121
+ var targetError = checkTarget(verb, request);
122
+ if (targetError) return { error: targetError };
67
123
  return { request: request };
68
124
  }
69
125
 
@@ -75,6 +131,29 @@ function normalizeResponse(res) {
75
131
  return { ok: false, result: "error", reason: reason };
76
132
  }
77
133
 
134
+ // Called from inside a console session, the caller's environment holds the
135
+ // console's reference to that session (lib/sender-ref.js). It is passed to the
136
+ // daemon automatically, no flag; outside a console session there is none.
137
+ function withSenderRef(request, env) {
138
+ var ref = senderRef.fromEnv(env);
139
+ if (ref) {
140
+ request.senderProject = ref.project;
141
+ request.senderSessionId = ref.sessionId;
142
+ }
143
+ return request;
144
+ }
145
+
146
+ // The process exit code for a result. request says how the target was named: an
147
+ // address or a reply is told apart from an id so a script can branch on it.
148
+ function exitCodeFor(res, request) {
149
+ if (res && res.ok) return EXIT.OK;
150
+ if (res && res.result === "ambiguous") return EXIT.AMBIGUOUS;
151
+ if (res && res.result === "not-found" && request && (request.to !== undefined || request.reply)) {
152
+ return EXIT.NOT_FOUND_BY_ADDRESS;
153
+ }
154
+ return EXIT.FAILED;
155
+ }
156
+
78
157
  function fail(message) {
79
158
  console.error(message);
80
159
  process.exit(1);
@@ -92,11 +171,12 @@ function runSessionVerb(verb, args) {
92
171
  request.prompt = fs.readFileSync(0, "utf8").replace(/\n$/, "");
93
172
  }
94
173
  request.cmd = IPC_COMMAND[verb];
174
+ if (verb !== "list-sessions") withSenderRef(request, process.env);
95
175
 
96
176
  requestDaemon(request).then(function (res) {
97
177
  console.log(JSON.stringify(res, null, 2));
98
178
  // Not process.exit: on a pipe it can cut the JSON off before stdout drains.
99
- process.exitCode = res && res.ok ? 0 : 1;
179
+ process.exitCode = exitCodeFor(res, request);
100
180
  });
101
181
  }
102
182
 
@@ -117,6 +197,9 @@ function requestDaemon(request, deps) {
117
197
  module.exports = {
118
198
  requestDaemon: requestDaemon,
119
199
  parseSessionArgs: parseSessionArgs,
200
+ withSenderRef: withSenderRef,
201
+ exitCodeFor: exitCodeFor,
120
202
  runSessionVerb: runSessionVerb,
203
+ EXIT: EXIT,
121
204
  SESSION_VERBS: Object.keys(IPC_COMMAND),
122
205
  };
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ // client-build-id.js — the one identity a browser compares to decide whether the
4
+ // client code it is running still matches the daemon that serves it.
5
+ //
6
+ // It is keyed on the BUILD, not on package.json's version: two builds can share
7
+ // a version (consecutive betas do), and a client keyed on the version then never
8
+ // notices the restart onto the newer one. The build SHA the daemon loaded at
9
+ // startup is used when the install carries one; a checkout without
10
+ // lib/build-sha.json gets a per-start nonce, so a restart still changes the id.
11
+
12
+ var crypto = require("crypto");
13
+
14
+ var SERVICE_WORKER_CACHE_PATTERN = /var CACHE_NAME = "clagentic-console-offline-[^"]*"/;
15
+
16
+ var current = null;
17
+
18
+ function newNonce() {
19
+ return "start-" + crypto.randomBytes(6).toString("hex");
20
+ }
21
+
22
+ /**
23
+ * Fixes the id for this process. Called once, with the SHA the daemon captured
24
+ * at startup (null when the install has none). Later calls are ignored: an id
25
+ * that moved mid-process would tell clients to reload for no deploy.
26
+ */
27
+ function init(buildSha) {
28
+ if (current) return current;
29
+ current = typeof buildSha === "string" && buildSha ? buildSha : newNonce();
30
+ return current;
31
+ }
32
+
33
+ /** The id for this process; a nonce when init was never given a SHA. */
34
+ function get() {
35
+ return current || init(null);
36
+ }
37
+
38
+ // Cache names are restricted to a conservative alphabet: the id is embedded in
39
+ // served JavaScript, and a hand-edited build-sha.json must not break out of it.
40
+ function cacheSafe(id) {
41
+ return String(id).replace(/[^A-Za-z0-9._-]/g, "_");
42
+ }
43
+
44
+ /**
45
+ * The service worker source with its cache name stamped for `buildId`. A
46
+ * different id yields different bytes, which is what makes the browser install
47
+ * the new worker after a restart onto a new build.
48
+ */
49
+ function stampServiceWorker(source, buildId) {
50
+ return source.replace(
51
+ SERVICE_WORKER_CACHE_PATTERN,
52
+ 'var CACHE_NAME = "clagentic-console-offline-v' + cacheSafe(buildId) + '"'
53
+ );
54
+ }
55
+
56
+ module.exports = { init: init, get: get, stampServiceWorker: stampServiceWorker };
package/lib/daemon.js CHANGED
@@ -44,10 +44,9 @@ var { createDrain } = require("./drain");
44
44
  var { setNewWorkGate } = require("./new-work-gate");
45
45
  var { shedMemory } = require("./memory-shed");
46
46
  var { dropSkillsCache } = require("./server-skills");
47
- var { waitForIdleThenAct } = require("./build-update-check");
48
47
  var { createBuildMonitor } = require("./build-monitor");
49
48
  var { createBuildUpdateRestart } = require("./build-update-restart");
50
- var { composeNotice, noticeCooldownFrom } = require("./build-update-offer");
49
+ var { composeNotice, noticeCooldownFrom, composeRestartingNotice } = require("./build-update-offer");
51
50
  var { createStandingOffer } = require("./build-update-standing");
52
51
  var { listBuildChanges, resolveHistoryRepo } = require("./build-changes");
53
52
  var { RESTART_EXIT_CODE, isSupervised, unsupervisedEnv } = require("./supervisor");
@@ -134,6 +133,9 @@ function checkStaleInodes() {
134
133
  // the file and it is gitignored): "no build-identity signal", not an error.
135
134
  var loadedBuildSha = null;
136
135
  loadedBuildSha = buildIdentity.loaded.sha;
136
+ // Browsers compare this id to know the client they run is the one this daemon
137
+ // serves; fixed here, from the SHA captured above, before any request is served.
138
+ require("./client-build-id").init(loadedBuildSha);
137
139
  console.log("[daemon] Build: sha=" + (loadedBuildSha || "(none)") +
138
140
  " files=" + (buildIdentity.loaded.contentHash ? buildIdentity.loaded.contentHash.slice(0, 12) : "(unreadable)"));
139
141
 
@@ -1424,9 +1426,9 @@ var buildUpdateRestart = createBuildUpdateRestart({
1424
1426
  console.log("[daemon] Restarting to adopt the installed build, as the operator confirmed");
1425
1427
  spawnAndRestart();
1426
1428
  },
1427
- waitForIdleThenAct: waitForIdleThenAct,
1428
- announce: function (message) {
1429
- relay.broadcastAll({ type: "diagnostic", severity: "warning", source: "build-update", message: message });
1429
+ onScheduled: function () {
1430
+ relay.broadcastAll({ type: "diagnostic_retract", source: "build-update" });
1431
+ relay.broadcastAll(composeRestartingNotice());
1430
1432
  },
1431
1433
  log: function (line) { console.log("[daemon] " + line); },
1432
1434
  });
@@ -1678,8 +1680,21 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1678
1680
  // counts as a human turn (session-input.js refuses that initiator).
1679
1681
  case "open_session":
1680
1682
  case "send_session_input":
1683
+ case "list_sessions":
1681
1684
  return require("./session-input-ipc").handleSessionCommand(relay.sessionInput, msg);
1682
1685
 
1686
+ // Scheduled input: text sent into a session later, once or on a repeat with
1687
+ // an end. The same service the clock button in the browser uses, so a record
1688
+ // made here shows there and the reverse. Same OS-level socket gate as the
1689
+ // commands above.
1690
+ case "schedule_input_create":
1691
+ case "schedule_input_list":
1692
+ case "schedule_input_delete":
1693
+ return require("./scheduled-input/ipc").handleScheduledInputCommand({
1694
+ service: relay.scheduledInput,
1695
+ getProject: relay.getProject,
1696
+ }, msg);
1697
+
1683
1698
  case "set_pin": {
1684
1699
  config.pinHash = msg.pinHash || null;
1685
1700
  relay.setAuthToken(config.pinHash);