@clagentic/console 1.10.0 → 1.11.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 (97) hide show
  1. package/README.md +14 -1
  2. package/bin/cli.js +38 -16
  3. package/lib/agents.js +1 -55
  4. package/lib/bash-auto-approve.js +133 -0
  5. package/lib/build-identity.js +23 -5
  6. package/lib/build-sha.json +2 -2
  7. package/lib/build-update-check.js +0 -62
  8. package/lib/build-update-offer.js +23 -13
  9. package/lib/build-update-restart.js +59 -43
  10. package/lib/cli/arg-validation.js +50 -0
  11. package/lib/cli/daemon-launch.js +5 -4
  12. package/lib/cli/menus.js +2 -2
  13. package/lib/cli/schedule-input-subcommands.js +327 -0
  14. package/lib/cli/session-subcommands.js +101 -17
  15. package/lib/client-build-id.js +56 -0
  16. package/lib/daemon.js +38 -6
  17. package/lib/identity/index.js +9 -4
  18. package/lib/injected-sender.js +225 -0
  19. package/lib/message-sender-record.js +133 -0
  20. package/lib/pending-prompts.js +55 -0
  21. package/lib/permission-mode-policy.js +63 -0
  22. package/lib/permission-settings.js +96 -0
  23. package/lib/permission-summary.js +67 -0
  24. package/lib/project-connection.js +10 -11
  25. package/lib/project-external-trigger.js +9 -1
  26. package/lib/project-loop.js +50 -23
  27. package/lib/project-permission-settings.js +59 -0
  28. package/lib/project-prompt-responses.js +25 -15
  29. package/lib/project-sessions.js +164 -60
  30. package/lib/project-user-message.js +18 -47
  31. package/lib/project.js +46 -74
  32. package/lib/public/app.js +4 -7
  33. package/lib/public/css/channel-layout.css +20 -0
  34. package/lib/public/css/diagnostics.css +7 -0
  35. package/lib/public/css/input.css +78 -0
  36. package/lib/public/css/menus.css +17 -0
  37. package/lib/public/css/overlays.css +0 -3
  38. package/lib/public/css/scheduler-modal.css +5 -0
  39. package/lib/public/index.html +44 -8
  40. package/lib/public/modules/app-connection.js +18 -1
  41. package/lib/public/modules/app-loop-ui.js +11 -1
  42. package/lib/public/modules/app-messages.js +23 -30
  43. package/lib/public/modules/app-panels.js +10 -3
  44. package/lib/public/modules/app-rate-limit.js +64 -88
  45. package/lib/public/modules/app-rendering.js +37 -6
  46. package/lib/public/modules/approve-tools-toggle.js +33 -0
  47. package/lib/public/modules/at-agents.js +8 -0
  48. package/lib/public/modules/build-guard.js +61 -0
  49. package/lib/public/modules/build-update-detail.js +1 -4
  50. package/lib/public/modules/diagnostics.js +98 -9
  51. package/lib/public/modules/injected-identity.js +78 -0
  52. package/lib/public/modules/injected-label.js +62 -0
  53. package/lib/public/modules/input.js +64 -114
  54. package/lib/public/modules/loop-hooks-warning.js +20 -0
  55. package/lib/public/modules/mode-options.js +35 -16
  56. package/lib/public/modules/permission-settings.js +56 -0
  57. package/lib/public/modules/project-settings.js +3 -0
  58. package/lib/public/modules/rate-limit-state.js +47 -22
  59. package/lib/public/modules/schedule-panel.js +234 -0
  60. package/lib/public/modules/schedule-time.js +193 -0
  61. package/lib/public/modules/scheduled-input-actions.js +19 -0
  62. package/lib/public/modules/scheduler-config.js +12 -0
  63. package/lib/public/modules/scheduler.js +8 -0
  64. package/lib/public/modules/server-settings.js +5 -9
  65. package/lib/public/modules/settings-defaults.js +18 -4
  66. package/lib/runtime-env.js +4 -0
  67. package/lib/scheduled-input/ipc.js +92 -0
  68. package/lib/scheduled-input/rate-limit-resume.js +53 -0
  69. package/lib/scheduled-input/records.js +350 -0
  70. package/lib/scheduled-input/service.js +743 -0
  71. package/lib/scheduled-input/store.js +132 -0
  72. package/lib/scheduled-input/ws.js +194 -0
  73. package/lib/scheduler.js +4 -0
  74. package/lib/sdk-bridge.js +194 -175
  75. package/lib/sdk-message-processor.js +13 -5
  76. package/lib/sdk-skill-discovery.js +17 -0
  77. package/lib/sender-ref.js +109 -0
  78. package/lib/server.js +37 -11
  79. package/lib/session-directory.js +224 -0
  80. package/lib/session-file-scan.js +55 -0
  81. package/lib/session-input-ipc.js +21 -0
  82. package/lib/session-input.js +396 -23
  83. package/lib/session-name-holder.js +82 -0
  84. package/lib/session-resume.js +3 -0
  85. package/lib/sessions.js +111 -2
  86. package/lib/turn-initiator.js +6 -2
  87. package/lib/updater.js +8 -2
  88. package/lib/ws-schema.js +20 -9
  89. package/lib/yoke/adapters/claude-worker.js +3 -1
  90. package/lib/yoke/adapters/claude.js +13 -17
  91. package/lib/yoke/adapters/codex.js +18 -5
  92. package/lib/yoke/adapters/permission-relay.js +9 -0
  93. package/lib/yoke/interface.js +7 -1
  94. package/package.json +1 -1
  95. package/scripts/check-test-count.js +1 -1
  96. package/scripts/install-local-test.js +45 -1
  97. package/scripts/postinstall.js +1 -0
