@prestyj/cli 5.33.0 → 5.34.0

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 (218) hide show
  1. package/README.md +16 -16
  2. package/dist/app-sidecar/app-settings.js +3 -0
  3. package/dist/app-sidecar/app-settings.js.map +1 -1
  4. package/dist/app-sidecar/autopilot-runner.d.ts +7 -0
  5. package/dist/app-sidecar/autopilot-runner.js +79 -19
  6. package/dist/app-sidecar/autopilot-runner.js.map +1 -1
  7. package/dist/app-sidecar/live-preview/dev-url.d.ts +32 -0
  8. package/dist/app-sidecar/live-preview/dev-url.js +97 -0
  9. package/dist/app-sidecar/live-preview/dev-url.js.map +1 -0
  10. package/dist/app-sidecar/live-preview/frame-server.d.ts +31 -0
  11. package/dist/app-sidecar/live-preview/frame-server.js +193 -0
  12. package/dist/app-sidecar/live-preview/frame-server.js.map +1 -0
  13. package/dist/app-sidecar/live-preview/manager.d.ts +44 -0
  14. package/dist/app-sidecar/live-preview/manager.js +215 -0
  15. package/dist/app-sidecar/live-preview/manager.js.map +1 -0
  16. package/dist/app-sidecar/live-preview/proxy.d.ts +30 -0
  17. package/dist/app-sidecar/live-preview/proxy.js +235 -0
  18. package/dist/app-sidecar/live-preview/proxy.js.map +1 -0
  19. package/dist/app-sidecar/live-preview/routes.d.ts +4 -0
  20. package/dist/app-sidecar/live-preview/routes.js +52 -0
  21. package/dist/app-sidecar/live-preview/routes.js.map +1 -0
  22. package/dist/app-sidecar/live-preview/servers.d.ts +36 -0
  23. package/dist/app-sidecar/live-preview/servers.js +228 -0
  24. package/dist/app-sidecar/live-preview/servers.js.map +1 -0
  25. package/dist/app-sidecar/mcp-routes.js +9 -0
  26. package/dist/app-sidecar/mcp-routes.js.map +1 -1
  27. package/dist/app-sidecar/mcp-shell-command.d.ts +36 -0
  28. package/dist/app-sidecar/mcp-shell-command.js +302 -0
  29. package/dist/app-sidecar/mcp-shell-command.js.map +1 -0
  30. package/dist/app-sidecar/mcp-sync.d.ts +18 -0
  31. package/dist/app-sidecar/mcp-sync.js +38 -0
  32. package/dist/app-sidecar/mcp-sync.js.map +1 -0
  33. package/dist/app-sidecar/prompt-routes.js +31 -26
  34. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  35. package/dist/app-sidecar/route-context.d.ts +3 -1
  36. package/dist/app-sidecar/run-control-routes.js +8 -1
  37. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  38. package/dist/app-sidecar/shell-routes.js +7 -0
  39. package/dist/app-sidecar/shell-routes.js.map +1 -1
  40. package/dist/app-sidecar/task-routes.js +1 -1
  41. package/dist/app-sidecar/task-routes.js.map +1 -1
  42. package/dist/app-sidecar/workspace-routes.js +35 -37
  43. package/dist/app-sidecar/workspace-routes.js.map +1 -1
  44. package/dist/app-sidecar.js +136 -38
  45. package/dist/app-sidecar.js.map +1 -1
  46. package/dist/cli/mcp.js +19 -5
  47. package/dist/cli/mcp.js.map +1 -1
  48. package/dist/cli/shared.js +4 -0
  49. package/dist/cli/shared.js.map +1 -1
  50. package/dist/cli.js +13 -3
  51. package/dist/cli.js.map +1 -1
  52. package/dist/config.js +2 -0
  53. package/dist/config.js.map +1 -1
  54. package/dist/core/agent-session/mcp-tools.d.ts +17 -0
  55. package/dist/core/agent-session/mcp-tools.js +31 -0
  56. package/dist/core/agent-session/mcp-tools.js.map +1 -1
  57. package/dist/core/agent-session/verification-tracker.js +2 -10
  58. package/dist/core/agent-session/verification-tracker.js.map +1 -1
  59. package/dist/core/agent-session.d.ts +29 -0
  60. package/dist/core/agent-session.js +196 -11
  61. package/dist/core/agent-session.js.map +1 -1
  62. package/dist/core/agents.d.ts +0 -10
  63. package/dist/core/agents.js +5 -1
  64. package/dist/core/agents.js.map +1 -1
  65. package/dist/core/ask-user.d.ts +2 -0
  66. package/dist/core/ask-user.js +8 -1
  67. package/dist/core/ask-user.js.map +1 -1
  68. package/dist/core/checklist-items.d.ts +2 -2
  69. package/dist/core/checklist-items.js +14 -2
  70. package/dist/core/checklist-items.js.map +1 -1
  71. package/dist/core/checklist-prompt.d.ts +1 -1
  72. package/dist/core/checklist-prompt.js +1 -1
  73. package/dist/core/claude-code/complete.d.ts +2 -0
  74. package/dist/core/claude-code/complete.js +3 -0
  75. package/dist/core/claude-code/complete.js.map +1 -1
  76. package/dist/core/claude-code/transcripts.d.ts +29 -0
  77. package/dist/core/claude-code/transcripts.js +117 -0
  78. package/dist/core/claude-code/transcripts.js.map +1 -0
  79. package/dist/core/codex-request-shape.js +1 -1
  80. package/dist/core/compaction/compactor.d.ts +2 -0
  81. package/dist/core/compaction/compactor.js +7 -3
  82. package/dist/core/compaction/compactor.js.map +1 -1
  83. package/dist/core/compaction/plan-step-policy.d.ts +1 -1
  84. package/dist/core/compaction/plan-step-policy.js +1 -1
  85. package/dist/core/compaction/policy.js +3 -2
  86. package/dist/core/compaction/policy.js.map +1 -1
  87. package/dist/core/compaction/tool-result-pruner.d.ts +12 -2
  88. package/dist/core/compaction/tool-result-pruner.js +14 -3
  89. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  90. package/dist/core/extensions/plugin-bundles.d.ts +0 -9
  91. package/dist/core/extensions/plugin-bundles.js +0 -185
  92. package/dist/core/extensions/plugin-bundles.js.map +1 -1
  93. package/dist/core/goals-store.d.ts +0 -2
  94. package/dist/core/goals-store.js +0 -5
  95. package/dist/core/goals-store.js.map +1 -1
  96. package/dist/core/live-preview.d.ts +24 -0
  97. package/dist/core/live-preview.js +76 -0
  98. package/dist/core/live-preview.js.map +1 -0
  99. package/dist/core/mcp/client.d.ts +9 -0
  100. package/dist/core/mcp/client.js +58 -5
  101. package/dist/core/mcp/client.js.map +1 -1
  102. package/dist/core/mcp/oauth-provider.d.ts +7 -1
  103. package/dist/core/mcp/oauth-provider.js +11 -4
  104. package/dist/core/mcp/oauth-provider.js.map +1 -1
  105. package/dist/core/mcp/oauth-store.d.ts +6 -0
  106. package/dist/core/mcp/oauth-store.js +14 -0
  107. package/dist/core/mcp/oauth-store.js.map +1 -1
  108. package/dist/core/mcp/parse-add-command.d.ts +29 -3
  109. package/dist/core/mcp/parse-add-command.js +196 -26
  110. package/dist/core/mcp/parse-add-command.js.map +1 -1
  111. package/dist/core/mcp/store.d.ts +16 -0
  112. package/dist/core/mcp/store.js +28 -0
  113. package/dist/core/mcp/store.js.map +1 -1
  114. package/dist/core/mcp/types.d.ts +9 -0
  115. package/dist/core/nolan-ask-answer.d.ts +24 -0
  116. package/dist/core/nolan-ask-answer.js +96 -0
  117. package/dist/core/nolan-ask-answer.js.map +1 -0
  118. package/dist/core/nolan-context.d.ts +20 -0
  119. package/dist/core/nolan-context.js +55 -0
  120. package/dist/core/nolan-context.js.map +1 -1
  121. package/dist/core/nolan-prompt.js +6 -0
  122. package/dist/core/nolan-prompt.js.map +1 -1
  123. package/dist/core/opencode-catalog-store.d.ts +20 -0
  124. package/dist/core/opencode-catalog-store.js +82 -0
  125. package/dist/core/opencode-catalog-store.js.map +1 -0
  126. package/dist/core/package-cooldown.d.ts +0 -2
  127. package/dist/core/package-cooldown.js +0 -4
  128. package/dist/core/package-cooldown.js.map +1 -1
  129. package/dist/core/process-manager.d.ts +1 -1
  130. package/dist/core/process-manager.js +1 -1
  131. package/dist/core/prompt-commands.js +66 -33
  132. package/dist/core/prompt-commands.js.map +1 -1
  133. package/dist/core/runtime-mode.d.ts +0 -8
  134. package/dist/core/runtime-mode.js.map +1 -1
  135. package/dist/core/session-history.js +15 -3
  136. package/dist/core/session-history.js.map +1 -1
  137. package/dist/core/session-manager.d.ts +5 -0
  138. package/dist/core/session-manager.js +12 -7
  139. package/dist/core/session-manager.js.map +1 -1
  140. package/dist/core/session-storage.d.ts +0 -2
  141. package/dist/core/session-storage.js +0 -2
  142. package/dist/core/session-storage.js.map +1 -1
  143. package/dist/core/settings-manager.d.ts +2 -0
  144. package/dist/core/settings-manager.js +3 -1
  145. package/dist/core/settings-manager.js.map +1 -1
  146. package/dist/core/shell-path.d.ts +2 -0
  147. package/dist/core/shell-path.js +10 -1
  148. package/dist/core/shell-path.js.map +1 -1
  149. package/dist/core/skills.d.ts +2 -0
  150. package/dist/core/skills.js +5 -0
  151. package/dist/core/skills.js.map +1 -1
  152. package/dist/core/subagent-policy.js +1 -1
  153. package/dist/core/subagent-policy.js.map +1 -1
  154. package/dist/core/task-store.d.ts +0 -1
  155. package/dist/core/task-store.js +0 -3
  156. package/dist/core/task-store.js.map +1 -1
  157. package/dist/core/trophies/catalog-more.js +3 -3
  158. package/dist/core/trophies/catalog-more.js.map +1 -1
  159. package/dist/core/trophies/catalog.js +3 -3
  160. package/dist/core/trophies/catalog.js.map +1 -1
  161. package/dist/modes/acp-mode.d.ts +1 -1
  162. package/dist/motion-agent/motion-review.d.ts +0 -75
  163. package/dist/motion-agent/motion-review.js +0 -189
  164. package/dist/motion-agent/motion-review.js.map +1 -1
  165. package/dist/system-prompt.d.ts +5 -1
  166. package/dist/system-prompt.js +14 -7
  167. package/dist/system-prompt.js.map +1 -1
  168. package/dist/test-support/system-tools.d.ts +6 -0
  169. package/dist/test-support/system-tools.js +36 -0
  170. package/dist/test-support/system-tools.js.map +1 -0
  171. package/dist/tools/ask-user.js +2 -1
  172. package/dist/tools/ask-user.js.map +1 -1
  173. package/dist/tools/bash.d.ts +2 -2
  174. package/dist/tools/bash.js +363 -358
  175. package/dist/tools/bash.js.map +1 -1
  176. package/dist/tools/live-preview.d.ts +21 -0
  177. package/dist/tools/live-preview.js +37 -0
  178. package/dist/tools/live-preview.js.map +1 -0
  179. package/dist/tools/path-utils.d.ts +0 -15
  180. package/dist/tools/path-utils.js +0 -17
  181. package/dist/tools/path-utils.js.map +1 -1
  182. package/dist/tools/truncate.d.ts +0 -2
  183. package/dist/tools/truncate.js +0 -2
  184. package/dist/tools/truncate.js.map +1 -1
  185. package/dist/tools/web-fetch.d.ts +7 -1
  186. package/dist/tools/web-fetch.js +15 -4
  187. package/dist/tools/web-fetch.js.map +1 -1
  188. package/dist/ui/App.js +0 -1
  189. package/dist/ui/App.js.map +1 -1
  190. package/dist/ui/app-items.d.ts +0 -2
  191. package/dist/ui/app-items.js +0 -2
  192. package/dist/ui/app-items.js.map +1 -1
  193. package/dist/ui/components/Footer.js +4 -4
  194. package/dist/ui/components/Footer.js.map +1 -1
  195. package/dist/ui/components/ModelSelector.js +2 -0
  196. package/dist/ui/components/ModelSelector.js.map +1 -1
  197. package/dist/ui/constants/figures.d.ts +0 -8
  198. package/dist/ui/constants/figures.js +0 -8
  199. package/dist/ui/constants/figures.js.map +1 -1
  200. package/dist/ui/layout-decisions.d.ts +0 -5
  201. package/dist/ui/layout-decisions.js +1 -10
  202. package/dist/ui/layout-decisions.js.map +1 -1
  203. package/dist/ui/terminal-history-status-renderers.d.ts +0 -1
  204. package/dist/ui/terminal-history-status-renderers.js +0 -12
  205. package/dist/ui/terminal-history-status-renderers.js.map +1 -1
  206. package/dist/ui/transcript/presentation.d.ts +1 -2
  207. package/dist/ui/transcript/presentation.js +0 -4
  208. package/dist/ui/transcript/presentation.js.map +1 -1
  209. package/dist/utils/image.d.ts +0 -4
  210. package/dist/utils/image.js +0 -10
  211. package/dist/utils/image.js.map +1 -1
  212. package/dist/web.d.ts +5 -0
  213. package/dist/web.js +5 -0
  214. package/dist/web.js.map +1 -0
  215. package/package.json +9 -5
  216. package/dist/motion-agent/motion-review-gate.d.ts +0 -48
  217. package/dist/motion-agent/motion-review-gate.js +0 -88
  218. package/dist/motion-agent/motion-review-gate.js.map +0 -1
