@oh-my-pi/pi-coding-agent 17.1.8 → 17.2.1

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 (246) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/dist/{CHANGELOG-vt8ene9g.md → CHANGELOG-dj46zzrm.md} +110 -0
  3. package/dist/cli.js +10009 -9654
  4. package/dist/{template-dys3vk5b.js → template-8vdv6xb4.js} +1 -1
  5. package/dist/types/advisor/runtime.d.ts +8 -2
  6. package/dist/types/advisor/transcript-recorder.d.ts +15 -0
  7. package/dist/types/auto-thinking/classifier.d.ts +9 -2
  8. package/dist/types/cli/args.d.ts +2 -0
  9. package/dist/types/cli/session-picker.d.ts +14 -7
  10. package/dist/types/collab/guest.d.ts +21 -2
  11. package/dist/types/commands/launch.d.ts +6 -0
  12. package/dist/types/config/model-discovery.d.ts +12 -0
  13. package/dist/types/config/settings-schema.d.ts +73 -8
  14. package/dist/types/cursor-bridge-tools.d.ts +54 -0
  15. package/dist/types/cursor.d.ts +193 -8
  16. package/dist/types/edit/edit-clipboard.d.ts +19 -0
  17. package/dist/types/edit/hashline/diff.d.ts +9 -1
  18. package/dist/types/edit/index.d.ts +8 -1
  19. package/dist/types/edit/streaming.d.ts +8 -1
  20. package/dist/types/extensibility/extensions/runner.d.ts +19 -2
  21. package/dist/types/extensibility/extensions/types.d.ts +25 -1
  22. package/dist/types/extensibility/legacy-pi-coding-agent-shim.d.ts +25 -0
  23. package/dist/types/internal-urls/index.d.ts +1 -0
  24. package/dist/types/internal-urls/local-protocol.d.ts +3 -2
  25. package/dist/types/internal-urls/security-protocol.d.ts +15 -0
  26. package/dist/types/internal-urls/types.d.ts +1 -1
  27. package/dist/types/launch/terminal-output-worker-client.d.ts +5 -0
  28. package/dist/types/launch/terminal-output-worker-protocol.d.ts +14 -0
  29. package/dist/types/launch/terminal-output-worker.d.ts +1 -0
  30. package/dist/types/lsp/client.d.ts +2 -0
  31. package/dist/types/main.d.ts +2 -0
  32. package/dist/types/mcp/manager.d.ts +33 -4
  33. package/dist/types/modes/components/codex-reset-fireworks.d.ts +51 -0
  34. package/dist/types/modes/components/read-tool-group.d.ts +12 -0
  35. package/dist/types/modes/components/session-selector.d.ts +6 -0
  36. package/dist/types/modes/components/status-line/component.d.ts +23 -0
  37. package/dist/types/modes/components/tool-execution.d.ts +16 -7
  38. package/dist/types/modes/components/usage-row.d.ts +2 -0
  39. package/dist/types/modes/controllers/mcp-command-controller.d.ts +26 -1
  40. package/dist/types/modes/controllers/selector-controller.d.ts +2 -1
  41. package/dist/types/modes/interactive-mode.d.ts +4 -2
  42. package/dist/types/modes/rpc/rpc-client.d.ts +7 -0
  43. package/dist/types/modes/rpc/rpc-types.d.ts +16 -0
  44. package/dist/types/modes/theme/theme.d.ts +12 -1
  45. package/dist/types/modes/types.d.ts +2 -1
  46. package/dist/types/sdk.d.ts +18 -0
  47. package/dist/types/security/auth.d.ts +30 -0
  48. package/dist/types/security/cloud.d.ts +79 -0
  49. package/dist/types/security/comparison.d.ts +49 -0
  50. package/dist/types/security/contracts/ids.d.ts +15 -0
  51. package/dist/types/security/contracts/index.d.ts +4 -0
  52. package/dist/types/security/contracts/schemas.d.ts +660 -0
  53. package/dist/types/security/contracts/types.d.ts +234 -0
  54. package/dist/types/security/contracts/validation.d.ts +5 -0
  55. package/dist/types/security/coordinator.d.ts +100 -0
  56. package/dist/types/security/importers/codex-security.d.ts +7 -0
  57. package/dist/types/security/importers/index.d.ts +2 -0
  58. package/dist/types/security/importers/sarif.d.ts +9 -0
  59. package/dist/types/security/index.d.ts +13 -0
  60. package/dist/types/security/preflight.d.ts +61 -0
  61. package/dist/types/security/provenance.d.ts +24 -0
  62. package/dist/types/security/publication.d.ts +78 -0
  63. package/dist/types/security/remediation.d.ts +27 -0
  64. package/dist/types/security/resource-output.d.ts +8 -0
  65. package/dist/types/security/sarif.d.ts +2 -0
  66. package/dist/types/security/store.d.ts +40 -0
  67. package/dist/types/session/agent-session-events.d.ts +2 -0
  68. package/dist/types/session/agent-session-types.d.ts +36 -1
  69. package/dist/types/session/agent-session.d.ts +4 -2
  70. package/dist/types/session/claude-session-store.d.ts +13 -0
  71. package/dist/types/session/codex-session-store.d.ts +14 -0
  72. package/dist/types/session/credential-pin.d.ts +58 -0
  73. package/dist/types/session/foreign-session-import.d.ts +15 -0
  74. package/dist/types/session/foreign-session-jsonl.d.ts +9 -0
  75. package/dist/types/session/foreign-session-store.d.ts +23 -0
  76. package/dist/types/session/session-advisors.d.ts +47 -2
  77. package/dist/types/session/session-entries.d.ts +19 -1
  78. package/dist/types/session/session-handoff.d.ts +4 -1
  79. package/dist/types/session/session-loader.d.ts +2 -0
  80. package/dist/types/session/session-maintenance.d.ts +1 -1
  81. package/dist/types/session/session-manager.d.ts +21 -0
  82. package/dist/types/session/session-tools.d.ts +25 -1
  83. package/dist/types/session/turn-recovery.d.ts +10 -4
  84. package/dist/types/slash-commands/helpers/security.d.ts +2 -0
  85. package/dist/types/system-prompt.d.ts +4 -1
  86. package/dist/types/task/executor.d.ts +14 -2
  87. package/dist/types/task/render.d.ts +7 -0
  88. package/dist/types/thinking.d.ts +18 -6
  89. package/dist/types/tools/acp-bridge.d.ts +28 -5
  90. package/dist/types/tools/builtin-names.d.ts +1 -1
  91. package/dist/types/tools/grep.d.ts +17 -1
  92. package/dist/types/tools/hub/launch.d.ts +5 -1
  93. package/dist/types/tools/index.d.ts +10 -2
  94. package/dist/types/tools/path-utils.d.ts +19 -0
  95. package/dist/types/tools/read.d.ts +2 -0
  96. package/dist/types/tools/security-scan.d.ts +96 -0
  97. package/dist/types/tools/xdev.d.ts +2 -1
  98. package/dist/types/utils/changelog.d.ts +19 -0
  99. package/dist/types/utils/git.d.ts +10 -0
  100. package/dist/types/utils/jj.d.ts +11 -4
  101. package/dist/types/web/search/types.d.ts +2 -2
  102. package/package.json +12 -12
  103. package/scripts/security-compare.ts +40 -0
  104. package/src/advisor/runtime.ts +138 -12
  105. package/src/advisor/transcript-recorder.ts +56 -0
  106. package/src/auto-thinking/classifier.ts +48 -10
  107. package/src/cli/args.ts +6 -0
  108. package/src/cli/flag-tables.ts +2 -0
  109. package/src/cli/gallery-fixtures/fs.ts +25 -0
  110. package/src/cli/session-picker.ts +34 -17
  111. package/src/cli/ttsr-cli.ts +19 -1
  112. package/src/cli.ts +9 -0
  113. package/src/collab/guest.ts +37 -4
  114. package/src/collab/host.ts +1 -0
  115. package/src/commands/launch.ts +6 -0
  116. package/src/config/model-discovery.ts +32 -5
  117. package/src/config/model-registry.ts +107 -25
  118. package/src/config/settings-schema.ts +77 -6
  119. package/src/config/settings.ts +25 -0
  120. package/src/cursor-bridge-tools.ts +81 -0
  121. package/src/cursor.ts +463 -12
  122. package/src/edit/edit-clipboard.ts +23 -0
  123. package/src/edit/hashline/diff.ts +49 -10
  124. package/src/edit/hashline/execute.ts +38 -6
  125. package/src/edit/hashline/filesystem.ts +27 -3
  126. package/src/edit/index.ts +12 -2
  127. package/src/edit/renderer.ts +4 -4
  128. package/src/edit/streaming.ts +17 -2
  129. package/src/eval/py/prelude.py +7 -3
  130. package/src/export/html/template.js +1 -1
  131. package/src/extensibility/extensions/runner.ts +70 -0
  132. package/src/extensibility/extensions/types.ts +30 -0
  133. package/src/extensibility/legacy-pi-coding-agent-shim.ts +65 -13
  134. package/src/internal-urls/index.ts +1 -0
  135. package/src/internal-urls/local-protocol.ts +3 -2
  136. package/src/internal-urls/mcp-protocol.ts +4 -1
  137. package/src/internal-urls/router.ts +4 -1
  138. package/src/internal-urls/security-protocol.ts +261 -0
  139. package/src/internal-urls/types.ts +1 -1
  140. package/src/launch/terminal-output-worker-client.ts +53 -0
  141. package/src/launch/terminal-output-worker-protocol.ts +11 -0
  142. package/src/launch/terminal-output-worker.ts +23 -0
  143. package/src/lsp/client.ts +18 -3
  144. package/src/lsp/index.ts +7 -0
  145. package/src/lsp/render.ts +1 -1
  146. package/src/main.ts +127 -56
  147. package/src/mcp/manager.ts +120 -18
  148. package/src/modes/acp/acp-agent.ts +15 -9
  149. package/src/modes/components/chat-transcript-builder.ts +30 -11
  150. package/src/modes/components/codex-reset-fireworks.ts +369 -0
  151. package/src/modes/components/read-tool-group.ts +159 -17
  152. package/src/modes/components/session-selector.ts +19 -3
  153. package/src/modes/components/status-line/component.ts +381 -54
  154. package/src/modes/components/tool-execution.ts +78 -31
  155. package/src/modes/components/usage-row.ts +10 -5
  156. package/src/modes/controllers/event-controller.ts +26 -4
  157. package/src/modes/controllers/mcp-command-controller.ts +68 -3
  158. package/src/modes/controllers/selector-controller.ts +94 -36
  159. package/src/modes/controllers/tan-command-controller.ts +14 -0
  160. package/src/modes/interactive-mode.ts +31 -17
  161. package/src/modes/rpc/host-uris.ts +6 -0
  162. package/src/modes/rpc/rpc-client.ts +18 -0
  163. package/src/modes/rpc/rpc-mode.ts +16 -1
  164. package/src/modes/rpc/rpc-types.ts +11 -0
  165. package/src/modes/theme/theme.ts +151 -6
  166. package/src/modes/types.ts +2 -1
  167. package/src/modes/utils/ui-helpers.ts +38 -21
  168. package/src/prompts/agents/security-reviewer.md +75 -0
  169. package/src/prompts/security/scan-coordinator.md +7 -0
  170. package/src/prompts/security/scan-request.md +21 -0
  171. package/src/prompts/security/validate-request.md +8 -0
  172. package/src/prompts/system/auto-thinking-difficulty.md +4 -2
  173. package/src/prompts/system/plan-mode-active.md +2 -2
  174. package/src/prompts/system/system-prompt.md +6 -0
  175. package/src/prompts/system/xdev-mount-notice.md +1 -1
  176. package/src/prompts/tools/bash.md +15 -17
  177. package/src/prompts/tools/checkpoint.md +1 -1
  178. package/src/prompts/tools/glob.md +7 -6
  179. package/src/prompts/tools/grep.md +7 -6
  180. package/src/prompts/tools/security-publish.md +1 -0
  181. package/src/prompts/tools/security-scan.md +1 -0
  182. package/src/sdk.ts +212 -21
  183. package/src/security/auth.ts +98 -0
  184. package/src/security/cloud.ts +686 -0
  185. package/src/security/comparison.ts +255 -0
  186. package/src/security/contracts/ids.ts +111 -0
  187. package/src/security/contracts/index.ts +4 -0
  188. package/src/security/contracts/schemas.ts +201 -0
  189. package/src/security/contracts/types.ts +254 -0
  190. package/src/security/contracts/validation.ts +65 -0
  191. package/src/security/coordinator.ts +708 -0
  192. package/src/security/importers/codex-security.ts +387 -0
  193. package/src/security/importers/index.ts +2 -0
  194. package/src/security/importers/sarif.ts +357 -0
  195. package/src/security/index.ts +13 -0
  196. package/src/security/preflight.ts +405 -0
  197. package/src/security/provenance.ts +106 -0
  198. package/src/security/publication.ts +326 -0
  199. package/src/security/remediation.ts +93 -0
  200. package/src/security/resource-output.ts +50 -0
  201. package/src/security/sarif.ts +78 -0
  202. package/src/security/store.ts +430 -0
  203. package/src/session/agent-session-events.ts +1 -0
  204. package/src/session/agent-session-types.ts +40 -1
  205. package/src/session/agent-session.ts +302 -175
  206. package/src/session/claude-session-store.ts +426 -0
  207. package/src/session/codex-session-store.ts +673 -0
  208. package/src/session/credential-pin.ts +93 -0
  209. package/src/session/foreign-session-import.ts +52 -0
  210. package/src/session/foreign-session-jsonl.ts +29 -0
  211. package/src/session/foreign-session-store.ts +26 -0
  212. package/src/session/model-controls.ts +11 -3
  213. package/src/session/session-advisors.ts +140 -16
  214. package/src/session/session-entries.ts +21 -1
  215. package/src/session/session-handoff.ts +20 -3
  216. package/src/session/session-loader.ts +25 -9
  217. package/src/session/session-maintenance.ts +59 -11
  218. package/src/session/session-manager.ts +61 -0
  219. package/src/session/session-tools.ts +107 -5
  220. package/src/session/settings-stream-fn.ts +1 -0
  221. package/src/session/turn-recovery.ts +97 -51
  222. package/src/slash-commands/builtin-registry.ts +152 -3
  223. package/src/slash-commands/helpers/security.ts +451 -0
  224. package/src/system-prompt.ts +7 -2
  225. package/src/task/agents.ts +2 -0
  226. package/src/task/executor.ts +20 -4
  227. package/src/task/render.ts +20 -4
  228. package/src/task/structured-subagent.ts +6 -4
  229. package/src/thinking.ts +29 -10
  230. package/src/tools/acp-bridge.ts +52 -8
  231. package/src/tools/browser.ts +5 -0
  232. package/src/tools/builtin-names.ts +1 -0
  233. package/src/tools/checkpoint.ts +0 -13
  234. package/src/tools/grep.ts +64 -8
  235. package/src/tools/hub/launch.ts +10 -15
  236. package/src/tools/index.ts +37 -5
  237. package/src/tools/path-utils.ts +91 -0
  238. package/src/tools/read.ts +3 -0
  239. package/src/tools/security-scan.ts +287 -0
  240. package/src/tools/write.ts +9 -3
  241. package/src/tools/xdev.ts +39 -14
  242. package/src/utils/changelog.ts +144 -4
  243. package/src/utils/git.ts +61 -14
  244. package/src/utils/jj.ts +19 -13
  245. package/src/web/search/providers/codex.ts +34 -0
  246. package/src/web/search/types.ts +1 -1