@@ -8,6 +8,7 @@ var usersModule = require("./users");
8
8
  var { writeHandoff, buildHandoffPreamble } = require("./loop-handoff");
9
9
  var { authOf } = require("./project-access");
10
10
  var { INITIATORS } = require("./turn-initiator");
11
+ var { consoleTurnEntry, stampRecord } = require("./injected-sender");
11
12
 
12
13
  var LOOP_ID_RE = /^loop_[A-Za-z0-9_-]+$/;
13
14
 
@@ -20,6 +21,12 @@ var LOOP_ID_RE = /^loop_[A-Za-z0-9_-]+$/;
20
21
  var LOOP_MESSAGE_MAX_QUEUE_LENGTH = 20;
21
22
  var LOOP_MESSAGE_MAX_TEXT_LENGTH = 4000;
22
23
 
24
+ // The detail a loop turn's chat label carries after "loop": the loop's name, when
25
+ // it has one, then what this turn is.
26
+ function loopNote(name, what) {
27
+ return name ? name + " · " + what : what;
28
+ }
29
+
23
30
  /**
24
31
  * Validate a loop ID before using it as a path component.
25
32
  *
@@ -460,6 +467,15 @@ function attachLoop(ctx) {
460
467
  runNextIteration();
461
468
  }
462
469
 
470
+ // The loop's "Approve tools automatically during this loop" setting, read
471
+ // from its registry record when each run's sessions are made. A loop with no
472
+ // record, or a record from before the field existed, approves, as every loop
473
+ // did.
474
+ function loopApprovesTools() {
475
+ var rec = loopRegistry.getById(loopState.loopId);
476
+ return !(rec && rec.approveToolsAutomatically === false);
477
+ }
478
+
463
479
  function runNextIteration() {
464
480
  console.log("[ralph-loop] runNextIteration called, iteration: " + loopState.iteration + ", active: " + loopState.active + ", stopping: " + loopState.stopping);
465
481
  if (!loopState.active || loopState.stopping) {
@@ -478,7 +494,7 @@ function attachLoop(ctx) {
478
494
  var loopName = (loopState.wizardData && loopState.wizardData.name) || (loopSource && loopSource.name) || "";
479
495
  var loopSourceTag = (loopSource && loopSource.source) || null;
480
496
  var isRalphLoop = loopSourceTag === "ralph";
481
- session.loop = { active: true, iteration: loopState.iteration, role: "coder", loopId: loopState.loopId, name: loopName, source: loopSourceTag, startedAt: loopState.startedAt };
497
+ session.loop = { active: true, iteration: loopState.iteration, role: "coder", loopId: loopState.loopId, name: loopName, source: loopSourceTag, startedAt: loopState.startedAt, approveTools: loopApprovesTools() };
482
498
  session.title = (isRalphLoop ? "Ralph" : "Task") + (loopName ? " " + loopName : "") + " #" + loopState.iteration;
483
499
  sm.saveSessionFile(session);
484
500
  sm.broadcastSessionList();
@@ -574,36 +590,35 @@ function attachLoop(ctx) {
574
590
 
575
591
  // lr-e31b: Deliver human messages queued during the prior iteration at this
576
592
  // boundary. Ephemeral loop-iteration sessions are single-turn (their SDK
577
- // input stream is closed immediately after the first push — see
593
+ // input stream is closed right after the messages are pushed - see
578
594
  // yoke/adapters/claude.js endInput()), so mid-flight injection into a live
579
- // iteration is not viable without a broader architecture change. Boundary
580
- // delivery reuses the same session.history / user_message path a normal
581
- // chat message takes, so the human's text is visible in the transcript and
582
- // the coder session actually reads it (folded into the iteration prompt).
595
+ // iteration is not viable without a broader architecture change.
596
+ //
597
+ // Each queued message is the operator's own words, so it is sent to the
598
+ // vendor as a user message of its own, ahead of the iteration message: it
599
+ // carries the human initiator (the vendor's per-turn origin and the
600
+ // published sender record) and its own message id, and is never merged into
601
+ // or recorded under the iteration message, which keeps the loop initiator.
583
602
  var _queuedMsgs = loopState.pendingUserMessages || [];
603
+ var _leadMessages = [];
584
604
  if (_queuedMsgs.length > 0) {
585
- var _queuedBlock = ["## Message from user (sent during the previous iteration)", ""];
586
605
  for (var _qi = 0; _qi < _queuedMsgs.length; _qi++) {
587
606
  var _qm = _queuedMsgs[_qi];
588
- _queuedBlock.push(_qm.text);
589
- // Record as its own history entry so the transcript shows exactly what
590
- // the human sent and when, distinct from the coder's own prompt text.
591
- var _qUserMsg = { type: "user_message", text: _qm.text, _ts: _qm.ts || Date.now() };
607
+ var _qUserMsg = stampRecord({ type: "user_message", text: _qm.text, _ts: _qm.ts || Date.now(), initiator: INITIATORS.HUMAN });
592
608
  if (_qm.from) { _qUserMsg.from = _qm.from; _qUserMsg.fromName = _qm.fromName || ""; }
593
609
  // lr-2ea2a7: routes through the shared history-cap helper (see
594
610
  // grep-guard test) — Ralph/crew loop sessions are exactly the
595
611
  // long-running isProcessing sessions this fix bounds.
596
612
  sm.recordHistoryEntry(session, _qUserMsg, true);
597
613
  sm.appendToSessionFile(session, _qUserMsg);
614
+ _leadMessages.push({ text: _qm.text, initiator: INITIATORS.HUMAN, messageId: _qUserMsg.messageId });
598
615
  }
599
- _queuedBlock.push("", "---", "");
600
- _iterationPrompt = _queuedBlock.join("\n") + _iterationPrompt;
601
616
  loopState.pendingUserMessages = [];
602
617
  saveLoopState();
603
618
  send({ type: "loop_pending_messages", messages: [] });
604
619
  }
605
620
 
606
- var userMsg = { type: "user_message", text: _iterationPrompt };
621
+ var userMsg = consoleTurnEntry(INITIATORS.LOOP, _iterationPrompt, loopNote(loopName, "iteration " + loopState.iteration));
607
622
  sm.recordHistoryEntry(session, userMsg, true);
608
623
  sm.appendToSessionFile(session, userMsg);
609
624
 
@@ -614,7 +629,7 @@ function attachLoop(ctx) {
614
629
  session.acceptEditsAfterStart = true;
615
630
  session.singleTurn = true;
616
631
  if (loopState.settings) session.loopSettings = loopState.settings;
617
- sdk.startQuery(session, _iterationPrompt, undefined, getLinuxUserForSession(session), INITIATORS.LOOP);
632
+ sdk.startQuery(session, _iterationPrompt, undefined, getLinuxUserForSession(session), INITIATORS.LOOP, userMsg.messageId, _leadMessages);
618
633
  }
619
634
 
620
635
  function runJudge() {
@@ -660,7 +675,7 @@ function attachLoop(ctx) {
660
675
  var judgeName = (loopState.wizardData && loopState.wizardData.name) || (judgeSource && judgeSource.name) || "";
661
676
  var judgeSourceTag = (judgeSource && judgeSource.source) || null;
662
677
  var isRalphJudge = judgeSourceTag === "ralph";
663
- judgeSession.loop = { active: true, iteration: loopState.iteration, role: "judge", loopId: loopState.loopId, name: judgeName, source: judgeSourceTag, startedAt: loopState.startedAt };
678
+ judgeSession.loop = { active: true, iteration: loopState.iteration, role: "judge", loopId: loopState.loopId, name: judgeName, source: judgeSourceTag, startedAt: loopState.startedAt, approveTools: loopApprovesTools() };
664
679
  judgeSession.title = (isRalphJudge ? "Ralph" : "Task") + (judgeName ? " " + judgeName : "") + " Judge #" + loopState.iteration;
665
680
  sm.saveSessionFile(judgeSession);
666
681
  sm.broadcastSessionList();
@@ -726,7 +741,7 @@ function attachLoop(ctx) {
726
741
  }
727
742
  }, 10 * 60 * 1000);
728
743
 
729
- var userMsg = { type: "user_message", text: judgePrompt };
744
+ var userMsg = consoleTurnEntry(INITIATORS.LOOP, judgePrompt, loopNote(judgeName, "judge, iteration " + loopState.iteration));
730
745
  // lr-2ea2a7: routes through the shared history-cap helper (see grep-guard test).
731
746
  sm.recordHistoryEntry(judgeSession, userMsg, true);
732
747
  sm.appendToSessionFile(judgeSession, userMsg);
@@ -737,7 +752,7 @@ function attachLoop(ctx) {
737
752
  judgeSession.acceptEditsAfterStart = true;
738
753
  judgeSession.singleTurn = true;
739
754
  if (loopState.settings) judgeSession.loopSettings = loopState.settings;
740
- sdk.startQuery(judgeSession, judgePrompt, undefined, getLinuxUserForSession(judgeSession), INITIATORS.LOOP);
755
+ sdk.startQuery(judgeSession, judgePrompt, undefined, getLinuxUserForSession(judgeSession), INITIATORS.LOOP, userMsg.messageId);
741
756
  }
742
757
 
743
758
  // lr-2ea2a7: forward-accumulates delta/text across the FULL heap array —
@@ -951,6 +966,11 @@ function attachLoop(ctx) {
951
966
  // --- Message handler for loop-related messages ---
952
967
  function handleLoopMessage(ws, msg) {
953
968
  if (msg.type === "loop_start") {
969
+ // The preview's "Approve tools automatically" choice is the record's, so it
970
+ // holds for a scheduled loop too, which returns below without running.
971
+ if (typeof msg.approveToolsAutomatically === "boolean" && loopState.loopId) {
972
+ loopRegistry.updateRecord(loopState.loopId, { approveToolsAutomatically: msg.approveToolsAutomatically });
973
+ }
954
974
  // If this loop has a cron schedule, don't run immediately
955
975
  if (loopState.wizardData && loopState.wizardData.cron) {
956
976
  loopState.active = false;
@@ -1155,7 +1175,7 @@ function attachLoop(ctx) {
1155
1175
  // heap entry and the durable append (previously two separate
1156
1176
  // literals — harmless before, but recordHistoryEntry mutates the
1157
1177
  // object it's given, so a shared reference is the correct shape).
1158
- var judgeCraftUserMsg = { type: "user_message", text: judgeCraftPrompt };
1178
+ var judgeCraftUserMsg = consoleTurnEntry(INITIATORS.LOOP, judgeCraftPrompt, loopNote(craftName, "writing the judge"));
1159
1179
  sm.recordHistoryEntry(judgeCraftSession, judgeCraftUserMsg, true);
1160
1180
  sm.appendToSessionFile(judgeCraftSession, judgeCraftUserMsg);
1161
1181
  sendToSession(judgeCraftSession.localId, judgeCraftUserMsg);
@@ -1163,7 +1183,7 @@ function attachLoop(ctx) {
1163
1183
  onProcessingChanged();
1164
1184
  judgeCraftSession.sentToolResults = {};
1165
1185
  sendToSession(judgeCraftSession.localId, { type: "status", status: "processing" });
1166
- sdk.startQuery(judgeCraftSession, judgeCraftPrompt, undefined, getLinuxUserForSession(judgeCraftSession), INITIATORS.LOOP);
1186
+ sdk.startQuery(judgeCraftSession, judgeCraftPrompt, undefined, getLinuxUserForSession(judgeCraftSession), INITIATORS.LOOP, judgeCraftUserMsg.messageId);
1167
1187
 
1168
1188
  send({ type: "ralph_crafting_started", sessionId: judgeCraftSession.localId, taskId: newLoopId, source: recordSource });
1169
1189
  send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: judgeCraftSession.localId });
@@ -1232,7 +1252,7 @@ function attachLoop(ctx) {
1232
1252
  // lr-2ea2a7: routes through the shared history-cap helper (see
1233
1253
  // grep-guard test); single object instance shared across the heap
1234
1254
  // entry, the durable append, and the client send.
1235
- var craftingUserMsg = { type: "user_message", text: craftingPrompt };
1255
+ var craftingUserMsg = consoleTurnEntry(INITIATORS.LOOP, craftingPrompt, loopNote(craftName, "crafting the loop files"));
1236
1256
  sm.recordHistoryEntry(craftingSession, craftingUserMsg, true);
1237
1257
  sm.appendToSessionFile(craftingSession, craftingUserMsg);
1238
1258
  sendToSession(craftingSession.localId, craftingUserMsg);
@@ -1240,7 +1260,7 @@ function attachLoop(ctx) {
1240
1260
  onProcessingChanged();
1241
1261
  craftingSession.sentToolResults = {};
1242
1262
  sendToSession(craftingSession.localId, { type: "status", status: "processing" });
1243
- sdk.startQuery(craftingSession, craftingPrompt, undefined, getLinuxUserForSession(craftingSession), INITIATORS.LOOP);
1263
+ sdk.startQuery(craftingSession, craftingPrompt, undefined, getLinuxUserForSession(craftingSession), INITIATORS.LOOP, craftingUserMsg.messageId);
1244
1264
 
1245
1265
  send({ type: "ralph_crafting_started", sessionId: craftingSession.localId, taskId: newLoopId, source: recordSource });
1246
1266
  send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: craftingSession.localId });
@@ -1391,6 +1411,7 @@ function attachLoop(ctx) {
1391
1411
  recurrenceEnd: sData.recurrenceEnd || null,
1392
1412
  skipIfRunning: sData.skipIfRunning !== undefined ? sData.skipIfRunning : true,
1393
1413
  intervalEnd: sData.intervalEnd || null,
1414
+ approveToolsAutomatically: sData.approveToolsAutomatically,
1394
1415
  });
1395
1416
  return true;
1396
1417
  }
@@ -1458,7 +1479,13 @@ function attachLoop(ctx) {
1458
1479
  }
1459
1480
 
1460
1481
  if (msg.type === "loop_registry_update") {
1461
- var updatedRec = loopRegistry.update(msg.id, msg.data || {});
1482
+ var updateData = msg.data || {};
1483
+ // The tool-approval choice alone is not a reschedule: update() would
1484
+ // recompute the next run, which can re-arm a one-off that already ran.
1485
+ var approvalOnly = Object.keys(updateData).length === 1 && typeof updateData.approveToolsAutomatically === "boolean";
1486
+ var updatedRec = approvalOnly
1487
+ ? loopRegistry.updateRecord(msg.id, updateData)
1488
+ : loopRegistry.update(msg.id, updateData);
1462
1489
  if (!updatedRec) {
1463
1490
  sendTo(ws, { type: "loop_registry_error", text: "Record not found" });
1464
1491
  }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+
3
+ // The WebSocket side of the server-wide permission settings
4
+ // (lib/permission-settings.js): one message to change them, answered to every
5
+ // client of the server so an open settings page follows the change.
6
+
7
+ var { pickSettingChanges, settingsMessage } = require("./permission-settings");
8
+
9
+ /**
10
+ * Whether a connection may change a server-wide setting: an administrator only
11
+ * (the server default mode is gated the same way). In single-user mode the
12
+ * authenticated connection is the implicit administrator (projectAccess.isAdmin).
13
+ */
14
+ function isServerAdmin(projectAccess, ws) {
15
+ if (!projectAccess || typeof projectAccess.isAdmin !== "function") return false;
16
+ return !!projectAccess.isAdmin(ws._clagenticUser, projectAccess.authOf(ws));
17
+ }
18
+
19
+ /**
20
+ * ctx fields: slug, sendTo, send, opts, projectAccess,
21
+ * checkRequestedMode(session, mode, what) -> {ok, error}
22
+ */
23
+ function attachPermissionSettings(ctx) {
24
+ var opts = ctx.opts || {};
25
+
26
+ function refuse(ws, text) {
27
+ ctx.sendTo(ws, { type: "error", text: text });
28
+ return true;
29
+ }
30
+
31
+ /** Returns true when msg was a permission-settings message (handled). */
32
+ function handlePermissionSettingsMessage(ws, msg) {
33
+ if (msg.type !== "set_permission_settings") return false;
34
+ if (!isServerAdmin(ctx.projectAccess, ws)) {
35
+ console.warn("[project-permission-settings] refused set_permission_settings in " + ctx.slug + ": caller is not an admin");
36
+ return refuse(ws, "Only admins can change the server permission settings.");
37
+ }
38
+ var picked = pickSettingChanges(msg);
39
+ if (picked.rejected.length > 0) {
40
+ return refuse(ws, "Unknown or invalid permission setting: " + picked.rejected.join(", "));
41
+ }
42
+ if (picked.values.openedSessionMode !== undefined) {
43
+ var verdict = ctx.checkRequestedMode(null, picked.values.openedSessionMode, "set_permission_settings openedSessionMode");
44
+ if (!verdict.ok) return refuse(ws, verdict.error);
45
+ }
46
+ if (Object.keys(picked.values).length === 0) return true;
47
+ if (typeof opts.onSetPermissionSettings !== "function" || typeof opts.onGetPermissionSettings !== "function") {
48
+ return refuse(ws, "The server cannot store permission settings.");
49
+ }
50
+ opts.onSetPermissionSettings(picked.values);
51
+ var announce = typeof opts.broadcastAll === "function" ? opts.broadcastAll : ctx.send;
52
+ announce(settingsMessage(opts.onGetPermissionSettings()));
53
+ return true;
54
+ }
55
+
56
+ return { handlePermissionSettingsMessage: handlePermissionSettingsMessage };
57
+ }
58
+
59
+ module.exports = { attachPermissionSettings: attachPermissionSettings, isServerAdmin: isServerAdmin };
@@ -16,7 +16,9 @@ var promptKinds = require("./prompt-kinds");
16
16
  var { mayAnswerPrompt } = require("./prompt-access");
