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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/LICENSES/README.md +5 -0
  2. package/bin/cli.js +4 -2
  3. package/lib/agent-roster-ws.js +84 -0
  4. package/lib/agent-roster.js +312 -0
  5. package/lib/auth-required-notify.js +42 -0
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-notify.js +45 -0
  8. package/lib/build-update-offer.js +3 -4
  9. package/lib/build-update-standing.js +34 -14
  10. package/lib/cli/session-subcommands.js +26 -8
  11. package/lib/client-address.js +44 -0
  12. package/lib/daemon.js +25 -10
  13. package/lib/idle-compaction-setting.js +203 -0
  14. package/lib/mcp-bridge-credential.js +41 -0
  15. package/lib/notification-prefs.js +16 -22
  16. package/lib/notify/core.js +53 -18
  17. package/lib/notify/payload.js +2 -3
  18. package/lib/notify/type-registry.js +17 -0
  19. package/lib/notify/types.js +38 -1
  20. package/lib/outbound-access.js +12 -1
  21. package/lib/outbound-entry.js +8 -1
  22. package/lib/project-connection.js +9 -8
  23. package/lib/project-filesystem.js +23 -0
  24. package/lib/project-loop.js +16 -19
  25. package/lib/project-notifications.js +68 -7
  26. package/lib/project-sessions.js +9 -0
  27. package/lib/project-user-mention.js +22 -34
  28. package/lib/project-user-message.js +208 -4
  29. package/lib/project-user-shell.js +298 -0
  30. package/lib/project.js +26 -4
  31. package/lib/prompt-answer.js +145 -0
  32. package/lib/prompt-expiry.js +50 -0
  33. package/lib/prompt-registry.js +24 -1
  34. package/lib/prompt-source.js +16 -0
  35. package/lib/public/app.js +31 -2
  36. package/lib/public/css/agent-messages.css +96 -0
  37. package/lib/public/css/agent-roster.css +93 -0
  38. package/lib/public/css/diagnostics.css +1 -1
  39. package/lib/public/css/input.css +20 -141
  40. package/lib/public/css/login-panel.css +73 -0
  41. package/lib/public/css/menus.css +2 -2
  42. package/lib/public/css/sidebar.css +11 -0
  43. package/lib/public/css/team-panel.css +1 -6
  44. package/lib/public/css/team-view.css +101 -0
  45. package/lib/public/css/title-bar.css +10 -0
  46. package/lib/public/css/user-shell.css +144 -0
  47. package/lib/public/index.html +41 -7
  48. package/lib/public/modules/agent-avatar-picker.js +162 -0
  49. package/lib/public/modules/agent-avatar.js +153 -0
  50. package/lib/public/modules/agent-messages.js +285 -0
  51. package/lib/public/modules/agent-roster.js +157 -0
  52. package/lib/public/modules/app-connection.js +12 -0
  53. package/lib/public/modules/app-messages.js +55 -16
  54. package/lib/public/modules/app-notifications.js +59 -29
  55. package/lib/public/modules/app-panels.js +26 -3
  56. package/lib/public/modules/app-rate-limit.js +8 -165
  57. package/lib/public/modules/app-rendering.js +22 -7
  58. package/lib/public/modules/collapsible-text.js +33 -18
  59. package/lib/public/modules/compaction-state.js +34 -0
  60. package/lib/public/modules/custom-icons.js +23 -5
  61. package/lib/public/modules/diagnostics.js +52 -55
  62. package/lib/public/modules/injected-identity.js +24 -21
  63. package/lib/public/modules/input.js +176 -15
  64. package/lib/public/modules/login-panel.js +136 -0
  65. package/lib/public/modules/login-parser.js +73 -0
  66. package/lib/public/modules/login-tab.js +66 -0
  67. package/lib/public/modules/notifications.js +9 -1
  68. package/lib/public/modules/notify-client.js +114 -21
  69. package/lib/public/modules/pending-term-request.js +30 -0
  70. package/lib/public/modules/project-icon.js +22 -2
  71. package/lib/public/modules/queued-button.js +11 -0
  72. package/lib/public/modules/scheduled-input-actions.js +12 -4
  73. package/lib/public/modules/scheduled-outbox.js +230 -0
  74. package/lib/public/modules/send-now.js +200 -0
  75. package/lib/public/modules/server-settings.js +47 -1
  76. package/lib/public/modules/shell-card.js +76 -0
  77. package/lib/public/modules/shell-line.js +49 -0
  78. package/lib/public/modules/shell-queue.js +253 -0
  79. package/lib/public/modules/shell-settings-controls.js +76 -0
  80. package/lib/public/modules/sidebar-mobile.js +3 -3
  81. package/lib/public/modules/sidebar-sessions.js +8 -0
  82. package/lib/public/modules/sidebar-users.js +5 -7
  83. package/lib/public/modules/team-panel.js +30 -88
  84. package/lib/public/modules/team-view.js +211 -0
  85. package/lib/public/modules/terminal-links.js +18 -0
  86. package/lib/public/modules/terminal.js +65 -4
  87. package/lib/public/modules/tools.js +19 -0
  88. package/lib/public/modules/user-shell.js +824 -0
  89. package/lib/public/notify-sw-logic.js +35 -83
  90. package/lib/public/notify-target.js +70 -10
  91. package/lib/public/style.css +5 -0
  92. package/lib/public/sw.js +7 -3
  93. package/lib/queued-chat.js +392 -0
  94. package/lib/scheduled-input/ws.js +67 -9
  95. package/lib/sdk-bridge.js +122 -43
  96. package/lib/sdk-message-processor.js +46 -39
  97. package/lib/server-auth.js +6 -4
  98. package/lib/server-dm.js +11 -20
  99. package/lib/server-settings.js +39 -1
  100. package/lib/server.js +83 -19
  101. package/lib/session-directory.js +33 -8
  102. package/lib/session-end.js +97 -0
  103. package/lib/session-input-ipc.js +26 -0
  104. package/lib/session-input.js +176 -9
  105. package/lib/session-resume.js +1 -0
  106. package/lib/session-settings-file.js +53 -0
  107. package/lib/sessions.js +49 -5
  108. package/lib/team-traffic-ws.js +68 -0
  109. package/lib/team-traffic.js +318 -0
  110. package/lib/usage-store.js +7 -0
  111. package/lib/user-shell-settings.js +105 -0
  112. package/lib/ws-schema.js +27 -4
  113. package/lib/yoke/adapters/claude-capabilities.js +2 -0
  114. package/lib/yoke/adapters/claude-vendor.js +6 -0
  115. package/lib/yoke/adapters/claude-worker.js +39 -11
  116. package/lib/yoke/adapters/claude.js +218 -6
  117. package/lib/yoke/adapters/codex-capabilities.js +6 -1
  118. package/lib/yoke/adapters/codex-user-shell.js +265 -0
  119. package/lib/yoke/adapters/codex-vendor.js +7 -0
  120. package/lib/yoke/adapters/codex.js +186 -52
  121. package/lib/yoke/codex-app-server.js +8 -2
  122. package/lib/yoke/interface.js +54 -1
  123. package/lib/yoke/mcp-bridge-server.js +12 -8
  124. package/lib/yoke/registry.js +32 -0
  125. package/lib/yoke/user-shell.js +224 -0
  126. package/package.json +1 -1
  127. package/lib/public/modules/build-notice-gate.js +0 -73
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
@@ -437,21 +443,53 @@ function createServer(opts) {
437
443
  },
