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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -0
  2. package/bin/cli.js +2 -1
  3. package/lib/build-changes.js +8 -2
  4. package/lib/build-sha.json +2 -2
  5. package/lib/build-update-offer.js +31 -7
  6. package/lib/claude-settings-env.js +142 -0
  7. package/lib/cli/duration.js +27 -0
  8. package/lib/cli/schedule-input-subcommands.js +1 -22
  9. package/lib/cli/session-subcommands.js +38 -7
  10. package/lib/daemon.js +6 -0
  11. package/lib/notification-prefs.js +2 -0
  12. package/lib/notify/core.js +175 -0
  13. package/lib/notify/index.js +31 -0
  14. package/lib/notify/live-prompts.js +36 -0
  15. package/lib/notify/payload.js +63 -0
  16. package/lib/notify/target.js +5 -0
  17. package/lib/notify/type-registry.js +64 -0
  18. package/lib/notify/types.js +20 -0
  19. package/lib/open-sockets.js +27 -0
  20. package/lib/outbound-access.js +74 -0
  21. package/lib/outbound-entry.js +109 -0
  22. package/lib/outbound-ledger.js +306 -0
  23. package/lib/outbound-query.js +153 -0
  24. package/lib/pending-prompts.js +31 -16
  25. package/lib/project-connection.js +40 -1
  26. package/lib/project-filesystem.js +20 -5
  27. package/lib/project-http.js +9 -1
  28. package/lib/project-loop.js +22 -7
  29. package/lib/project-notifications.js +54 -32
  30. package/lib/project-prompt-responses.js +1 -1
  31. package/lib/project-sessions.js +2 -1
  32. package/lib/project.js +15 -1
  33. package/lib/prompt-registry.js +74 -24
  34. package/lib/prompt-reminders.js +38 -33
  35. package/lib/prompt-source.js +43 -8
  36. package/lib/public/app.js +1 -0
  37. package/lib/public/css/diagnostics.css +28 -0
  38. package/lib/public/css/home-hub.css +12 -0
  39. package/lib/public/css/icon-strip.css +9 -0
  40. package/lib/public/css/mobile-nav.css +11 -0
  41. package/lib/public/css/sidebar.css +7 -0
  42. package/lib/public/index.html +3 -0
  43. package/lib/public/modules/activity-state.js +20 -4
  44. package/lib/public/modules/app-connection.js +22 -5
  45. package/lib/public/modules/app-notifications.js +47 -48
  46. package/lib/public/modules/app-projects.js +3 -1
  47. package/lib/public/modules/app-rendering.js +10 -0
  48. package/lib/public/modules/build-update-sessions.js +81 -0
  49. package/lib/public/modules/diagnostics.js +9 -2
  50. package/lib/public/modules/env-shadow-notice.js +34 -0
  51. package/lib/public/modules/notify-client.js +153 -0
  52. package/lib/public/modules/project-settings.js +5 -0
  53. package/lib/public/modules/prompt-state.js +3 -3
  54. package/lib/public/modules/prompts.js +1 -1
  55. package/lib/public/modules/server-settings.js +3 -0
  56. package/lib/public/modules/terminal-links.js +175 -0
  57. package/lib/public/modules/terminal.js +19 -103
  58. package/lib/public/notify-sw-logic.js +300 -0
  59. package/lib/public/notify-target.js +97 -0
  60. package/lib/public/sw.js +15 -68
  61. package/lib/push.js +63 -19
  62. package/lib/runtime-env.js +1 -0
  63. package/lib/sdk-bridge.js +62 -30
  64. package/lib/sdk-message-processor.js +78 -37
  65. package/lib/server.js +34 -2
  66. package/lib/session-directory.js +6 -4
  67. package/lib/session-input-ipc.js +11 -1
  68. package/lib/session-input.js +89 -14
  69. package/lib/session-liveness.js +53 -0
  70. package/lib/session-reclaim.js +37 -2
  71. package/lib/sessions.js +31 -4
  72. package/lib/usage-store.js +29 -7
  73. package/lib/vendor-auth.js +33 -2
  74. package/lib/ws-schema.js +6 -1
  75. package/lib/yoke/adapters/claude-vendor.js +11 -1
  76. package/lib/yoke/adapters/claude.js +7 -0
  77. package/lib/yoke/auth-checks.js +17 -2
  78. package/lib/yoke/index.js +21 -3
  79. package/lib/yoke/provider-credentials.js +24 -0
  80. package/lib/yoke/registry.js +8 -1
  81. package/package.json +2 -2
  82. package/scripts/check-test-count.js +14 -0