@@ -117,6 +117,7 @@ export interface TurnRecoveryHost {
117
117
  scheduleAgentContinue(options: { delayMs?: number; generation?: number; onError?: (error: unknown) => void }): void;
118
118
  waitForSessionMessagePersistence(message: AssistantMessage): Promise<void>;
119
119
  appendSessionMessage(message: AssistantMessage): void;
120
+ persistedAssistantEntryId(message: AssistantMessage): string | undefined;
120
121
  sessionMessageAlreadyPersisted(message: AssistantMessage): boolean;
121
122
  setModelWithProviderSessionReset(model: Model): Promise<void>;
122
123
  resetCurrentResponsesProviderSession(reason: string): void;
@@ -151,6 +152,12 @@ type PendingRecoveredRetryError = {
151
152
  note: string;
152
153
  };
153
154
 
155
+ type UsageLimitOutcome = {
156
+ switchedCredential: boolean;
157
+ retryAfterMs: number;
158
+ retryAtMs: number | undefined;
159
+ };
160
+
154
161
  /** Owns terminal-stop recovery, automatic retries, and fallback routing. */
155
162
  export class TurnRecovery {
156
163
  readonly #host: TurnRecoveryHost;
@@ -160,6 +167,7 @@ export class TurnRecovery {
160
167
  #retryResolve: (() => void) | undefined;
161
168
  #activeRetryFallback: ActiveRetryFallbackState | undefined;
162
169
  #pendingRecoveredRetryErrors: PendingRecoveredRetryError[] = [];
170
+ #usageLimitOutcomes = new WeakMap<AssistantMessage, Promise<UsageLimitOutcome>>();
163
171
  #emptyStopRetryCount = 0;
164
172
  #unexpectedStopRetryCount = 0;
165
173
  #acceptTerminalEmptyStopForPrompt = false;
@@ -297,6 +305,40 @@ export class TurnRecovery {
297
305
  return this.#handleRetryableError(message, options);
298
306
  }
299
307
 
308
+ /**
309
+ * Records a usage-limit failure before replay eligibility decides whether the
310
+ * failed turn may be discarded. Returns whether credential recovery switched
311
+ * the active account.
312
+ */
313
+ async recordUsageLimitOutcome(message: AssistantMessage): Promise<boolean> {
314
+ if (message.stopReason !== "error") return false;
315
+ const id = this.#classifyRetryMessage(message);
316
+ const activeModel = this.#host.model();
317
+ if (!activeModel || !AIError.is(id, AIError.Flag.UsageLimit)) return false;
318
+
319
+ let recorded = this.#usageLimitOutcomes.get(message);
320
+ if (!recorded) {
321
+ const errorMessage = message.errorMessage || "Unknown error";
322
+ const retryAfterMs =
323
+ this.#parseRetryAfterMsFromError(errorMessage) ??
324
+ calculateRateLimitBackoffMs(parseRateLimitReason(errorMessage));
325
+ recorded = (async (): Promise<UsageLimitOutcome> => {
326
+ const outcome = await this.#host.modelRegistry.authStorage.markUsageLimitReached(
327
+ activeModel.provider,
328
+ this.#host.sessionId(),
329
+ { retryAfterMs, baseUrl: activeModel.baseUrl, modelId: activeModel.id },
330
+ );
331
+ return {
332
+ switchedCredential: outcome.switched,
333
+ retryAfterMs,
334
+ retryAtMs: outcome.retryAtMs,
335
+ };
336
+ })();
337
+ this.#usageLimitOutcomes.set(message, recorded);
338
+ }
339
+ return (await recorded).switchedCredential;
340
+ }
341
+
300
342
  /** Prompts after transient overlap with a prior agent run. */
301
343
  promptAgentWithIdleRetry(messages: AgentMessage[], options?: { toolChoice?: ToolChoice }): Promise<void> {
302
344
  return this.#promptAgentWithIdleRetry(messages, options);
@@ -729,16 +771,24 @@ export class TurnRecovery {
729
771
  discardAssistantTurn(assistantMessage: AssistantMessage): void {
730
772
  this.removeAssistantMessageFromActiveContext(assistantMessage);
731
773
 
732
- const branchEntry = this.#host.sessionManager
733
- .getBranch()
734
- .slice()
735
- .reverse()
736
- .find(
737
- entry =>
738
- entry.type === "message" &&
739
- entry.message.role === "assistant" &&
740
- this.#isSameAssistantMessage(entry.message as AssistantMessage, assistantMessage),
741
- );
774
+ const branch = this.#host.sessionManager.getBranch();
775
+ const persistedEntryId = this.#host.persistedAssistantEntryId(assistantMessage);
776
+ const branchEntry =
777
+ (persistedEntryId === undefined
778
+ ? undefined
779
+ : branch.find(
780
+ entry =>
781
+ entry.id === persistedEntryId && entry.type === "message" && entry.message.role === "assistant",
782
+ )) ??
783
+ branch
784
+ .slice()
785
+ .reverse()
786
+ .find(
787
+ entry =>
788
+ entry.type === "message" &&
789
+ entry.message.role === "assistant" &&
790
+ this.#isSameAssistantMessage(entry.message as AssistantMessage, assistantMessage),
791
+ );
742
792
  if (!branchEntry) {
743
793
  return;
744
794
  }
@@ -757,7 +807,9 @@ export class TurnRecovery {
757
807
  (left.timestamp === right.timestamp &&
758
808
  left.provider === right.provider &&
759
809
  left.model === right.model &&
760
- left.stopReason === right.stopReason)
810
+ left.stopReason === right.stopReason &&
811
+ left.errorMessage === right.errorMessage &&
812
+ Bun.hash(JSON.stringify(left.content)) === Bun.hash(JSON.stringify(right.content)))
761
813
  );
762
814
  }
763
815
 
@@ -831,8 +883,13 @@ export class TurnRecovery {
831
883
  const contextWindow = this.#host.model()?.contextWindow ?? 0;
832
884
  if (AIError.isContextOverflow(message, contextWindow)) return false;
833
885
 
886
+ // A classifier refusal/sensitivity stop is the model's decision, not a route
887
+ // failure, but only after we confirm no user-visible output has already been
888
+ // streamed. Visible text, images, tool calls, or server tools must not be
889
+ // discarded and replayed.
890
+ if (this.#hasReplayUnsafeOutput(message)) return false;
834
891
  if (this.isClassifierRefusal(message)) return true;
835
- return AIError.retriable(id, { replayUnsafe: this.#hasReplayUnsafeToolOutput(message) });
892
+ return AIError.retriable(id);
836
893
  }
837
894
 
838
895
  /**
@@ -900,12 +957,22 @@ export class TurnRecovery {
900
957
  }
901
958
  /**
902
959
  * Retried turns remove the failed assistant message from active context.
903
- * Text/thinking-only partials are safe to discard and replay. Retained
904
- * tool calls are not: a completed tool call may already have emitted its
905
- * tool result after this assistant message, so replaying can duplicate work.
960
+ * Thinking-only partials are safe to discard and replay: reasoning models
961
+ * routinely stall after long thinking with no visible output, and duplicated
962
+ * thinking display is materially lower harm than duplicated final text.
963
+ * Whitespace-only text is likewise safe since nothing meaningful reached the
964
+ * user. Visible text, generated images, server tools, and retained tool calls
965
+ * are NOT safe: each has already rendered or may have side effects, so replaying
966
+ * the turn can duplicate user-visible output or work.
906
967
  */
907
- #hasReplayUnsafeToolOutput(message: AssistantMessage): boolean {
908
- return message.content.some(block => block.type === "toolCall");
968
+ #hasReplayUnsafeOutput(message: AssistantMessage): boolean {
969
+ return message.content.some(
970
+ block =>
971
+ block.type === "toolCall" ||
972
+ block.type === "image" ||
973
+ block.type === "anthropicServerTool" ||
974
+ (block.type === "text" && block.text.trim().length > 0),
975
+ );
909
976
  }
910
977
 
911
978
  /**
@@ -1087,14 +1154,14 @@ export class TurnRecovery {
1087
1154
  * transient overload/5xx or a hard "router/model not found / unsupported" —
1088
1155
  * is worth retrying on the base id. Skips failures the base model shares:
1089
1156
  * context overflow (compaction's job), usage limits and auth errors (same
1090
- * account/key), and turns that already emitted a tool call (replaying would
1091
- * duplicate work). Requires the base model to exist in the registry.
1157
+ * account/key), and turns that already emitted any replay-unsafe output.
1158
+ * Requires the base model to exist in the registry.
1092
1159
  */
1093
1160
  isFireworksFastFallbackEligible(message: AssistantMessage): boolean {
1094
1161
  const model = this.#activeFireworksFastModel();
1095
1162
  if (!model) return false;
1096
1163
  if (message.stopReason !== "error") return false;
1097
- if (message.content.some(block => block.type === "toolCall")) return false;
1164
+ if (this.#hasReplayUnsafeOutput(message)) return false;
1098
1165
  // A content refusal/sensitivity stop is the model's decision, not a route
1099
1166
  // failure — switching to the base model would just re-trigger it.
1100
1167
  if (this.isClassifierRefusal(message)) return false;
@@ -1113,8 +1180,7 @@ export class TurnRecovery {
1113
1180
  * model switch cannot fix or must not replay: cancellations (abort-flavored
1114
1181
  * errors are not model faults), context overflow (compaction's job),
1115
1182
  * classifier refusals (chain consult is handled on the retryable path with
1116
- * `pinFallback`), and turns that already emitted a tool call (replaying
1117
- * could duplicate work).
1183
+ * `pinFallback`), and turns that already emitted replay-unsafe output.
1118
1184
  */
1119
1185
  isHardErrorFallbackEligible(message: AssistantMessage): boolean {
1120
1186
  if (message.stopReason !== "error") return false;
@@ -1126,7 +1192,7 @@ export class TurnRecovery {
1126
1192
  const id = this.#classifyRetryMessage(message);
1127
1193
  if (AIError.is(id, AIError.Flag.Abort) || AIError.is(id, AIError.Flag.UserInterrupt)) return false;
1128
1194
  if (AIError.isContextOverflow(message, model.contextWindow ?? 0)) return false;
1129
- if (this.#hasReplayUnsafeToolOutput(message)) return false;
1195
+ if (this.#hasReplayUnsafeOutput(message)) return false;
1130
1196
  const currentSelector = formatRetryFallbackSelector(model, this.#host.thinkingLevel());
1131
1197
  const role = this.#activeRetryFallback?.role ?? this.resolveRetryFallbackRole(currentSelector);
1132
1198
  if (!role) return false;
@@ -1308,6 +1374,7 @@ export class TurnRecovery {
1308
1374
  const errorMessage = message.errorMessage || "Unknown error";
1309
1375
  const id = this.#classifyRetryMessage(message);
1310
1376
  const staleOpenAIResponsesReplayError = AIError.is(id, AIError.Flag.StaleResponsesItem);
1377
+ const recordedUsageLimitOutcome = await this.#usageLimitOutcomes.get(message);
1311
1378
  const parsedRetryAfterMs = this.#parseRetryAfterMsFromError(errorMessage);
1312
1379
  let delayMs = staleOpenAIResponsesReplayError
1313
1380
  ? 0
@@ -1322,31 +1389,8 @@ export class TurnRecovery {
1322
1389
  this.#host.resetCurrentResponsesProviderSession("stale replay error");
1323
1390
  }
1324
1391
 
1325
- const activeModel = this.#host.model();
1326
- if (
1327
- !retryBudgetExhausted &&
1328
- activeModel &&
1329
- !staleOpenAIResponsesReplayError &&
1330
- AIError.is(id, AIError.Flag.UsageLimit)
1331
- ) {
1332
- const retryAfterMs = parsedRetryAfterMs ?? calculateRateLimitBackoffMs(parseRateLimitReason(errorMessage));
1333
- const outcome = await this.#host.modelRegistry.authStorage.markUsageLimitReached(
1334
- activeModel.provider,
1335
- this.#host.sessionId(),
1336
- {
1337
- retryAfterMs,
1338
- baseUrl: activeModel.baseUrl,
1339
- modelId: activeModel.id,
1340
- },
1341
- );
1342
- if (outcome.switched) {
1343
- switchedCredential = true;
1344
- delayMs = 0;
1345
- } else if (await this.#host.maybeAutoRedeemCodexReset()) {
1346
- // A live usage-limit 429 on the active Codex account, with a banked
1347
- // reset and the opt-in setting on: spend the reset and retry
1348
- // immediately instead of waiting out the window. Runs after the
1349
- // free sibling-switch above and before model fallback below.
1392
+ if (!retryBudgetExhausted && !staleOpenAIResponsesReplayError && recordedUsageLimitOutcome) {
1393
+ if (recordedUsageLimitOutcome.switchedCredential || (await this.#host.maybeAutoRedeemCodexReset())) {
1350
1394
  switchedCredential = true;
1351
1395
  delayMs = 0;
1352
1396
  } else {
@@ -1358,9 +1402,10 @@ export class TurnRecovery {
1358
1402
  // Without this, one short-lived sibling block escalates a
1359
1403
  // recoverable situation into the provider's multi-hour wait and
1360
1404
  // trips the fail-fast cap below.
1361
- usageLimitWaitMs = retryAfterMs;
1362
- if (outcome.retryAtMs !== undefined) {
1363
- const siblingWaitMs = Math.max(0, outcome.retryAtMs - Date.now()) + SIBLING_UNBLOCK_BUFFER_MS;
1405
+ usageLimitWaitMs = recordedUsageLimitOutcome.retryAfterMs;
1406
+ if (recordedUsageLimitOutcome.retryAtMs !== undefined) {
1407
+ const siblingWaitMs =
1408
+ Math.max(0, recordedUsageLimitOutcome.retryAtMs - Date.now()) + SIBLING_UNBLOCK_BUFFER_MS;
1364
1409
  if (siblingWaitMs < usageLimitWaitMs) {
1365
1410
  usageLimitWaitMs = siblingWaitMs;
1366
1411
  }
@@ -1398,6 +1443,7 @@ export class TurnRecovery {
1398
1443
  delayMs = parsedRetryAfterMs;
1399
1444
  }
1400
1445
  }
1446
+
1401
1447
  if (retryBudgetExhausted) {
1402
1448
  if (!switchedModel) {
1403
1449
  await this.persistTerminalEmptyErrorTurn(message);
@@ -3,7 +3,7 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { getOAuthProviders } from "@oh-my-pi/pi-ai/oauth";
5
5
  import { type AutocompleteItem, Spacer } from "@oh-my-pi/pi-tui";
6
- import { APP_NAME, getProjectDir, setProjectDir } from "@oh-my-pi/pi-utils";
6
+ import { APP_NAME, getMCPConfigPath, getProjectDir, logger, setProjectDir } from "@oh-my-pi/pi-utils";
7
7
  import { reset as resetCapabilities } from "../capability";
8
8
  import { COLLAB_GUEST_ALLOWED_COMMANDS, CollabGuestLink } from "../collab/guest";
9
9
  import { CollabHost } from "../collab/host";
@@ -31,8 +31,10 @@ import {
31
31
  getPluginsCacheDir,
32
32
  MarketplaceManager,
33
33
  } from "../extensibility/plugins/marketplace";
34
+ import { readMCPConfigFile } from "../mcp/config-writer";
34
35
  import { resolveMemoryBackend } from "../memory-backend";
35
36
  import { runPauseScreen } from "../modes/components/pause-screen";
37
+ import { collectMcpServerNames } from "../modes/controllers/mcp-command-controller";
36
38
  import { describeLoopLimitRuntime } from "../modes/loop-limit";
37
39
  import { theme } from "../modes/theme/theme";
38
40
  import type { InteractiveModeContext } from "../modes/types";
@@ -61,6 +63,7 @@ import { createMarketplaceManager } from "./helpers/marketplace-manager";
61
63
  import { handleMcpAcp } from "./helpers/mcp";
62
64
  import { commandConsumed, errorMessage, parseSlashCommand, parseSubcommand, usage } from "./helpers/parse";
63
65
  import { describeRedeemOutcome, type ResetUsageAccount, toResetUsageAccounts } from "./helpers/reset-usage";
66
+ import { handleSecurityCommand } from "./helpers/security";
64
67
  import { matchSessionPinAccounts, toSessionPinAccounts } from "./helpers/session-pin";
65
68
  import { handleSshAcp } from "./helpers/ssh";
66
69
  import { launchStatsDashboard, parseStatsDashboardArgs } from "./helpers/stats-dashboard";
@@ -372,6 +375,26 @@ function formatWorkspaceDirectories(runtime: SlashCommandRuntime, note?: string)
372
375
  }
373
376
 
374
377
  const BUILTIN_SLASH_COMMAND_REGISTRY: ReadonlyArray<SlashCommandSpec> = [
378
+ {
379
+ name: "security",
380
+ description: "Plan, run, inspect, import, and compare OMP-native security scans",
381
+ allowArgs: true,
382
+ acpInputHint: "<plan|scan|status|cancel|scans|show|import|export|validate|compare|disposition>",
383
+ subcommands: [
384
+ { name: "plan", description: "Create an immutable security scan plan" },
385
+ { name: "scan", description: "Start a planned or newly planned native scan" },
386
+ { name: "status", description: "Show native scan operation status" },
387
+ { name: "cancel", description: "Cancel a running native scan" },
388
+ { name: "scans", description: "List stored project security scans" },
389
+ { name: "show", description: "Render a scan or security:// resource" },
390
+ { name: "import", description: "Import SARIF or a Codex Security bundle" },
391
+ { name: "export", description: "Export a canonical bundle, SARIF, or report" },
392
+ { name: "validate", description: "Validate one finding with OMP-native tools" },
393
+ { name: "compare", description: "Compare finding lineage across two scans" },
394
+ { name: "disposition", description: "Set a finding disposition with rationale" },
395
+ ],
396
+ handle: handleSecurityCommand,
397
+ },
375
398
  {
376
399
  name: "settings",
377
400
  description: "Open settings menu",
@@ -1790,11 +1813,16 @@ const BUILTIN_SLASH_COMMAND_REGISTRY: ReadonlyArray<SlashCommandSpec> = [
1790
1813
  {
1791
1814
  name: "resume",
1792
1815
  description: "Resume a different session",
1793
- inlineHint: "[session id]",
1816
+ inlineHint: "[session id|@claude|@codex]",
1794
1817
  allowArgs: true,
1795
1818
  handleTui: async (command, runtime) => {
1796
1819
  const sessionArg = command.args.trim();
1797
1820
  runtime.ctx.editor.setText("");
1821
+ const foreignSource = sessionArg === "@claude" ? "claude" : sessionArg === "@codex" ? "codex" : undefined;
1822
+ if (foreignSource) {
1823
+ runtime.ctx.showSessionSelector(foreignSource);
1824
+ return;
1825
+ }
1798
1826
  if (!sessionArg) {
1799
1827
  runtime.ctx.showSessionSelector();
1800
1828
  return;
@@ -2714,6 +2742,124 @@ function buildArgumentCompletions(subcommands: SubcommandDef[]): (prefix: string
2714
2742
  };
2715
2743
  }
2716
2744
 
2745
+ /** /mcp subcommands whose argument is a server name (per their `usage: "<name>..."`). */
2746
+ const MCP_SERVER_NAME_SUBCOMMANDS: Readonly<Record<string, true>> = {
2747
+ enable: true,
2748
+ disable: true,
2749
+ test: true,
2750
+ remove: true,
2751
+ reconnect: true,
2752
+ reauth: true,
2753
+ unauth: true,
2754
+ };
2755
+
2756
+ /** Subcommands that accept names found only in `userConfig.disabledServers`. */
2757
+ const MCP_DISABLED_ONLY_ELIGIBLE_SUBCOMMANDS: Readonly<Record<string, true>> = {
2758
+ enable: true,
2759
+ disable: true,
2760
+ };
2761
+
2762
+ /**
2763
+ * Subcommands that accept configured servers whose `enabled` flag is false.
2764
+ * `unauth` can clear persisted credentials without connecting; test,
2765
+ * reconnect, and reauth explicitly require an enabled server.
2766
+ */
2767
+ const MCP_DISABLED_CONFIG_ELIGIBLE_SUBCOMMANDS: Readonly<Record<string, true>> = {
2768
+ enable: true,
2769
+ disable: true,
2770
+ unauth: true,
2771
+ };
2772
+
2773
+ /**
2774
+ * Build getArgumentCompletions for /mcp. Delegates to the generic
2775
+ * declarative subcommand completer while the subcommand name itself is
2776
+ * still being typed, then switches to MCP server-name completion (sourced
2777
+ * from {@link collectMcpServerNames}) once a recognized server-name
2778
+ * subcommand (enable/disable/test/remove/reconnect/reauth/unauth) is
2779
+ * followed by a space. `remove` gets its own scope-aware completions (see
2780
+ * {@link buildMcpRemoveCompletions}) since — unlike the others —
2781
+ * it only ever succeeds against a config-file entry. Subcommands with a
2782
+ * different argument shape (add, smithery-search, ...) get no argument
2783
+ * completion.
2784
+ */
2785
+ function buildMcpArgumentCompletions(
2786
+ subcommands: SubcommandDef[],
2787
+ runtime: TuiSlashCommandRuntime,
2788
+ ): (argumentPrefix: string) => Promise<AutocompleteItem[] | null> {
2789
+ const genericCompletions = buildArgumentCompletions(subcommands);
2790
+ return async (argumentPrefix: string) => {
2791
+ const spaceIndex = argumentPrefix.indexOf(" ");
2792
+ if (spaceIndex === -1) return genericCompletions(argumentPrefix);
2793
+
2794
+ const rawSubcommand = argumentPrefix.slice(0, spaceIndex);
2795
+ const lowerSubcommand = rawSubcommand.toLowerCase();
2796
+ if (MCP_SERVER_NAME_SUBCOMMANDS[lowerSubcommand] !== true) return null;
2797
+ const namePrefix = argumentPrefix.slice(spaceIndex + 1).toLowerCase();
2798
+ if (lowerSubcommand === "remove") {
2799
+ return await buildMcpRemoveCompletions(rawSubcommand, namePrefix);
2800
+ }
2801
+
2802
+ let serverNames: string[];
2803
+ try {
2804
+ serverNames = await collectMcpServerNames(
2805
+ runtime.ctx,
2806
+ undefined,
2807
+ MCP_DISABLED_ONLY_ELIGIBLE_SUBCOMMANDS[lowerSubcommand] === true,
2808
+ MCP_DISABLED_CONFIG_ELIGIBLE_SUBCOMMANDS[lowerSubcommand] === true,
2809
+ );
2810
+ } catch (error) {
2811
+ logger.warn("MCP server-name autocomplete failed to read config", { error });
2812
+ return null;
2813
+ }
2814
+ const matches: AutocompleteItem[] = serverNames
2815
+ .filter(name => name.toLowerCase().startsWith(namePrefix))
2816
+ .map(name => ({ value: `${rawSubcommand} ${name} `, label: name }));
2817
+ return matches.length > 0 ? matches : null;
2818
+ };
2819
+ }
2820
+
2821
+ /**
2822
+ * Build `/mcp remove <name>` completions. Unlike the other server-name
2823
+ * subcommands, `#handleRemove` only ever succeeds against a config-file
2824
+ * `mcpServers` entry in the target scope (project by default, user with an
2825
+ * explicit `--scope user`) — a purely runtime-discovered server has no
2826
+ * config entry to remove and always fails with `Server "<name>" not found
2827
+ * in <scope> config.`. Completions are therefore restricted to config-file
2828
+ * names, and a name that exists only in the user config is completed with
2829
+ * `--scope user` appended so the inserted command is directly executable.
2830
+ */
2831
+ async function buildMcpRemoveCompletions(
2832
+ rawSubcommand: string,
2833
+ namePrefix: string,
2834
+ ): Promise<AutocompleteItem[] | null> {
2835
+ const cwd = getProjectDir();
2836
+ let projectNames: string[];
2837
+ let userNames: string[];
2838
+ try {
2839
+ const [projectConfig, userConfig] = await Promise.all([
2840
+ readMCPConfigFile(getMCPConfigPath("project", cwd)),
2841
+ readMCPConfigFile(getMCPConfigPath("user", cwd)),
2842
+ ]);
2843
+ projectNames = Object.keys(projectConfig.mcpServers ?? {});
2844
+ userNames = Object.keys(userConfig.mcpServers ?? {});
2845
+ } catch (error) {
2846
+ logger.warn("MCP remove autocomplete failed to read config", { error });
2847
+ return null;
2848
+ }
2849
+
2850
+ const projectNameSet = new Set(projectNames);
2851
+ const allNames = new Set([...projectNames, ...userNames]);
2852
+ const matches: AutocompleteItem[] = [...allNames]
2853
+ .filter(name => name.toLowerCase().startsWith(namePrefix))
2854
+ .map(name =>
2855
+ projectNameSet.has(name)
2856
+ ? { value: `${rawSubcommand} ${name} `, label: name }
2857
+ : { value: `${rawSubcommand} ${name} --scope user `, label: `${name} (user)` },
2858
+ )
2859
+ .sort((a, b) => a.label.localeCompare(b.label, undefined, { sensitivity: "base" }));
2860
+ return matches.length > 0 ? matches : null;
2861
+ }
2862
+
2717
2863
  /**
2718
2864
  * Build getInlineHint from declarative subcommand definitions.
2719
2865
  * Shows remaining completion + usage as dim ghost text after cursor.
@@ -2877,7 +3023,10 @@ function materializeTuiBuiltinSlashCommand(
2877
3023
  ): TuiBuiltinSlashCommand {
2878
3024
  const materialized: TuiBuiltinSlashCommand = { ...cmd };
2879
3025
  if (cmd.subcommands) {
2880
- materialized.getArgumentCompletions = buildArgumentCompletions(cmd.subcommands);
3026
+ materialized.getArgumentCompletions =
3027
+ cmd.name === "mcp" && runtime
3028
+ ? buildMcpArgumentCompletions(cmd.subcommands, runtime)
3029
+ : buildArgumentCompletions(cmd.subcommands);
2881
3030
  materialized.getInlineHint = buildSubcommandInlineHint(cmd.subcommands);
2882
3031
  } else if (cmd.name === "move") {
2883
3032
  materialized.getArgumentCompletions = buildDirectoryArgumentCompletions();