@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/sessions.js CHANGED
@@ -7,13 +7,16 @@ var users = require("./users");
7
7
  var { CODEX_DEFAULTS } = require("./codex-defaults");
8
8
  var { isVisibleHistoryEvent } = require("./history-visibility");
9
9
  var { createPromptRegistry } = require("./prompt-registry");
10
+ var promptSource = require("./prompt-source");
10
11
  var { registerExitFlush } = require("./exit-flush");
11
12
  var sessionReclaim = require("./session-reclaim");
13
+ var sessionLiveness = require("./session-liveness");
12
14
  var sessionFileScan = require("./session-file-scan");
13
15
  var { findNameHolder } = require("./session-name-holder");
14
16
  var { createSenderRecorder } = require("./message-sender-record");
15
17
  var { checkPermissionMode, savedModeOrDefault } = require("./permission-mode-policy");
16
18
  var { logField } = require("./log-field");
19
+ var queuedChat = require("./queued-chat");
17
20
 
18
21
  // lr-2ea2a7: hard cap on how many history entries a session may hold in the
19
22
  // heap array, regardless of isProcessing state. On-disk JSONL remains the
@@ -123,15 +126,31 @@ function createSessionManager(opts) {
123
126
  // Sole writer of every session's operator-prompt state; see
124
127
  // lib/prompt-registry.js. Built before any session exists because
125
128
  // construction itself may create and switch to one.
129
+ // A prompt opening or settling changes what the session list shows (the
130
+ // waiting indicator), and nothing else broadcasts the list for it. Coalesced
131
+ // to one broadcast per tick: a cancelled turn can settle several at once.
132
+ var listBroadcastQueued = false;
133
+ var managerDestroyed = false;
134
+ function onPromptsChanged() {
135
+ if (typeof opts.onProcessingChanged === "function") opts.onProcessingChanged();
136
+ if (listBroadcastQueued || managerDestroyed || (!send && !sendEach)) return;
137
+ listBroadcastQueued = true;
138
+ setImmediate(function () {
139
+ listBroadcastQueued = false;
140
+ if (!managerDestroyed) broadcastSessionList();
141
+ });
142
+ }
126
143
  var prompts = createPromptRegistry({
127
144
  index: permissionRequestIndex,
128
145
  getSession: function (localId) { return sessions.get(localId) || null; },
129
146
  sendAndRecord: function (session, obj) { return doSendAndRecord(session, obj); },
130
147
  saveSessionFile: function (session) { return saveSessionFile(session); },
131
148
  getNotificationsModule: opts.getNotificationsModule,
132
- onProcessingChanged: opts.onProcessingChanged,
149
+ onProcessingChanged: onPromptsChanged,
133
150
  getProjectName: opts.getProjectName,
134
151
  getProjectSlug: opts.getProjectSlug,
152
+ getPushModule: opts.getPushModule,
153
+ getConfig: function () { return config.loadConfig(); },
135
154
  });
136
155
  var capabilitiesByVendor = null; // set by sdk-bridge after adapter init
137
156
  var defaultVendor = null; // set by sdk-bridge
@@ -184,6 +203,8 @@ function createSessionManager(opts) {
184
203
  // The session's own permission mode, so a resume or a restart keeps it
185
204
  // instead of taking whatever the project default is by then.
186
205
  if (session.permissionMode) metaObj.permissionMode = session.permissionMode;
206
+ // The session's additive settings file path, kept across resume and restart.
207
+ if (session.settingsFile) metaObj.settingsFile = session.settingsFile;
187
208
  // Persist per-session "allow for session" tool grants (lr-8b2e) so they
188
209
  // survive daemon restart / resume-by-cliSessionId rehydration instead of
189
210
  // silently re-prompting. Only written when non-empty — grants that were
@@ -217,6 +238,10 @@ function createSessionManager(opts) {
217
238
  // Which identity provider vouched for the session and at what grade. Only
218
239
  // present when a provider is configured: a plain session has no such field.
219
240
  if (session.identity) metaObj.identity = session.identity;
241
+ // Chat the agent has not taken in, and text handed back to no page yet: what a
242
+ // restart would otherwise lose (lib/queued-chat.js). Present only while any waits.
243
+ var queued = queuedChat.durable(session);
244
+ if (queued.length > 0) metaObj.queuedChat = queued;
220
245
  return JSON.stringify(metaObj);
221
246
  }
222
247
 
@@ -742,11 +767,21 @@ function createSessionManager(opts) {
742
767
  var firstLine = "";
743
768
  try {
744
769
  fd = fs.openSync(path.join(sessionsDir, files[i]), "r");
770
+ // The meta line can be long (queued chat text rides on it), so read on
771
+ // until the line ends rather than stopping at a fixed size.
745
772
  var buf = Buffer.alloc(4096);
746
- var bytesRead = fs.readSync(fd, buf, 0, 4096, 0);
747
- var chunk = buf.toString("utf8", 0, bytesRead);
748
- var nl = chunk.indexOf("\n");
749
- firstLine = nl !== -1 ? chunk.substring(0, nl) : chunk;
773
+ var offset = 0;
774
+ var chunks = [];
775
+ var lineEnd = -1;
776
+ while (lineEnd === -1) {
777
+ var bytesRead = fs.readSync(fd, buf, 0, 4096, offset);
778
+ if (bytesRead === 0) break;
779
+ var piece = Buffer.from(buf.subarray(0, bytesRead));
780
+ lineEnd = piece.indexOf(10);
781
+ chunks.push(lineEnd === -1 ? piece : piece.subarray(0, lineEnd));
782
+ offset += bytesRead;
783
+ }
784
+ firstLine = Buffer.concat(chunks).toString("utf8");
750
785
  } catch { continue; } finally {
751
786
  if (fd !== undefined) try { fs.closeSync(fd); } catch (e) {}
752
787
  }
@@ -818,6 +853,7 @@ function createSessionManager(opts) {
818
853
  }
819
854
  session.permissionMode = savedMode.mode;
820
855
  }
856
+ if (typeof m.settingsFile === "string" && m.settingsFile) session.settingsFile = m.settingsFile;
821
857
  if (m.ownerId) session.ownerId = m.ownerId;
822
858
  session.sessionVisibility = m.sessionVisibility || "shared";
823
859
  session.bookmarked = !!m.bookmarked;
@@ -843,6 +879,9 @@ function createSessionManager(opts) {
843
879
  var identityRecord = require("./identity/record").sanitizeRecord(m.identity);
844
880
  if (identityRecord) session.identity = identityRecord;
845
881
  }
882
+ // Chat that was waiting when the daemon last stopped: no agent holds it now,
883
+ // so it is handed back the first time a page shows the session.
884
+ queuedChat.loadParked(session, m.queuedChat);
846
885
  sessions.set(localId, session);
847
886
  }
848
887
  }