@@ -0,0 +1,97 @@
1
+ // The notification target model, shared by the server notification core
2
+ // (lib/notify/), the service worker (importScripts) and the page's ES modules
3
+ // (side-effect import, then read from globalThis). A classic script with no
4
+ // import/export so all three can load it.
5
+ //
6
+ // A target names where a notification's action lives: the project (slug), the
7
+ // console session (sessionId) and, where there is one, the prompt (requestId).
8
+ // Session ids restart in every project, so a target without its slug is
9
+ // ambiguous: the slug is always part of its identity.
10
+ (function (root, factory) {
11
+ var api = factory();
12
+ // Always published on the global too: a module-graph import in a CommonJS
13
+ // host (the tests) evaluates this file as CJS and reads it from there.
14
+ root.NotifyTarget = api;
15
+ if (typeof module === "object" && module.exports) module.exports = api;
16
+ })(typeof self !== "undefined" ? self : globalThis, function () {
17
+ var SLUG_RE = /^[a-z0-9_-]+$/;
18
+
19
+ // An id is a string or a number; anything else (an object from a hostile or
20
+ // broken message) names nothing, and is never coerced to text.
21
+ function present(v) {
22
+ return (typeof v === "string" && v !== "") || typeof v === "number";
23
+ }
24
+
25
+ /**
26
+ * @param {{slug: ?string, sessionId: ?(number|string), requestId: ?string}} t
27
+ * @returns {{slug: ?string, sessionId: ?string, requestId: ?string}|null}
28
+ * a normalised target, or null when the input names no valid target. An id
29
+ * is carried as a string; a slug that is not a plain project slug is
30
+ * refused, since it ends up in a URL path.
31
+ */
32
+ function makeTarget(t) {
33
+ if (!t || typeof t !== "object") return null;
34
+ var slug = present(t.slug) ? String(t.slug) : null;
35
+ if (slug !== null && !SLUG_RE.test(slug)) return null;
36
+ return {
37
+ slug: slug,
38
+ sessionId: present(t.sessionId) ? String(t.sessionId) : null,
39
+ requestId: present(t.requestId) ? String(t.requestId) : null,
40
+ };
41
+ }
42
+
43
+ /** The one identity behind collapse, close and route: slug:sessionId[:requestId]. */
44
+ function targetKey(t) {
45
+ var n = makeTarget(t);
46
+ if (!n) return "";
47
+ var key = (n.slug || "") + ":" + (n.sessionId || "");
48
+ return n.requestId ? key + ":" + n.requestId : key;
49
+ }
50
+
51
+ /** The session-level identity (no request): slug:sessionId. */
52
+ function sessionKey(t) {
53
+ var n = makeTarget(t);
54
+ return n ? (n.slug || "") + ":" + (n.sessionId || "") : "";
55
+ }
56
+
57
+ /**
58
+ * The deep link that opens a target: <base>p/<slug>/?session=<id>[&request=<id>].
59
+ * A target with no slug (a system notice) opens the base page.
60
+ * @param {object} target
61
+ * @param {string} [base] the app root with a trailing slash; "/" by default.
62
+ */
63
+ function urlForTarget(target, base) {
64
+ var n = makeTarget(target);
65
+ var root = base || "/";
66
+ if (root.charAt(root.length - 1) !== "/") root += "/";
67
+ if (!n || !n.slug) return root;
68
+ var url = root + "p/" + n.slug + "/";
69
+ var q = [];
70
+ if (n.sessionId) q.push("session=" + encodeURIComponent(n.sessionId));
71
+ if (n.requestId) q.push("request=" + encodeURIComponent(n.requestId));
72
+ return q.length ? url + "?" + q.join("&") : url;
73
+ }
74
+
75
+ /**
76
+ * Reads a deep link's query. The slug comes from the path the page was
77
+ * served on, so only the session and the request are in the query.
78
+ * @param {string} search location.search
79
+ * @returns {{sessionId: string, requestId: ?string}|null}
80
+ */
81
+ function parseDeepLink(search) {
82
+ if (typeof search !== "string" || !search) return null;
83
+ var params = new URLSearchParams(search);
84
+ var session = params.get("session");
85
+ if (!session || !/^[0-9]+$/.test(session)) return null;
86
+ var request = params.get("request");
87
+ return { sessionId: session, requestId: request || null };
88
+ }
89
+
90
+ return {
91
+ makeTarget: makeTarget,
92
+ targetKey: targetKey,
93
+ sessionKey: sessionKey,
94
+ urlForTarget: urlForTarget,
95
+ parseDeepLink: parseDeepLink,
96
+ };
97
+ });
package/lib/public/sw.js CHANGED
@@ -115,81 +115,28 @@ self.addEventListener("fetch", function (event) {
115
115
 
116
116
  // --- Push notifications ---
117
117
 
118
+ // The show, close and tap logic lives in notify-sw-logic.js so it can be tested
119
+ // without a browser; this file only wires it to the worker's events.
120
+ importScripts("/notify-target.js", "/notify-sw-logic.js");
121
+
122
+ function notifyEnv() {
123
+ return {
124
+ registration: self.registration,
125
+ clients: self.clients,
126
+ userAgent: self.navigator ? self.navigator.userAgent : "",
127
+ scope: self.registration.scope || "/",
128
+ };
129
+ }
130
+
118
131
  self.addEventListener("push", function (event) {
119
132
  var data = {};
120
133
  try { data = event.data.json(); } catch (e) { return; }
121
-
122
- // Silent validation push, do not show notification
123
- if (data.type === "test") return;
124
-
125
- var options = {
126
- body: data.body || "",
127
- tag: data.tag || "clagentic",
128
- data: data,
129
- };
130
-
131
- if (data.type === "permission_request") {
132
- options.requireInteraction = true;
133
- options.tag = "perm-" + data.requestId;
134
- } else if (data.type === "permission_reminder") {
135
- // One reminder per session: the tag makes a new one replace the last, and
136
- // renotify makes the replacement alert again.
137
- options.requireInteraction = true;
138
- options.tag = data.tag || "prompt-reminder";
139
- options.renotify = true;
140
- } else if (data.type === "done") {
141
- options.tag = data.tag || "claude-done";
142
- } else if (data.type === "ask_user") {
143
- options.requireInteraction = true;
144
- options.tag = "claude-ask";
145
- } else if (data.type === "error") {
146
- options.requireInteraction = true;
147
- options.tag = "claude-error";
148
- } else if (data.type === "dm") {
149
- options.tag = data.tag || "dm";
150
- }
151
-
152
- event.waitUntil(
153
- self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clientList) {
154
- // Always show permission requests, questions, and errors
155
- // Only suppress "done" notifications when app is in foreground
156
- if (data.type !== "permission_request" && data.type !== "permission_reminder" && data.type !== "ask_user" && data.type !== "error") {
157
- for (var i = 0; i < clientList.length; i++) {
158
- if (clientList[i].focused || clientList[i].visibilityState === "visible") return;
159
- }
160
- }
161
- return self.registration.showNotification(data.title || "Clagentic: Console", options);
162
- }).catch(function () {})
163
- );
134
+ event.waitUntil(NotifySw.handlePush(notifyEnv(), data).catch(function () {}));
164
135
  });
