@clagentic/console 1.10.0-beta.2 → 1.10.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 (42) hide show
  1. package/lib/activity-clock.js +23 -0
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli-transcript-title.js +131 -0
  4. package/lib/debug-log.js +17 -0
  5. package/lib/exit-flush.js +44 -0
  6. package/lib/grant-keys.js +179 -0
  7. package/lib/log-field.js +34 -0
  8. package/lib/project-http.js +2 -0
  9. package/lib/project-notifications.js +4 -0
  10. package/lib/project-prompt-responses.js +2 -1
  11. package/lib/project-session-grants.js +73 -0
  12. package/lib/project-sessions.js +12 -0
  13. package/lib/project-user-message.js +6 -5
  14. package/lib/project.js +2 -0
  15. package/lib/prompt-kinds/permission.js +18 -0
  16. package/lib/prompt-label.js +60 -0
  17. package/lib/prompt-registry.js +116 -13
  18. package/lib/prompt-source.js +65 -0
  19. package/lib/public/css/notifications-center.css +15 -0
  20. package/lib/public/css/overlays.css +18 -0
  21. package/lib/public/css/rewind.css +8 -0
  22. package/lib/public/modules/app-messages.js +3 -0
  23. package/lib/public/modules/app-notifications.js +9 -1
  24. package/lib/public/modules/prompt-banner.js +12 -0
  25. package/lib/public/modules/prompt-kinds/permission-choices.js +6 -1
  26. package/lib/public/modules/prompt-kinds/permission.js +15 -0
  27. package/lib/public/modules/prompt-label.js +44 -0
  28. package/lib/public/modules/prompts.js +9 -0
  29. package/lib/public/modules/session-grants.js +131 -0
  30. package/lib/public/modules/sidebar-sessions.js +11 -0
  31. package/lib/runtime-env.js +1 -1
  32. package/lib/sdk-bridge.js +53 -101
  33. package/lib/sdk-message-processor.js +14 -67
  34. package/lib/session-ai-title.js +80 -0
  35. package/lib/session-input.js +32 -2
  36. package/lib/sessions.js +14 -18
  37. package/lib/utils.js +9 -47
  38. package/lib/ws-schema.js +6 -3
  39. package/lib/yoke/adapters/claude.js +0 -57
  40. package/lib/yoke/adapters/codex.js +4 -75
  41. package/lib/yoke/interface.js +3 -7
  42. package/package.json +1 -1
@@ -16,6 +16,7 @@ import {
16
16
  } from './prompt-card.js';
17
17
  import { PROMPT_KINDS } from './prompt-kinds/index.js';
18
18
  import { ownValue } from './prompt-kinds/own-key.js';
19
+ import { promptLabelElement } from './prompt-label.js';
19
20
 
