@clagentic/console 1.12.0-beta.1 → 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 (161) hide show
  1. package/LICENSES/README.md +5 -0
  2. package/README.md +1 -0
  3. package/bin/cli.js +5 -2
  4. package/lib/agent-roster-ws.js +84 -0
  5. package/lib/agent-roster.js +312 -0
  6. package/lib/auth-required-notify.js +42 -0
  7. package/lib/build-changes.js +8 -2
  8. package/lib/build-sha.json +2 -2
  9. package/lib/build-update-notify.js +45 -0
  10. package/lib/build-update-offer.js +34 -11
  11. package/lib/build-update-standing.js +34 -14
  12. package/lib/claude-settings-env.js +142 -0
  13. package/lib/cli/duration.js +27 -0
  14. package/lib/cli/schedule-input-subcommands.js +1 -22
  15. package/lib/cli/session-subcommands.js +60 -11
  16. package/lib/client-address.js +44 -0
  17. package/lib/daemon.js +31 -10
  18. package/lib/idle-compaction-setting.js +203 -0
  19. package/lib/mcp-bridge-credential.js +41 -0
  20. package/lib/notification-prefs.js +18 -22
  21. package/lib/notify/core.js +210 -0
  22. package/lib/notify/index.js +31 -0
  23. package/lib/notify/live-prompts.js +36 -0
  24. package/lib/notify/payload.js +62 -0
  25. package/lib/notify/target.js +5 -0
  26. package/lib/notify/type-registry.js +81 -0
  27. package/lib/notify/types.js +57 -0
  28. package/lib/open-sockets.js +27 -0
  29. package/lib/outbound-access.js +85 -0
  30. package/lib/outbound-entry.js +116 -0
  31. package/lib/outbound-ledger.js +306 -0
  32. package/lib/outbound-query.js +153 -0
  33. package/lib/pending-prompts.js +31 -16
  34. package/lib/project-connection.js +48 -8
  35. package/lib/project-filesystem.js +43 -5
  36. package/lib/project-http.js +9 -1
  37. package/lib/project-loop.js +38 -26
  38. package/lib/project-notifications.js +122 -39
  39. package/lib/project-prompt-responses.js +1 -1
  40. package/lib/project-sessions.js +11 -1
  41. package/lib/project-user-mention.js +22 -34
  42. package/lib/project-user-message.js +208 -4
  43. package/lib/project-user-shell.js +298 -0
  44. package/lib/project.js +41 -5
  45. package/lib/prompt-answer.js +145 -0
  46. package/lib/prompt-expiry.js +50 -0
  47. package/lib/prompt-registry.js +98 -25
  48. package/lib/prompt-reminders.js +38 -33
  49. package/lib/prompt-source.js +59 -8
  50. package/lib/public/app.js +32 -2
  51. package/lib/public/css/agent-messages.css +96 -0
  52. package/lib/public/css/agent-roster.css +93 -0
  53. package/lib/public/css/diagnostics.css +29 -1
  54. package/lib/public/css/home-hub.css +12 -0
  55. package/lib/public/css/icon-strip.css +9 -0
  56. package/lib/public/css/input.css +20 -141
  57. package/lib/public/css/login-panel.css +73 -0
  58. package/lib/public/css/menus.css +2 -2
  59. package/lib/public/css/mobile-nav.css +11 -0
  60. package/lib/public/css/sidebar.css +18 -0
  61. package/lib/public/css/team-panel.css +1 -6
  62. package/lib/public/css/team-view.css +101 -0
  63. package/lib/public/css/title-bar.css +10 -0
  64. package/lib/public/css/user-shell.css +144 -0
  65. package/lib/public/index.html +44 -7
  66. package/lib/public/modules/activity-state.js +20 -4
  67. package/lib/public/modules/agent-avatar-picker.js +162 -0
  68. package/lib/public/modules/agent-avatar.js +153 -0
  69. package/lib/public/modules/agent-messages.js +285 -0
  70. package/lib/public/modules/agent-roster.js +157 -0
  71. package/lib/public/modules/app-connection.js +34 -5
  72. package/lib/public/modules/app-messages.js +55 -16
  73. package/lib/public/modules/app-notifications.js +104 -75
  74. package/lib/public/modules/app-panels.js +26 -3
  75. package/lib/public/modules/app-projects.js +3 -1
  76. package/lib/public/modules/app-rate-limit.js +8 -165
  77. package/lib/public/modules/app-rendering.js +32 -7
  78. package/lib/public/modules/build-update-sessions.js +81 -0
  79. package/lib/public/modules/collapsible-text.js +33 -18
  80. package/lib/public/modules/compaction-state.js +34 -0
  81. package/lib/public/modules/custom-icons.js +23 -5
  82. package/lib/public/modules/diagnostics.js +61 -57
  83. package/lib/public/modules/env-shadow-notice.js +34 -0
  84. package/lib/public/modules/injected-identity.js +24 -21
  85. package/lib/public/modules/input.js +176 -15
  86. package/lib/public/modules/login-panel.js +136 -0
  87. package/lib/public/modules/login-parser.js +73 -0
  88. package/lib/public/modules/login-tab.js +66 -0
  89. package/lib/public/modules/notifications.js +9 -1
  90. package/lib/public/modules/notify-client.js +246 -0
  91. package/lib/public/modules/pending-term-request.js +30 -0
  92. package/lib/public/modules/project-icon.js +22 -2
  93. package/lib/public/modules/project-settings.js +5 -0
  94. package/lib/public/modules/prompt-state.js +3 -3
  95. package/lib/public/modules/prompts.js +1 -1
  96. package/lib/public/modules/queued-button.js +11 -0
  97. package/lib/public/modules/scheduled-input-actions.js +12 -4
  98. package/lib/public/modules/scheduled-outbox.js +230 -0
  99. package/lib/public/modules/send-now.js +200 -0
  100. package/lib/public/modules/server-settings.js +50 -1
  101. package/lib/public/modules/shell-card.js +76 -0
  102. package/lib/public/modules/shell-line.js +49 -0
  103. package/lib/public/modules/shell-queue.js +253 -0
  104. package/lib/public/modules/shell-settings-controls.js +76 -0
  105. package/lib/public/modules/sidebar-mobile.js +3 -3
  106. package/lib/public/modules/sidebar-sessions.js +8 -0
  107. package/lib/public/modules/sidebar-users.js +5 -7
  108. package/lib/public/modules/team-panel.js +30 -88
  109. package/lib/public/modules/team-view.js +211 -0
  110. package/lib/public/modules/terminal-links.js +193 -0
  111. package/lib/public/modules/terminal.js +84 -107
  112. package/lib/public/modules/tools.js +19 -0
  113. package/lib/public/modules/user-shell.js +824 -0
  114. package/lib/public/notify-sw-logic.js +252 -0
  115. package/lib/public/notify-target.js +157 -0
  116. package/lib/public/style.css +5 -0
  117. package/lib/public/sw.js +20 -69
  118. package/lib/push.js +63 -19
  119. package/lib/queued-chat.js +392 -0
  120. package/lib/runtime-env.js +1 -0
  121. package/lib/scheduled-input/ws.js +67 -9
  122. package/lib/sdk-bridge.js +184 -73
  123. package/lib/sdk-message-processor.js +124 -76
  124. package/lib/server-auth.js +6 -4
  125. package/lib/server-dm.js +11 -20
  126. package/lib/server-settings.js +39 -1
  127. package/lib/server.js +112 -16
  128. package/lib/session-directory.js +39 -12
  129. package/lib/session-end.js +97 -0
  130. package/lib/session-input-ipc.js +37 -1
  131. package/lib/session-input.js +263 -21
  132. package/lib/session-liveness.js +53 -0
  133. package/lib/session-reclaim.js +37 -2
  134. package/lib/session-resume.js +1 -0
  135. package/lib/session-settings-file.js +53 -0
  136. package/lib/sessions.js +80 -9
  137. package/lib/team-traffic-ws.js +68 -0
  138. package/lib/team-traffic.js +318 -0
  139. package/lib/usage-store.js +36 -7
  140. package/lib/user-shell-settings.js +105 -0
  141. package/lib/vendor-auth.js +33 -2
  142. package/lib/ws-schema.js +33 -5
  143. package/lib/yoke/adapters/claude-capabilities.js +2 -0
  144. package/lib/yoke/adapters/claude-vendor.js +17 -1
  145. package/lib/yoke/adapters/claude-worker.js +39 -11
  146. package/lib/yoke/adapters/claude.js +225 -6
  147. package/lib/yoke/adapters/codex-capabilities.js +6 -1
  148. package/lib/yoke/adapters/codex-user-shell.js +265 -0
  149. package/lib/yoke/adapters/codex-vendor.js +7 -0
  150. package/lib/yoke/adapters/codex.js +186 -52
  151. package/lib/yoke/auth-checks.js +17 -2
  152. package/lib/yoke/codex-app-server.js +8 -2
  153. package/lib/yoke/index.js +21 -3
  154. package/lib/yoke/interface.js +54 -1
  155. package/lib/yoke/mcp-bridge-server.js +12 -8
  156. package/lib/yoke/provider-credentials.js +24 -0
  157. package/lib/yoke/registry.js +40 -1
  158. package/lib/yoke/user-shell.js +224 -0
  159. package/package.json +2 -2
  160. package/scripts/check-test-count.js +14 -0
  161. package/lib/public/modules/build-notice-gate.js +0 -73
