@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
@@ -263,6 +263,8 @@ function attachMessageProcessor(ctx) {
263
263
  var _isNewSessionId = !session.cliSessionId;
264
264
  session.cliSessionId = parsed.sessionId;
265
265
  sm.saveSessionFile(session);
266
+ // Messages sent before the vendor named the session were held until now.
267
+ if (typeof sm.flushSenderRecords === "function") sm.flushSenderRecords(session);
266
268
  if (_isNewSessionId) {
267
269
  sendAndRecord(session, { type: "session_id", cliSessionId: session.cliSessionId });
268
270
  }
@@ -331,6 +333,11 @@ function attachMessageProcessor(ctx) {
331
333
  if (parsed.inputTokens) {
332
334
  session.lastStreamInputTokens = parsed.inputTokens;
333
335
  }
336
+ // A vendor that numbers its own turns (Codex) names the turn the message
337
+ // started: published beside the message's sender record.
338
+ if (parsed.messageId && parsed.turnId && typeof sm.bindSenderTurn === "function") {
339
+ sm.bindSenderTurn(session, parsed.messageId, parsed.turnId);
340
+ }
334
341
 
335
342
  } else if (parsed.yokeType === "tool_start" || parsed.yokeType === "thinking_start" || parsed.yokeType === "text_start") {
336
343
  var idx = parsed.blockId;
@@ -938,7 +945,8 @@ function attachMessageProcessor(ctx) {
938
945
 
939
946
  // Schedule auto-continue immediately on rejection (don't wait for
940
947
  // query completion which has timing issues with worker/non-worker paths).
941
- if (!session.scheduledMessage && !session.destroying) {
948
+ var resumeArmed = typeof opts.hasRateLimitResume === "function" && opts.hasRateLimitResume(session);
949
+ if (!resumeArmed && !session.destroying) {
942
950
  var acEnabled = session.onQueryComplete ||
943
951
  (typeof opts.getAutoContinueSetting === "function" && opts.getAutoContinueSetting(session));
944
952
  console.log("[sdk-bridge] rate_limit rejected: acEnabled=" + acEnabled + " overage=" + !!info.isUsingOverage + " session=" + session.localId);
@@ -948,16 +956,16 @@ function attachMessageProcessor(ctx) {
948
956
  // Extra usage available: send continue immediately (5s delay for query to finish)
949
957
  console.log("[sdk-bridge] Overage available, sending immediate continue for session " + session.localId);
950
958
  session.rateLimitResetsAt = null;
951
- if (typeof opts.scheduleMessage === "function") {
952
- opts.scheduleMessage(session, "continue", Date.now());
959
+ if (typeof opts.scheduleRateLimitResume === "function") {
960
+ opts.scheduleRateLimitResume(session, Date.now());
953
961
  }
954
962
  } else {
955
963
  // No overage: schedule after rate limit resets
956
964
  var acResetsAt = session.rateLimitResetsAt;
957
965
  session.rateLimitResetsAt = null;
958
966
  console.log("[sdk-bridge] Scheduling auto-continue on rate limit rejection for session " + session.localId);
959
- if (typeof opts.scheduleMessage === "function") {
960
- opts.scheduleMessage(session, "continue", acResetsAt);
967
+ if (typeof opts.scheduleRateLimitResume === "function") {
968
+ opts.scheduleRateLimitResume(session, acResetsAt);
961
969
  }
962
970
  }
963
971
  }
@@ -24,6 +24,22 @@ function resolveContainedSkillDir(base, entryName) {
24
24
  }
25
25
  }
26
26
 
27
+ // The only characters a command may hold and still be auto-approved: letters,
28
+ // digits, space, tab and . _ / : @ ^ ~ + , % - | ; and "&" (only as "&&").
29
+ // This is an allowlist because every denylist of shell syntax kept missing a
30
+ // shape that builds a word after the check (${X:---output}, {--output,f},
31
+ // -\-output, "--out""put", a glob matching a file named like a flag). With no
32
+ // quote, escape, expansion, brace, glob, redirection, assignment or newline in
33
+ // the text, each token is exactly what the command receives, so the per-command
34
+ // argument checks see the real arguments. Anything else costs a prompt.
35
+ var AUTO_APPROVABLE_SHELL_RE = /^[A-Za-z0-9 \t._\/:@^~+,%|;&-]*$/;
36
+
37
+ function hasUnapprovableShellSyntax(cmd) {
38
+ if (typeof cmd !== "string" || !AUTO_APPROVABLE_SHELL_RE.test(cmd)) return true;
39
+ // A "&" that is not half of "&&" is a background job.
40
+ return cmd.replace(/&&/g, "").indexOf("&") !== -1;
41
+ }
42
+
27
43
  // Split shell command on operators (&&, ||, ;, |) while respecting quotes
28
44
  // and parentheses. Returns array of command segments.
29
45
  function splitShellSegments(cmd) {
@@ -360,6 +376,7 @@ function attachSkillDiscovery(ctx) {
360
376
 
361
377
  module.exports = {
362
378
  splitShellSegments: splitShellSegments,
379
+ hasUnapprovableShellSyntax: hasUnapprovableShellSyntax,
363
380
  attachSkillDiscovery: attachSkillDiscovery,
364
381
  extractDescriptionFromContent: extractDescriptionFromContent,
365
382
  extractSkillDescription: extractSkillDescription,
@@ -0,0 +1,109 @@
1
+ // sender-ref.js - the plain reference a console-started agent process carries to
2
+ // its own console session, and how the daemon resolves one.
3
+ //
4
+ // Part of the console's session-record format. Two non-secret variables are set
5
+ // in the environment of every Claude process the console starts, whatever
6
+ // identity provider is configured:
7
+ //
8
+ // CLAGENTIC_CONSOLE_PROJECT the project slug the session belongs to
9
+ // CLAGENTIC_CONSOLE_SESSION_ID the console session id (localId) in that project
10
+ //
11
+ // The pair is not an identity assertion and grants nothing. send-input,
12
+ // open-session and a file-drop writer pass it along; the daemon looks it up in
13
+ // its OWN session store and records the sender as "extracted". It is not proof
14
+ // against a same-user process copying the variables; only an attested sender is.
15
+
16
+ var PROJECT_ENV = "CLAGENTIC_CONSOLE_PROJECT";
17
+ var SESSION_ENV = "CLAGENTIC_CONSOLE_SESSION_ID";
18
+
19
+ var SESSION_ID_RE = /^[0-9]{1,9}$/;
20
+
21
+ // The environment additions for a session, or {} when it has no usable reference.
22
+ function envFor(ref) {
23
+ if (!ref || typeof ref.project !== "string" || !ref.project) return {};
24
+ var id = String(ref.sessionId);
25
+ if (!SESSION_ID_RE.test(id)) return {};
26
+ var out = {};
27
+ out[PROJECT_ENV] = ref.project;
28
+ out[SESSION_ENV] = id;
29
+ return out;
30
+ }
31
+
32
+ // Removes any inherited reference: the console sets it only for a session it
33
+ // started, so a daemon launched from inside a session must not pass its own on.
34
+ function strip(env) {
35
+ delete env[PROJECT_ENV];
36
+ delete env[SESSION_ENV];
37
+ return env;
38
+ }
39
+
40
+ // The reference a caller process holds, from its environment. null when absent.
41
+ function fromEnv(env) {
42
+ env = env || {};
43
+ var project = env[PROJECT_ENV];
44
+ var sessionId = env[SESSION_ENV];
45
+ if (typeof project !== "string" || !project || typeof sessionId !== "string" || !sessionId) return null;
46
+ return { project: project, sessionId: sessionId };
47
+ }
48
+
49
+ // The one label for a session, "<agent>@<project>" or, with no named agent,
50
+ // "<vendor>@<project>". null when it has neither. The chat's sender label and
51
+ // the session directory's addresses are both this.
52
+ function labelFor(agent, vendor, project) {
53
+ var who = agent || vendor;
54
+ if (!who || !project) return null;
55
+ return who + "@" + project;
56
+ }
57
+
58
+ function isLive(session) {
59
+ return !!(session.isProcessing || session.queryInstance || (session.worker && session.messageQueue === "worker"));
60
+ }
61
+
62
+ // Resolves a reference against the daemon's own store. Returns
63
+ // { project, sessionId, agent, vendor, cliSessionId, name } or null. null (never a guess) when
64
+ // the project or session is not held, the session has no live runtime (the
65
+ // caller of a reference is a running process of that session), or it runs as
66
+ // another OS user (the daemon's socket and trigger directory admit only its own).
67
+ //
68
+ // getProject(slug) -> project context | null
69
+ function resolve(getProject, ref) {
70
+ if (!ref || typeof ref.project !== "string" || !ref.project) return null;
71
+ var id = typeof ref.sessionId === "number" ? String(ref.sessionId) : ref.sessionId;
72
+ if (typeof id !== "string" || !SESSION_ID_RE.test(id)) return null;
73
+ var project = getProject(ref.project);
74
+ if (!project || !project.sm || !project.sm.sessions) return null;
75
+ var found = null;
76
+ project.sm.sessions.forEach(function (s) {
77
+ if (!found && String(s.localId) === id) found = s;
78
+ });
79
+ if (!found || !isLive(found)) return null;
80
+ if (typeof project.getLinuxUserForSession === "function" && project.getLinuxUserForSession(found)) return null;
81
+ // Required here: the worker loads this module for its env helpers only.
82
+ var slugifyAgentName = require("./agents").slugifyAgentName;
83
+ var agent = found.agentName || null;
84
+ var vendor = found.vendor || project.sm.defaultVendor || null;
85
+ var name = labelFor(agent, vendor, ref.project);
86
+ if (!name) return null;
87
+ return {
88
+ project: ref.project,
89
+ sessionId: id,
90
+ agent: agent,
91
+ agentSlug: agent ? slugifyAgentName(agent) : null,
92
+ vendor: vendor,
93
+ // The vendor's own session id: unlike the console id it survives a daemon
94
+ // restart, so it can prove later that a console id still names this session.
95
+ cliSessionId: found.cliSessionId || null,
96
+ name: name,
97
+ };
98
+ }
99
+
100
+ module.exports = {
101
+ labelFor: labelFor,
102
+ isLive: isLive,
103
+ PROJECT_ENV: PROJECT_ENV,
104
+ SESSION_ENV: SESSION_ENV,
105
+ envFor: envFor,
106
+ strip: strip,
107
+ fromEnv: fromEnv,
108
+ resolve: resolve,
109
+ };
package/lib/server.js CHANGED
@@ -23,6 +23,7 @@ var { resolveEffectiveProtocol } = require("./effective-protocol");
23
23
  var { createProjectAccess } = require("./project-access");
24
24
  var { checkWsOrigin } = require("./ws-origin");
25
25
  var sessionReclaim = require("./session-reclaim");
26
+ var clientBuildId = require("./client-build-id");
26
27
 
27
28
  var https = require("https");
28
29
  var pkg = require("../package.json");
@@ -70,17 +71,13 @@ var MIME_TYPES = {
70
71
  function serveStatic(urlPath, res) {
71
72
  if (urlPath === "/") urlPath = "/index.html";
72
73
 
73
- // Special case: inject version into sw.js cache name at serve time
74
+ // Special case: stamp the sw.js cache name with the build id at serve time.
75
+ // The build id, not the package version: consecutive builds can share a
76
+ // version, and the worker must change bytes on every restart onto a new build.
74
77
  if (urlPath === "/sw.js") {
75
78
  var swPath = path.join(publicDir, "sw.js");
76
79
  try {
77
- var swContent = fs.readFileSync(swPath, "utf8");
78
- var appVersion = pkg.version;
79
- // Replace the static cache name with a version-stamped one
80
- swContent = swContent.replace(
81
- /var CACHE_NAME = "clagentic-console-offline-[^"]*"/,
82
- 'var CACHE_NAME = "clagentic-console-offline-v' + appVersion + '"'
83
- );
80
+ var swContent = clientBuildId.stampServiceWorker(fs.readFileSync(swPath, "utf8"), clientBuildId.get());
84
81
  res.writeHead(200, {
85
82
  "Content-Type": "application/javascript; charset=utf-8",
86
83
  "Cache-Control": "no-cache",
@@ -225,14 +222,13 @@ function isPublicShellAssetPath(projectUrlPath) {
225
222
 
226
223
  /**
227
224
  * Create a multi-project server.
228
- * opts: { tlsOptions, caPath, pinHash, port, debug, dangerouslySkipPermissions }
225
+ * opts: { tlsOptions, caPath, pinHash, port, debug }
229
226
  */
230
227
  function createServer(opts) {
231
228
  var tlsOptions = opts.tlsOptions || null;
232
229
  var caPath = opts.caPath || null;
233
230
  var portNum = opts.port || 2633;
234
231
  var debug = opts.debug || false;
235
- var dangerouslySkipPermissions = opts.dangerouslySkipPermissions || false;
236
232
  var osUsers = opts.osUsers || false;
237
233
  var lanHost = opts.lanHost || null;
238
234
  // lr-20e71c: operator-declared trust boundary for reading X-Forwarded-Proto
@@ -269,6 +265,8 @@ function createServer(opts) {
269
265
  var onSetServerDefaultMode = opts.onSetServerDefaultMode || null;
270
266
  var onGetProjectDefaultMode = opts.onGetProjectDefaultMode || null;
271
267
  var onSetProjectDefaultMode = opts.onSetProjectDefaultMode || null;
268
+ var onGetPermissionSettings = opts.onGetPermissionSettings || null;
269
+ var onSetPermissionSettings = opts.onSetPermissionSettings || null;
272
270
  var onGetServerDefaultBetas = opts.onGetServerDefaultBetas || null;
273
271
  var onSetServerDefaultBetas = opts.onSetServerDefaultBetas || null;
274
272
  var onGetProjectDefaultBetas = opts.onGetProjectDefaultBetas || null;
@@ -401,6 +399,26 @@ function createServer(opts) {
401
399
  // send-input).
402
400
  var _sessionInput = require("./session-input").createSessionInput({
403
401
  getProject: function (slug) { return projects.get(slug) || null; },
402
+ // Read when a session is opened, so a change needs no restart.
403
+ getPermissionSettings: function () {
404
+ return onGetPermissionSettings ? onGetPermissionSettings() : null;
405
+ },
406
+ listProjects: function () {
407
+ var held = [];
408
+ projects.forEach(function (ctx, slug) { held.push({ slug: slug, project: ctx }); });
409
+ return held;
410
+ },
411
+ });
412
+ // Scheduled input for every project: one persisted list per project, one
413
+ // timer, and the firing through the same _sessionInput (lib/scheduled-input/).
414
+ var _scheduledInput = require("./scheduled-input/service").createScheduledInputService({
415
+ dir: path.join(CONFIG_DIR, "scheduled-input"),
416
+ getProject: function (slug) { return projects.get(slug) || null; },
417
+ sessionInput: _sessionInput,
418
+ publish: require("./scheduled-input/ws").createPublisher({
419
+ getProject: function (slug) { return projects.get(slug) || null; },
420
+ listFor: function (slug, session) { return _scheduledInput.armedForSession(slug, session); },
421
+ }),
404
422
  });
405
423
  var _externalTrigger = attachExternalTrigger({
406
424
  triggersDir: EXTERNAL_TRIGGERS_DIR,
@@ -724,6 +742,7 @@ function createServer(opts) {
724
742
  res.end(JSON.stringify({
725
743
  projects: projectList,
726
744
  version: currentVersion,
745
+ buildId: clientBuildId.get(),
727
746
  authenticated: true,
728
747
  liteInstalled: liteStatus.installed,
729
748
  liteHome: liteStatus.liteHome,
@@ -1316,7 +1335,6 @@ function createServer(opts) {
1316
1335
  worktreeMeta: worktreeMeta || null,
1317
1336
  pushModule: pushModule,
1318
1337
  debug: debug,
1319
- dangerouslySkipPermissions: dangerouslySkipPermissions,
1320
1338
  osUsers: osUsers,
1321
1339
  currentVersion: currentVersion,
1322
1340
  lanHost: lanHost,
@@ -1432,6 +1450,7 @@ function createServer(opts) {
1432
1450
  // when a session in this project is deleted — see onSessionDeleted's
1433
1451
  // header above.
1434
1452
  onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1453
+ scheduledInput: _scheduledInput,
1435
1454
  // lr-13c047: expose the non-switch "mark read" clear path (see
1436
1455
  // markCrossProjectRead's header above) so lib/project-sessions.js can
1437
1456
  // wire a client-initiated mark_cross_project_read WS message without
@@ -1468,6 +1487,8 @@ function createServer(opts) {
1468
1487
  onSetServerDefaultMode: onSetServerDefaultMode,
1469
1488
  onGetProjectDefaultMode: onGetProjectDefaultMode,
1470
1489
  onSetProjectDefaultMode: onSetProjectDefaultMode,
1490
+ onGetPermissionSettings: onGetPermissionSettings,
1491
+ onSetPermissionSettings: onSetPermissionSettings,
1471
1492
  onGetServerDefaultBetas: onGetServerDefaultBetas,
1472
1493
  onSetServerDefaultBetas: onSetServerDefaultBetas,
1473
1494
  onGetProjectDefaultBetas: onGetProjectDefaultBetas,
@@ -1499,6 +1520,7 @@ function createServer(opts) {
1499
1520
  isUserOnline: isUserOnline,
1500
1521
  });
1501
1522
  projects.set(slug, ctx);
1523
+ _scheduledInput.attachProject(slug);
1502
1524
  // ctx.warmup() is now deferred to the first websocket connection into
1503
1525
  // this project (see project-connection.js handleConnection). Warming
1504
1526
  // every project at startup spawned a CodexAppServer and an mcp-bridge
@@ -1530,6 +1552,7 @@ function createServer(opts) {
1530
1552
  // A deliberate removal: its sessions are not recorded as resumable.
1531
1553
  var shutdownResult = ctx.destroy({ reason: "project_removed" });
1532
1554
  projects.delete(slug);
1555
+ _scheduledInput.detachProject(slug);
1533
1556
  if (shutdownResult && typeof shutdownResult.catch === "function") {
1534
1557
  shutdownResult.catch(function(err) {
1535
1558
  console.error("[server] Project destroy failed for " + slug + ":", err && err.message ? err.message : err);
@@ -1751,6 +1774,7 @@ function createServer(opts) {
1751
1774
 
1752
1775
  function destroyAll() {
1753
1776
  _externalTrigger.stopWatcher();
1777
+ _scheduledInput.stop();
1754
1778
  var shutdowns = [];
1755
1779
  var tally = sessionReclaim.createShutdownTally();
1756
1780
  projects.forEach(function (ctx, slug) {
@@ -1835,6 +1859,8 @@ function createServer(opts) {
1835
1859
  broadcastAll: broadcastAll,
1836
1860
  forEachProject: forEachProject,
1837
1861
  sessionInput: _sessionInput,
1862
+ scheduledInput: _scheduledInput,
1863
+ getProject: function (slug) { return projects.get(slug) || null; },
1838
1864
  destroyProject: removeProject,
1839
1865
  destroyAll: destroyAll,
1840
1866
  // Drain controller injection (lr-6b30).
@@ -0,0 +1,224 @@
1
+ // session-directory.js - discover the console's sessions and resolve an address
2
+ // to one of them. Read-only: nothing here changes a session or delivers input;
3
+ // lib/session-input.js does the delivery once an address has become a session id.
4
+ //
5
+ // The directory is the console's own session store as the daemon holds it: every
6
+ // session recorded on disk is loaded into its project's session manager at start,
7
+ // whether or not it has a runtime, so a session whose runtime was reaped is listed
8
+ // and addressable exactly like a running one. A session started outside the
9
+ // console is not in the store and is not listed.
10
+ //
11
+ // States:
12
+ // live a turn is running
13
+ // idle a runtime is attached and no turn is running
14
+ // reaped no runtime (idle reaper, daemon restart); input resumes it
15
+ //
16
+ // Addresses (the label format of lib/sender-ref.js):
17
+ // <agent>@<project> a session running that named agent
18
+ // <vendor>@<project> a PLAIN session (no named agent) on that vendor
19
+ // @<project> any session in the project
20
+ // Each form takes an optional "/<name>" after the project, naming one session by
21
+ // the name it was opened with (see validateName):
22
+ // <agent>@<project>/<name>, <vendor>@<project>/<name>, @<project>/<name>
23
+ //
24
+ // Resolution never guesses. Among the sessions an address matches, the highest
25
+ // state tier that has any match decides: live, then idle, then reaped. Exactly
26
+ // one there is the answer; several there are refused with candidates; a lower
27
+ // tier is not consulted once a higher one matched.
28
+
29
+ var senderRef = require("./sender-ref");
30
+ var { slugifyAgentName } = require("./agents");
31
+ var { isInjected } = require("./injected-sender");
32
+ var { pendingPrompts } = require("./pending-prompts");
33
+
34
+ var STATE = Object.freeze({ LIVE: "live", IDLE: "idle", REAPED: "reaped" });
35
+ var ANY_STATE = "any";
36
+ var STATE_FILTERS = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED, ANY_STATE]);
37
+
38
+ var MAX_ADDRESS_LENGTH = 192;
39
+ var ADDRESS_RE = /^([^@\s]*)@([^@\s]+)$/;
40
+
41
+ // Highest first: the order resolve() consults the tiers in.
42
+ var TIER_ORDER = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED]);
43
+
44
+ // A session name is a path-free token so it can follow the project after a "/"
45
+ // in an address. Project slugs never contain "/" (lib/config.js generateSlug).
46
+ var NAME_RE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
47
+
48
+ // Returns { name } (lowercased: names compare case-insensitively) or { error }.
49
+ function validateName(raw) {
50
+ if (typeof raw !== "string" || !raw) return { error: "session name must be a non-empty string" };
51
+ var name = raw.toLowerCase();
52
+ if (!NAME_RE.test(name)) {
53
+ return { error: "session name " + JSON.stringify(raw.slice(0, 40)) + " must be 1-32 characters of a-z, 0-9, \"-\" and \"_\", starting with a letter or digit" };
54
+ }
55
+ return { name: name };
56
+ }
57
+
58
+ function stateOf(session) {
59
+ if (!senderRef.isLive(session)) return STATE.REAPED;
60
+ return session.isProcessing ? STATE.LIVE : STATE.IDLE;
61
+ }
62
+
63
+ function isoOrNull(ms) {
64
+ return typeof ms === "number" && isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : null;
65
+ }
66
+
67
+ // One directory entry. slug is the project's slug, the same string the label
68
+ // carries.
69
+ function describe(slug, project, session, now) {
70
+ var agent = session.agentName || null;
71
+ var vendor = session.vendor || project.sm.defaultVendor || null;
72
+ return {
73
+ consoleSessionId: String(session.localId),
74
+ sessionId: session.cliSessionId || null,
75
+ project: slug,
76
+ agent: agent,
77
+ vendor: vendor,
78
+ label: senderRef.labelFor(agent, vendor, slug),
79
+ name: session.sessionName || null,
80
+ title: session.title || "",
81
+ state: stateOf(session),
82
+ lastActivity: isoOrNull(session.lastActivity || session.createdAt),
83
+ pendingPrompts: pendingPrompts(session, now),
84
+ };
85
+ }
86
+
87
+ // Newest first; ties keep the lower console id first so the order is stable.
88
+ function byRecency(a, b) {
89
+ var ta = a.lastActivity || "";
90
+ var tb = b.lastActivity || "";
91
+ if (ta !== tb) return ta < tb ? 1 : -1;
92
+ return Number(a.consoleSessionId) - Number(b.consoleSessionId);
93
+ }
94
+
95
+ // projects: [{ slug, project }] with project a context holding sm.sessions.
96
+ // A hidden session (a background helper) is not part of the directory, and a
97
+ // session that has no id from its vendor yet and no runtime was never recorded.
98
+ function collect(projects, now) {
99
+ var out = [];
100
+ var at = typeof now === "number" ? now : Date.now();
101
+ (projects || []).forEach(function (p) {
102
+ if (!p || !p.project || !p.project.sm || !p.project.sm.sessions) return;
103
+ p.project.sm.sessions.forEach(function (s) {
104
+ if (s.hidden) return;
105
+ if (!s.cliSessionId && !senderRef.isLive(s)) return;
106
+ out.push(describe(p.slug, p.project, s, at));
107
+ });
108
+ });
109
+ return out.sort(byRecency);
110
+ }
111
+
112
+ // filter: { project?, agent?, vendor?, state?, now? } (now: ms epoch for the
113
+ // prompt ages, default the current time). Returns { entries } or { error }.
114
+ function list(projects, filter) {
115
+ filter = filter || {};
116
+ var state = filter.state === undefined || filter.state === null ? ANY_STATE : filter.state;
117
+ if (STATE_FILTERS.indexOf(state) === -1) {
118
+ return { error: "unknown state " + JSON.stringify(String(state).slice(0, 32)) + " (accepted: " + STATE_FILTERS.join(", ") + ")" };
119
+ }
120
+ var agentSlug = filter.agent ? slugifyAgentName(filter.agent) : null;
121
+ if (filter.agent && !agentSlug) return { error: "agent must name an agent" };
122
+ var vendor = filter.vendor ? String(filter.vendor).toLowerCase() : null;
123
+ var entries = collect(projects, filter.now).filter(function (e) {
124
+ if (filter.project && e.project !== filter.project) return false;
125
+ if (agentSlug && slugifyAgentName(e.agent) !== agentSlug) return false;
126
+ if (vendor && String(e.vendor || "").toLowerCase() !== vendor) return false;
127
+ if (state !== ANY_STATE && e.state !== state) return false;
128
+ return true;
129
+ });
130
+ return { entries: entries };
131
+ }
132
+
133
+ // Returns { project, token } (token is "" for @<project>) or { error }, plus
134
+ // name when the address carries "/<name>".
135
+ function parseAddress(raw) {
136
+ if (typeof raw !== "string" || !raw) return { error: "address must be a non-empty string" };
137
+ if (raw.length > MAX_ADDRESS_LENGTH) return { error: "address is longer than " + MAX_ADDRESS_LENGTH + " characters" };
138
+ var m = ADDRESS_RE.exec(raw);
139
+ if (!m) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " is not <agent>@<project>, <vendor>@<project> or @<project>, each with an optional /<name>" };
140
+ var token = slugifyAgentName(m[1]);
141
+ if (m[1] && !token) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " names no agent or vendor" };
142
+ var slash = m[2].indexOf("/");
143
+ if (slash === -1) return { project: m[2], token: token };
144
+ var project = m[2].slice(0, slash);
145
+ var named = validateName(m[2].slice(slash + 1));
146
+ if (!project) return { error: "address " + JSON.stringify(raw.slice(0, 64)) + " names no project" };
147
+ if (named.error) return { error: named.error };
148
+ return { project: project, token: token, name: named.name };
149
+ }
150
+
151
+ // Which sessions an address names, among the entries of its project. A named
152
+ // session matches by its agent, a plain one by its vendor. A recorded identity
153
+ // ({ project, vendor, sessionId } with sessionId the vendor's own session id)
154
+ // names a session only when all three are equal.
155
+ function matchesOf(entries, parsed) {
156
+ return entries.filter(function (e) {
157
+ if (e.project !== parsed.project) return false;
158
+ if (parsed.sessionId !== undefined) {
159
+ return !!parsed.sessionId && e.sessionId === parsed.sessionId
160
+ && String(e.vendor || "").toLowerCase() === String(parsed.vendor || "").toLowerCase();
161
+ }
162
+ if (parsed.name !== undefined && e.name !== parsed.name) return false;
163
+ if (!parsed.token) return true;
164
+ if (e.agent) return slugifyAgentName(e.agent) === parsed.token;
165
+ return String(e.vendor || "").toLowerCase() === parsed.token;
166
+ });
167
+ }
168
+
169
+ // Resolves an address, or a recorded identity, against the entries (collect()).
170
+ // Never guesses:
171
+ // { match } exactly one session
172
+ // { candidates } more than one; the caller chooses with a session id
173
+ // { none: true } no session
174
+ // The highest state tier (live, idle, reaped) holding any match decides: one
175
+ // there is the answer, several are the candidates, and lower tiers are not
176
+ // looked at. A named address (parsed.name) is exact: it matches only sessions
177
+ // of that name, so it never falls to a different session; the tiers then only
178
+ // separate same-named twins (a reaped one beside a running one).
179
+ function resolve(entries, parsed) {
180
+ var matches = matchesOf(entries, parsed);
181
+ for (var i = 0; i < TIER_ORDER.length; i++) {
182
+ var tier = matches.filter(function (e) { return e.state === TIER_ORDER[i]; });
183
+ if (tier.length === 1) return { match: tier[0] };
184
+ if (tier.length > 1) return { candidates: tier };
185
+ }
186
+ return { none: true };
187
+ }
188
+
189
+ // The sender of the most recent injected message in a session's history.
190
+ // Returns { project, vendor, cliSessionId, name } or { reason } saying why there
191
+ // is none. Only an extracted sender names a session; a declared or undeclared
192
+ // one cannot be answered. The sender is identified by project, vendor and the
193
+ // vendor's own session id, all recorded together at injection time; an entry
194
+ // lacking any of them (one recorded before they were kept) has no answerable
195
+ // sender. The console session id is deliberately not returned. Searches the
196
+ // history window held in memory.
197
+ function lastInjectedSender(history) {
198
+ for (var i = (history || []).length - 1; i >= 0; i--) {
199
+ var entry = history[i];
200
+ if (!isInjected(entry)) continue;
201
+ if (entry.senderKind !== "extracted" || !entry.senderProject) {
202
+ return { reason: "the most recent injected message in this session has no recorded sender session (its sender is " + (entry.senderKind || "unrecorded") + ")" };
203
+ }
204
+ if (!entry.senderVendor || !entry.senderCliSessionId) {
205
+ return { reason: "reply refused: the most recent injected message recorded no vendor or vendor session id for its sender (it predates them, or the sender had no vendor session id yet), so the sender session cannot be proven" };
206
+ }
207
+ return { project: entry.senderProject, vendor: entry.senderVendor, cliSessionId: entry.senderCliSessionId, name: entry.fromName || null };
208
+ }
209
+ // `none` tells a caller holding only a window of the history that this is a
210
+ // miss in that window, not proof that the session never received one.
211
+ return { none: true, reason: "this session has received no injected message to reply to" };
212
+ }
213
+
214
+ module.exports = {
215
+ STATE: STATE,
216
+ STATE_FILTERS: STATE_FILTERS,
217
+ stateOf: stateOf,
218
+ collect: collect,
219
+ list: list,
220
+ parseAddress: parseAddress,
221
+ validateName: validateName,
222
+ resolve: resolve,
223
+ lastInjectedSender: lastInjectedSender,
224
+ };
@@ -0,0 +1,55 @@
1
+ // session-file-scan.js - a bounded reverse scan of a session's JSONL file.
2
+ // The file is read backwards in fixed-size chunks and the scan stops at the
3
+ // first (newest) entry the predicate accepts, so the memory held is the chunk
4
+ // plus the one line being assembled, never the file. Line 0 of a session file
5
+ // is its meta record and is never offered to the predicate.
6
+
7
+ var fs = require("fs");
8
+
9
+ var DEFAULT_CHUNK_BYTES = 64 * 1024;
10
+ var NEWLINE = 0x0a;
11
+
12
+ // Offers each history entry of the file at `filePath`, newest first, to
13
+ // `accept(entry)`; returns the first entry it accepts, or null when none does.
14
+ // A missing or unreadable file throws (the caller decides what that means). A
15
+ // line that is not JSON is skipped, as the full-history parse skips it.
16
+ function findNewestEntry(filePath, accept, chunkBytes) {
17
+ var chunkSize = chunkBytes > 0 ? chunkBytes : DEFAULT_CHUNK_BYTES;
18
+ var fd = fs.openSync(filePath, "r");
19
+ try {
20
+ var pos = fs.fstatSync(fd).size;
21
+ // Bytes of a line whose start lies in an earlier chunk. Kept as bytes, not
22
+ // text, so a multibyte character split by a chunk boundary stays intact.
23
+ var carry = Buffer.alloc(0);
24
+ var chunk = Buffer.alloc(chunkSize);
25
+
26
+ function offer(lineBuf) {
27
+ if (lineBuf.length === 0) return null;
28
+ var entry;
29
+ try { entry = JSON.parse(lineBuf.toString("utf8")); } catch { return null; }
30
+ return accept(entry) ? entry : null;
31
+ }
32
+
33
+ while (pos > 0) {
34
+ var n = Math.min(chunkSize, pos);
35
+ pos -= n;
36
+ var got = fs.readSync(fd, chunk, 0, n, pos);
37
+ var buf = Buffer.concat([chunk.subarray(0, got), carry]);
38
+ var end = buf.length;
39
+ var nl = buf.lastIndexOf(NEWLINE, end - 1);
40
+ while (nl !== -1) {
41
+ var hit = offer(buf.subarray(nl + 1, end));
42
+ if (hit) return hit;
43
+ end = nl;
44
+ nl = end > 0 ? buf.lastIndexOf(NEWLINE, end - 1) : -1;
45
+ }
46
+ carry = Buffer.from(buf.subarray(0, end));
47
+ }
48
+ // What remains is line 0: the meta record, which is not history.
49
+ return null;
50
+ } finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ }
54
+
55
+ module.exports = { findNewestEntry: findNewestEntry, DEFAULT_CHUNK_BYTES: DEFAULT_CHUNK_BYTES };
@@ -9,11 +9,18 @@ function handleSessionCommand(sessionInput, msg) {
9
9
  if (msg.cmd === "open_session") {
10
10
  return sessionInput.openSession({
11
11
  projectSlug: msg.projectSlug,
12
+ to: msg.to,
12
13
  prompt: msg.prompt,
13
14
  contextNote: msg.contextNote,
15
+ from: msg.from,
16
+ fromSession: msg.fromSession,
17
+ senderProject: msg.senderProject,
18
+ senderSessionId: msg.senderSessionId,
14
19
  vendor: msg.vendor,
15
20
  agentName: msg.agentName,
21
+ sessionName: msg.sessionName,
16
22
  sessionVisibility: msg.sessionVisibility,
23
+ permissionMode: msg.permissionMode,
17
24
  initiator: msg.initiator,
18
25
  });
19
26
  }
@@ -21,11 +28,25 @@ function handleSessionCommand(sessionInput, msg) {
21
28
  return sessionInput.sendInput({
22
29
  projectSlug: msg.projectSlug,
23
30
  sessionId: msg.sessionId,
31
+ to: msg.to,
32
+ reply: msg.reply,
24
33
  prompt: msg.prompt,
25
34
  contextNote: msg.contextNote,
35
+ from: msg.from,
36
+ fromSession: msg.fromSession,
37
+ senderProject: msg.senderProject,
38
+ senderSessionId: msg.senderSessionId,
26
39
  initiator: msg.initiator,
27
40
  });
28
41
  }
42
+ if (msg.cmd === "list_sessions") {
43
+ return sessionInput.listSessions({
44
+ projectSlug: msg.projectSlug,
45
+ agentName: msg.agentName,
46
+ vendor: msg.vendor,
47
+ state: msg.state,
48
+ });
49
+ }
29
50
  return undefined;
30
51
  }
31
52