20
21
  /**
21
22
  * @param {object} host
@@ -63,6 +64,14 @@ export function createPromptController(host) {
63
64
  });
64
65
  var container = renderer.draw(n.fields, n.requestId, rendererHost);
65
66
  container.dataset.promptKind = n.kind;
67
+ // Whose prompt this is, above everything else on the card. The kinds lay
68
+ // themselves out differently (a body block, a flex row with an avatar), so
69
+ // it goes in the first block that holds the card's text.
70
+ var label = promptLabelElement(n.fields && n.fields.label);
71
+ if (label) {
72
+ var holder = container.querySelector(".permission-body, .dm-bubble-content") || container;
73
+ holder.insertBefore(label, holder.firstChild);
74
+ }
66
75
  cards[n.requestId] = { container: container, kind: n.kind, fields: n.fields, host: rendererHost };
67
76
  host.place(container, renderer.focusSelector || null);
68
77
  return cards[n.requestId];
@@ -0,0 +1,131 @@
1
+ // session-grants.js - the operator's list of what a session may do without
2
+ // asking (its Allow for session grants), with a Revoke for each. The server
3
+ // owns the grants (lib/prompt-registry.js); this only asks for the list,
4
+ // draws what it is told and sends a revoke. A revoke takes effect on the
5
+ // session's next tool call, and the server answers with the list as it now is.
6
+ //
7
+ // Free of the rest of the frontend module graph apart from the connection, so
8
+ // a test can drive it with a hand-built DOM.
9
+
10
+ import { getWs } from './ws-ref.js';
11
+
12
+ var MODAL_ID = "session-grants-modal";
13
+
14
+ function send(msg) {
15
+ var ws = getWs();
16
+ if (!ws || ws.readyState !== 1) return false;
17
+ ws.send(JSON.stringify(msg));
18
+ return true;
19
+ }
20
+
21
+ function modal() {
22
+ return document.getElementById(MODAL_ID);
23
+ }
24
+
25
+ function close() {
26
+ var m = modal();
27
+ if (m && m.parentNode) m.parentNode.removeChild(m);
28
+ }
29
+
30
+ /**
31
+ * Draw a grant list into list; exported for tests.
32
+ * @param {Element} list
33
+ * @param {{key: string, text: string, wholeTool: boolean}[]} grants
34
+ * @param {number} sessionId
35
+ * @param {function(object): boolean} sendMsg
36
+ */
37
+ export function renderGrantList(list, grants, sessionId, sendMsg) {
38
+ list.textContent = "";
39
+ var error = document.createElement("div");
40
+ error.className = "session-grants-error";
41
+ list.appendChild(error);
42
+ if (!grants.length) {
43
+ var empty = document.createElement("div");
44
+ empty.className = "session-grants-empty";
45
+ empty.textContent = "This session has no Allow for session grants. Every tool call that needs approval asks.";
46
+ list.appendChild(empty);
47
+ return;
48
+ }
49
+ grants.forEach(function (g) {
50
+ var row = document.createElement("div");
51
+ row.className = "session-grants-row" + (g.wholeTool ? " session-grants-whole" : "");
52
+ row.dataset.grantKey = g.key;
53
+ var text = document.createElement("span");
54
+ text.className = "session-grants-text";
55
+ text.textContent = g.text;
56
+ var revoke = document.createElement("button");
57
+ revoke.className = "session-grants-revoke";
58
+ revoke.textContent = "Revoke";
59
+ // Disabled only while the request is in flight. The row goes when the
60
+ // server's list arrives without the grant; a failed send or a server
61
+ // refusal re-enables the button so the revoke can be retried.
62
+ revoke.addEventListener("click", function () {
63
+ revoke.disabled = true;
64
+ error.textContent = "";
65
+ var sent = sendMsg({ type: "revoke_session_grant", sessionId: sessionId, key: g.key });
66
+ if (sent === false) {
67
+ revoke.disabled = false;
68
+ error.textContent = "Could not revoke: not connected. Try again.";
69
+ }
70
+ });
71
+ row.appendChild(text);
72
+ row.appendChild(revoke);
73
+ list.appendChild(row);
74
+ });
75
+ }
76
+
77
+ /** Open the grants list for a session. */
78
+ export function openSessionGrants(sessionId) {
79
+ close();
80
+ var m = document.createElement("div");
81
+ m.id = MODAL_ID;
82
+ m.dataset.sessionId = String(sessionId);
83
+ var backdrop = document.createElement("div");
84
+ backdrop.className = "confirm-backdrop";
85
+ backdrop.addEventListener("click", close);
86
+ var dialog = document.createElement("div");
87
+ dialog.className = "confirm-dialog session-grants-dialog";
88
+ var title = document.createElement("div");
89
+ title.className = "session-grants-title";
90
+ title.textContent = "Allow for session grants";
91
+ var list = document.createElement("div");
92
+ list.className = "session-grants-list";
93
+ list.textContent = "Loading...";
94
+ var done = document.createElement("button");
95
+ done.className = "confirm-btn confirm-cancel";
96
+ done.textContent = "Close";
97
+ done.addEventListener("click", close);
98
+ dialog.appendChild(title);
99
+ dialog.appendChild(list);
100
+ dialog.appendChild(done);
101
+ m.appendChild(backdrop);
102
+ m.appendChild(dialog);
103
+ document.body.appendChild(m);
104
+ send({ type: "list_session_grants", sessionId: sessionId });
105
+ }
106
+
107
+ /**
108
+ * A server refusal: keep the rows, show why, and let each Revoke be tried
109
+ * again. Exported for tests.
110
+ * @param {Element} list
111
+ * @param {string} message
112
+ */
113
+ export function showGrantError(list, message) {
114
+ var buttons = list.querySelectorAll(".session-grants-revoke");
115
+ for (var i = 0; i < buttons.length; i++) buttons[i].disabled = false;
116
+ var error = list.querySelector(".session-grants-error");
117
+ if (error) error.textContent = message;
118
+ }
119
+
120
+ /** The server's session_grants message: redraw the list if it is the one open. */
121
+ export function handleSessionGrants(msg) {
122
+ var m = modal();
123
+ if (!m || m.dataset.sessionId !== String(msg.sessionId)) return;
124
+ var list = m.querySelector(".session-grants-list");
125
+ if (!list) return;
126
+ if (typeof msg.error === "string" && msg.error) {
127
+ showGrantError(list, "Could not revoke: " + msg.error);
128
+ return;
129
+ }
130
+ renderGrantList(list, Array.isArray(msg.grants) ? msg.grants : [], msg.sessionId, send);
131
+ }
@@ -8,6 +8,7 @@ import { openSearch as openSessionSearch } from './session-search.js';
8
8
  import { store } from './store.js';
9
9
  import { capabilityGate } from './vendor-registry.js';
10
10
  import { getWs } from './ws-ref.js';
11
+ import { openSessionGrants } from './session-grants.js';
11
12
  import { getSessionListEl } from './dom-refs.js';
12
13
  import { dismissOverlayPanels, closeSidebar, updatePageTitle, spawnDustParticles } from './sidebar.js';