@@ -889,6 +928,8 @@ function createSessionManager(opts) {
889
928
  title: s.title || "New Session",
890
929
  active: isActive,
891
930
  isProcessing: s.isProcessing,
931
+ compacting: !!s.compacting,
932
+ waiting: sessionLiveness.activityOf(s) === sessionLiveness.ACTIVITY.WAITING,
892
933
  lastActivity: s.lastActivity || s.createdAt || 0,
893
934
  loop: loop,
894
935
  ownerId: s.ownerId || null,
@@ -987,10 +1028,19 @@ function createSessionManager(opts) {
987
1028
  vendor: (sessionOpts && sessionOpts.vendor) || null,
988
1029
  agentName: (sessionOpts && sessionOpts.agentName) || null,
989
1030
  sessionName: (sessionOpts && sessionOpts.sessionName) || null,
1031
+ settingsFile: (sessionOpts && sessionOpts.settingsFile) || null,
990
1032
  };
991
1033
  giveStartingMode(session, sessionOpts);
992
1034
  sessions.set(localId, session);
993
- switchSession(localId, targetWs);
1035
+ // activate:false has the meaning it has in resumeSession: the session is
1036
+ // created and listed, but no client's active session (and not
1037
+ // activeSessionId) changes. For an IPC-opened session nobody asked to look
1038
+ // at: switching would move every connected tab off the session it is on.
1039
+ if (sessionOpts && sessionOpts.activate === false) {
1040
+ broadcastSessionList();
1041
+ } else {
1042
+ switchSession(localId, targetWs);
1043
+ }
994
1044
  return session;
995
1045
  }
