@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
@@ -1,5 +1,6 @@
1
1
  var usersModule = require("./users");
2
2
  var { pushForSession } = require("./push-audience");
3
+ var { notifyFor } = require("./notify");
3
4
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
4
5
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
5
6
  var { promptsFor } = require("./prompt-registry");
@@ -95,6 +96,48 @@ function attachMessageProcessor(ctx) {
95
96
  session.taskIdMap = next;
96
97
  }
97
98
 
99
+ // Whether a tool_result block is the launch acknowledgement of a tracked
100
+ // background Task. The discriminator is the SDK's structured tool output
101
+ // (parsed.asyncLaunch, from tool_use_result.status "async_launched"), never
102
+ // the result text. When both sides name the agent id they must agree, so a
103
+ // launch of one agent cannot be mistaken for the ack of another.
104
+ function isBackgroundLaunchAck(session, parsed, toolUseId) {
105
+ if (!parsed.asyncLaunch) return false;
106
+ if (!promptsFor(sm).isTaskTracked(session, toolUseId)) return false;
107
+ var knownAgentId = session.taskIdMap ? session.taskIdMap[toolUseId] : null;
108
+ return !(parsed.asyncLaunch.agentId && knownAgentId && parsed.asyncLaunch.agentId !== knownAgentId);
109
+ }
110
+
111
+ function buildToolResultMsg(block) {
112
+ var resultText = "";
113
+ var resultImages = [];
114
+ if (typeof block.content === "string") {
115
+ resultText = block.content;
116
+ } else if (Array.isArray(block.content)) {
117
+ resultText = block.content
118
+ .filter(function(c) { return c.type === "text"; })
119
+ .map(function(c) { return c.text; })
120
+ .join("\n");
121
+ for (var ri = 0; ri < block.content.length; ri++) {
122
+ var rc = block.content[ri];
123
+ if (rc.type === "image" && rc.source) {
124
+ resultImages.push({
125
+ mediaType: rc.source.media_type,
126
+ data: rc.source.data,
127
+ });
128
+ }
129
+ }
130
+ }
131
+ var msg = {
132
+ type: "tool_result",
133
+ id: block.tool_use_id,
134
+ content: resultText,
135
+ is_error: block.is_error || false,
136
+ };
137
+ if (resultImages.length > 0) msg.images = resultImages;
138
+ return msg;
139
+ }
140
+
98
141
  function sendToSession(session, obj) {
99
142
  sm.sendToSession(session, obj);
100
143
  }