package/lib/server.js CHANGED
@@ -3,6 +3,8 @@ var fs = require("fs");
3
3
  var path = require("path");
4
4
  var { WebSocketServer } = require("ws");
5
5
  var pages = require("./pages");
6
+ var mcpBridgeCredential = require("./mcp-bridge-credential");
7
+ var { resolveClientAddress } = require("./client-address");
6
8
  var smtp = require("./smtp");
7
9
  var { createProjectContext } = require("./project");
8
10
  var users = require("./users");
@@ -267,6 +269,8 @@ function createServer(opts) {
267
269
  var onSetProjectDefaultMode = opts.onSetProjectDefaultMode || null;
268
270
  var onGetPermissionSettings = opts.onGetPermissionSettings || null;
269
271
  var onSetPermissionSettings = opts.onSetPermissionSettings || null;
272
+ var onGetUserShellSettings = opts.onGetUserShellSettings || null;
273
+ var onSetUserShellSettings = opts.onSetUserShellSettings || null;
270
274
  var onGetServerDefaultBetas = opts.onGetServerDefaultBetas || null;
271
275
  var onSetServerDefaultBetas = opts.onSetServerDefaultBetas || null;
272
276
  var onGetProjectDefaultBetas = opts.onGetProjectDefaultBetas || null;
@@ -288,7 +292,7 @@ function createServer(opts) {
288
292
  var onShutdown = opts.onShutdown || null;
289
293
  var onRestart = opts.onRestart || null;
290
294
  var onRestartForBuildUpdate = opts.onRestartForBuildUpdate || null;
291
- var onGetBuildUpdateDiagnostic = opts.onGetBuildUpdateDiagnostic || null;
295
+ var onNotificationResolved = opts.onNotificationResolved || null;
292
296
  var onSetUpdateChannel = opts.onSetUpdateChannel || null;
293
297
  var onSetProjectVisibility = opts.onSetProjectVisibility || null;
294
298
  var onSetProjectAllowedUsers = opts.onSetProjectAllowedUsers || null;
@@ -317,6 +321,7 @@ function createServer(opts) {
317
321
  osUsers: osUsers,
318
322
  provisionLinuxUser: provisionLinuxUser,
319
323
  onUserProvisioned: onUserProvisioned,
324
+ trustedProxy: trustedProxy,
320
325
  });
321
326
  var getMultiUserFromReq = auth.getMultiUserFromReq;
322
327
  var isRequestAuthed = auth.isRequestAuthed;
@@ -392,6 +397,7 @@ function createServer(opts) {
392
397
  pushModule: pushModule,
393
398
  prefsStore: _prefsStore,
394
399
  isMultiUser: users.isMultiUser,
400
+ onResolvedByOperator: onNotificationResolved,
395
401
  });