17
17
  var { ownValue } = require("./prompt-kinds/codecs");
18
18
  var { INITIATORS } = require("./turn-initiator");
19
+ var { stampRecord } = require("./injected-sender");
19
20
  var promptSource = require("./prompt-source");
21
+ var { effectiveSessionMode } = require("./sessions");
20
22
 
21
23
  // alias type -> { toPrompt(msg), kinds it may answer, stale reply type }
22
24
  var LEGACY_RESPONSES = {
@@ -57,11 +59,13 @@ function attachPromptResponses(ctx) {
57
59
  var onProcessingChanged = ctx.onProcessingChanged || function () {};
58
60
  var ensureProjectAccessForSession = ctx.ensureProjectAccessForSession;
59
61
 
60
- function sendConfigState() {
61
- send({
62
+ // The config card for ONE session, with that session's own mode. A plan
63
+ // answer changes the answering session only, so only its viewers hear it.
64
+ function sendConfigState(session) {
65
+ sendToSession(session.localId, {
62
66
  type: "config_state",
63
- model: sm.currentModel || "",
64
- mode: sm.currentPermissionMode,
67
+ model: sm.effectiveSessionModel ? sm.effectiveSessionModel(session) : (sm.currentModel || ""),
68
+ mode: effectiveSessionMode(session, sm),
65
69
  effort: sm.currentEffort || CONFIG_STATE_DEFAULTS.effort,
66
70
  betas: sm.currentBetas || [],
67
71
  thinking: sm.currentThinking || CONFIG_STATE_DEFAULTS.thinking,
@@ -72,12 +76,12 @@ function attachPromptResponses(ctx) {
72
76
  // A user message delivered to the session as if typed, starting a query
73
77
  // when none is running.
74
78
  function deliverUserMessage(session, text) {
75
- var userMsg = { type: "user_message", text: text };
79
+ var userMsg = stampRecord({ type: "user_message", text: text, initiator: INITIATORS.HUMAN });
76
80
  sm.recordHistoryEntry(session, userMsg, true);
77
81
  sm.appendToSessionFile(session, userMsg);
78
82
  sendToSession(session.localId, userMsg);
79
83
  if (session.isProcessing) {
80
- sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN);
84
+ sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN, userMsg.messageId);
81
85
  return;
82
86
  }
83
87
  session.isProcessing = true;
@@ -85,9 +89,9 @@ function attachPromptResponses(ctx) {
85
89
  session.sentToolResults = {};
86
90
  sendToSession(session.localId, { type: "status", status: "processing" });
87
91
  if (!session.queryInstance && !session.worker) {
88
- sdk.startQuery(session, text, undefined, ensureProjectAccessForSession(session), INITIATORS.HUMAN);
92
+ sdk.startQuery(session, text, undefined, ensureProjectAccessForSession(session), INITIATORS.HUMAN, userMsg.messageId);
89
93
  } else {
90
- sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN);
94
+ sdk.pushMessage(session, text, undefined, INITIATORS.HUMAN, userMsg.messageId);
91
95
  }
92
96
  }
93
97
 
@@ -106,8 +110,11 @@ function attachPromptResponses(ctx) {
106
110
  if (session.abortController) session.abortController.abort();
107
111
  });
108
112
 
109
- sm.currentPermissionMode = "acceptEdits";
110
- sendConfigState();
113
+ // Only the answering session's mode changes (the new session's is set
114
+ // below); the project default and every other session are untouched.
115
+ session.permissionMode = "acceptEdits";
116
+ sm.saveSessionFile(session);
117
+ sendConfigState(session);
111
118
 
112
119
  var planPrompt;
113
120
  if (planContent) {
@@ -124,8 +131,9 @@ function attachPromptResponses(ctx) {
124
131
  new Promise(function (resolve) { setTimeout(resolve, 3000); }),
125
132
  ]).then(function () {
126
133
  try {
127
- var newSession = sm.createSession(null, ws);
128
- var userMsg = { type: "user_message", text: planPrompt, planContent: planContent || null };
134
+ // Given at creation so the first session_switched carries it.
135
+ var newSession = sm.createSession({ permissionMode: "acceptEdits" }, ws);
136
+ var userMsg = stampRecord({ type: "user_message", text: planPrompt, planContent: planContent || null, initiator: INITIATORS.HUMAN });
129
137
  sm.recordHistoryEntry(newSession, userMsg, true);
130
138
  sm.appendToSessionFile(newSession, userMsg);
131
139
  newSession.title = "Plan execution (cleared context)";
@@ -138,7 +146,8 @@ function attachPromptResponses(ctx) {
138
146
  newSession.sentToolResults = {};
139
147
  sendToSession(newSession.localId, { type: "status", status: "processing" });
140
148
  newSession.acceptEditsAfterStart = true;
141
- sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession), INITIATORS.HUMAN);
149
+ sm.saveSessionFile(newSession);
150
+ sdk.startQuery(newSession, planPrompt, undefined, ensureProjectAccessForSession(newSession), INITIATORS.HUMAN, userMsg.messageId);
142
151
  } catch (e) {
143
152
  console.error("[project] Error starting plan execution:", e);
144
153
  if (ws) sendTo(ws, { type: "error", text: "Failed to start plan execution: " + (e.message || e) });
@@ -151,8 +160,9 @@ function attachPromptResponses(ctx) {
151
160
  function applyPlanDecision(ws, session, prompt, response) {
152
161
  if (response.decision === "allow_accept_edits") {
153
162
  sdk.setPermissionMode(session, "acceptEdits");
154
- sm.currentPermissionMode = "acceptEdits";
155
- sendConfigState();
163
+ session.permissionMode = "acceptEdits";
164
+ sm.saveSessionFile(session);
165
+ sendConfigState(session);
156
166
  } else if (response.decision === "allow_clear_context") {
157
167
  executePlanInFreshContext(ws, session, prompt, response.planContent || "");
158
168
  } else if (response.decision === "deny_with_feedback" && response.feedback) {