@@ -13,12 +13,13 @@ import { loadWorkspaceCustomCommands } from "./custom-commands.js";
13
13
  import { expandPromptCommand } from "./prompt-command-expansion.js";
14
14
  import { SettingsManager } from "./settings-manager.js";
15
15
  import { AuthStorage, NotLoggedInError } from "./auth-storage.js";
16
- import { dualAuthProvider } from "@prestyj/core";
16
+ import { claudeCodeConfigDir, dualAuthProvider } from "@prestyj/core";
17
17
  import { getClaudeCliUserAgent } from "./claude-code-version.js";
18
+ import { claudeCodeTranscriptExists, holdClaudeCodeTranscript, pruneClaudeCodeTranscriptsOnce, } from "./claude-code/transcripts.js";
18
19
  import { runSideWebSearch, runSideWebSearchViaClaudeCode, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
19
20
  import { kimiCodingHeaders, isKimiCodingEndpoint } from "./oauth/kimi.js";
20
21
  import { isGrokCliEndpoint } from "./oauth/xai.js";
21
- import { SessionManager, } from "./session-manager.js";
22
+ import { SessionManager, processIsAlive, } from "./session-manager.js";
22
23
  import { ExtensionLoader } from "./extensions/loader.js";
23
24
  import { shouldCompact, compact, } from "./compaction/compactor.js";
24
25
  import { getHistoryMessageVisibility } from "./session-history.js";
@@ -446,6 +447,8 @@ export class AgentSession {
446
447
  */
447
448
  /** Commands the user ran themselves, held until their next message. */
448
449
  pendingUserShell = [];
450
+ /** MCP servers the user added or removed mid-session, not yet told to the model. */
451
+ pendingMcpNotices = [];
449
452
  persistedTranscriptCount() {
450
453
  return this.messages.slice(0, this.lastPersistedIndex).filter((m) => m.role !== "system")
451
454
  .length;
@@ -756,6 +759,7 @@ export class AgentSession {
756
759
  message: error instanceof Error ? error.message : String(error),
757
760
  });
758
761
  });