396
402
 
397
403
  // Reminders for prompts nobody has answered (lib/prompt-reminders.js): a
@@ -427,10 +433,63 @@ function createServer(opts) {
427
433
  // emitted — the trigger carries its own notification channel (e.g. ntfy).
428
434
  var { attachExternalTrigger } = require("./project-external-trigger");
429
435
  var { EXTERNAL_TRIGGERS_DIR } = require("./config");
436
+ // The sender-side record of what each session sent out (lib/outbound-ledger.js).
437
+ // Retention is read from daemon.json at use, so a change needs no restart.
438
+ var _outboundLedger = require("./outbound-ledger").createOutboundLedger({
439
+ getBaseDir: function () { return CONFIG_DIR; },
440
+ getRetentionDays: function () {
441
+ var cfg = require("./config").loadConfig();
442
+ return cfg ? cfg.outboundRetentionDays : undefined;
443
+ },
444
+ });
445
+ _outboundLedger.start();
446
+ var _outboundAccess = require("./outbound-access").createOutboundAccess({
447
+ projectAccess: projectAccess,
448
+ getProject: function (slug) { return projects.get(slug) || null; },
449
+ });
450
+ // `list-outbound` arrives on the daemon-owner socket: no user record, and
451
+ // authenticated by the OS gate on the socket itself.
452
+ var _outboundQuery = require("./outbound-query").createOutboundQuery({
453
+ ledger: _outboundLedger,
454
+ access: _outboundAccess,
455
+ caller: { user: null, authenticated: true },
456
+ });
457
+ // The Team view's agent-messages section (lib/team-traffic.js). A connection
458
+ // is told that something landed and asks for what it may read; the broadcast
459
+ // carries no message content.
460
+ var _teamTrafficNotifier = require("./team-traffic-ws").createNotifier({
461
+ broadcast: function (msg) { broadcastAll(msg); },
462
+ });
463
+ // The Team view's agent roster (lib/agent-roster.js): every agent identity the
464
+ // console has seen, and the avatar chosen for it. A change is broadcast as a
465
+ // content-free nudge; each connection then asks for the roster and gets only
466
+ // the places in projects it may read (_agentRoster.visibleEntry).
467
+ var _agentRosterNotifier = require("./team-traffic-ws").createNotifier({
468
+ broadcast: function (msg) { broadcastAll(msg); },
469
+ build: function () { return { type: require("./agent-roster-ws").CHANGED }; },
470
+ });
471
+ var _agentRoster = require("./agent-roster").createAgentRoster({
472
+ file: path.join(CONFIG_DIR, "agent-roster.json"),
473
+ writeJson: function (file, value) { return require("./store").writeJsonAt(file, value); },
474
+ onChange: _agentRosterNotifier.notify,
475
+ mayReadProject: function (slug, caller) { return _outboundAccess.canReadProject(slug, caller); },
476
+ });
477
+ // The ledger as session-input.js sees it: the same record(), plus a nudge to
478
+ // the live view when an open or a send lands.
479
+ var _announcingLedger = {
480
+ record: function (entry) {
481
+ var wrote = _outboundLedger.record(entry);
482
+ if (wrote && entry && (entry.verb === "send_input" || entry.verb === "open_session")) _teamTrafficNotifier.notify();
483
+ return wrote;
484
+ },
485
+ };
430
486
  // One implementation for the file drop and the daemon IPC verbs (open-session,
431
487
  // send-input).
432
488
  var _sessionInput = require("./session-input").createSessionInput({
433
489
  getProject: function (slug) { return projects.get(slug) || null; },
490
+ outboundLedger: _announcingLedger,
491
+ onAutomationInjected: _teamTrafficNotifier.notify,
492
+ onAgentSeen: _agentRoster.observe,
434
493
  // Read when a session is opened, so a change needs no restart.
435
494
  getPermissionSettings: function () {
436
495
  return onGetPermissionSettings ? onGetPermissionSettings() : null;
@@ -452,6 +511,17 @@ function createServer(opts) {
452
511
  listFor: function (slug, session) { return _scheduledInput.armedForSession(slug, session); },
453
512
  }),
454
513
  });
514
+ var _teamTraffic = require("./team-traffic").createTeamTraffic({
515
+ ledger: _outboundLedger,
516
+ access: _outboundAccess,
517
+ getProject: function (slug) { return projects.get(slug) || null; },
518
+ listProjects: function () {
519
+ var held = [];
520
+ projects.forEach(function (ctx, slug) { held.push({ slug: slug, project: ctx }); });
521
+ return held;
522
+ },
523
+ scheduledInput: _scheduledInput,
524
+ });
455
525
  var _externalTrigger = attachExternalTrigger({
456
526
  triggersDir: EXTERNAL_TRIGGERS_DIR,
457
527
  getProject: function (slug) { return projects.get(slug) || null; },
@@ -580,7 +650,11 @@ function createServer(opts) {
580
650
  var parsed = JSON.parse(body);
581
651
  var sub = parsed.subscription || parsed;
582
652
  var _httpPushUser = getMultiUserFromReq(req);
583
- pushModule.addSubscription(sub, parsed.replaceEndpoint, _httpPushUser ? _httpPushUser.id : null);
653
+ if (pushModule.addSubscription(sub, parsed.replaceEndpoint, _httpPushUser ? _httpPushUser.id : null) === false && sub && sub.endpoint) {
654
+ res.writeHead(401, { "Content-Type": "application/json" });
655
+ res.end('{"error":"sign in to enable push notifications"}');
656
+ return;
657
+ }
584
658
  res.writeHead(200, { "Content-Type": "application/json" });
585
659
  res.end('{"ok":true}');
586
660
  } catch (e) {
@@ -811,18 +885,17 @@ function createServer(opts) {
811
885
  }
812
886
 
813
887
  // Auth check for project routes
814
- // Bypass auth for MCP bridge endpoint (localhost only).
815
- // The mcp-bridge-server.js runs as a local child process and cannot carry cookies.
888
+ // The MCP bridge endpoint is admitted by a per-project bridge credential
889
+ // alone (the mcp-bridge-server.js child cannot carry a login cookie). The
890
+ // peer address grants nothing: a same-host reverse proxy makes every client
891
+ // look local. The credential is never logged.
816
892
  var projectUrlForAuth = stripPrefix(req.url.split("?")[0], slug);
817
- // req.socket.remoteAddress may differ between HTTP/HTTPS (TLSSocket wraps net.Socket).
818
- // Also check req.connection.remoteAddress for compatibility.
819
893
  var remoteAddr = req.socket.remoteAddress
820
894
  || (req.connection && req.connection.remoteAddress)
821
895
  || "";
822
- var isLocalhost = remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1";
823
896
  var isMcpBridgeLocal = projectUrlForAuth === "/api/mcp-bridge"
824
897
  && req.method === "POST"
825
- && isLocalhost;
898
+ && mcpBridgeCredential.verifyCredential(slug, req.headers[mcpBridgeCredential.HEADER_NAME]);
826
899
  if (projectUrlForAuth === "/api/mcp-bridge") {
827
900
  console.log("[server] MCP bridge auth: method=" + req.method + " addr=" + remoteAddr + " bypass=" + isMcpBridgeLocal);
828
901
  }
@@ -873,8 +946,8 @@ function createServer(opts) {
873
946
  }).protocol;
874
947
  res.setHeader("Set-Cookie", "clagentic_last_project=" + slug + "; Path=/; SameSite=Strict; Max-Age=31536000" + (cookieEffectiveProtocol === "https" ? "; Secure" : ""));
875
948
 
876
- // Check project access for HTTP requests. The local MCP bridge carries no
877
- // login (it is a child process of the daemon's own host); every other
949
+ // Check project access for HTTP requests. The MCP bridge carries no login
950
+ // (its credential admitted it above); every other
878
951
  // request must belong to a user who may use this project.
879
952
  if (!isMcpBridgeLocal) {
880
953
  var httpUser = getMultiUserFromReq(req);
@@ -1172,8 +1245,7 @@ function createServer(opts) {
1172
1245
  // The only place a connection is marked authenticated: handleUpgrade
1173
1246
  // answered 401 above for anything that failed the login check.
1174
1247
  ws._clagenticAuthenticated = true;
1175
- var remoteAddr = req.socket.remoteAddress || "";
1176
- ws._clagenticLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
1248
+ ws._clagenticLocal = resolveClientAddress(req, trustedProxy).local;
1177
1249
  // lr-20e71c: resolve the real external protocol for THIS connection at
1178
1250
  // upgrade time, while req.headers is still in scope — project-sessions.js's
1179
1251
  // per-message dispatch only has ws/msg, not the original upgrade req.
@@ -1483,6 +1555,9 @@ function createServer(opts) {
1483
1555
  // header above.
1484
1556
  onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1485
1557
  scheduledInput: _scheduledInput,
1558
+ teamTraffic: _teamTraffic,
1559
+ agentRoster: _agentRoster,
1560
+ onAgentSeen: _agentRoster.observe,
1486
1561
  // lr-13c047: expose the non-switch "mark read" clear path (see
1487
1562
  // markCrossProjectRead's header above) so lib/project-sessions.js can
1488
1563
  // wire a client-initiated mark_cross_project_read WS message without
@@ -1505,7 +1580,13 @@ function createServer(opts) {
1505
1580
  onSetProjectFolder: onSetProjectFolder,
1506
1581
  onRenameProjectFolder: onRenameProjectFolder,
1507
1582
  onSetFolderIcon: onSetFolderIcon,
1508
- onRenameCustomIcon: onRenameCustomIcon,
1583
+ // The daemon rewrites the project and folder references; agent avatar
1584
+ // choices that named the old slug follow it here.
1585
+ onRenameCustomIcon: onRenameCustomIcon ? function (oldSlug, newSlug) {
1586
+ var renamed = onRenameCustomIcon(oldSlug, newSlug);
1587
+ if (renamed && renamed.ok === true) _agentRoster.renameCustomIcon(oldSlug, newSlug);
1588
+ return renamed;
1589
+ } : null,
1509
1590
  onProjectOwnerChanged: onProjectOwnerChanged,
1510
1591
  onGetServerDefaultEffort: onGetServerDefaultEffort,
1511
1592
  onSetServerDefaultEffort: onSetServerDefaultEffort,
@@ -1521,6 +1602,8 @@ function createServer(opts) {
1521
1602
  onSetProjectDefaultMode: onSetProjectDefaultMode,
1522
1603
  onGetPermissionSettings: onGetPermissionSettings,
1523
1604
  onSetPermissionSettings: onSetPermissionSettings,
1605
+ onGetUserShellSettings: onGetUserShellSettings,
1606
+ onSetUserShellSettings: onSetUserShellSettings,
1524
1607
  onGetServerDefaultBetas: onGetServerDefaultBetas,
1525
1608
  onSetServerDefaultBetas: onSetServerDefaultBetas,
1526
1609
  onGetProjectDefaultBetas: onGetProjectDefaultBetas,
@@ -1544,7 +1627,6 @@ function createServer(opts) {
1544
1627
  onShutdown: onShutdown,
1545
1628
  onRestart: onRestart,
1546
1629
  onRestartForBuildUpdate: onRestartForBuildUpdate,
1547
- onGetBuildUpdateDiagnostic: onGetBuildUpdateDiagnostic,
1548
1630
  onDmMessage: handleDmMessage,
1549
1631
  broadcastAll: broadcastAll,
1550
1632
  notificationsModule: _globalNotifications,
@@ -1817,9 +1899,12 @@ function createServer(opts) {
1817
1899
 
1818
1900
  function destroyAll() {
1819
1901
  _promptReminders.stop();
1902
+ _outboundLedger.stop();
1903
+ _teamTrafficNotifier.stop();
1904
+ _agentRosterNotifier.stop();
1820
1905
  _externalTrigger.stopWatcher();
1821
1906
  _scheduledInput.stop();
1822
- var shutdowns = [];
1907
+ var shutdowns = [_agentRoster.flush()];
1823
1908
  var tally = sessionReclaim.createShutdownTally();
1824
1909
  projects.forEach(function (ctx, slug) {
1825
1910
  console.log("[server] Destroying project:", slug);
@@ -1833,7 +1918,12 @@ function createServer(opts) {
1833
1918
  });
1834
1919
  projects.clear();
1835
1920
  sessionReclaim.logShutdownSummary(tally);
1836
- return Promise.all(shutdowns);
1921
+ // The prompts settled above sent their close pushes; the process must not
1922
+ // exit before they leave.
1923
+ return Promise.all(shutdowns).then(function (results) {
1924
+ if (!pushModule || typeof pushModule.flush !== "function") return results;
1925
+ return pushModule.flush().then(function () { return results; });
1926
+ });
1837
1927
  }
1838
1928
 
1839
1929
  // --- Periodic cleanup of old chat images ---
@@ -1901,8 +1991,14 @@ function createServer(opts) {
1901
1991
  setRecovery: auth.setRecovery,
1902
1992
  clearRecovery: auth.clearRecovery,
1903
1993
  broadcastAll: broadcastAll,
1994
+ // What the daemon's own notifications go through: the push module and the
1995
+ // in-app banner store the notification core delivers to.
1996
+ notifyEnv: function () {
1997
+ return { push: pushModule, inApp: _globalNotifications, isMultiUser: users.isMultiUser };
1998
+ },
1904
1999
  forEachProject: forEachProject,
1905
2000
  sessionInput: _sessionInput,
2001
+ outboundQuery: _outboundQuery,
1906
2002
  scheduledInput: _scheduledInput,
1907
2003
  getProject: function (slug) { return projects.get(slug) || null; },
1908
2004
  destroyProject: removeProject,
@@ -9,9 +9,11 @@
9
9
  // console is not in the store and is not listed.
10
10
  //
11
11
  // States:
12
- // live a turn is running
13
- // idle a runtime is attached and no turn is running
12
+ // live a turn is running, or the session is blocked on a pending prompt
13
+ // (pendingPrompts tells the two apart)
14
+ // idle a runtime is attached, nothing running, nothing pending
14
15
  // reaped no runtime (idle reaper, daemon restart); input resumes it
16
+ // The three come from the shared derivation in lib/session-liveness.js.
15
17
  //
16
18
  // Addresses (the label format of lib/sender-ref.js):
17
19
  // <agent>@<project> a session running that named agent
@@ -22,14 +24,23 @@
22
24
  // <agent>@<project>/<name>, <vendor>@<project>/<name>, @<project>/<name>
23
25
  //
24
26
  // 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.
27
+ // tier that has any match decides: running, then idle, then prompt-blocked, then
28
+ // reaped. Exactly one there is the answer; several there are refused with
29
+ // candidates; a lower tier is not consulted once a higher one matched.
30
+ // "running" and "prompt-blocked" split the live state for resolution only: a
31
+ // live session with a pending prompt is stuck on the operator, so it ranks below
32
+ // an idle twin that is free to take the input. The reported state is unchanged.
33
+ //
34
+ // answer-prompt --to is the exception: its target is by definition the session
35
+ // holding the named request, so it resolves by holding that request id among the
36
+ // address matches (resolve() with holdsRequest), whatever the tier. None holds it
37
+ // is no session; several hold it are candidates.
28
38
 
29
39
  var senderRef = require("./sender-ref");
30
40
  var { slugifyAgentName } = require("./agents");
31
41
  var { isInjected } = require("./injected-sender");
32
42
  var { pendingPrompts } = require("./pending-prompts");
43
+ var liveness = require("./session-liveness");
33
44
 
34
45
  var STATE = Object.freeze({ LIVE: "live", IDLE: "idle", REAPED: "reaped" });
35
46
  var ANY_STATE = "any";
@@ -38,8 +49,16 @@ var STATE_FILTERS = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED, ANY_STA
38
49
  var MAX_ADDRESS_LENGTH = 192;
39
50
  var ADDRESS_RE = /^([^@\s]*)@([^@\s]+)$/;
40
51
 
41
- // Highest first: the order resolve() consults the tiers in.
42
- var TIER_ORDER = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED]);
52
+ // Highest first: the order resolve() consults the tiers in. A tier is a
53
+ // predicate over a directory entry; the live state is split in two here and
54
+ // nowhere else.
55
+ function isPromptBlocked(e) { return e.state === STATE.LIVE && !!e.pendingPrompts && e.pendingPrompts.length > 0; }
56
+ var TIER_ORDER = Object.freeze([
57
+ function (e) { return e.state === STATE.LIVE && !isPromptBlocked(e); },
58
+ function (e) { return e.state === STATE.IDLE; },
59
+ isPromptBlocked,
60
+ function (e) { return e.state === STATE.REAPED; },
61
+ ]);
43
62
 
44
63
  // A session name is a path-free token so it can follow the project after a "/"
45
64
  // in an address. Project slugs never contain "/" (lib/config.js generateSlug).
@@ -56,8 +75,7 @@ function validateName(raw) {
56
75
  }
57
76
 
58
77
  function stateOf(session) {
59
- if (!senderRef.isLive(session)) return STATE.REAPED;
60
- return session.isProcessing ? STATE.LIVE : STATE.IDLE;
78
+ return liveness.liveStateOf(liveness.activityOf(session));
61
79
  }
62
80
 
63
81
  function isoOrNull(ms) {
@@ -171,15 +189,24 @@ function matchesOf(entries, parsed) {
171
189
  // { match } exactly one session
172
190
  // { candidates } more than one; the caller chooses with a session id
173
191
  // { none: true } no session
174
- // The highest state tier (live, idle, reaped) holding any match decides: one
192
+ // The highest tier (running, idle, prompt-blocked, reaped) holding any match decides: one
175
193
  // there is the answer, several are the candidates, and lower tiers are not
176
194
  // looked at. A named address (parsed.name) is exact: it matches only sessions
177
195
  // of that name, so it never falls to a different session; the tiers then only
178
196
  // separate same-named twins (a reaped one beside a running one).
179
- function resolve(entries, parsed) {
197
+ // With holdsRequest (a prompt request id) the matches are first narrowed to the
198
+ // sessions with that request pending and the tiers are not consulted.
199
+ function resolve(entries, parsed, holdsRequest) {
180
200
  var matches = matchesOf(entries, parsed);
201
+ if (holdsRequest !== undefined) {
202
+ var holders = matches.filter(function (e) {
203
+ return (e.pendingPrompts || []).some(function (p) { return p.requestId === holdsRequest; });
204
+ });
205
+ if (holders.length === 1) return { match: holders[0] };
206
+ return holders.length ? { candidates: holders } : { none: true };
207
+ }
181
208
  for (var i = 0; i < TIER_ORDER.length; i++) {
182
- var tier = matches.filter(function (e) { return e.state === TIER_ORDER[i]; });
209
+ var tier = matches.filter(TIER_ORDER[i]);
183
210
  if (tier.length === 1) return { match: tier[0] };
184
211
  if (tier.length > 1) return { candidates: tier };
185
212
  }
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+
3
+ // session-end.js - stands one live session down on request (the end-session
4
+ // verb). The mechanics are the idle reaper's (lib/sdk-bridge.js), plus the two
5
+ // steps a session blocked on an operator prompt needs: its pending prompts are
6
+ // settled and the running turn is aborted, because a turn waiting on a prompt
7
+ // never reads the closed input queue.
8
+ //
9
+ // An end is a reap, not a delete: the session file and history stay, and input
10
+ // to the session's id resumes it.
11
+
12
+ var sessionReclaim = require("./session-reclaim");
13
+ var promptSource = require("./prompt-source");
14
+ var { promptsFor } = require("./prompt-registry");
15
+
16
+ var CANCEL_REASON = "ended";
17
+ var ANNOUNCE_REASON = "ended_by_request";
18
+ var ANNOUNCE_SOURCE = "end-session";
19
+ var REASON_MAX = 200;
20
+
21
+ function errText(e) {
22
+ return e && e.message ? e.message : String(e);
23
+ }
24
+
25
+ // The cancel source for an end: caller:<from> when a caller named itself, else
26
+ // user (the operator's own CLI). Returns { source } or { error }.
27
+ function sourceFor(from) {
28
+ return promptSource.callerSource(from, "an end");
29
+ }
30
+
31
+ // The free-text reason as one bounded line, or "" when none was given.
32
+ function cleanReason(raw) {
33
+ if (typeof raw !== "string") return "";
34
+ return raw.replace(/\s+/g, " ").trim().slice(0, REASON_MAX);
35
+ }
36
+
37
+ function causeFor(endedBy, reason) {
38
+ var cause = "Clagentic: Console ended this session at the request of " + (endedBy === promptSource.CANCEL.USER ? "the operator" : endedBy.replace(/^caller:/, "")) + ".";
39
+ return reason ? cause + " Reason: " + reason + "." : cause;
40
+ }
41
+
42
+ // Ends the session's runtime. Never throws: each step reports its own failure
43
+ // and the later steps still run, so a failed abort cannot leave the prompts
44
+ // pending or the query open. A failed step is returned, not hidden, so the
45
+ // caller can tell an end that left prompts unsettled from a clean one.
46
+ //
47
+ // o: { session, sm, send, slug, source, reason }
48
+ // Returns { agents, failures } - the background agents the announcement named,
49
+ // and { step, error } for each step that failed (step: announce, prompts, abort, close).
50
+ function endLiveSession(o) {
51
+ var session = o.session;
52
+ var failures = [];
53
+
54
+ function failed(step, what, e) {
55
+ console.error("[session-end] could not " + what + " of session " + session.localId + ":", errText(e));
56
+ failures.push({ step: step, error: errText(e) });
57
+ }
58
+
59
+ // First: cancelling the prompts forgets the background agents, and the
60
+ // announcement has to name them.
61
+ var announced = { labels: [] };
62
+ try {
63
+ announced = sessionReclaim.announceLiveAgentReclaim({
64
+ session: session,
65
+ sm: o.sm,
66
+ send: o.send,
67
+ slug: o.slug,
68
+ reason: ANNOUNCE_REASON,
69
+ source: ANNOUNCE_SOURCE,
70
+ cause: causeFor(o.source, cleanReason(o.reason)),
71
+ });
72
+ } catch (e) {
73
+ failed("announce", "announce the end", e);
74
+ }
75
+
76
+ try {
77
+ promptsFor(o.sm).cancelSession(session, CANCEL_REASON, { source: o.source });
78
+ } catch (e) {
79
+ failed("prompts", "settle the prompts", e);
80
+ }
81
+
82
+ if (session.abortController && typeof session.abortController.abort === "function") {
83
+ try { session.abortController.abort(); }
84
+ catch (e) { failed("abort", "abort the turn", e); }
85
+ }
86
+
87
+ try {
88
+ if (session.queryInstance && typeof session.queryInstance.close === "function") session.queryInstance.close();
89
+ else if (session.messageQueue && typeof session.messageQueue.end === "function") session.messageQueue.end();
90
+ } catch (e) {
91
+ failed("close", "close the query", e);
92
+ }
93
+
94
+ return { agents: announced.labels, failures: failures };
95
+ }
96
+
97
+ module.exports = { endLiveSession: endLiveSession, sourceFor: sourceFor, cleanReason: cleanReason };
@@ -21,6 +21,7 @@ function handleSessionCommand(sessionInput, msg) {
21
21
  sessionName: msg.sessionName,
22
22
  sessionVisibility: msg.sessionVisibility,
23
23
  permissionMode: msg.permissionMode,
24
+ settingsFile: msg.settingsFile,
24
25
  initiator: msg.initiator,
25
26
  });
26
27
  }
@@ -39,6 +40,31 @@ function handleSessionCommand(sessionInput, msg) {
39
40
  initiator: msg.initiator,
40
41
  });
41
42
  }
43
+ if (msg.cmd === "end_session") {
44
+ return sessionInput.endSession({
45
+ projectSlug: msg.projectSlug,
46
+ sessionId: msg.sessionId,
47
+ to: msg.to,
48
+ reason: msg.reason,
49
+ from: msg.from,
50
+ fromSession: msg.fromSession,
51
+ senderProject: msg.senderProject,
52
+ senderSessionId: msg.senderSessionId,
53
+ });
54
+ }
55
+ if (msg.cmd === "answer_prompt") {
56
+ return sessionInput.answerPrompt({
57
+ projectSlug: msg.projectSlug,
58
+ sessionId: msg.sessionId,
59
+ to: msg.to,
60
+ requestId: msg.requestId,
61
+ decision: msg.decision,
62
+ from: msg.from,
63
+ fromSession: msg.fromSession,
64
+ senderProject: msg.senderProject,
65
+ senderSessionId: msg.senderSessionId,
66
+ });
67
+ }
42
68
  if (msg.cmd === "list_sessions") {
43
69
  return sessionInput.listSessions({
44
70
  projectSlug: msg.projectSlug,
@@ -50,4 +76,14 @@ function handleSessionCommand(sessionInput, msg) {
50
76
  return undefined;
51
77
  }
52
78
 
53
- module.exports = { handleSessionCommand: handleSessionCommand };
79
+ // The read side of the outbound ledger (lib/outbound-query.js).
80
+ function handleOutboundCommand(outboundQuery, msg) {
81
+ return outboundQuery.list({
82
+ sessionId: msg.sessionId,
83
+ projectSlug: msg.projectSlug,
84
+ sinceMs: msg.sinceMs,
85
+ kind: msg.kind,
86
+ });
87
+ }
88
+
89
+ module.exports = { handleSessionCommand: handleSessionCommand, handleOutboundCommand: handleOutboundCommand };