996
1046
 
@@ -1227,7 +1277,7 @@ function createSessionManager(opts) {
1227
1277
  // client hydrating from session_switched alone (no separate config_state
1228
1278
  // round-trip needed) never has to fall back to guessing the shared
1229
1279
  // project/global default — see effectiveSessionModel() above.
1230
- _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, model: effectiveSessionModel(session, _instance), mode: effectiveSessionMode(session, _instance), hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
1280
+ _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, model: effectiveSessionModel(session, _instance), mode: effectiveSessionMode(session, _instance), hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null, compacting: !!session.compacting });
1231
1281
  // Send vendor-specific slash commands
1232
1282
  var _vendorCmds = slashCommandsByVendor[_sessionVendor] || slashCommands || [];
1233
1283
  _send({ type: "slash_commands", commands: _vendorCmds, vendor: _sessionVendor });
@@ -1241,6 +1291,25 @@ function createSessionManager(opts) {
1241
1291
  // Re-present every prompt still awaiting the operator.
1242
1292
  prompts.pendingMessages(session).forEach(_send);
1243
1293
 
1294
+ // Chat the agent has not taken in. The page rebuilt its transcript and holds no
1295
+ // queued item of its own (a reload, a second tab), so it is told what is still
1296
+ // waiting and draws it again. Text that no page has been handed (the daemon
1297
+ // restarted, or the query closed with nobody viewing) goes back to the composer
1298
+ // of the first page that shows the session, once.
1299
+ queuedChat.pending(session).forEach(function (p) {
1300
+ var tracked = { type: "queued_message_tracked", messageId: p.messageId, text: p.text, pastes: p.pastes, imageCount: p.imageCount, unconfirmed: p.unconfirmed };
1301
+ // Send now was pressed: the page draws it as sending, never as queued again.
1302
+ if (p.sendNow) tracked.sendNow = true;
1303
+ _send(tracked);
1304
+ });
1305
+ var parkedChat = queuedChat.takeParked(session);
1306
+ if (parkedChat.length > 0) {
1307
+ parkedChat.forEach(function (p) {
1308
+ _send({ type: "queued_message_cancelled", messageId: p.messageId, result: "dropped", cause: p.cause, text: p.text, pastes: p.pastes, imageCount: p.imageCount });
1309
+ });
1310
+ saveSessionFile(session);
1311
+ }
1312
+
1244
1313
  // Re-send active mention indicator so returning clients restore the mate avatar state
1245
1314
  if (session._mentionInProgress && session._mentionActiveMateId) {
1246
1315
  _send({ type: "mention_processing", mateId: session._mentionActiveMateId, active: true });
@@ -1281,7 +1350,7 @@ function createSessionManager(opts) {
1281
1350
  cleanupMentionSessions(session);
1282
1351
  // Settled before the abort below so no abort listener records an event
1283
1352
  // into a history that is about to be deleted.
1284
- prompts.cancelSession(session, "session_deleted", { record: false });
1353
+ prompts.cancelSession(session, "session_deleted", { record: false, source: promptSource.CANCEL.SESSION_END });
1285
1354
 
1286
1355
  if (session.abortController) {
1287
1356
  try { session.abortController.abort(); } catch(e) {}
@@ -1330,7 +1399,7 @@ function createSessionManager(opts) {
1330
1399
  _lruRemove(localId);
1331
1400
 
1332
1401
  cleanupMentionSessions(session);
1333
- prompts.cancelSession(session, "session_deleted", { record: false });
1402
+ prompts.cancelSession(session, "session_deleted", { record: false, source: promptSource.CANCEL.SESSION_END });
1334
1403
  if (session.abortController) {
1335
1404
  try { session.abortController.abort(); } catch(e) {}
1336
1405
  }
@@ -1508,6 +1577,7 @@ function createSessionManager(opts) {
1508
1577
  };
1509
1578
  if (opts && opts.vendor) session.vendor = opts.vendor;
1510
1579
  if (opts && opts.agentName) session.agentName = opts.agentName;
1580
+ if (opts && opts.settingsFile) session.settingsFile = opts.settingsFile;
1511
1581
  // A session resumed from its stored record keeps the mode saved with it.
1512
1582
  giveStartingMode(session, opts);
1513
1583
  if (opts && opts.sessionName) {
@@ -1977,6 +2047,7 @@ function createSessionManager(opts) {
1977
2047
  // outcome is flushed to disk; then the exit flusher registered above is
1978
2048
  // unregistered so nothing accumulates across project open/close cycles.
1979
2049
  destroy: function() {
2050
+ managerDestroyed = true;
1980
2051
  prompts.shutdown();
1981
2052
  _onProcessExit();
1982
2053
  unregisterExitFlush();
@@ -0,0 +1,68 @@
1
+ // team-traffic-ws.js - the browser's side of the Team view's agent-messages
2
+ // section (lib/team-traffic.js).
3
+ //
4
+ // team_traffic_request c2s ask for the traffic this connection may see
5
+ // team_traffic s2c the answer: pairs, messages, pending, withheld
6
+ // team_traffic_changed s2c something landed; ask again. It carries no
7
+ // content, so what a connection may read is
8
+ // decided only when it asks, never by a broadcast.
9
+
10
+ var REQUEST = "team_traffic_request";
11
+ var CHANGED = "team_traffic_changed";
12
+ var DEFAULT_DELAY_MS = 200;
13
+
14
+ // deps: { service (createTeamTraffic() result, or null), sendTo(ws, obj) }
15
+ function createWsHandlers(deps) {
16
+ var service = deps.service;
17
+
18
+ // Answers true when the message was one of ours.
19
+ function handle(ws, msg) {
20
+ if (!msg || msg.type !== REQUEST) return false;
21
+ if (!service) {
22
+ deps.sendTo(ws, { type: "team_traffic", ok: false, result: "error", reason: "agent messages are not available here" });
23
+ return true;
24
+ }
25
+ var caller = { user: ws._clagenticUser || null, authenticated: ws._clagenticAuthenticated === true };
26
+ var answer;
27
+ try {
28
+ answer = service.snapshot(caller);
29
+ } catch (e) {
30
+ console.error("[team-traffic] snapshot failed:", e && e.message ? e.message : e);
31
+ answer = { ok: false, result: "error", reason: "the agent messages could not be read" };
32
+ }
33
+ deps.sendTo(ws, Object.assign({ type: "team_traffic" }, answer));
34
+ return true;
35
+ }
36
+
37
+ return { handle: handle };
38
+ }
39
+
40
+ // A burst of entries (a sender opening several sessions) makes one broadcast.
41
+ // deps: { broadcast(msg), delayMs?, build()? }. build() makes the message to
42
+ // send; the default is the content-free nudge. The agent roster reuses this
43
+ // burst-coalescing timer and sends its own content-free agent_roster_changed
44
+ // nudge, so each connection asks for the roster it may read.
45
+ function createNotifier(deps) {
46
+ var delay = typeof deps.delayMs === "number" ? deps.delayMs : DEFAULT_DELAY_MS;
47
+ var build = typeof deps.build === "function" ? deps.build : function () { return { type: CHANGED }; };
48
+ var timer = null;
49
+
50
+ function notify() {
51
+ if (timer) return;
52
+ timer = setTimeout(function () {
53
+ timer = null;
54
+ try { deps.broadcast(build()); }
55
+ catch (e) { console.error("[team-traffic] broadcast failed:", e && e.message ? e.message : e); }
56
+ }, delay);
57
+ if (typeof timer.unref === "function") timer.unref();
58
+ }
59
+
60
+ function stop() {
61
+ if (timer) clearTimeout(timer);
62
+ timer = null;
63
+ }
64
+
65
+ return { notify: notify, stop: stop };
66
+ }
67
+
68
+ module.exports = { createWsHandlers: createWsHandlers, createNotifier: createNotifier, REQUEST: REQUEST, CHANGED: CHANGED };
@@ -0,0 +1,318 @@
1
+ // team-traffic.js - the read side of the Team view's agent-messages section:
2
+ // the agent-to-agent traffic that went through the console, grouped by
3
+ // counterpart pair, for one caller.
4
+ //
5
+ // Read-only. The outbound ledger (lib/outbound-ledger.js) is the primary source:
6
+ // every open-session and send-input leaves one entry there. Two routes never
7
+ // reach the ledger and are filled from the receiving session's own history, in
8
+ // the same aggregation (no second view):
9
+ // - a scheduled firing (fireScheduled in session-input.js records the turn the
10
+ // console composed, never a ledger entry)
11
+ // - a loop iteration (project-loop.js starts its sessions itself and does not
12
+ // call session-input.js)
13
+ // Both are recorded on the target as a user_message from the console's own
14
+ // automation (senderKind "automation"). The fill reads the sessions the console
15
+ // holds in memory, so it only reaches back as far as their loaded history.
16
+ // Armed scheduled inputs are listed as pending, read-only.
17
+ //
18
+ // The read rules are the ledger's (lib/outbound-access.js), unchanged. An entry
19
+ // is shown only when its text may be shown to this caller: one whose text the
20
+ // caller cannot read, or that was never stored because the target runs as
21
+ // another OS user, is counted and its reason reported, and is not listed.
22
+
23
+ var outboundEntry = require("./outbound-entry");
24
+ var injectedSender = require("./injected-sender");
25
+ var { INITIATORS } = require("./turn-initiator");
26
+
27
+ var MAX_MESSAGES = 1000;
28
+ var MAX_TEXT_CHARS = 4000;
29
+ var MAX_REASONS = 5;
30
+ var DAY_MS = 24 * 60 * 60 * 1000;
31
+ var OTHER_OS_USER = "the target session runs as another OS user";
32
+
33
+ var KIND = Object.freeze({ OPEN: "open", INPUT: "input", SCHEDULED: "scheduled", REPLY: "reply", LOOP: "loop" });
34
+
35
+ var OUTBOUND_VERBS = new Set([outboundEntry.VERB.SEND_INPUT, outboundEntry.VERB.OPEN_SESSION]);
36
+
37
+ function clip(text) {
38
+ if (typeof text !== "string") return { text: null, truncated: false };
39
+ if (text.length <= MAX_TEXT_CHARS) return { text: text, truncated: false };
40
+ return { text: text.slice(0, MAX_TEXT_CHARS), truncated: true };
41
+ }
42
+
43
+ function kindOfEntry(entry) {
44
+ if (entry.target && entry.target.reply === true) return KIND.REPLY;
45
+ if (entry.initiator === INITIATORS.SCHEDULED || entry.initiator === INITIATORS.SCHEDULED_NOW) return KIND.SCHEDULED;
46
+ return entry.verb === outboundEntry.VERB.OPEN_SESSION ? KIND.OPEN : KIND.INPUT;
47
+ }
48
+
49
+ function kindOfAutomation(initiator) {
50
+ return initiator === INITIATORS.LOOP ? KIND.LOOP : KIND.SCHEDULED;
51
+ }
52
+
53
+ // A sender as the client's identity adapter takes it (injected-identity.js).
54
+ function identityOfLedgerSender(sender) {
55
+ sender = sender || {};
56
+ var out = { senderKind: sender.kind || injectedSender.SENDER_KIND.UNDECLARED, attribution: sender.attribution || "unverified" };
57
+ if (sender.name) out.fromName = sender.name;
58
+ if (sender.agent) out.senderAgent = sender.agent;
59
+ if (sender.project) out.senderProject = sender.project;
60
+ if (sender.sessionId) out.senderSessionId = sender.sessionId;
61
+ if (sender.declaredName) out.declaredName = sender.declaredName;
62
+ return out;
63
+ }
64
+
65
+ function identityOfAutomation(entry) {
66
+ return {
67
+ senderKind: injectedSender.SENDER_KIND.AUTOMATION,
68
+ attribution: "console",
69
+ fromName: entry.fromName,
70
+ initiator: entry.initiator,
71
+ };
72
+ }
73
+
74
+ // Stable text for "who": the pair is the same pair whichever entry names it.
75
+ function senderKey(sender) {
76
+ sender = sender || {};
77
+ if (sender.attribution === "extracted" && sender.project && (sender.cliSessionId || sender.sessionId)) {
78
+ return "s:" + sender.project + "/" + (sender.cliSessionId || "console-" + sender.sessionId);
79
+ }
80
+ if (sender.kind === "declared" && sender.name) return "d:" + sender.name + (sender.fromSession ? "/" + sender.fromSession : "");
81
+ return "u:";
82
+ }
83
+
84
+ function targetKey(target) {
85
+ target = target || {};
86
+ return (target.project || "") + "/" + (target.cliSessionId || (target.sessionId ? "console-" + target.sessionId : target.address || ""));
87
+ }
88
+
89
+ // deps:
90
+ // ledger lib/outbound-ledger.js createOutboundLedger() result
91
+ // access lib/outbound-access.js createOutboundAccess() result
92
+ // getProject(slug) -> project context | null
93
+ // listProjects() -> [{ slug, project }] every project held
94
+ // scheduledInput optional { armedForSession(slug, session) } (lib/scheduled-input/service.js)
95
+ // now() ms clock (default Date.now)
96
+ function createTeamTraffic(deps) {
97
+ var ledger = deps.ledger;
98
+ var access = deps.access;
99
+ var getProject = deps.getProject;
100
+ var listProjects = deps.listProjects || function () { return []; };
101
+ var scheduledInput = deps.scheduledInput || null;
102
+ var now = deps.now || Date.now;
103
+
104
+ // The caller's view of one session, by the same decision the ledger applies to
105
+ // its prompts. A session is named by project and vendor id only.
106
+ function mayRead(project, cliSessionId, caller) {
107
+ return access.canReadPrompt({ target: { project: project, cliSessionId: cliSessionId } }, caller);
108
+ }
109
+
110
+ // The live session behind a vendor id, as the sidebar addresses it now. A
111
+ // console id is renumbered by a restart, so it is looked up here at read time
112
+ // and never stored. null when the session is gone or the caller may not read it.
113
+ function linkFor(slug, cliSessionId, caller) {
114
+ if (!slug || !cliSessionId) return null;
115
+ var project = getProject(slug);
116
+ if (!project || !project.sm || !project.sm.sessions) return null;
117
+ var found = null;
118
+ project.sm.sessions.forEach(function (s) {
119
+ if (!found && s.cliSessionId === cliSessionId) found = s;
120
+ });
121
+ if (!found || !mayRead(slug, cliSessionId, caller).allowed) return null;
122
+ return { project: slug, id: found.localId };
123
+ }
124
+
125
+ function describeTarget(target) {
126
+ target = target || {};
127
+ var out = { project: target.project || null };
128
+ if (target.agent) out.agent = target.agent;
129
+ if (target.name) out.name = target.name;
130
+ return out;
131
+ }
132
+
133
+ // Collects what the caller may see into `state`; counts and explains the rest.
134
+ function collect(state, caller, cutoff) {
135
+ function withhold(reason) {
136
+ state.withheldCount++;
137
+ if (reason && state.reasons.indexOf(reason) === -1 && state.reasons.length < MAX_REASONS) state.reasons.push(reason);
138
+ }
139
+
140
+ ledger.readAttributed({}).concat(ledger.readUnattributed({})).forEach(function (e) {
141
+ if (!OUTBOUND_VERBS.has(e.verb)) return;
142
+ var verdict = access.canReadPrompt(e, caller);
143
+ if (!verdict.allowed) return withhold(verdict.reason);
144
+ if (e.promptWithheld === true) return withhold(e.promptWithheldReason || OTHER_OS_USER);
145
+ var sender = e.sender || {};
146
+ var text = clip(e.prompt);
147
+ state.items.push({
148
+ ts: e.ts,
149
+ pairKey: senderKey(sender) + ">" + targetKey(e.target),
150
+ senderIdentity: identityOfLedgerSender(sender),
151
+ senderRef: { project: sender.project || null, cliSessionId: sender.cliSessionId || null },
152
+ target: describeTarget(e.target),
153
+ targetRef: { project: (e.target || {}).project || null, cliSessionId: (e.target || {}).cliSessionId || null },
154
+ message: {
155
+ ts: e.ts,
156
+ kind: kindOfEntry(e),
157
+ result: e.result,
158
+ reason: e.reason || null,
159
+ initiator: e.initiator || null,
160
+ messageId: e.messageId || null,
161
+ text: text.text,
162
+ truncated: text.truncated,
163
+ contextNote: typeof e.contextNote === "string" ? e.contextNote : null,
164
+ source: "ledger",
165
+ },
166
+ });
167
+ });
168
+
169
+ listProjects().forEach(function (held) {
170
+ var project = held.project;
171
+ if (!project || !project.sm || !project.sm.sessions) return;
172
+ project.sm.sessions.forEach(function (s) {
173
+ var history = Array.isArray(s.history) ? s.history : [];
174
+ var fromHistory = history.filter(function (h) {
175
+ return injectedSender.isInjected(h) && h.senderKind === injectedSender.SENDER_KIND.AUTOMATION
176
+ && typeof h._ts === "number" && h._ts >= cutoff;
177
+ });
178
+ if (!fromHistory.length) return;
179
+ var linux = typeof project.getLinuxUserForSession === "function" ? project.getLinuxUserForSession(s) : null;
180
+ var verdict = mayRead(held.slug, s.cliSessionId, caller);
181
+ fromHistory.forEach(function (h) {
182
+ if (!verdict.allowed) return withhold(verdict.reason);
183
+ if (linux) return withhold(OTHER_OS_USER);
184
+ var text = clip(h.text);
185
+ var tRef = { project: held.slug, cliSessionId: s.cliSessionId || null };
186
+ state.items.push({
187
+ ts: new Date(h._ts).toISOString(),
188
+ pairKey: "a:" + h.fromName + ">" + targetKey({ project: held.slug, cliSessionId: s.cliSessionId, sessionId: String(s.localId) }),
189
+ senderIdentity: identityOfAutomation(h),
190
+ senderRef: { project: null, cliSessionId: null },
191
+ target: { project: held.slug, agent: s.agentName || undefined, name: s.sessionName || undefined },
192
+ targetRef: tRef,
193
+ message: {
194
+ ts: new Date(h._ts).toISOString(),
195
+ kind: kindOfAutomation(h.initiator),
196
+ result: "delivered",
197
+ reason: null,
198
+ initiator: h.initiator || null,
199
+ messageId: h.messageId || null,
200
+ text: text.text,
201
+ truncated: text.truncated,
202
+ contextNote: typeof h.contextNote === "string" ? h.contextNote : null,
203
+ source: "session",
204
+ },
205
+ });
206
+ });
207
+ });
208
+ });
209
+ }
210
+
211
+ // Armed scheduled inputs of the sessions the caller may read, as pending items.
212
+ function collectPending(state, caller) {
213
+ if (!scheduledInput || typeof scheduledInput.armedForSession !== "function") return;
214
+ listProjects().forEach(function (held) {
215
+ var project = held.project;
216
+ if (!project || !project.sm || !project.sm.sessions) return;
217
+ project.sm.sessions.forEach(function (s) {
218
+ var armed;
219
+ try { armed = scheduledInput.armedForSession(held.slug, s); } catch (e) {
220
+ console.error("[team-traffic] could not list the armed scheduled inputs of " + held.slug + ":", e && e.message ? e.message : e);
221
+ return;
222
+ }
223
+ if (!armed.length || !mayRead(held.slug, s.cliSessionId, caller).allowed) return;
224
+ if (typeof project.getLinuxUserForSession === "function" && project.getLinuxUserForSession(s)) return;
225
+ armed.forEach(function (r) {
226
+ var text = clip(r.text);
227
+ state.pending.push({
228
+ pairKey: "a:" + injectedSender.AUTOMATION_NAMES[INITIATORS.SCHEDULED] + ">" + targetKey({ project: held.slug, cliSessionId: s.cliSessionId, sessionId: String(s.localId) }),
229
+ senderIdentity: { senderKind: injectedSender.SENDER_KIND.AUTOMATION, attribution: "console", fromName: injectedSender.AUTOMATION_NAMES[INITIATORS.SCHEDULED], initiator: INITIATORS.SCHEDULED },
230
+ target: { project: held.slug, agent: s.agentName || undefined, name: s.sessionName || undefined },
231
+ targetRef: { project: held.slug, cliSessionId: s.cliSessionId || null },
232
+ pending: {
233
+ id: r.id,
234
+ kind: KIND.SCHEDULED,
235
+ nextAt: r.nextAt,
236
+ every: r.every,
237
+ createdBy: r.createdBy,
238
+ text: text.text,
239
+ truncated: text.truncated,
240
+ },
241
+ });
242
+ });
243
+ });
244
+ });
245
+ }
246
+
247
+ // caller: { user, authenticated } as for lib/outbound-query.js.
248
+ // Returns { ok, result, retentionDays, pairs, messages, pending, withheld }
249
+ // or { ok: false, result: "error", reason } when the ledger cannot be read.
250
+ function snapshot(caller) {
251
+ var days = ledger.retentionDays();
252
+ var base = { ok: true, result: "listed", retentionDays: days };
253
+ if (days === 0) {
254
+ return Object.assign(base, {
255
+ pairs: [], messages: [], pending: [], withheld: { count: 0, reasons: [] },
256
+ note: "the outbound ledger is turned off (outboundRetentionDays is 0)",
257
+ });
258
+ }
259
+ var state = { items: [], pending: [], withheldCount: 0, reasons: [] };
260
+ try {
261
+ collect(state, caller, now() - days * DAY_MS);
262
+ } catch (e) {
263
+ // The detail (a message can carry a host path) stays in the server log; the
264
+ // client gets the same generic reason the ws handler uses.
265
+ console.error("[team-traffic] could not read the outbound ledger:", e && e.message ? e.message : e, e && e.code ? "(" + e.code + ")" : "");
266
+ return { ok: false, result: "error", reason: "the agent messages could not be read" };
267
+ }
268
+ collectPending(state, caller);
269
+
270
+ state.items.sort(function (a, b) { return Date.parse(a.ts) - Date.parse(b.ts); });
271
+ var pairs = new Map();
272
+ function pairOf(item) {
273
+ var p = pairs.get(item.pairKey);
274
+ if (!p) {
275
+ p = {
276
+ key: item.pairKey,
277
+ sender: Object.assign({}, item.senderIdentity, { link: item.senderRef ? linkFor(item.senderRef.project, item.senderRef.cliSessionId, caller) : null }),
278
+ target: Object.assign({}, item.target, { link: linkFor(item.targetRef.project, item.targetRef.cliSessionId, caller) }),
279
+ count: 0,
280
+ pendingCount: 0,
281
+ lastAt: null,
282
+ };
283
+ pairs.set(item.pairKey, p);
284
+ }
285
+ return p;
286
+ }
287
+ state.items.forEach(function (item) {
288
+ var p = pairOf(item);
289
+ p.count++;
290
+ p.lastAt = item.ts;
291
+ });
292
+ var pending = state.pending.map(function (item) {
293
+ pairOf(item).pendingCount++;
294
+ return Object.assign({ pairKey: item.pairKey }, item.pending);
295
+ });
296
+
297
+ var shown = state.items;
298
+ var truncated = 0;
299
+ if (shown.length > MAX_MESSAGES) {
300
+ truncated = shown.length - MAX_MESSAGES;
301
+ shown = shown.slice(truncated);
302
+ }
303
+ var list = Array.from(pairs.values()).sort(function (a, b) {
304
+ return (b.lastAt ? Date.parse(b.lastAt) : 0) - (a.lastAt ? Date.parse(a.lastAt) : 0);
305
+ });
306
+ return Object.assign(base, {
307
+ pairs: list,
308
+ messages: shown.map(function (item) { return Object.assign({ pairKey: item.pairKey }, item.message); }),
309
+ messagesTruncated: truncated,
310
+ pending: pending,
311
+ withheld: { count: state.withheldCount, reasons: state.reasons },
312
+ });
313
+ }
314
+
315
+ return { snapshot: snapshot };
316
+ }
317
+
318
+ module.exports = { createTeamTraffic: createTeamTraffic, KIND: KIND, MAX_MESSAGES: MAX_MESSAGES, MAX_TEXT_CHARS: MAX_TEXT_CHARS };