762
+ void pruneClaudeCodeTranscriptsOnce(claudeCodeConfigDir());
759
763
  }
760
764
  // EZ Coder owns its command registry. Other agents start with an isolated
761
765
  // empty registry and can register their own commands in their own file.
@@ -881,7 +885,9 @@ export class AgentSession {
881
885
  // empty catalog and tool_search would answer "the catalog is empty" for
882
886
  // capabilities that genuinely exist — a wrong answer, not a slow one.
883
887
  await this.seedMcpCatalogFromCache(servers);
884
- const connected = await mcpManager.connectAll(servers);
888
+ const results = await mcpManager.connectAllDetailed(servers);
889
+ this.mcp.recordServers(servers, results);
890
+ const connected = results.flatMap((r) => r.tools);
885
891
  // Defense-in-depth: even from a whitelisted server, only push tools that
886
892
  // pass the allow-list (no-op when there's no allow-list).
887
893
  const mcpTools = this.opts.allowedTools
@@ -907,6 +913,80 @@ export class AgentSession {
907
913
  log("WARN", "mcp", `MCP initialization failed: ${err instanceof Error ? err.message : String(err)}`);
908
914
  }
909
915
  }
916
+ /**
917
+ * The user added, changed or removed one MCP server mid-session: connect,
918
+ * reconnect or drop just that server, without a restart. `config` is its
919
+ * current effective config, or undefined when it is gone (or not allowed).
920
+ *
921
+ * Append-only for the prompt cache: new tools go into the tool_search
922
+ * catalog (or are appended when deferral is off), and the model learns about
923
+ * the change from a hidden note with the next message, never from a
924
+ * re-rendered system prompt. Returns null when nothing changed here.
925
+ */
926
+ async applyMcpServerChange(name, config) {
927
+ const manager = this.mcp.manager;
928
+ if (!manager)
929
+ return null;
930
+ const whitelist = this.opts.allowedMcpServers;
931
+ if (this.opts.allowedTools && !whitelist?.includes(name))
932
+ return null;
933
+ const wanted = config && config.enabled !== false ? config : undefined;
934
+ const previous = this.mcp.serverState(name);
935
+ // Same config still connected: nothing to do. Same config that failed
936
+ // (e.g. before an OAuth sign-in) is retried.
937
+ if (wanted && previous?.ok && previous.config === JSON.stringify(wanted))
938
+ return null;
939
+ if (!wanted && !previous)
940
+ return null;
941
+ if (previous) {
942
+ await manager.disconnect(name);
943
+ this.mcp.removeServer(name);
944
+ }
945
+ if (!wanted) {
946
+ this.pendingMcpNotices.push(`- MCP server "${name}" was removed by the user. Its mcp__${name}__* tools no longer work; don't call them.`);
947
+ log("INFO", "mcp", `Removed MCP server "${name}" mid-session`);
948
+ return { name, removed: true, connected: false, toolCount: 0 };
949
+ }
950
+ const [result] = await manager.connectAllDetailed([wanted]);
951
+ const ok = result?.ok ?? false;
952
+ this.mcp.recordServers([wanted], result ? [result] : []);
953
+ const tools = (result?.tools ?? []).filter((t) => !this.opts.allowedTools || this.isToolAllowed(t.name));
954
+ this.addMcpTools(tools);
955
+ if (ok) {
956
+ const deferred = !this.opts.allowedTools && this.settingsManager.get("deferredMcpTools");
957
+ const names = tools.map((t) => t.name);
958
+ const shown = names.slice(0, 20).join(", ") + (names.length > 20 ? ", …" : "");
959
+ this.pendingMcpNotices.push(`- The user connected MCP server "${name}" with ${tools.length} tool${tools.length === 1 ? "" : "s"}` +
960
+ (names.length > 0 ? `: ${shown}.` : ".") +
961
+ (deferred
962
+ ? " Load them with tool_search (e.g. by capability or the server name) when they help."
963
+ : " They are in your tool list now."));
964
+ }
965
+ log("INFO", "mcp", `Applied MCP server "${name}" mid-session`, {
966
+ ok: String(ok),
967
+ tools: String(tools.length),
968
+ });
969
+ return {
970
+ name,
971
+ removed: false,
972
+ connected: ok,
973
+ toolCount: tools.length,
974
+ ...(result?.error ? { error: result.error } : {}),
975
+ ...(result?.requiresAuth ? { requiresAuth: true } : {}),
976
+ };
977
+ }
978
+ takeMcpNotice() {
979
+ if (this.pendingMcpNotices.length === 0)
980
+ return null;
981
+ const lines = this.pendingMcpNotices.splice(0);
982
+ return {
983
+ role: "user",
984
+ provenance: { source: "runtime", kind: "notification", visibility: "hidden" },
985
+ content: "MCP update. The user changed MCP servers during this session:\n" +
986
+ lines.join("\n") +
987
+ "\nTrust this over anything earlier that disagrees. Do not restate this note; just proceed.",
988
+ };
989
+ }
910
990
  /** Persist `cwd` as a trusted project for project-scope MCP. Called by the
911
991
  * sidecar's `/mcp/add` handler when a user adds a project-scope server via
912
992
  * the MCP modal — the explicit add is itself the trust signal. The next
@@ -1069,7 +1149,14 @@ export class AgentSession {
1069
1149
  /** One run on the Claude subscription route: Claude Code drives the loop with our prompt and tools. */