165
136
 
166
137
  // --- Notification click ---
167
138
 
168
139
  self.addEventListener("notificationclick", function (event) {
169
- var data = event.notification.data || {};
170
140
  event.notification.close();
171
-
172
- // Build target URL from slug so we open the correct project
173
- var baseUrl = self.registration.scope || "/";
174
- var targetUrl = data.slug ? baseUrl + "p/" + data.slug + "/" : baseUrl;
175
-
176
- event.waitUntil(
177
- self.clients.matchAll({ type: "window", includeUncontrolled: true }).then(function (clientList) {
178
- // Prefer a client already on the correct project
179
- for (var i = 0; i < clientList.length; i++) {
180
- if (clientList[i].url.indexOf(targetUrl) !== -1) {
181
- return clientList[i].focus();
182
- }
183
- }
184
- // Fall back to any visible client
185
- for (var i = 0; i < clientList.length; i++) {
186
- if (clientList[i].visibilityState !== "hidden") {
187
- return clientList[i].focus();
188
- }
189
- }
190
- if (clientList.length > 0) return clientList[0].focus();
191
- return self.clients.openWindow(targetUrl);
192
- })
193
- );
141
+ event.waitUntil(NotifySw.handleClick(notifyEnv(), event.notification));
194
142
  });
195
-
package/lib/push.js CHANGED
@@ -4,6 +4,17 @@ var path = require("path");
4
4
  var config = require("./config");