13
14
  import { showConfirm } from './app-misc.js';
@@ -677,6 +678,16 @@ function showSessionCtxMenu(anchorBtn, sessionId, title, cliSid, sessionData) {
677
678
  });
678
679
  menu.appendChild(renameItem);
679
680
 
681
+ var grantsItem = document.createElement("button");
682
+ grantsItem.className = "session-ctx-item";
683
+ grantsItem.innerHTML = iconHtml("shield") + " <span>Permission grants</span>";
684
+ grantsItem.addEventListener("click", function (e) {
685
+ e.stopPropagation();
686
+ closeSessionCtxMenu();
687
+ openSessionGrants(sessionId);
688
+ });
689
+ menu.appendChild(grantsItem);
690
+
680
691
  // Session visibility toggle (only the session owner can change)
681
692
  if (sessionData && sessionData.ownerId && sessionData.ownerId === store.get('myUserId')) {
682
693
  var currentVis = (sessionData && sessionData.sessionVisibility) || "shared";
@@ -2,7 +2,7 @@
2
2
  //
3
3
  // Settings hold two environment texts: shared (every project, administrators
4
4
  // only) and per project. Every agent-runtime start (a Claude query in process
5
- // or in a worker, a Codex app-server, title generation, a model-list warmup)
5
+ // or in a worker, a Codex app-server, a model-list warmup)
6
6
  // takes its environment from here: the runtime's own environment first, then
7
7
  // the shared text, then the project text.
8
8
  //
package/lib/sdk-bridge.js CHANGED
@@ -15,6 +15,7 @@ var { promptsFor } = require("./prompt-registry");
15
15
  var { toolApprovalKind } = require("./prompt-kinds");
16
16
  var sessionActivity = require("./session-activity");
17
17
  var sessionReclaim = require("./session-reclaim");
18
+ var { withPromptLabel } = require("./prompt-label");
18
19
  var { isAgentDispatchTool } = require("./agent-dispatch-tool");
19
20
  var { getNewWorkRefusal } = require("./new-work-gate");
20
21
  var runtimeEnv = require("./runtime-env");
@@ -23,6 +24,9 @@ var { registry: yokeRegistry } = require("./yoke");
23
24
  var sessionCapabilities = require("./session-capabilities");
24
25
  var { buildVendorRegistryMessage, recordInstallState } = require("./vendor-registry-message");
25
26
  var { authRequiredFacts } = require("./vendor-auth");
27
+ var { bumpLastActivity } = require("./activity-clock");
28
+ var { logField } = require("./log-field");
29
+ var { createAiTitleRefresher } = require("./session-ai-title");
26
30
 
27
31
  // --- lr-29f9: Global concurrent-session ceiling ---
28
32
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -625,6 +629,7 @@ function createSDKBridge(opts) {
625
629
  if (_idleReaperTimer) return;
626
630
  _idleReaperTimer = setInterval(function () {
627
631
  var now = Date.now();
632
+ var skippedForPrompt = [];
628
633
  sm.sessions.forEach(function (session) {
629
634
  if (session.destroying) return;
630
635
 
@@ -670,7 +675,12 @@ function createSDKBridge(opts) {
670
675
  // emits no stream events, so the activity clock cannot tell. Ending
671
676
  // it would abort the pending tool call and destroy the agent's work.
672
677
  // Memory pressure is handled by lib/memory-shed.js, not this timer.
673
- if (promptsFor(sm).pendingCount(session) > 0) return;
678
+ var openPrompts = promptsFor(sm).pendingCount(session);
679
+ if (openPrompts > 0) {
680
+ skippedForPrompt.push(logField(session.localId) + ":prompts=" + openPrompts
681
+ + ":idle=" + Math.round((now - (session.lastActivityAt || 0)) / 60000) + "min");
682
+ return;
683
+ }
674
684
 
675
685
  var lastActivity = session.lastActivityAt || 0;
676
686
  if (now - lastActivity > IDLE_TIMEOUT_MS) {
@@ -699,6 +709,13 @@ function createSDKBridge(opts) {
699
709
  }
700
710
  }
701
711
  });
712
+ // One line per sweep, so "a session with an open prompt is never reaped"
713
+ // can be read from the journal rather than inferred from its absence.
714
+ if (skippedForPrompt.length) {
715
+ console.log("[sdk-bridge] Idle reaper: skipped " + skippedForPrompt.length
716
+ + " session(s) with an open prompt: project=" + logField(slug)
717
+ + " sessions=" + skippedForPrompt.join(","));
718
+ }
702
719
  }, IDLE_CHECK_INTERVAL_MS);
703
720
  // Don't prevent process exit
704
721
  if (_idleReaperTimer.unref) _idleReaperTimer.unref();
@@ -717,82 +734,26 @@ function createSDKBridge(opts) {
717
734
  var mergeSkills = skills.mergeSkills;
718
735
 
719
736
  // --- Message processing (extracted to sdk-message-processor.js) ---
720
- // Auto-generate a session title via YOKE adapter.generateTitle().
721
- // Triggered by sdk-message-processor after AUTO_TITLE_TURN_THRESHOLD turns.
722
- //
723
- // lr-2ea2a7: this fires early (AUTO_TITLE_TURN_THRESHOLD=2 turns), so the
724
- // heap tail normally holds all 5 target user messages — scanning from
725
- // index 0 forward is a scan over the heap array (which starts at absolute
726
- // index session._historyBaseIndex, NOT 0, once any trim has happened).
727
- // If the session's heap has already been trimmed (_historyBaseIndex > 0
728
- // — a title-generation retry on a long-lived session, or an unusually
729
- // small HISTORY_INMEM_MAX override) and the heap scan alone doesn't find 5
730
- // user messages, fall back to a disk-backed full scan via
731
- // loadFullSessionHistory + retrimHistory rather than silently under-titling
732
- // with whatever partial set the trimmed heap happened to retain. The full
733
- // load is never left resident — retrimHistory() re-applies the cap
734
- // immediately after this function reads what it needs.
735
- function autoGenerateTitle(session) {
736
- var sessionAdapter = getAdapterForSession(session);
737
- if (typeof sessionAdapter.generateTitle !== "function") {
738
- console.log("[auto-title] adapter.generateTitle not available for vendor=" + sessionAdapter.vendor);
739
- return;
740
- }
741
- function collectUserMessages(history) {
742
- var out = [];
743
- for (var i = 0; i < history.length; i++) {
744
- var entry = history[i];
745
- if (entry.type === "user_message" && entry.text) {
746
- out.push(entry.text.substring(0, 200));
747
- if (out.length >= 5) break;
748
- }
749
- }
750
- return out;
751
- }
752
- var userMessages = collectUserMessages(session.history);
753
- if (userMessages.length < 5 && (session._historyBaseIndex || 0) > 0) {
754
- sm.loadFullSessionHistory(session);
755
- userMessages = collectUserMessages(session.history);
756
- sm.retrimHistory(session);
757
- }
758
- if (userMessages.length === 0) {
759
- console.log("[auto-title] No user messages found in session " + session.localId);
760
- return;
761
- }
762
- console.log("[auto-title] Calling adapter.generateTitle with " + userMessages.length + " messages for session " + session.localId);
763
-
764
- // lr-62157d: returns the promise chain (previously fire-and-forget) so
765
- // this is directly awaitable in tests via _test_autoGenerateTitle; the
766
- // real onAutoTitle callers (sdk-message-processor.js) call this
767
- // fire-and-forget already and are unaffected by a function now
768
- // returning a value they don't use.
769
- return sessionAdapter.generateTitle(userMessages, withRuntimeEnv({ cwd: cwd }, session)).then(function(title) {
770
- if (!title || title.length < 2) return;
771
- title = title.substring(0, 100);
772
- // lr-62157d: overwrite whenever the current title is provisional (the
773
- // raw first-message truncation from project-user-message.js, or no
774
- // title at all) and the user hasn't manually renamed the session.
775
- // Before titleProvisional existed, the first-message fallback looked
776
- // exactly like a real title, so this guard had nothing that let it
777
- // tell "already properly titled" apart from "still carrying the raw
778
- // 50-char truncation" — this is what actually lets a real LLM title
779
- // replace that truncation.
780
- if ((session.titleProvisional || !session.title) && !session.titleManuallySet) {
781
- session.title = title;
782
- session.titleAutoGenerated = true;
783
- session.titleProvisional = false;
784
- sm.saveSessionFile(session);
785
- sm.broadcastSessionList();
786
- if (session.cliSessionId && typeof adapter.renameSession === "function") {
787
- adapter.renameSession(session.cliSessionId, title, { dir: cwd }).catch(function () {});
788
- }
789
- console.log("[auto-title] Generated title for session " + session.localId + ": " + title);
790
- }
791
- }).catch(function(e) {
792
- console.error("[auto-title] Failed:", e.message || e);
793
- });
737
+ // The session title is the one the vendor CLI wrote into the session's
738
+ // transcript; no query is ever started to produce one (session-ai-title.js).
739
+ // The home is the session owner's on a shared multi-user daemon, null for the
740
+ // daemon's own.
741
+ function resolveOwnerHome(session) {
742
+ var ownerId = session && session.ownerId;
743
+ if (!ownerId) return null;
744
+ var owner = usersModule.findUserById(ownerId);
745
+ var ownerLinuxUser = owner && owner.linuxUser ? owner.linuxUser : null;
746
+ return resolveEffectiveHome(ownerLinuxUser);
794
747
  }
795
748
 
749
+ var refreshAiTitle = createAiTitleRefresher({
750
+ sm: sm,
751
+ cwd: cwd,
752
+ resolveHome: resolveOwnerHome,
753
+ getRuntimeEnvOverlay: getRuntimeEnvOverlay,
754
+ daemonHome: require("./config").REAL_HOME || require("os").homedir(),
755
+ });
756
+
796
757
  var msgProcessor = attachMessageProcessor({
797
758
  sm: sm,
798
759
  send: send,
@@ -803,7 +764,7 @@ function createSDKBridge(opts) {
803
764
  adapter: adapter,
804
765
  onProcessingChanged: onProcessingChanged,
805
766
  onTurnDone: onTurnDone,
806
- onAutoTitle: function (session) { autoGenerateTitle(session); },
767
+ refreshAiTitle: refreshAiTitle,
807
768
  onTeamCreate: opts.onTeamCreate || null,
808
769
  onTeamDelete: opts.onTeamDelete || null,
809
770
  opts: opts,
@@ -814,13 +775,7 @@ function createSDKBridge(opts) {
814
775
  // lr-3ccc78 — session-owner home resolution for skill/agent discovery on
815
776
  // a shared multi-user daemon. usersModule.findUserById(session.ownerId)
816
777
  // is the same pattern already used elsewhere in this file (getFreshAuthState).
817
- resolveSessionHome: function(session) {
818
- var ownerId = session && session.ownerId;
819
- if (!ownerId) return null;
820
- var owner = usersModule.findUserById(ownerId);
821
- var ownerLinuxUser = owner && owner.linuxUser ? owner.linuxUser : null;
822
- return resolveEffectiveHome(ownerLinuxUser);
823
- },
778
+ resolveSessionHome: resolveOwnerHome,
824
779
  });
825
780
  var processSDKMessage = msgProcessor.processSDKMessage;
826
781
  var sendAndRecord = msgProcessor.sendAndRecord;
@@ -842,7 +797,7 @@ function createSDKBridge(opts) {
842
797
  type: "elicitation",
843
798
  slug: slug,
844
799
  title: (request.serverName || "MCP Server") + " needs input",
845
- body: request.message || "Waiting for your response",
800
+ body: withPromptLabel(opened.label, request.message || "Waiting for your response"),
846
801
  tag: "claude-elicitation",
847
802
  };
848
803
  // Route to session owner only — body carries MCP message text.
@@ -1188,7 +1143,7 @@ function createSDKBridge(opts) {
1188
1143
  slug: slug,
1189
1144
  requestId: opened.requestId,
1190
1145
  title: agentPrefix + permissionPushTitle(toolName, input),
1191
- body: permissionPushBody(toolName, input),
1146
+ body: withPromptLabel(opened.label, permissionPushBody(toolName, input)),
1192
1147
  };
1193
1148
  // Route to session owner only — body carries tool name and input (may contain paths/code).
1194
1149
  if (session.ownerId && pushModule.sendPushToUser) {
@@ -1479,7 +1434,7 @@ function createSDKBridge(opts) {
1479
1434
  if (session._isCountedLive) {
1480
1435
  session._isCountedLive = false;
1481
1436
  _activeLiveCount = Math.max(0, _activeLiveCount - 1);
1482
- console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (session " + session.localId + " done)");
1437
+ console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (project " + slug + " session " + session.localId + " done)");
1483
1438
  }
1484
1439
  session.taskStopRequested = false;
1485
1440
  // lr-8355: A rewind (or any other replacement) may have already started
@@ -1775,7 +1730,9 @@ function createSDKBridge(opts) {
1775
1730
  }
1776
1731
  // Select adapter based on session vendor (fallback to default)
1777
1732
  var sessionAdapter = (session.vendor && adapters[session.vendor]) || adapter;
1778
- console.log("[sdk-bridge] startQuery: vendor=" + sessionAdapter.vendor + " session=" + session.localId + " text=" + (text || "").substring(0, 50));
1733
+ // Console session ids repeat across projects, so the line names the project.
1734
+ // The prompt text is not logged.
1735
+ console.log("[sdk-bridge] startQuery: project=" + slug + " vendor=" + sessionAdapter.vendor + " session=" + session.localId);
1779
1736
  // Remember linuxUser for auto-continue after rate limit
1780
1737
  session.lastLinuxUser = linuxUser || null;
1781
1738
 
@@ -1786,7 +1743,7 @@ function createSDKBridge(opts) {
1786
1743
  // Multi-turn pushes to an existing query are not new processes — don't gate them.
1787
1744
  var isNewQuery = !session.queryInstance;
1788
1745
  if (isNewQuery && _activeLiveCount >= MAX_CONCURRENT_SESSIONS) {
1789
- console.warn("[sdk-bridge] Concurrent session ceiling hit (" + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + ") — rejecting new query for session " + session.localId);
1746
+ console.warn("[sdk-bridge] Concurrent session ceiling hit (" + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + ") — rejecting new query for project " + slug + " session " + session.localId);
1790
1747
  session.isProcessing = false;
1791
1748
  onProcessingChanged();
1792
1749
  sendAndRecord(session, {
@@ -1803,7 +1760,7 @@ function createSDKBridge(opts) {
1803
1760
  // slot is claimed so a refusal never increments the live counter.
1804
1761
  var newWorkRefusal = isNewQuery ? getNewWorkRefusal() : null;
1805
1762
  if (newWorkRefusal) {
1806
- console.warn("[sdk-bridge] New-work gate closed — refusing new query for session " + session.localId);
1763
+ console.warn("[sdk-bridge] New-work gate closed — refusing new query for project " + slug + " session " + session.localId);
1807
1764
  session.isProcessing = false;
1808
1765
  onProcessingChanged();
1809
1766
  sendAndRecord(session, { type: "error", text: newWorkRefusal });
@@ -1819,7 +1776,7 @@ function createSDKBridge(opts) {
1819
1776
  var getConfig = opts.getConfig;
1820
1777
  var memThresholdMB = resolveMemAvailableThresholdMB(typeof getConfig === "function" ? getConfig() : null);
1821
1778
  if (memAvailMB !== null && memAvailMB < memThresholdMB) {
1822
- console.warn("[sdk-bridge] MemAvailable gate: " + memAvailMB + " MB available, " + memThresholdMB + " MB required — rejecting new query for session " + session.localId);
1779
+ console.warn("[sdk-bridge] MemAvailable gate: " + memAvailMB + " MB available, " + memThresholdMB + " MB required — rejecting new query for project " + slug + " session " + session.localId);
1823
1780
  session.isProcessing = false;
1824
1781
  onProcessingChanged();
1825
1782
  var memMsg = "Not enough memory to start a new query (" + memAvailMB + " MB available, " + memThresholdMB + " MB required). Wait for an active session to finish or close unused sessions.";
@@ -1927,13 +1884,13 @@ function createSDKBridge(opts) {
1927
1884
  if (session._isCountedLive) {
1928
1885
  session._isCountedLive = false;
1929
1886
  _activeLiveCount = Math.max(0, _activeLiveCount - 1);
1930
- console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (session " + session.localId + " slot released)");
1887
+ console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (project " + slug + " session " + session.localId + " slot released)");
1931
1888
  }
1932
1889
  }
1933
1890
  if (isNewQuery) {
1934
1891
  _activeLiveCount++;
1935
1892
  session._isCountedLive = true;
1936
- console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (session " + session.localId + " starting)");
1893
+ console.log("[sdk-bridge] Live query count: " + _activeLiveCount + "/" + MAX_CONCURRENT_SESSIONS + " (project " + slug + " session " + session.localId + " starting)");
1937
1894
  }
1938
1895
 
1939
1896
  // Guard the rest of startQuery so any unexpected synchronous throw releases
@@ -2250,7 +2207,7 @@ function createSDKBridge(opts) {
2250
2207
  // lr-b61b: Flush any messages that arrived between turns (after the previous
2251
2208
  // finally block nulled queryInstance and before this startQuery call).
2252
2209
  if (session.pendingMessages && session.pendingMessages.length > 0) {
2253
- console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for session " + session.localId);
2210
+ console.log("[sdk-bridge] startQuery: flushing " + session.pendingMessages.length + " buffered pending message(s) for project " + slug + " session " + session.localId);
2254
2211
  for (var pi = 0; pi < session.pendingMessages.length; pi++) {
2255
2212
  var pm = session.pendingMessages[pi];
2256
2213
  handle.pushMessage(pm.text, pm.images, pm.initiator);
@@ -2268,7 +2225,7 @@ function createSDKBridge(opts) {
2268
2225
  handle.endInput();
2269
2226
  }
2270
2227
 
2271
- session.lastActivityAt = Date.now();
2228
+ bumpLastActivity(session, "query-start", slug);
2272
2229
  session.streamPromise = processQueryStream(session).catch(function(err) {
2273
2230
  console.error("[sdk-bridge] Unhandled stream error for session " + session.localId + ":", err && err.message || err);
2274
2231
  sendToSession(session, { type: "error", text: "Stream error: " + (err && err.message || String(err)) });
@@ -2292,7 +2249,7 @@ function createSDKBridge(opts) {
2292
2249
  }
2293
2250
 
2294
2251
  function pushMessage(session, text, images, initiator) {
2295
- session.lastActivityAt = Date.now();
2252
+ bumpLastActivity(session, "push-message", slug);
2296
2253
  // Route through QueryHandle (works for both in-process and worker paths)
2297
2254
  if (session.queryInstance && typeof session.queryInstance.pushMessage === "function") {
2298
2255
  session.queryInstance.pushMessage(text, images, initiator);
@@ -2640,12 +2597,7 @@ function createSDKBridge(opts) {
2640
2597
  stopIdleReaper: stopIdleReaper,
2641
2598
  getRuntimeEnvOverlay: getRuntimeEnvOverlay,
2642
2599
  getMemoryStats: getMemoryStats,
2643
- // lr-62157d: exposed for direct unit testing of the provisional-title
2644
- // overwrite guard, following the _test_-prefixed exposure convention
2645
- // already used by lib/yoke/adapters/codex.js's resolveTitleModel. Not
2646
- // part of the bridge's real call surface (project.js never calls it by
2647
- // this name) — it is the same closure onAutoTitle wraps internally.
2648
- _test_autoGenerateTitle: autoGenerateTitle,
2600
+ refreshAiTitle: refreshAiTitle,
2649
2601
  };
2650
2602
  }
2651
2603
 
@@ -6,7 +6,9 @@ var sessionActivity = require("./session-activity");
6
6
  var yokeRegistry = require("./yoke").registry;
7
7
  var { authRequiredFacts } = require("./vendor-auth");
8
8
  var sessionReclaim = require("./session-reclaim");
9
+ var { withPromptLabel } = require("./prompt-label");
9
10
  var { isAgentDispatchTool } = require("./agent-dispatch-tool");
11
+ var { bumpLastActivity } = require("./activity-clock");
10
12
 
11
13
  // Source names of the activity tokens an agent with the activityTokens
12
14
  // trait holds for its own tool and thinking blocks.
@@ -31,7 +33,7 @@ function attachMessageProcessor(ctx) {
31
33
  var cwd = ctx.cwd;
32
34
  var onProcessingChanged = ctx.onProcessingChanged;
33
35
  var onTurnDone = ctx.onTurnDone;
34
- var onAutoTitle = ctx.onAutoTitle;
36
+ var refreshAiTitle = ctx.refreshAiTitle || null;
35
37
  var onTeamCreate = ctx.onTeamCreate || null;
36
38
  var onTeamDelete = ctx.onTeamDelete || null;
37
39
  var opts = ctx.opts;
@@ -45,8 +47,6 @@ function attachMessageProcessor(ctx) {
45
47
  // Allows callers (and tests) to inject a mock; falls back to the real implementation.
46
48
  var discoverWorkflowsFn = ctx.discoverWorkflows || discoverWorkflows;
47
49
 
48
- var AUTO_TITLE_TURN_THRESHOLD = 2;
49
-
50
50
  function sendAndRecord(session, obj) {
51
51
  sm.sendAndRecord(session, obj);
52
52
  }
@@ -198,7 +198,7 @@ function attachMessageProcessor(ctx) {
198
198
  // producing output; a dead/silent child stops bumping and the session
199
199
  // still times out and is reaped normally (no blanket "never reap if a
200
200
  // child is registered" rule — see startIdleReaper in sdk-bridge.js).
201
- session.lastActivityAt = Date.now();
201
+ bumpLastActivity(session, "subagent-stream", slug);
202
202
 
203
203
  if (parsed.messageRole === "assistant") {
204
204
  // Extract tool_use blocks from sub-agent assistant messages
@@ -501,7 +501,7 @@ function attachMessageProcessor(ctx) {
501
501
  type: "ask_user",
502
502
  slug: slug,
503
503
  title: "Claude has a question",
504
- body: q ? q.question : "Waiting for your response",
504
+ body: withPromptLabel(promptsFor(sm).labelFor(session, block.id), q ? q.question : "Waiting for your response"),
505
505
  tag: "claude-ask",
506
506
  };
507
507
  // Route to session owner only — content carries prompt text.
@@ -642,7 +642,7 @@ function attachMessageProcessor(ctx) {
642
642
  if (parsed.cost && parsed.cost > 0) {
643
643
  session.rateLimitResetsAt = null;
644
644
  }
645
- console.log("[sdk-bridge] result handler: session " + session.localId + " cost=" + parsed.cost + " rateLimitResetsAt=" + session.rateLimitResetsAt);
645
+ console.log("[sdk-bridge] result handler: project " + slug + " session " + session.localId + " cost=" + parsed.cost + " rateLimitResetsAt=" + session.rateLimitResetsAt);
646
646
 
647
647
  // Handle SDK execution errors: show the error to the user instead of
648
648
  // silently swallowing it. These have subtype "error_during_execution".
@@ -761,69 +761,16 @@ function attachMessageProcessor(ctx) {
761
761
  });
762
762
  }
763
763
  // Reset for next turn in the same query
764
- session.lastActivityAt = Date.now();
764
+ bumpLastActivity(session, "turn-result", slug);
765
765
  session.turnCount = (session.turnCount || 0) + 1;
766
766
  var donePreview = session.responsePreview || "";
767
767
  session.responsePreview = "";
768
768
  session.streamedText = false;
769
769
  sm.broadcastSessionList();
770
770
 
771
- // Auto-generate title after N turns (skip if loop or already auto-generated).
772
- // lr-62157d: '===' -> '>=' so a session that skips past the exact
773
- // threshold turn (early return, error path, non-result terminal event,
774
- // or a turnCount that was never persisted before this fix) still gets
775
- // titled on a later turn instead of being permanently disqualified.
776
- // Idempotence comes from !session.titleAutoGenerated, which is now
777
- // durable (see sessions.js buildMetaLine/loadSessions).
778
- if (session.turnCount >= AUTO_TITLE_TURN_THRESHOLD
779
- && !session.titleAutoGenerated
780
- && !session.titleManuallySet
781
- && !session.loop
782
- && onAutoTitle) {
783
- try { onAutoTitle(session); } catch (e) {
784
- console.error("[auto-title] onAutoTitle threw:", e.message || e);
785
- }
786
- } else {
787
- // lr-efdab6 (DRUMMER decision, comment #1): the taken branch above
788
- // already logs on every path (sdk-bridge.js [auto-title] sites) — but
789
- // logging existed on NOTHING that recorded the gate NOT firing, so
790
- // silence read identically for "ran fine and logged nothing notable",
791
- // "never invoked", and "invoked and died before the first log". That
792
- // ambiguity is exactly what let lr-62157d's dead auto-title feature
793
- // survive ~3 months / ~160 sessions undetected. This branch makes the
794
- // negative case unambiguous: every turn where the gate evaluates
795
- // false gets exactly one line naming why.
796
- //
797
- // already_auto_generated is the expected steady-state reason for the
798
- // overwhelming majority of turns in a mature session (fires every
799
- // turn after the session's title is set) and is logged at a lower
800
- // level (console.debug) so a normal journald view isn't dominated by
801
- // it; every other reason is diagnostic of a gate that should be
802
- // firing but isn't, and stays at console.log so it is visible by
803
- // default. Nothing here transmits session content — only flags/counts.
804
- var _autoTitleReason;
805
- if (!onAutoTitle) {
806
- _autoTitleReason = "no_callback";
807
- } else if (session.loop) {
808
- _autoTitleReason = "loop_running";
809
- } else if (session.titleManuallySet) {
810
- _autoTitleReason = "manually_set";
811
- } else if (session.titleAutoGenerated) {
812
- _autoTitleReason = "already_auto_generated";
813
- } else if (session.turnCount < AUTO_TITLE_TURN_THRESHOLD) {
814
- _autoTitleReason = "turn_threshold_not_met";
815
- } else {
816
- _autoTitleReason = "unknown";
817
- }
818
- var _autoTitleLogFn = (_autoTitleReason === "already_auto_generated") ? console.debug : console.log;
819
- _autoTitleLogFn(
820
- "[auto-title] gate did not fire: reason=" + _autoTitleReason
821
- + " turnCount=" + session.turnCount
822
- + " titleAutoGenerated=" + !!session.titleAutoGenerated
823
- + " titleManuallySet=" + !!session.titleManuallySet
824
- + " loop=" + !!session.loop
825
- );
826
- }
771
+ // The CLI may have written a newer title into the transcript during
772
+ // this turn; every turn picks up the latest. Never rejects.
773
+ if (refreshAiTitle) refreshAiTitle(session);
827
774
 
828
775
  if (onTurnDone) {
829
776
  try { onTurnDone(session, donePreview); } catch (e) {}
@@ -858,7 +805,7 @@ function attachMessageProcessor(ctx) {
858
805
  // matching comment on processSubagentMessage's bump above and on
859
806
  // startIdleReaper in sdk-bridge.js for why this keeps a WAITING
860
807
  // parent session non-idle for as long as its child keeps reporting in.
861
- session.lastActivityAt = Date.now();
808
+ bumpLastActivity(session, "task_started", slug);
862
809
  if (!session.taskIdMap) session.taskIdMap = {};
863
810
  session.taskIdMap[parentId] = parsed.taskId;
864
811
  sendAndRecord(session, {
@@ -872,7 +819,7 @@ function attachMessageProcessor(ctx) {
872
819
  } else if (parsed.yokeType === "task_progress") {
873
820
  var parentId = parsed.parentToolId;
874
821
  if (parentId) {
875
- session.lastActivityAt = Date.now(); // lr-f36626 — see task_started above
822
+ bumpLastActivity(session, "task_progress", slug); // see task_started above
876
823
  sendAndRecord(session, {
877
824
  type: "task_progress",
878
825
  parentToolId: parentId,
@@ -895,7 +842,7 @@ function attachMessageProcessor(ctx) {
895
842
  }
896
843
  }
897
844
  if (parentId) {
898
- session.lastActivityAt = Date.now(); // lr-f36626 — see task_started above
845
+ bumpLastActivity(session, "task_updated", slug); // see task_started above
899
846
  sendAndRecord(session, {
900
847
  type: "task_updated",
901
848
  parentToolId: parentId,
@@ -908,7 +855,7 @@ function attachMessageProcessor(ctx) {
908
855
  // Sub-agent tool_progress: forward as activity update
909
856
  var parentId = parsed.parentToolId;
910
857
  if (parentId) {
911
- session.lastActivityAt = Date.now(); // lr-f36626 — see task_started above
858
+ bumpLastActivity(session, "tool_progress", slug); // see task_started above
912
859
  sendAndRecord(session, {
913
860
  type: "subagent_activity",
914
861
  parentToolId: parentId,