1070
1150
  async runClaudeCodeLoop(process, options) {
1071
1151
  let loopMessages = await this.prepareDynamicContext();
1072
- const resume = claudeCodeResumeId(this.claudeCodeSession, loopMessages);
1152
+ let resume = claudeCodeResumeId(this.claudeCodeSession, loopMessages);
1153
+ // Claude Code fails a resume whose transcript is gone (retention pass, or
1154
+ // removed by hand); our history can seed a fresh session instead.
1155
+ if (resume &&
1156
+ !(await claudeCodeTranscriptExists(process.env.CLAUDE_CONFIG_DIR ?? claudeCodeConfigDir(), resume))) {
1157
+ log("INFO", "claude-code", "Transcript missing; seeding a fresh session from history");
1158
+ resume = undefined;
1159
+ }
1073
1160
  // A fresh Claude Code session gets our history as text; summarize it first
1074
1161
  // when it would not fit.
1075
1162
  if (!resume &&
@@ -1135,6 +1222,35 @@ export class AgentSession {
1135
1222
  policy: CLAUDE_CODE_CACHE_TTL,
1136
1223
  });
1137
1224
  }
1225
+ // Same line names as the public-API route, which logs them from the agent loop.
1226
+ if (event.type === "turn_end") {
1227
+ const cacheRead = event.usage.cacheRead ?? 0;
1228
+ const cacheWrite = event.usage.cacheWrite ?? 0;
1229
+ const promptTokens = event.usage.inputTokens + cacheRead + cacheWrite;
1230
+ log("INFO", "stream", "cache_health", {
1231
+ promptTokens,
1232
+ cacheRead,
1233
+ cacheWrite,
1234
+ ...(promptTokens > 0
1235
+ ? { ratio: Math.round((cacheRead / promptTokens) * 100) / 100 }
1236
+ : {}),
1237
+ ...(event.timing.ttftMs !== undefined ? { ttftMs: event.timing.ttftMs } : {}),
1238
+ providerDurationMs: event.timing.providerDurationMs,
1239
+ outputTokens: event.usage.outputTokens,
1240
+ provider: this.provider,
1241
+ model: this.model,
1242
+ transport: "claude_code",
1243
+ });
1244
+ }
1245
+ else if (event.type === "retry") {
1246
+ log("INFO", "stream", "retry", {
1247
+ reason: event.reason,
1248
+ attempt: event.attempt,
1249
+ maxAttempts: event.maxAttempts,
1250
+ delayMs: event.delayMs,
1251
+ transport: "claude_code",
1252
+ });
1253
+ }
1138
1254
  this.eventBus.forwardAgentEvent(event);