5
5
  var store = require("./store");
6
6
  var { categoryOfPush } = require("./notification-prefs");
7
+ var usersModule = require("./users");
8
+
9
+ // The daemon's mode; a mode that cannot be read counts as multi-user, the
10
+ // stricter one (same rule as lib/push-audience.js).
11
+ function multiUserMode(isMultiUser) {
12
+ try {
13
+ return isMultiUser() !== false;
14
+ } catch (e) {
15
+ return true;
16
+ }
17
+ }
7
18
 
8
19
  function loadOrCreateVapidKeys() {
9
20
  var dir = config.CONFIG_DIR;
@@ -31,9 +42,13 @@ function loadOrCreateVapidKeys() {
31
42
  * user has muted is not sent to that user's subscriptions; this is the one
32
43
  * place push is filtered, so a muted type never reaches the phone whichever
33
44
  * caller raised it.
45
+ * @param {function(): boolean} [opts.isMultiUser] the daemon's mode; defaults to
46
+ * the users store. In multi-user mode a subscription with no user is neither
47
+ * stored nor sent to: nobody can say whose device it is.
34
48
  */
35
49
  function initPush(opts) {
36
50
  var prefs = opts && opts.prefs ? opts.prefs : null;
51
+ var isMultiUser = opts && opts.isMultiUser ? opts.isMultiUser : usersModule.isMultiUser;
37
52
 
38
53
  var keys = loadOrCreateVapidKeys();
39
54
 
@@ -89,8 +104,16 @@ function initPush(opts) {
89
104
  })(startupEndpoints[si]);
90
105
  }
91
106
 
107
+ /**
108
+ * @returns {boolean} false when the subscription was refused: it has no
109
+ * endpoint, or it has no user in multi-user mode.
110
+ */
92
111
  function addSubscription(sub, replaceEndpoint, userId) {
93
- if (!sub || !sub.endpoint) return;
112
+ if (!sub || !sub.endpoint) return false;
113
+ if (!userId && multiUserMode(isMultiUser)) {
114
+ console.log("[push] refused anonymous subscription in multi-user mode");
115
+ return false;
116
+ }
94
117
  // Remove previous subscription from the same client if endpoint changed.
95
118
  // Only delete replaceEndpoint if it belongs to the same caller — prevents an
96
119
  // unauthenticated request from unsubscribing arbitrary known endpoints.
@@ -106,8 +129,14 @@ function initPush(opts) {
106
129
  subscriptions.delete(replaceEndpoint);
107
130
  }
108
131
  }
109
- // Attach userId for per-user targeting (backward-compatible: old subs without userId still work for broadcast)
110
- if (userId) sub._userId = userId;
132
+ // Attach userId for per-user targeting. An authenticated re-register of an
133
+ // endpoint stored without a user claims it, so a device subscribed before
134
+ // the user was recorded recovers when its client re-sends the subscription.
135
+ if (userId) {
136
+ var stored = subscriptions.get(sub.endpoint);
137
+ if (stored && !stored._userId) console.log("[push] claimed anonymous subscription user=" + userId);
138
+ sub._userId = userId;
139
+ }
111
140
  // Store immediately, then validate async. Invalid subs get cleaned on first sendPush.
112
141
  subscriptions.set(sub.endpoint, sub);
113
142
  save();
@@ -137,36 +166,50 @@ function initPush(opts) {
137
166
  return allowed;
138
167
  }
139
168
 
169
+ // Sends still on the wire, so a shutdown can wait for them (flush).
170
+ var inflight = new Set();
171
+
172
+ function sendTo(sub, endpoint, json) {
173
+ var sent = webpush.sendNotification(sub, json, { vapidDetails: vapidDetails })
174
+ .then(function () {})
175
+ .catch(function (err) {
176
+ if (err.statusCode === 410 || err.statusCode === 404 || err.statusCode === 403) {
177
+ subscriptions.delete(endpoint);
178
+ save();
179
+ }
180
+ })
181
+ .then(function () { inflight.delete(sent); });
182
+ inflight.add(sent);
183
+ }
184
+
185
+ /** Resolves once every push sent so far has been handed to the push service. */
186
+ function flush() {
187
+ return Promise.all(Array.from(inflight));
188
+ }
189
+
140
190
  function sendPush(payload) {
141
191
  var json = JSON.stringify(payload);
192
+ var multi = multiUserMode(isMultiUser);
142
193
  subscriptions.forEach(function (sub, endpoint) {
194
+ // A subscription stored before users were recorded has no owner; in
195
+ // multi-user mode a broadcast must not reach a device nobody can name.
196
+ if (multi && !sub._userId) return;
143
197
  if (!wanted(sub, payload)) return;
144
- webpush.sendNotification(sub, json, { vapidDetails: vapidDetails })
145
- .then(function () {})
146
- .catch(function (err) {
147
- if (err.statusCode === 410 || err.statusCode === 404 || err.statusCode === 403) {
148
- subscriptions.delete(endpoint);
149
- save();
150
- }
151
- });
198
+ sendTo(sub, endpoint, json);
152
199
  });
153
200
  }
154
201
 
155
202
  function sendPushToUser(userId, payload) {
156
203
  if (!userId) return;
157
204
  var json = JSON.stringify(payload);
205
+ var matched = 0;
158
206
  subscriptions.forEach(function (sub, endpoint) {
159
207
  if (sub._userId !== userId) return;
208
+ matched++;
160
209
  if (!wanted(sub, payload)) return;
161
- webpush.sendNotification(sub, json, { vapidDetails: vapidDetails })
162
- .then(function () {})
163
- .catch(function (err) {
164
- if (err.statusCode === 410 || err.statusCode === 404 || err.statusCode === 403) {
165
- subscriptions.delete(endpoint);
166
- save();
167
- }
168
- });
210
+ sendTo(sub, endpoint, json);
169
211
  });
212
+ if (!matched) console.log("[push] no-subscription user=" + userId + " type=" + payload.type);
170
213
  }
171
214
 
172
215
  return {
@@ -175,6 +218,7 @@ function initPush(opts) {
175
218
  removeSubscription: removeSubscription,
176
219
  sendPush: sendPush,
177
220
  sendPushToUser: sendPushToUser,
221
+ flush: flush,
178
222
  };
179
223
  }
180
224
 
@@ -231,6 +231,7 @@ function envSignature(overlay) {
231
231
  }
232
232
 
233
233
  module.exports = {
234
+ scanEnvText: scanEnvText,
234
235
  validateEnvText: validateEnvText,
235
236
  buildRuntimeEnvOverlay: buildRuntimeEnvOverlay,
236
237
  composeRuntimeEnv: composeRuntimeEnv,
package/lib/sdk-bridge.js CHANGED
@@ -3,7 +3,8 @@ var path = require("path");
3
3
  var execSync = require("child_process").execSync;
4
4
  var execFileSync = require("child_process").execFileSync;
5
5
  var usersModule = require("./users");
6
- var { pushForSession } = require("./push-audience");
6
+ var openSockets = require("./open-sockets");
7
+ var { notifyFor } = require("./notify");
7
8
  var { getCodexConfig } = require("./codex-defaults");
8
9
  var { isAutoApprovableSegment } = require("./bash-auto-approve");
9
10
  var { splitShellSegments, hasUnapprovableShellSyntax, attachSkillDiscovery, discoverSkillsWithMeta, mergeSkillsWithMeta } = require("./sdk-skill-discovery");
@@ -27,7 +28,7 @@ var mcpToolSchema = require("./mcp-tool-schema");
27
28
  var { registry: yokeRegistry } = require("./yoke");
28
29
  var sessionCapabilities = require("./session-capabilities");
29
30
  var { buildVendorRegistryMessage, recordInstallState } = require("./vendor-registry-message");
30
- var { authRequiredFacts } = require("./vendor-auth");
31
+ var { authRequiredFacts, providerAuthFailure } = require("./vendor-auth");
31
32
  var { bumpLastActivity } = require("./activity-clock");
32
33
  var { logField } = require("./log-field");
33
34
  var { debugLog } = require("./debug-log");
@@ -169,6 +170,7 @@ function buildActivityDiagnosticsResponse() {
169
170
  activeLiveCount: getActiveLiveCount(),
170
171
  activityDivergenceCount: divergence.count,
171
172
  activityDivergenceRecentSamples: divergence.recentSamples,
173
+ openSockets: openSockets.snapshot(),
172
174
  };
173
175
  }
174
176
 
@@ -525,18 +527,37 @@ function createSDKBridge(opts) {
525
527
  var _cachedFreshAuthState = null;
526
528
  var _cachedFreshAuthAt = 0;
527
529
 
528
- function getFreshAuthState(force) {
530
+ var _cachedFreshAuthSig = null;
531
+
532
+ // The auth probes read the environment the session's runtime starts with
533
+ // (Settings over the daemon's), so a provider chosen in Settings counts.
534
+ function getFreshAuthState(force, session) {
529
535
  var yoke = require("./yoke");
530
536
  var now = Date.now();
531
- if (!force && _cachedFreshAuthState && now - _cachedFreshAuthAt < 15000) {
537
+ var overlay = getRuntimeEnvOverlay(session);
538
+ var sig = runtimeEnv.envSignature(overlay) + "\0" + (osUsersMode ? "os" : "");
539
+ if (!force && _cachedFreshAuthState && _cachedFreshAuthSig === sig && now - _cachedFreshAuthAt < 15000) {
532
540
  return _cachedFreshAuthState;
533
541
  }
534
542
  if (force) yoke.invalidateAuthCache();
535
- _cachedFreshAuthState = yoke.checkAuth();
543
+ _cachedFreshAuthState = yoke.checkAuth(overlay, osUsersMode);
544
+ _cachedFreshAuthSig = sig;
536
545
  _cachedFreshAuthAt = now;
537
546
  return _cachedFreshAuthState;
538
547
  }
539
548
 
549
+ // The environment a session's runtime is started with: the daemon's own,
550
+ // then the Settings variables. The same composition the spawn performs.
551
+ function getEffectiveRuntimeEnv(session) {
552
+ return runtimeEnv.composeRuntimeEnv(process.env, getRuntimeEnvOverlay(session));
553
+ }
554
+
555
+ // The message that replaces "not logged in" when the session's agent talks
556
+ // to a configured cloud provider, or null.
557
+ function providerFailureFor(session, vendorId) {
558
+ return providerAuthFailure(vendorId, getEffectiveRuntimeEnv(session), osUsersMode);
559
+ }
560
+
540
561
  function isAuthErrorMessage(errDetail) {
541
562
  if (!errDetail) return false;
542
563
  var errLower = String(errDetail).toLowerCase();
@@ -744,7 +765,10 @@ function createSDKBridge(opts) {
744
765
 
745
766
  // Skip sessions that are actively processing, have no query,
746
767
  // or are single-turn (Ralph Loop — managed by onQueryComplete).
747
- if (session.isProcessing) return;
768
+ // A session busy only through background agents is waiting on them,
769
+ // not running a turn: it stays reapable, so a silent agent is named
770
+ // in the reclaim notice instead of pinning the session forever.
771
+ if (session.isProcessing && !sessionReclaim.onlyBackgroundAgentsActive(session)) return;
748
772
  if (!session.queryInstance) return;
749
773
  if (session.singleTurn) return;
750
774
 
@@ -869,6 +893,7 @@ function createSDKBridge(opts) {
869
893
  // a shared multi-user daemon. usersModule.findUserById(session.ownerId)
870
894
  // is the same pattern already used elsewhere in this file (getFreshAuthState).
871
895
  resolveSessionHome: resolveOwnerHome,
896
+ providerFailureFor: providerFailureFor,
872
897
  });
873
898
  var processSDKMessage = msgProcessor.processSDKMessage;
874
899
  var sendAndRecord = msgProcessor.sendAndRecord;
@@ -886,15 +911,15 @@ function createSDKBridge(opts) {
886
911
 
887
912
  // No push for a prompt that ended at once (its signal was already aborted).
888
913
  if (pushModule && opened.pending) {
889
- var _elicitPayload = {
890
- type: "elicitation",
914
+ // Body carries MCP message text: owner only, never a blind broadcast.
915
+ notifyFor(pushModule).notify("elicitation", {
891
916
  slug: slug,
917
+ sessionId: session.localId,
918
+ requestId: opened.requestId,
919
+ }, {
892
920
  title: (request.serverName || "MCP Server") + " needs input",
893
921
  body: withPromptLabel(opened.label, request.message || "Waiting for your response"),
894
- tag: "claude-elicitation",
895
- };
896
- // Body carries MCP message text: owner only, never a blind broadcast.
897
- pushForSession(pushModule, session.ownerId, _elicitPayload);
922
+ }, { ownerId: session.ownerId });
898
923
  }
899
924
 
900
925
  return opened.answer;
@@ -1183,28 +1208,16 @@ function createSDKBridge(opts) {
1183
1208
  notification: {
1184
1209
  title: agentPrefix + permissionPushTitle(toolName, input),
1185
1210
  body: permissionPushBody(toolName, input),
1211
+ // Body carries tool name and input (may contain paths/code); the core
1212
+ // sends it to the session's owner only, never as a blind broadcast.
1213
+ push: { title: agentPrefix + permissionPushTitle(toolName, input), body: permissionPushBody(toolName, input) },
1186
1214
  slug: slug,
1187
1215
  sessionId: session.localId,
1188
- ownerId: session.ownerId || null,
1189
1216
  toolName: toolName,
1190
1217
  toolInput: input,
1191
1218
  },
1192
1219
  });
1193
1220
 
1194
- // No push for a prompt that ended at once (its signal was already aborted).
1195
- if (pushModule && opened.pending) {
1196
- var _permPayload = {
1197
- type: "permission_request",
1198
- slug: slug,
1199
- requestId: opened.requestId,
1200
- title: agentPrefix + permissionPushTitle(toolName, input),
1201
- body: withPromptLabel(opened.label, permissionPushBody(toolName, input)),
1202
- };
1203
- // Body carries tool name and input (may contain paths/code): owner only,
1204
- // never a blind broadcast.
1205
- pushForSession(pushModule, session.ownerId, _permPayload);
1206
- }
1207
-
1208
1221
  return opened.answer;
1209
1222
  }
1210
1223
 
@@ -1397,13 +1410,19 @@ function createSDKBridge(opts) {
1397
1410
  || errLower.indexOf("context_length") !== -1
1398
1411
  || errLower.indexOf("maximum context length") !== -1;
1399
1412
  var isAuthError = isAuthErrorMessage(errDetail);
1413
+ var providerFail = null;
1400
1414
  if (isContextOverflow) {
1401
1415
  sendAndRecord(session, {
1402
1416
  type: "context_overflow",
1403
1417
  text: "Conversation too long to continue.",
1404
1418
  });
1419
+ } else if (isAuthError && (providerFail = providerFailureFor(session, sessionVendorId(session)))) {
1420
+ sendAndRecord(session, { type: "error", text: providerFail.message });
1421
+ sendAndRecord(session, { type: "done", code: 1 });
1422
+ sm.broadcastSessionList();
1423
+ return;
1405
1424
  } else if (isAuthError) {
1406
- var freshAuth = getFreshAuthState();
1425
+ var freshAuth = getFreshAuthState(false, session);
1407
1426
  logAuthDecision("catch-auth-error", session, errDetail, freshAuth);
1408
1427
  if (freshAuth[session.vendor]) {
1409
1428
  sendAndRecord(session, {
@@ -1527,6 +1546,10 @@ function createSDKBridge(opts) {
1527
1546
  promptsFor(sm).endQuery(session, myQueryInstance, ownsSession);
1528
1547
  if (ownsSession) {
1529
1548
  msgProcessor.retainTaskIdMap(session);
1549
+ // The query's end took its background agents down; only a Task still
1550
+ // owning an open prompt stays tracked, so every other token (a
1551
+ // launched agent's included) is released here.
1552
+ msgProcessor.releaseTurnActivity(session);
1530
1553
 
1531
1554
  // Auto-continue on rate limit (scheduler sessions, or user setting)
1532
1555
  // Mark session as done processing so the late rate_limit_event handler
@@ -1772,7 +1795,7 @@ function createSDKBridge(opts) {
1772
1795
  await ensureVendorReady(session.vendor);
1773
1796
  }
1774
1797
  if (session.vendor && !adapters[session.vendor]) {
1775
- var freshAuth = getFreshAuthState();
1798
+ var freshAuth = getFreshAuthState(false, session);
1776
1799
  logAuthDecision("pre-auth-required", session, null, freshAuth);
1777
1800
  if (freshAuth[session.vendor]) {
1778
1801
  var recoveredAdapter = await ensureVendorReady(session.vendor);
@@ -1789,7 +1812,7 @@ function createSDKBridge(opts) {
1789
1812
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
1790
1813
  var canAutoLogin = !!authLinuxUser
1791
1814
  || (authUser && authUser.role === "admin");
1792
- var authState = getFreshAuthState();
1815
+ var authState = getFreshAuthState(false, session);
1793
1816
  logAuthDecision("emit-auth-required", session, "missing adapter", authState);
1794
1817
  if (authState[session.vendor]) {
1795
1818
  sendAndRecord(session, {
@@ -1799,6 +1822,14 @@ function createSDKBridge(opts) {
1799
1822
  sendAndRecord(session, { type: "done", code: 1 });
1800
1823
  return;
1801
1824
  }
1825
+ // A provider selected in the environment whose credential set is
1826
+ // incomplete: naming the provider, not offering a sign-in.
1827
+ var providerFailure = providerFailureFor(session, session.vendor);
1828
+ if (providerFailure) {
1829
+ sendAndRecord(session, { type: "error", text: providerFailure.message });
1830
+ sendAndRecord(session, { type: "done", code: 1 });
1831
+ return;
1832
+ }
1802
1833
  var authMsg2 = {
1803
1834
  type: "auth_required",
1804
1835
  text: authFacts2.title,
@@ -2709,6 +2740,7 @@ function createSDKBridge(opts) {
2709
2740
  startIdleReaper: startIdleReaper,
2710
2741
  stopIdleReaper: stopIdleReaper,
2711
2742
  getRuntimeEnvOverlay: getRuntimeEnvOverlay,
2743
+ providerFailureFor: providerFailureFor,
2712
2744
  getMemoryStats: getMemoryStats,
2713
2745
  refreshAiTitle: refreshAiTitle,
2714
2746
  };