438
444
  });
439
445
  _outboundLedger.start();
446
+ var _outboundAccess = require("./outbound-access").createOutboundAccess({
447
+ projectAccess: projectAccess,
448
+ getProject: function (slug) { return projects.get(slug) || null; },
449
+ });
440
450
  // `list-outbound` arrives on the daemon-owner socket: no user record, and
441
451
  // authenticated by the OS gate on the socket itself.
442
452
  var _outboundQuery = require("./outbound-query").createOutboundQuery({
443
453
  ledger: _outboundLedger,
444
- access: require("./outbound-access").createOutboundAccess({
445
- projectAccess: projectAccess,
446
- getProject: function (slug) { return projects.get(slug) || null; },
447
- }),
454
+ access: _outboundAccess,
448
455
  caller: { user: null, authenticated: true },
449
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
+ };
450
486
  // One implementation for the file drop and the daemon IPC verbs (open-session,
451
487
  // send-input).
452
488
  var _sessionInput = require("./session-input").createSessionInput({
453
489
  getProject: function (slug) { return projects.get(slug) || null; },
454
- outboundLedger: _outboundLedger,
490
+ outboundLedger: _announcingLedger,
491
+ onAutomationInjected: _teamTrafficNotifier.notify,
492
+ onAgentSeen: _agentRoster.observe,
455
493
  // Read when a session is opened, so a change needs no restart.
456
494
  getPermissionSettings: function () {
457
495
  return onGetPermissionSettings ? onGetPermissionSettings() : null;
@@ -473,6 +511,17 @@ function createServer(opts) {
473
511
  listFor: function (slug, session) { return _scheduledInput.armedForSession(slug, session); },
474
512
  }),
475
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
+ });
476
525
  var _externalTrigger = attachExternalTrigger({
477
526
  triggersDir: EXTERNAL_TRIGGERS_DIR,
478
527
  getProject: function (slug) { return projects.get(slug) || null; },
@@ -836,18 +885,17 @@ function createServer(opts) {
836
885
  }
837
886
 
838
887
  // Auth check for project routes
839
- // Bypass auth for MCP bridge endpoint (localhost only).
840
- // 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.
841
892
  var projectUrlForAuth = stripPrefix(req.url.split("?")[0], slug);
842
- // req.socket.remoteAddress may differ between HTTP/HTTPS (TLSSocket wraps net.Socket).
843
- // Also check req.connection.remoteAddress for compatibility.
844
893
  var remoteAddr = req.socket.remoteAddress
845
894
  || (req.connection && req.connection.remoteAddress)
846
895
  || "";
847
- var isLocalhost = remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1";
848
896
  var isMcpBridgeLocal = projectUrlForAuth === "/api/mcp-bridge"
849
897
  && req.method === "POST"
850
- && isLocalhost;
898
+ && mcpBridgeCredential.verifyCredential(slug, req.headers[mcpBridgeCredential.HEADER_NAME]);
851
899
  if (projectUrlForAuth === "/api/mcp-bridge") {
852
900
  console.log("[server] MCP bridge auth: method=" + req.method + " addr=" + remoteAddr + " bypass=" + isMcpBridgeLocal);
853
901
  }
@@ -898,8 +946,8 @@ function createServer(opts) {
898
946
  }).protocol;
899
947
  res.setHeader("Set-Cookie", "clagentic_last_project=" + slug + "; Path=/; SameSite=Strict; Max-Age=31536000" + (cookieEffectiveProtocol === "https" ? "; Secure" : ""));
900
948
 
901
- // Check project access for HTTP requests. The local MCP bridge carries no
902
- // 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
903
951
  // request must belong to a user who may use this project.
904
952
  if (!isMcpBridgeLocal) {
905
953
  var httpUser = getMultiUserFromReq(req);
@@ -1197,8 +1245,7 @@ function createServer(opts) {
1197
1245
  // The only place a connection is marked authenticated: handleUpgrade
1198
1246
  // answered 401 above for anything that failed the login check.
1199
1247
  ws._clagenticAuthenticated = true;
1200
- var remoteAddr = req.socket.remoteAddress || "";
1201
- ws._clagenticLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
1248
+ ws._clagenticLocal = resolveClientAddress(req, trustedProxy).local;
1202
1249
  // lr-20e71c: resolve the real external protocol for THIS connection at
1203
1250
  // upgrade time, while req.headers is still in scope — project-sessions.js's
1204
1251
  // per-message dispatch only has ws/msg, not the original upgrade req.
@@ -1508,6 +1555,9 @@ function createServer(opts) {
1508
1555
  // header above.
1509
1556
  onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1510
1557
  scheduledInput: _scheduledInput,
1558
+ teamTraffic: _teamTraffic,
1559
+ agentRoster: _agentRoster,
1560
+ onAgentSeen: _agentRoster.observe,
1511
1561
  // lr-13c047: expose the non-switch "mark read" clear path (see
1512
1562
  // markCrossProjectRead's header above) so lib/project-sessions.js can
1513
1563
  // wire a client-initiated mark_cross_project_read WS message without
@@ -1530,7 +1580,13 @@ function createServer(opts) {
1530
1580
  onSetProjectFolder: onSetProjectFolder,
1531
1581
  onRenameProjectFolder: onRenameProjectFolder,
1532
1582
  onSetFolderIcon: onSetFolderIcon,
1533
- 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,
1534
1590
  onProjectOwnerChanged: onProjectOwnerChanged,
1535
1591
  onGetServerDefaultEffort: onGetServerDefaultEffort,
1536
1592
  onSetServerDefaultEffort: onSetServerDefaultEffort,
@@ -1546,6 +1602,8 @@ function createServer(opts) {
1546
1602
  onSetProjectDefaultMode: onSetProjectDefaultMode,
1547
1603
  onGetPermissionSettings: onGetPermissionSettings,
1548
1604
  onSetPermissionSettings: onSetPermissionSettings,
1605
+ onGetUserShellSettings: onGetUserShellSettings,
1606
+ onSetUserShellSettings: onSetUserShellSettings,
1549
1607
  onGetServerDefaultBetas: onGetServerDefaultBetas,
1550
1608
  onSetServerDefaultBetas: onSetServerDefaultBetas,
1551
1609
  onGetProjectDefaultBetas: onGetProjectDefaultBetas,
@@ -1569,7 +1627,6 @@ function createServer(opts) {
1569
1627
  onShutdown: onShutdown,
1570
1628
  onRestart: onRestart,
1571
1629
  onRestartForBuildUpdate: onRestartForBuildUpdate,
1572
- onGetBuildUpdateDiagnostic: onGetBuildUpdateDiagnostic,
1573
1630
  onDmMessage: handleDmMessage,
1574
1631
  broadcastAll: broadcastAll,
1575
1632
  notificationsModule: _globalNotifications,
@@ -1843,9 +1900,11 @@ function createServer(opts) {
1843
1900
  function destroyAll() {
1844
1901
  _promptReminders.stop();
1845
1902
  _outboundLedger.stop();
1903
+ _teamTrafficNotifier.stop();
1904
+ _agentRosterNotifier.stop();
1846
1905
  _externalTrigger.stopWatcher();
1847
1906
  _scheduledInput.stop();
1848
- var shutdowns = [];
1907
+ var shutdowns = [_agentRoster.flush()];
1849
1908
  var tally = sessionReclaim.createShutdownTally();
1850
1909
  projects.forEach(function (ctx, slug) {
1851
1910
  console.log("[server] Destroying project:", slug);
@@ -1932,6 +1991,11 @@ function createServer(opts) {
1932
1991
  setRecovery: auth.setRecovery,
1933
1992
  clearRecovery: auth.clearRecovery,
1934
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
+ },
1935
1999
  forEachProject: forEachProject,
1936
2000
  sessionInput: _sessionInput,
1937
2001
  outboundQuery: _outboundQuery,
@@ -24,9 +24,17 @@
24
24
  // <agent>@<project>/<name>, <vendor>@<project>/<name>, @<project>/<name>
25
25
  //
26
26
  // Resolution never guesses. Among the sessions an address matches, the highest
27
- // state tier that has any match decides: live, then idle, then reaped. Exactly
28
- // one there is the answer; several there are refused with candidates; a lower
29
- // 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.
30
38
 
31
39
  var senderRef = require("./sender-ref");
32
40
  var { slugifyAgentName } = require("./agents");
@@ -41,8 +49,16 @@ var STATE_FILTERS = Object.freeze([STATE.LIVE, STATE.IDLE, STATE.REAPED, ANY_STA
41
49
  var MAX_ADDRESS_LENGTH = 192;
42
50
  var ADDRESS_RE = /^([^@\s]*)@([^@\s]+)$/;
43
51
 
44
- // Highest first: the order resolve() consults the tiers in.
45
- 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
+ ]);
46
62
 
47
63
  // A session name is a path-free token so it can follow the project after a "/"
48
64
  // in an address. Project slugs never contain "/" (lib/config.js generateSlug).
@@ -173,15 +189,24 @@ function matchesOf(entries, parsed) {
173
189
  // { match } exactly one session
174
190
  // { candidates } more than one; the caller chooses with a session id
175
191
  // { none: true } no session
176
- // 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
177
193
  // there is the answer, several are the candidates, and lower tiers are not
178
194
  // looked at. A named address (parsed.name) is exact: it matches only sessions
179
195
  // of that name, so it never falls to a different session; the tiers then only
180
196
  // separate same-named twins (a reaped one beside a running one).
181
- 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) {
182
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
+ }
183
208
  for (var i = 0; i < TIER_ORDER.length; i++) {
184
- var tier = matches.filter(function (e) { return e.state === TIER_ORDER[i]; });
209
+ var tier = matches.filter(TIER_ORDER[i]);
185
210
  if (tier.length === 1) return { match: tier[0] };
186
211
  if (tier.length > 1) return { candidates: tier };
187
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,