1139
1255
  }
1140
1256
  }
@@ -1202,6 +1318,7 @@ export class AgentSession {
1202
1318
  const history = this.messages.filter((m) => m.role !== "system");
1203
1319
  const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
1204
1320
  this.claudeCodeSession = state;
1321
+ this.holdClaudeCodeTranscript();
1205
1322
  if (!this.sessionPath)
1206
1323
  return;
1207
1324
  await this.sessionManager.appendEntry(this.sessionPath, {
@@ -1229,6 +1346,26 @@ export class AgentSession {
1229
1346
  this.tools.push(tool);
1230
1347
  return tool;
1231
1348
  }
1349
+ // A restored conversation still calls the on-demand tools it used; Claude
1350
+ // Code refuses any name missing from the list this process gives it.
1351
+ reloadUsedTools(messages) {
1352
+ if (this.deferredBuiltinToolNames.length === 0)
1353
+ return;
1354
+ for (const message of messages) {
1355
+ if (message.role === "assistant" && Array.isArray(message.content)) {
1356
+ for (const part of message.content) {
1357
+ if (part.type === "tool_call")
1358
+ this.promoteDeferredBuiltin(part.name);
1359
+ }
1360
+ }
1361
+ else if (message.role === "tool") {
1362
+ for (const result of message.content) {
1363
+ for (const name of result.loadedTools ?? [])
1364
+ this.promoteDeferredBuiltin(name);
1365
+ }
1366
+ }
1367
+ }
1368
+ }
1232
1369
  wrapToPromote(trigger, followUps, when = () => true) {
1233
1370
  const index = this.tools.findIndex((t) => t.name === trigger);
1234
1371
  const tool = index >= 0 ? this.tools[index] : undefined;
@@ -1651,6 +1788,7 @@ export class AgentSession {
1651
1788
  if (planNotice) {
1652
1789
  log("INFO", "session", "Injecting plan state update instead of rebuilding the prompt");
1653
1790
  }
1791
+ const mcpNotice = this.takeMcpNotice();
1654
1792
  if (environmentDelta) {
1655
1793
  // The model has now been told; only a further change re-triggers this.
1656
1794
  this.renderedEnvironment = this.promptEnvironment();
@@ -1722,15 +1860,17 @@ export class AgentSession {
1722
1860
  return [
1723
1861
  ...(environmentDelta ? [environmentDelta] : []),
1724
1862
  ...(planNotice ? [planNotice] : []),
1863
+ ...(mcpNotice ? [mcpNotice] : []),
1725
1864
  ...(userShell ? [userShell] : []),
1726
1865
  ...steeringMessages,
1727
1866
  ...(notificationMessage ? [notificationMessage] : []),
1728
1867
  ];
1729
1868
  }
1730
- if (environmentDelta || planNotice || notificationMessage) {
1869
+ if (environmentDelta || planNotice || mcpNotice || notificationMessage) {
1731
1870
  return [
1732
1871
  ...(environmentDelta ? [environmentDelta] : []),
1733
1872
  ...(planNotice ? [planNotice] : []),
1873
+ ...(mcpNotice ? [mcpNotice] : []),
1734
1874
  ...(notificationMessage ? [notificationMessage] : []),
1735
1875
  ];
1736
1876
  }
@@ -2406,7 +2546,7 @@ export class AgentSession {
2406
2546
  if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
2407
2547
  const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
2408
2548
  const pruneResult = pruneStaleToolResults(messages, {
2409
- minimumTokens: pruneMinimumTokens(activeTokens, cacheCold),
2549
+ minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, policy.targetTokens),
2410
2550
  });
2411
2551
  if (pruneResult.pruned) {
2412
2552
  this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
@@ -2732,11 +2872,13 @@ export class AgentSession {
2732
2872
  const servers = await getAllMcpServers(this.provider, apiKey, this.cwd, {
2733
2873
  allowProjectScope: this.settingsManager.isProjectTrusted(this.cwd),
2734
2874
  });
2735
- const mcpTools = await mcpManager.connectAll(servers);
2875
+ const results = await mcpManager.connectAllDetailed(servers);
2876
+ const mcpTools = results.flatMap((r) => r.tools);
2736
2877
  // Drop stale MCP tools from both the live set and deferred catalog before
2737
2878
  // re-adding. Some tools may already have been promoted out of the catalog.
2738
2879
  this.tools = this.tools.filter((t) => !t.name.startsWith("mcp__"));
2739
2880
  this.mcp.clearMcpTools();
2881
+ this.mcp.recordServers(servers, results);
2740
2882
  this.addMcpTools(mcpTools);
2741
2883
  }
2742
2884
  catch (err) {
@@ -3027,6 +3169,18 @@ export class AgentSession {
3027
3169
  }
3028
3170
  })();
3029
3171
  }
3172
+ // A caller's token was captured at run start; the loop may have rotated it since.
3173
+ async withLiveAccessToken(captured) {
3174
+ try {
3175
+ const live = await this.authStorage.resolveCredentials(this.provider, {
3176
+ storageKeys: this.currentAuthStorageKeys(),
3177
+ });
3178
+ return { ...captured, accessToken: live.accessToken };
3179
+ }
3180
+ catch {
3181
+ return captured;
3182
+ }
3183
+ }
3030
3184
  async compact(existingCredentials, mode = "manual",
3031
3185
  /** User-stated focus (`/compact <focus>`): what must survive verbatim. */
3032
3186
  focus,
@@ -3037,12 +3191,13 @@ export class AgentSession {
3037
3191
  ? AbortSignal.any([this.opts.signal, abortSignal])
3038
3192
  : (abortSignal ?? this.opts.signal);
3039
3193
  const claudeCode = existingCredentials ? null : await this.claudeCodeProcess();
3040
- const creds = existingCredentials ??
3041
- (claudeCode
3194
+ const creds = existingCredentials
3195
+ ? await this.withLiveAccessToken(existingCredentials)
3196
+ : claudeCode
3042
3197
  ? { accessToken: "" }
3043
3198
  : await this.authStorage.resolveCredentials(this.provider, {
3044
3199
  storageKeys: this.currentAuthStorageKeys(),
3045
- }));
3200
+ });
3046
3201
  const contextWindow = getContextWindow(this.model, {
3047
3202
  provider: this.provider,
3048
3203
  accountId: creds.accountId,
@@ -3885,6 +4040,8 @@ export class AgentSession {
3885
4040
  }
3886
4041
  const toolNames = this.tools.map((tool) => tool.name);
3887
4042
  const deferredToolNames = this.deferredToolNamesForPrompt(toolNames);
4043
+ // A missing Claude Code binary fails the run itself with a clear message, not the prompt build.
4044
+ const deferredNeedSearch = deferredToolNames.length > 0 && (await this.claudeCodeProcess().then(Boolean, () => false));
3888
4045
  // Whatever is rendered now is what the model has been told.
3889
4046
  this.announcedLanguages = new Set(this.activeLanguages);
3890
4047
  if (this.agentPrompt !== undefined) {
@@ -3892,6 +4049,7 @@ export class AgentSession {
3892
4049
  cwd: this.cwd,
3893
4050
  toolNames,
3894
4051
  deferredToolNames,
4052
+ deferredNeedSearch,
3895
4053
  context: this.opts.agentContext,
3896
4054
  role: this.opts.agentRole,
3897
4055
  environment: this.recordRenderedEnvironment(),
@@ -3899,7 +4057,7 @@ export class AgentSession {
3899
4057
  ...(this.languagesApply() ? { activeLanguages: this.activeLanguages } : {}),
3900
4058
  });
3901
4059
  }
3902
- return buildSystemPrompt(this.cwd, this.skills, planMode, approvedPlanPath, toolNames, this.activeLanguages, this.provider, this.recordRenderedEnvironment(), deferredToolNames, this.contextLimits);
4060
+ return buildSystemPrompt(this.cwd, this.skills, planMode, approvedPlanPath, toolNames, this.activeLanguages, this.provider, this.recordRenderedEnvironment(), deferredToolNames, this.contextLimits, undefined, deferredNeedSearch);
3903
4061
  }
3904
4062
  /**
3905
4063
  * Bring the system prompt to the exact state the next provider request will
@@ -3928,6 +4086,12 @@ export class AgentSession {
3928
4086
  * update is saved in order with the rest of the conversation.
3929
4087
  */
3930
4088
  async announceNewLanguages() {
4089
+ const mcpNotice = this.takeMcpNotice();
4090
+ if (mcpNotice) {
4091
+ this.messages.push(mcpNotice);
4092
+ await this.persistMessage(mcpNotice);
4093
+ this.lastPersistedIndex = this.messages.length;
4094
+ }
3931
4095
  const planNotice = this.takePlanNotice();
3932
4096
  if (planNotice) {
3933
4097
  this.messages.push(planNotice);
@@ -4229,6 +4393,7 @@ export class AgentSession {
4229
4393
  generation,
4230
4394
  startedAt: new Date().toISOString(),
4231
4395
  afterMessageCount: this.persistedTranscriptCount(),
4396
+ pid: process.pid,
4232
4397
  });
4233
4398
  }
4234
4399
  /** Close the run journal. Its absence is what marks a run as crashed. */
@@ -4358,6 +4523,13 @@ export class AgentSession {
4358
4523
  prewarmController = null;
4359
4524
  /** Claude Code session that has seen this history (Claude subscription route). */
4360
4525
  claudeCodeSession = null;
4526
+ releaseClaudeCodeTranscript;
4527
+ /** Keep the retention pass off the transcript this chat would resume. */
4528
+ holdClaudeCodeTranscript() {
4529
+ this.releaseClaudeCodeTranscript?.();
4530
+ const sessionId = this.claudeCodeSession?.sessionId;
4531
+ this.releaseClaudeCodeTranscript = sessionId ? holdClaudeCodeTranscript(sessionId) : undefined;
4532
+ }
4361
4533
  /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4362
4534
  claudeCodeLive = null;
4363
4535
  /**
@@ -4530,6 +4702,8 @@ export class AgentSession {
4530
4702
  // step leaves background commands running after the app has quit.
4531
4703
  this.stopBackgroundProcesses();
4532
4704
  this.installedWatchStop?.();
4705
+ this.releaseClaudeCodeTranscript?.();
4706
+ this.releaseClaudeCodeTranscript = undefined;
4533
4707
  // Quiesce any in-flight post-turn compaction BEFORE tearing down state:
4534
4708
  // the background compact() snapshots and replaces `this.messages`, so
4535
4709
  // letting it run past this point would checkpoint a near-empty history
@@ -4655,7 +4829,9 @@ export class AgentSession {
4655
4829
  // not fail when Anthropic's stricter many-image limit activates later.
4656
4830
  const systemMsg = this.messages[0]; // Already built
4657
4831
  this.messages = [systemMsg, ...loadedMessages];
4832
+ this.reloadUsedTools(loadedMessages);
4658
4833
  this.claudeCodeSession = parseClaudeCodeSessionState(savedClaudeCode?.type === "custom" ? savedClaudeCode.data : null, loadedMessages);
4834
+ this.holdClaudeCodeTranscript();
4659
4835
  // Reads recorded for the previous conversation don't carry over.
4660
4836
  this.clearReadTracker?.();
4661
4837
  const normalizedImageCount = await normalizeMessageImages(this.messages);
@@ -4748,6 +4924,15 @@ export class AgentSession {
4748
4924
  */
4749
4925
  async recordInterruptedRuns(runs) {
4750
4926
  for (const run of runs) {
4927
+ // Another app has this chat open and is still running it: not a crash.
4928
+ if (run.pid !== undefined && run.pid !== process.pid && processIsAlive(run.pid)) {
4929
+ log("WARN", "session", "Unfinished run belongs to another live process; left open", {
4930
+ generation: String(run.generation),
4931
+ startedAt: run.startedAt,
4932
+ pid: String(run.pid),
4933
+ });
4934
+ continue;
4935
+ }
4751
4936
  log("WARN", "session", "Restored a session with an unfinished run", {
4752
4937
  generation: String(run.generation),
4753
4938
  startedAt: run.startedAt,