@@ -547,15 +590,16 @@ function attachMessageProcessor(ctx) {
547
590
 
548
591
  if (pushModule && block.name === "AskUserQuestion" && input.questions) {
549
592
  var q = input.questions[0];
550
- var _askPayload = {
551
- type: "ask_user",
593
+ // Content carries prompt text: owner only, never a blind broadcast.
594
+ // The prompt's id is the tool call's id.
595
+ notifyFor(pushModule).notify("ask_user", {
552
596
  slug: slug,
597
+ sessionId: session.localId,
598
+ requestId: block.id,
599
+ }, {
553
600
  title: "Claude has a question",
554
601
  body: withPromptLabel(promptsFor(sm).labelFor(session, block.id), q ? q.question : "Waiting for your response"),
555
- tag: "claude-ask",
556
- };
557
- // Content carries prompt text: owner only, never a blind broadcast.
558
- pushForSession(pushModule, session.ownerId, _askPayload);
602
+ }, { ownerId: session.ownerId });
559
603
  }
560
604
  } else if (block && block.type === "thinking") {
561
605
  var duration = block.startTime ? (Date.now() - block.startTime) / 1000 : 0;
@@ -608,6 +652,15 @@ function attachMessageProcessor(ctx) {
608
652
  for (var i = 0; i < content.length; i++) {
609
653
  var block = content[i];
610
654
  if (block.type === "tool_result" && !session.sentToolResults[block.tool_use_id]) {
655
+ // The acknowledgement of a background Task is its launch: the agent
656
+ // runs on, and its own terminal task_notification (or the query
657
+ // ending) is what ends tracking and releases its activity token.
658
+ if (isBackgroundLaunchAck(session, parsed, block.tool_use_id)) {
659
+ sessionReclaim.noteBackgroundLaunch(session, block.tool_use_id);
660
+ session.sentToolResults[block.tool_use_id] = true;
661
+ sendAndRecord(session, buildToolResultMsg(block));
662
+ continue;
663
+ }
611
664
  // A tracked Task's result means its sub-agent is done.
612
665
  var resultPrompts = promptsFor(sm);
613
666
  if (resultPrompts.isTaskTracked(session, block.tool_use_id)) {
@@ -633,34 +686,8 @@ function attachMessageProcessor(ctx) {
633
686
  // released by task_notification), so calling it unconditionally
634
687
  // for every tool_result is always safe.
635
688
  releaseActivity(session, block.tool_use_id);
636
- var resultText = "";
637
- var resultImages = [];
638
- if (typeof block.content === "string") {
639
- resultText = block.content;
640
- } else if (Array.isArray(block.content)) {
641
- resultText = block.content
642
- .filter(function(c) { return c.type === "text"; })
643
- .map(function(c) { return c.text; })
644
- .join("\n");
645
- for (var ri = 0; ri < block.content.length; ri++) {
646
- var rc = block.content[ri];
647
- if (rc.type === "image" && rc.source) {
648
- resultImages.push({
649
- mediaType: rc.source.media_type,
650
- data: rc.source.data,
651
- });
652
- }
653
- }
654
- }
655
689
  session.sentToolResults[block.tool_use_id] = true;
656
- var toolResultMsg = {
657
- type: "tool_result",
658
- id: block.tool_use_id,
659
- content: resultText,
660
- is_error: block.is_error || false,
661
- };
662
- if (resultImages.length > 0) toolResultMsg.images = resultImages;
663
- sendAndRecord(session, toolResultMsg);
690
+ sendAndRecord(session, buildToolResultMsg(block));
664
691
  }
665
692
  }
666
693
  }
@@ -746,12 +773,19 @@ function attachMessageProcessor(ctx) {
746
773
  }
747
774
  // Detect "Not logged in / Please run /login" from SDK.
748
775
  // This is a short canned response with zero cost, not actual AI output.
749
- if (isLoginPrompt) {
776
+ var loginVendor = [session.vendor, adapter && adapter.vendor].filter(yokeRegistry.isKnown)[0] || yokeRegistry.ids()[0];
777
+ var loginPromptProviderFailure = isLoginPrompt && typeof ctx.providerFailureFor === "function"
778
+ ? ctx.providerFailureFor(session, loginVendor)
779
+ : null;
780
+ if (loginPromptProviderFailure) {
781
+ // The canned "please log in" reply under a configured cloud provider is
782
+ // that provider's credentials failing; no sign-in is offered.
783
+ sendAndRecord(session, { type: "error", text: loginPromptProviderFailure.message });
784
+ } else if (isLoginPrompt) {
750
785
  var authUser = session.ownerId ? usersModule.findUserById(session.ownerId) : null;
751
786
  var authLinuxUser = authUser && authUser.linuxUser ? authUser.linuxUser : null;
752
787
  var canAutoLogin = !!authLinuxUser
753
788
  || (authUser && authUser.role === "admin");
754
- var loginVendor = [session.vendor, adapter && adapter.vendor].filter(yokeRegistry.isKnown)[0] || yokeRegistry.ids()[0];
755
789
  var authFacts = authRequiredFacts(loginVendor);
756
790
  var authTitle = authFacts.title;
757
791
  var loginCommand = authFacts.loginCommand;
@@ -778,10 +812,16 @@ function attachMessageProcessor(ctx) {
778
812
  canAutoLogin: canAutoLogin,
779
813
  });
780
814
  }
781
- // Reset CLI session so next query starts fresh with new auth
815
+ }
816
+ if (isLoginPrompt) {
817
+ // The CLI kept the canned reply as a turn of that session, so the next
818
+ // query starts fresh whether the fix is a sign-in or provider credentials.
782
819
  session.cliSessionId = null;
783
820
  }
784
- sendAndRecord(session, { type: "done", code: 0 });
821
+ // The canned reply is a failed turn, under a provider or a missing
822
+ // sign-in alike; code 1 is how every other failed turn ends, and what the
823
+ // loop engine reads to count an iteration as errored.
824
+ sendAndRecord(session, { type: "done", code: isLoginPrompt ? 1 : 0 });
785
825
  var _donePreviewText = (session.responsePreview || "").replace(/\s+/g, " ").trim();
786
826
  if (_donePreviewText.length > 140) _donePreviewText = _donePreviewText.substring(0, 140) + "...";
787
827
  var _doneTitle = session.title || "Claude";
@@ -1092,6 +1132,7 @@ function attachMessageProcessor(ctx) {
1092
1132
  processSubagentMessage: processSubagentMessage,
1093
1133
  toolActivityTextForSubagent: toolActivityTextForSubagent,
1094
1134
  retainTaskIdMap: retainTaskIdMap,
1135
+ releaseTurnActivity: releaseTurnActivity,
1095
1136
  };
1096
1137
  }
1097
1138
 
package/lib/server.js CHANGED
@@ -427,10 +427,31 @@ function createServer(opts) {
427
427
  // emitted — the trigger carries its own notification channel (e.g. ntfy).
428
428
  var { attachExternalTrigger } = require("./project-external-trigger");
429
429
  var { EXTERNAL_TRIGGERS_DIR } = require("./config");
430
+ // The sender-side record of what each session sent out (lib/outbound-ledger.js).
431
+ // Retention is read from daemon.json at use, so a change needs no restart.
432
+ var _outboundLedger = require("./outbound-ledger").createOutboundLedger({
433
+ getBaseDir: function () { return CONFIG_DIR; },
434
+ getRetentionDays: function () {
435
+ var cfg = require("./config").loadConfig();
436
+ return cfg ? cfg.outboundRetentionDays : undefined;
437
+ },
438
+ });
439
+ _outboundLedger.start();
440
+ // `list-outbound` arrives on the daemon-owner socket: no user record, and
441
+ // authenticated by the OS gate on the socket itself.
442
+ var _outboundQuery = require("./outbound-query").createOutboundQuery({
443
+ ledger: _outboundLedger,
444
+ access: require("./outbound-access").createOutboundAccess({
445
+ projectAccess: projectAccess,
446
+ getProject: function (slug) { return projects.get(slug) || null; },
447
+ }),
448
+ caller: { user: null, authenticated: true },
449
+ });
430
450
  // One implementation for the file drop and the daemon IPC verbs (open-session,
431
451
  // send-input).
432
452
  var _sessionInput = require("./session-input").createSessionInput({
433
453
  getProject: function (slug) { return projects.get(slug) || null; },
454
+ outboundLedger: _outboundLedger,
434
455
  // Read when a session is opened, so a change needs no restart.
435
456
  getPermissionSettings: function () {
436
457
  return onGetPermissionSettings ? onGetPermissionSettings() : null;
@@ -580,7 +601,11 @@ function createServer(opts) {
580
601
  var parsed = JSON.parse(body);
581
602
  var sub = parsed.subscription || parsed;
582
603
  var _httpPushUser = getMultiUserFromReq(req);
583
- pushModule.addSubscription(sub, parsed.replaceEndpoint, _httpPushUser ? _httpPushUser.id : null);
604
+ if (pushModule.addSubscription(sub, parsed.replaceEndpoint, _httpPushUser ? _httpPushUser.id : null) === false && sub && sub.endpoint) {
605
+ res.writeHead(401, { "Content-Type": "application/json" });
606
+ res.end('{"error":"sign in to enable push notifications"}');
607
+ return;
608
+ }
584
609
  res.writeHead(200, { "Content-Type": "application/json" });
585
610
  res.end('{"ok":true}');
586
611
  } catch (e) {
@@ -1817,6 +1842,7 @@ function createServer(opts) {
1817
1842
 
1818
1843
  function destroyAll() {
1819
1844
  _promptReminders.stop();
1845
+ _outboundLedger.stop();
1820
1846
  _externalTrigger.stopWatcher();
1821
1847
  _scheduledInput.stop();
1822
1848
  var shutdowns = [];
@@ -1833,7 +1859,12 @@ function createServer(opts) {
1833
1859
  });
1834
1860
  projects.clear();
1835
1861
  sessionReclaim.logShutdownSummary(tally);
1836
- return Promise.all(shutdowns);
1862
+ // The prompts settled above sent their close pushes; the process must not
1863
+ // exit before they leave.
1864
+ return Promise.all(shutdowns).then(function (results) {
1865
+ if (!pushModule || typeof pushModule.flush !== "function") return results;
1866
+ return pushModule.flush().then(function () { return results; });
1867
+ });
1837
1868
  }
1838
1869
 
1839
1870
  // --- Periodic cleanup of old chat images ---
@@ -1903,6 +1934,7 @@ function createServer(opts) {
1903
1934
  broadcastAll: broadcastAll,
1904
1935
  forEachProject: forEachProject,
1905
1936
  sessionInput: _sessionInput,
1937
+ outboundQuery: _outboundQuery,
1906
1938
  scheduledInput: _scheduledInput,
1907
1939
  getProject: function (slug) { return projects.get(slug) || null; },
1908
1940
  destroyProject: removeProject,
@@ -9,9 +9,11 @@
9
9
  // console is not in the store and is not listed.
10
10
  //
11
11
  // States:
12
- // live a turn is running
13
- // idle a runtime is attached and no turn is running
12
+ // live a turn is running, or the session is blocked on a pending prompt
13
+ // (pendingPrompts tells the two apart)
14
+ // idle a runtime is attached, nothing running, nothing pending
14
15
  // reaped no runtime (idle reaper, daemon restart); input resumes it
16
+ // The three come from the shared derivation in lib/session-liveness.js.
15
17
  //
16
18
  // Addresses (the label format of lib/sender-ref.js):
17
19
  // <agent>@<project> a session running that named agent
@@ -30,6 +32,7 @@ var senderRef = require("./sender-ref");
30
32
  var { slugifyAgentName } = require("./agents");
31
33
  var { isInjected } = require("./injected-sender");
32
34
  var { pendingPrompts } = require("./pending-prompts");
35
+ var liveness = require("./session-liveness");
33
36
 
34
37
  var STATE = Object.freeze({ LIVE: "live", IDLE: "idle", REAPED: "reaped" });
35
38
  var ANY_STATE = "any";
@@ -56,8 +59,7 @@ function validateName(raw) {
56
59
  }
57
60
 
58
61
  function stateOf(session) {
59
- if (!senderRef.isLive(session)) return STATE.REAPED;
60
- return session.isProcessing ? STATE.LIVE : STATE.IDLE;
62
+ return liveness.liveStateOf(liveness.activityOf(session));
61
63
  }
62
64
 
63
65
  function isoOrNull(ms) {
@@ -50,4 +50,14 @@ function handleSessionCommand(sessionInput, msg) {
50
50
  return undefined;
51
51
  }
52
52
 
53
- module.exports = { handleSessionCommand: handleSessionCommand };
53
+ // The read side of the outbound ledger (lib/outbound-query.js).
54
+ function handleOutboundCommand(outboundQuery, msg) {
55
+ return outboundQuery.list({
56
+ sessionId: msg.sessionId,
57
+ projectSlug: msg.projectSlug,
58
+ sinceMs: msg.sinceMs,
59
+ kind: msg.kind,
60
+ });
61
+ }
62
+
63
+ module.exports = { handleSessionCommand: handleSessionCommand, handleOutboundCommand: handleOutboundCommand };
@@ -25,6 +25,7 @@ var directory = require("./session-directory");
25
25
  var permissionSettings = require("./permission-settings");
26
26
  var { checkPermissionMode } = require("./permission-mode-policy");
27
27
  var { slugifyAgentName } = agentsModule;
28
+ var outboundEntry = require("./outbound-entry");
28
29
 
29
30
  // The result vocabulary reported to the caller. "error" is not a verdict on
30
31
  // the request: delivery was attempted and failed, so a caller may retry.
@@ -162,14 +163,23 @@ function logResult(verb, req, out) {
162
163
  console.log(line);
163
164
  }
164
165
 
165
- function logged(verb, fn) {
166
+ // after(verb, req, result), when given, runs once the line is logged. It must
167
+ // not throw into the caller: the result is already decided.
168
+ function logged(verb, fn, after) {
169
+ function finish(req, result) {
170
+ logResult(verb, req, result);
171
+ if (after) {
172
+ try { after(verb, req, result); }
173
+ catch (e) { console.error("[session-input] after-result hook failed:", messageOf(e)); }
174
+ }
175
+ return result;
176
+ }
166
177
  return function (req) {
167
178
  var out = fn(req);
168
179
  if (out && typeof out.then === "function") {
169
- return out.then(function (result) { logResult(verb, req, result); return result; });
180
+ return out.then(function (result) { return finish(req, result); });
170
181
  }
171
- logResult(verb, req, out);
172
- return out;
182
+ return finish(req, out);
173
183
  };
174
184
  }
175
185
 
@@ -183,9 +193,14 @@ function present(value) {
183
193
  // agentCatalog(project) -> [{ name }] named agents on offer (default: the picker's catalog)
184
194
  // getPermissionSettings() -> the server's permission settings (lib/permission-settings.js)
185
195
  // or null (default: the settings' defaults)
196
+ // outboundLedger -> { record(entry) } the sender-side ledger
197
+ // (lib/outbound-ledger.js); default: none kept
198
+ // now() -> ms clock for ledger entries (default Date.now)
186
199
  function createSessionInput(deps) {
187
200
  var getProject = deps.getProject;
188
201
  var listProjects = deps.listProjects || function () { return []; };
202
+ var outboundLedger = deps.outboundLedger || null;
203
+ var clock = deps.now || Date.now;
189
204
 
190
205
  function defaultAgentCatalog(project) {
191
206
  // Neither lookup throws: both answer [] when discovery has not run or the
@@ -333,10 +348,71 @@ function createSessionInput(deps) {
333
348
  return {};
334
349
  }
335
350
 
351
+ // The sender fields of a request. The reference a console-started caller holds
352
+ // is resolved in the daemon's own store; one it does not hold falls through to
353
+ // declared or undeclared.
354
+ function senderOf(req, initiator) {
355
+ var extracted = senderRef.resolve(getProject, { project: req.senderProject, sessionId: req.senderSessionId });
356
+ return senderFields(initiator, validateFrom(req.from).from, extracted, validateFromSession(req.fromSession).fromSession);
357
+ }
358
+
359
+ // Appends to the sender-side ledger. A ledger that cannot be written is
360
+ // logged by the ledger and never changes the answer to the request.
361
+ function writeLedger(entry) {
362
+ if (!outboundLedger) return;
363
+ try { outboundLedger.record(entry); }
364
+ catch (e) { console.error("[session-input] outbound ledger failed:", messageOf(e)); }
365
+ }
366
+
367
+ // The verb a result is logged under, as the ledger names it. Other verbs
368
+ // (listing, a scheduled firing) are not outbound calls of a sender.
369
+ var LEDGER_VERB = { open_session: outboundEntry.VERB.OPEN_SESSION, send_session_input: outboundEntry.VERB.SEND_INPUT };
370
+
371
+ // A delivery, recorded where the history entry is, so both carry the same
372
+ // message id and sender.
373
+ function ledgerDelivery(verb, project, session, req, initiator, messageId, sender) {
374
+ if (!outboundLedger) return;
375
+ // Building the entry reads the session and the project; none of it may
376
+ // throw into the delivery.
377
+ try {
378
+ var linuxUser = typeof project.getLinuxUserForSession === "function" ? project.getLinuxUserForSession(session) : null;
379
+ writeLedger(outboundEntry.buildEntry({
380
+ verb: verb,
381
+ ts: new Date(clock()).toISOString(),
382
+ req: req,
383
+ out: null,
384
+ initiator: initiator,
385
+ messageId: messageId,
386
+ sender: sender,
387
+ target: Object.assign({ project: req.projectSlug, runsAs: linuxUser || outboundEntry.RUNS_AS_DAEMON }, describe(project, session)),
388
+ }));
389
+ } catch (e) {
390
+ console.error("[session-input] outbound ledger entry failed:", messageOf(e));
391
+ }
392
+ }
393
+
394
+ // A request that was not delivered (refused, not found, ambiguous, failed).
395
+ // A delivery already left its entry in recordInjected.
396
+ function ledgerOutcome(verb, req, out) {
397
+ if (!outboundLedger || !LEDGER_VERB[verb] || !out || out.ok === true) return;
398
+ req = req || {};
399
+ var init = resolveInitiator(req.initiator);
400
+ var initiator = init.initiator || null;
401
+ writeLedger(outboundEntry.buildEntry({
402
+ verb: LEDGER_VERB[verb],
403
+ ts: new Date(clock()).toISOString(),
404
+ req: req,
405
+ out: out,
406
+ initiator: initiator,
407
+ sender: senderOf(req, initiator),
408
+ target: { project: req.projectSlug, consoleSessionId: out.consoleSessionId, sessionId: out.sessionId, agent: out.agent, vendor: out.vendor, name: out.name },
409
+ }));
410
+ }
411
+
336
412
  // History entry that marks the turn as injected, not typed. The input is
337
413
  // already delivered when this runs, so a failure to record is logged and does
338
414
  // not turn a delivered turn into an error a caller would retry.
339
- function recordInjected(project, session, req, initiator, messageId) {
415
+ function recordInjected(verb, project, session, req, initiator, messageId) {
340
416
  var entry;
341
417
  if (req.automation) {
342
418
  // A turn the console composed itself (fireScheduled): the console is the
@@ -353,11 +429,9 @@ function createSessionInput(deps) {
353
429
  });
354
430
  if (req.triggerId) entry.triggerId = req.triggerId;
355
431
  if (req.contextNote) entry.contextNote = req.contextNote;
356
- // The reference a console-started caller holds, resolved in the daemon's own
357
- // store; one it does not hold falls through to declared or undeclared.
358
- var extracted = senderRef.resolve(getProject, { project: req.senderProject, sessionId: req.senderSessionId });
359
- var sender = senderFields(initiator, validateFrom(req.from).from, extracted, validateFromSession(req.fromSession).fromSession);
432
+ var sender = senderOf(req, initiator);
360
433
  for (var k in sender) entry[k] = sender[k];
434
+ ledgerDelivery(verb, project, session, req, initiator, messageId, sender);
361
435
  }
362
436
  try {
363
437
  project.sm.recordHistoryEntry(session, entry, true);
@@ -420,7 +494,7 @@ function createSessionInput(deps) {
420
494
  var messageId = newMessageId();
421
495
 
422
496
  function delivered() {
423
- recordInjected(project, session, req, initiator, messageId);
497
+ recordInjected(outboundEntry.VERB.SEND_INPUT, project, session, req, initiator, messageId);
424
498
  if (req.automation && !processing) announceStartedTurn(project, session);
425
499
  var out = describe(project, session);
426
500
  out.ok = true;
@@ -707,7 +781,8 @@ function createSessionInput(deps) {
707
781
  // that session's owner, so its prompts push to a person who can read it. A
708
782
  // declared or undeclared sender is a claim, never an inheritance.
709
783
  var openedBy = senderRef.resolve(getProject, { project: req.senderProject, sessionId: req.senderSessionId });
710
- var created = Object.assign({}, kind.options, { permissionMode: openMode.mode });
784
+ // activate:false: an opened session is listed but never moves a connected tab.
785
+ var created = Object.assign({}, kind.options, { permissionMode: openMode.mode, activate: false });
711
786
  if (openedBy && openedBy.ownerId) created.ownerId = openedBy.ownerId;
712
787
  var sess = sm.createSession(created);
713
788
  var label = req.triggerId ? " — " + String(req.triggerId).substring(0, 12) : "";
@@ -732,7 +807,7 @@ function createSessionInput(deps) {
732
807
  }, function () {
733
808
  // Recorded once, only now that the query has started: a rejected start
734
809
  // leaves no history entry for a prompt that never ran.
735
- recordInjected(project, sess, req, init.initiator, openedMessageId);
810
+ recordInjected(outboundEntry.VERB.OPEN_SESSION, project, sess, req, init.initiator, openedMessageId);
736
811
  // A name has one holder: the claim took effect in memory at open (the new
737
812
  // session is non-reaped and wins over its reaped twins meanwhile), and
738
813
  // only now, with the start done, is it taken from the reaped sessions
@@ -764,8 +839,8 @@ function createSessionInput(deps) {
764
839
  }
765
840
 
766
841
  return {
767
- openSession: logged("open_session", neverThrows(openSession)),
768
- sendInput: logged("send_session_input", neverThrows(sendInput)),
842
+ openSession: logged("open_session", neverThrows(openSession), ledgerOutcome),
843
+ sendInput: logged("send_session_input", neverThrows(sendInput), ledgerOutcome),
769
844
  listSessions: logged("list_sessions", neverThrows(listSessions)),
770
845
  fireScheduled: logged("fire_scheduled_input", neverThrows(fireScheduled)),
771
846
  };
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+
3
+ // session-liveness.js - the one daemon-side derivation of what a session is
4
+ // doing, read by every surface that shows it: the build-update confirm card,
5
+ // the session list served to the client (picker dots, sidebar), and
6
+ // list-sessions.
7
+ //
8
+ // Inputs are the three facts a session holds: whether a runtime is attached,
9
+ // whether a turn is running, and whether an operator prompt is pending.
10
+ //
11
+ // reaped no runtime (idle reaper, daemon restart); input resumes it
12
+ // waiting a runtime is attached and at least one operator prompt is
13
+ // pending: a turn or runtime is blocked on the operator
14
+ // running a runtime is attached, a turn is running, nothing is pending
15
+ // idle a runtime is attached, nothing running, nothing pending
16
+ //
17
+ // A pending prompt outranks a running turn: a turn stopped on a prompt is
18
+ // not progressing, and "running" would hide that the operator is the one
19
+ // being waited on. A prompt on a session with no runtime is not waited on by
20
+ // anything (nothing can use the answer), so that session is reaped; its
21
+ // prompt stays visible in list-sessions pendingPrompts.
22
+ //
23
+ // list-sessions keeps its three-valued `state` (live | idle | reaped); a
24
+ // waiting session is live there. liveStateOf() is that projection.
25
+
26
+ var senderRef = require("./sender-ref");
27
+ var { countPending } = require("./pending-prompts");
28
+
29
+ var ACTIVITY = Object.freeze({ REAPED: "reaped", IDLE: "idle", RUNNING: "running", WAITING: "waiting" });
30
+
31
+ // facts: { attached, turnRunning, pendingCount }
32
+ function derive(facts) {
33
+ if (!facts.attached) return ACTIVITY.REAPED;
34
+ if (facts.pendingCount > 0) return ACTIVITY.WAITING;
35
+ return facts.turnRunning ? ACTIVITY.RUNNING : ACTIVITY.IDLE;
36
+ }
37
+
38
+ // The activity of a session object held by a project's session manager.
39
+ function activityOf(session) {
40
+ return derive({
41
+ attached: senderRef.isLive(session),
42
+ turnRunning: !!session.isProcessing,
43
+ pendingCount: countPending(session),
44
+ });
45
+ }
46
+
47
+ // list-sessions' `state`: waiting and running are both "live".
48
+ function liveStateOf(activity) {
49
+ if (activity === ACTIVITY.REAPED) return "reaped";
50
+ return activity === ACTIVITY.IDLE ? "idle" : "live";
51
+ }
52
+
53
+ module.exports = { ACTIVITY: ACTIVITY, derive: derive, activityOf: activityOf, liveStateOf: liveStateOf };
@@ -7,6 +7,8 @@
7
7
  // announceLiveAgentReclaim: the agents are named, the session is marked as
8
8
  // expected to resume, and both UI surfaces are told.
9
9
 
10
+ var sessionActivity = require("./session-activity");
11
+
10
12
  var LABEL_MAX = 80;
11
13
  var FALLBACK_LABEL = "background agent";
12
14
 
@@ -42,9 +44,16 @@ function noteTaskLabel(session, taskId, input) {
42
44
  * answer instead of guessing at the end event.
43
45
  */
44
46
  function pruneTaskLabels(session) {
45
- var table = session && session.taskLabels;
46
- if (!table) return;
47
+ if (!session) return;
47
48
  var tracked = session.activeTaskToolIds || {};
49
+ var marks = session.backgroundTaskIds;
50
+ if (marks) {
51
+ Object.keys(marks).forEach(function (id) {
52
+ if (!Object.prototype.hasOwnProperty.call(tracked, id) || !tracked[id]) delete marks[id];
53
+ });
54
+ }
55
+ var table = session.taskLabels;
56
+ if (!table) return;
48
57
  Object.keys(table).forEach(function (id) {
49
58
  if (!Object.prototype.hasOwnProperty.call(tracked, id) || !tracked[id]) delete table[id];
50
59
  });
@@ -68,6 +77,30 @@ function liveAgentTasks(session) {
68
77
  });
69
78
  }
70
79
 
80
+ /** Record that a tracked Task was acknowledged as launched in the background. */
81
+ function noteBackgroundLaunch(session, taskId) {
82
+ if (typeof taskId !== "string" || !taskId) return;
83
+ if (!session.backgroundTaskIds) session.backgroundTaskIds = Object.create(null);
84
+ session.backgroundTaskIds[taskId] = true;
85
+ }
86
+
87
+ /**
88
+ * True when the session is busy only because tracked background agents hold
89
+ * activity tokens: no tool call, thinking block or other live work of its own.
90
+ * The idle reaper reads this so a session waiting on silent agents stays
91
+ * reapable (and announced) instead of looking like a running turn.
92
+ */
93
+ function onlyBackgroundAgentsActive(session) {
94
+ var tracked = session && session.activeTaskToolIds;
95
+ var marks = session && session.backgroundTaskIds;
96
+ if (!tracked || !marks) return false;
97
+ var has = Object.prototype.hasOwnProperty;
98
+ var sources = sessionActivity.listActiveSources(session);
99
+ return sources.length > 0 && sources.every(function (s) {
100
+ return has.call(tracked, s.token) && !!tracked[s.token] && has.call(marks, s.token);
101
+ });
102
+ }
103
+
71
104
  /** Operator-facing names of every Task the session still tracks. */
72
105
  function liveAgentLabels(session) {
73
106
  return liveAgentTasks(session).map(function (t) { return t.label; });
@@ -276,6 +309,8 @@ module.exports = {
276
309
  surfaceRestartReclaims: surfaceRestartReclaims,
277
310
  restartDiagnostics: restartDiagnostics,
278
311
  noteTaskLabel: noteTaskLabel,
312
+ noteBackgroundLaunch: noteBackgroundLaunch,
313
+ onlyBackgroundAgentsActive: onlyBackgroundAgentsActive,
279
314
  pruneTaskLabels: pruneTaskLabels,
280
315
  liveAgentLabels: liveAgentLabels,
281
316
  liveAgentTasks: liveAgentTasks,