@miphamai/cli 0.85.24 → 0.85.26

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 (45) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +34 -24
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +23 -3
  5. package/src/agent/sub-agent.ts +29 -15
  6. package/src/artifacts/server.ts +5 -1
  7. package/src/commands/git.ts +9 -1
  8. package/src/commands/project.ts +34 -17
  9. package/src/core/context-token.ts +55 -3
  10. package/src/core/context.ts +54 -42
  11. package/src/core/crsi-sandbox.ts +5 -1
  12. package/src/core/engine.ts +91 -10
  13. package/src/core/instructions.ts +130 -18
  14. package/src/core/permission-rule-ack.ts +67 -0
  15. package/src/core/permission-rules.ts +141 -25
  16. package/src/daemon/remote-engine.ts +11 -5
  17. package/src/daemon/schedule-manager.ts +32 -3
  18. package/src/daemon/server.ts +6 -0
  19. package/src/i18n-core/locales/en-US.json +1 -1
  20. package/src/i18n-core/locales/zh-CN.json +1 -1
  21. package/src/index.tsx +34 -4
  22. package/src/mcp/client.ts +37 -2
  23. package/src/mcp/http-transport.ts +20 -1
  24. package/src/mcp/protocol.ts +13 -5
  25. package/src/mcp/registry.ts +8 -3
  26. package/src/mcp/transport.ts +40 -3
  27. package/src/plugin/plugin-manager.ts +23 -2
  28. package/src/providers/anthropic.ts +3 -1
  29. package/src/providers/fetch-utils.ts +40 -6
  30. package/src/providers/openai-compat.ts +2 -1
  31. package/src/providers/registry.ts +23 -1
  32. package/src/shared/git-env.ts +18 -0
  33. package/src/shared/package-info.ts +3 -3
  34. package/src/shared/sanitize.ts +21 -0
  35. package/src/shared/types.ts +9 -0
  36. package/src/skills/loader.ts +14 -0
  37. package/src/tools/exec/bash.ts +168 -6
  38. package/src/tools/exec/enter-worktree.ts +26 -2
  39. package/src/tools/exec/task.ts +144 -21
  40. package/src/tools/network/web-fetch.ts +7 -7
  41. package/src/tools/network/web-search.ts +6 -5
  42. package/src/ui/app.tsx +22 -7
  43. package/src/ui/chat.tsx +3 -2
  44. package/src/ui/commands.ts +65 -5
  45. package/src/workflow/primitives/agent.ts +17 -1
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { DaemonDatabase } from './database'
6
6
  import type { WorkerPool } from './worker-pool'
7
+ import type { SessionWorker } from './session-worker'
7
8
  import type { DaemonSchedule } from './types'
8
9
  import { logger } from './logger'
9
10
  import { computeNextFire } from '../core/cron'
@@ -12,12 +13,26 @@ export class ScheduleManager {
12
13
  private db: DaemonDatabase
13
14
  private pool: WorkerPool
14
15
  private intervalId: Timer | null = null
16
+ private spawnWorker: ((sessionId: string) => SessionWorker | null) | null = null
15
17
 
16
18
  constructor(db: DaemonDatabase, pool: WorkerPool) {
17
19
  this.db = db
18
20
  this.pool = pool
19
21
  }
20
22
 
23
+ /**
24
+ * Register the daemon's "bring this session's worker back" hook.
25
+ *
26
+ * Workers are otherwise created lazily, on an inbound prompt — so a session
27
+ * whose worker was never started, or was recycled by the idle timeout, has
28
+ * nobody to deliver a due schedule to, and the cron entry silently never runs.
29
+ * The daemon wires this once its own engine factory exists (it is created after
30
+ * this manager), which is why it is a setter and not a constructor argument.
31
+ */
32
+ setWorkerSpawner(fn: (sessionId: string) => SessionWorker | null): void {
33
+ this.spawnWorker = fn
34
+ }
35
+
21
36
  createSchedule(sessionId: string, cronExpr: string, prompt: string): number {
22
37
  const now = new Date()
23
38
  const nextFire = computeNextFire(cronExpr, now)
@@ -43,15 +58,29 @@ export class ScheduleManager {
43
58
  * Check for due schedules and fire them.
44
59
  *
45
60
  * For each schedule whose nextFire has passed:
46
- * 1. Look up the session worker — skip if none is active
61
+ * 1. Look up the session worker — start one if none is active and the daemon
62
+ * supplied a spawner (a recycled or never-started session must still get its
63
+ * scheduled prompt; skipping it means the cron entry never runs at all)
47
64
  * 2. Send the prompt to the worker (fire-and-forget)
48
65
  * 3. Update lastFired and compute the next fire time
66
+ *
67
+ * A schedule that still has no worker is left alone — `nextFire` stays in the
68
+ * past, so the next tick tries again rather than dropping the run.
49
69
  */
50
70
  checkAndFire(): void {
51
71
  const due = this.db.getDueSchedules()
52
72
  for (const schedule of due) {
53
- const worker = this.pool.getWorker(schedule.sessionId)
54
- if (!worker) continue
73
+ const worker =
74
+ this.pool.getWorker(schedule.sessionId) ??
75
+ this.spawnWorker?.(schedule.sessionId) ??
76
+ undefined
77
+ if (!worker) {
78
+ logger.warn('scheduled prompt skipped: no worker for session', {
79
+ scheduleId: schedule.id,
80
+ sessionId: schedule.sessionId,
81
+ })
82
+ continue
83
+ }
55
84
 
56
85
  worker.processPrompt(schedule.prompt).catch((err: unknown) => {
57
86
  logger.error('error firing schedule', { scheduleId: schedule.id, error: err })
@@ -325,6 +325,12 @@ export function createServer(config: ServerConfig): Server<WsData> {
325
325
  }
326
326
  }
327
327
 
328
+ // Scheduled prompts must not depend on someone having opened the session: the
329
+ // scheduler fires into whatever worker exists, and workers only exist after an
330
+ // inbound prompt or `set_mode`. Handing it the same factory the WS handlers use
331
+ // makes a due schedule able to bring its own worker up.
332
+ scheduleManager.setWorkerSpawner((sessionId) => getOrCreateWorker(sessionId))
333
+
328
334
  // ── Feishu remote-control adapter(独立签名验证,复用同一 worker 池)──
329
335
  const feishuAdapter = feishu
330
336
  ? createFeishuAdapter(feishu.config, {
@@ -968,7 +968,7 @@
968
968
  "max_tool_turns": "Max tool-calling turns ({max}) reached. Some tool calls were not executed.",
969
969
  "max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
970
970
  "turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
971
- "turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed.",
971
+ "turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed. If you reach the provider through a proxy or a corporate gateway, check that first; otherwise check your VPN and firewall rules.",
972
972
  "turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
973
973
  "turn_refused_reason": "The model declined this request: {reason}",
974
974
  "stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
@@ -968,7 +968,7 @@
968
968
  "max_tool_turns": "超出最大工具调用轮次({max})。部分工具调用未执行。",
969
969
  "max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
970
970
  "turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
971
- "turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。",
971
+ "turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。如果是经代理或公司网关访问提供商,先查那一层;否则检查 VPN 与防火墙规则。",
972
972
  "turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
973
973
  "turn_refused_reason": "模型拒绝了这次请求:{reason}",
974
974
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
package/src/index.tsx CHANGED
@@ -28,6 +28,8 @@ import { ContextManager } from './core/context'
28
28
  import { PrefixCacheTracker } from './core/context-token'
29
29
  import { QueryEngine } from './core/engine'
30
30
  import { RulesLoader } from './core/rules-loader'
31
+ import { setActiveTaskSession } from './tools/exec/task'
32
+ import { unacknowledgedRuleWarnings } from './core/permission-rule-ack'
31
33
  import { generateSessionName } from './core/session-name'
32
34
  import { ExperienceRuleEngine } from './core/rule-engine.js'
33
35
  import { SessionLog } from './core/session-log'
@@ -320,7 +322,12 @@ async function connectMcpServers(
320
322
  const name = mcpServers[i]!.name
321
323
  const reason = String(result.reason)
322
324
  failures.push({ name, reason })
323
- console.error(`[mcp] Failed to connect "${name}": ${reason}`)
325
+ // Say the retry out loud when there is one: the client is already trying
326
+ // again in the background, and a bare "failed" reads as a final verdict.
327
+ const retrying = mcp.isRetrying(name)
328
+ ? ' — retrying in the background; /mcp shows the current state'
329
+ : ''
330
+ console.error(`[mcp] Failed to connect "${name}": ${reason}${retrying}`)
324
331
  }
325
332
  }
326
333
  // No success line before the TUI: with five configured servers this was a line
@@ -590,6 +597,10 @@ export async function runApp(options: RunOptions): Promise<void> {
590
597
  compactionThreshold: 0.9,
591
598
  contextWindow: adaptiveThresholds ? modelContextWindow : undefined,
592
599
  })
600
+ // Load this session's task list up front. The Task tool would load it on first
601
+ // touch anyway, but the goal panel renders from it before then — and on a
602
+ // resumed session the whole point is that the plan comes back on screen.
603
+ setActiveTaskSession(sessionName)
593
604
  const sessionLog = new SessionLog(sessionName)
594
605
  sessionLog.append({
595
606
  type: 'session/start',
@@ -620,6 +631,23 @@ export async function runApp(options: RunOptions): Promise<void> {
620
631
  // Adaptive memory budget: scale with model's context window
621
632
  getMemoryManager().setContextWindow(modelContextWindow)
622
633
 
634
+ /**
635
+ * 把系统提示装进上下文,并且留下重建方式。
636
+ *
637
+ * 提示里的指令文件(`CLAUDE.md` / `AGENTS.md` / `USER.md`)是启动那一刻读的,
638
+ * 会话中被改过就只有重启才生效。压缩之后引擎会让提示重建一次,重建器在拼装前
639
+ * 先回读磁盘;**只换指令那一段**,`extra` 原样保留 —— 那是启动时拼进来的会话级
640
+ * 上下文(技能提醒、记忆召回、上一会话摘要、首跑提示),再生成一遍等于把它们
641
+ * 重复塞进每个请求。
642
+ */
643
+ const applySystemPrompt = (base: string, extra: string): void => {
644
+ context.setSystemPrompt(base + extra)
645
+ context.setSystemPromptRebuilder(() => {
646
+ instructions.refresh()
647
+ return instructions.buildSystemPrompt() + extra
648
+ })
649
+ }
650
+
623
651
  if (options.resume) {
624
652
  const log = SessionStore.loadLog(options.resume)
625
653
  const events = log.events()
@@ -654,7 +682,7 @@ export async function runApp(options: RunOptions): Promise<void> {
654
682
  }
655
683
  }
656
684
  context.restoreLog(log)
657
- context.setSystemPrompt(instructions.buildSystemPrompt())
685
+ applySystemPrompt(instructions.buildSystemPrompt(), '')
658
686
  }
659
687
  }
660
688
 
@@ -730,7 +758,7 @@ export async function runApp(options: RunOptions): Promise<void> {
730
758
  prompt = `${prompt}\n\n<system-reminder name="missing-mipham-md">\n${partialReminder}\n</system-reminder>`
731
759
  }
732
760
 
733
- context.setSystemPrompt(prompt)
761
+ applySystemPrompt(basePrompt, prompt.slice(basePrompt.length))
734
762
  }
735
763
 
736
764
  // Initialize credential masking pipeline (strategies: Full, Extract, JWT)
@@ -834,7 +862,9 @@ export async function runApp(options: RunOptions): Promise<void> {
834
862
 
835
863
  // Surface malformed permission rules as warnings instead of silently letting
836
864
  // them never match (e.g. a deny rule typed `Bash(ls) x` would fail closed).
837
- for (const msg of engine.getPermission().getInvalidRules()) {
865
+ // 同一句警告每个用户只报一次:settings 文件不修,它每次启动都一样,重复到第七
866
+ // 次就不再是提醒 —— 而新出现的那条坏规则会混在旧噪音里没人看见。
867
+ for (const msg of unacknowledgedRuleWarnings(engine.getPermission().getInvalidRules())) {
838
868
  process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
839
869
  }
840
870
 
package/src/mcp/client.ts CHANGED
@@ -314,6 +314,14 @@ export class McpClient {
314
314
  this.connections.delete(name)
315
315
 
316
316
  await this.connect(config)
317
+ // The startup path registers tools right after a successful `connect()`;
318
+ // a server that only came up on a retry never goes through it, so the
319
+ // registry would answer "no such tool" for a server that is green in
320
+ // `/mcp`. Push the list this connection just discovered. `applyToolChanges`
321
+ // overwrites by name, so on a mid-session reconnect (tools already known)
322
+ // this is a no-op.
323
+ const fresh = this.connections.get(name)
324
+ if (fresh) this.emit('tools-changed', name, fresh.tools, [])
317
325
  this.emit('reconnected', name)
318
326
  return
319
327
  } catch (err) {
@@ -393,12 +401,33 @@ export class McpClient {
393
401
  this.connecting.set(config.name, attempt)
394
402
  try {
395
403
  await attempt
404
+ } catch (err) {
405
+ // A handshake that never finished is not a verdict. The server that timed
406
+ // out at 15 s is often ready a few seconds later (a cold `npx` download, a
407
+ // Python server still importing), and a refused socket means "not up yet"
408
+ // just as often as "gone". Mid-session losses already come back unaided;
409
+ // a startup failure used to latch 'error' for the rest of the session, so
410
+ // the tools never appeared at all. A definitive refusal (4xx auth) is not
411
+ // retried — see `isTransientConnectError`.
412
+ if (isTransientConnectError(err) && this.autoReconnect && !this.closing) {
413
+ this.scheduleAutoReconnect(config.name)
414
+ }
415
+ throw err
396
416
  } finally {
397
417
  // 无论成败都要放开这个名字:失败后用户重连,得能真的重连。
398
418
  this.connecting.delete(config.name)
399
419
  }
400
420
  }
401
421
 
422
+ /**
423
+ * Whether a server that just failed to connect is being retried in the
424
+ * background. The startup reporter uses this to say so: a bare "failed" line
425
+ * is a verdict the client is about to contradict.
426
+ */
427
+ isRetrying(name: string): boolean {
428
+ return this.reconnecting.has(name)
429
+ }
430
+
402
431
  private async connectOnce(config: McpServerConfig): Promise<void> {
403
432
  const transport: StdioTransport | HttpTransport = config.url
404
433
  ? new HttpTransport(undefined, config.request_timeout_ms)
@@ -504,11 +533,16 @@ export class McpClient {
504
533
  * connecting. A server this client knows nothing about is `true`: there is
505
534
  * nothing to wait for, and `callTool` will say so.
506
535
  */
507
- async waitUntilReady(name: string, timeoutMs: number = connectTimeoutMs()): Promise<boolean> {
536
+ async waitUntilReady(
537
+ name: string,
538
+ timeoutMs: number = connectTimeoutMs(),
539
+ signal?: AbortSignal,
540
+ ): Promise<boolean> {
508
541
  // Awake time, same as the handshake budget it mirrors: a sleep mid-wait must
509
542
  // not spend the deadline the server never got to use.
510
543
  const deadline = performance.now() + timeoutMs
511
544
  for (;;) {
545
+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
512
546
  const conn = this.connections.get(name)
513
547
  if (!conn || conn.status !== 'connecting') return true
514
548
  if (performance.now() >= deadline) return false
@@ -608,6 +642,7 @@ export class McpClient {
608
642
  serverName: string,
609
643
  toolName: string,
610
644
  params?: Record<string, unknown>,
645
+ signal?: AbortSignal,
611
646
  ): Promise<ToolCallResult> {
612
647
  const conn = this.connections.get(serverName)
613
648
  if (!conn || conn.status !== 'connected') {
@@ -618,7 +653,7 @@ export class McpClient {
618
653
  }
619
654
 
620
655
  try {
621
- return await conn.protocol.callTool(toolName, params)
656
+ return await conn.protocol.callTool(toolName, params, signal)
622
657
  } catch (err) {
623
658
  this.markIfTransportLost(serverName, conn)
624
659
  // A scope refusal is actionable and nothing else is: the user has to go
@@ -191,10 +191,17 @@ export class HttpTransport implements Transport {
191
191
  }
192
192
  }
193
193
 
194
- async sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown> {
194
+ async sendRequest(
195
+ method: string,
196
+ params?: Record<string, unknown>,
197
+ signal?: AbortSignal,
198
+ ): Promise<unknown> {
195
199
  if (!this.url || this.closed) {
196
200
  throw new Error('Transport not connected')
197
201
  }
202
+ if (signal?.aborted) {
203
+ throw new DOMException('Aborted', 'AbortError')
204
+ }
198
205
 
199
206
  const id = ++this.msgId
200
207
  const request: JsonRpcRequest = {
@@ -205,6 +212,12 @@ export class HttpTransport implements Transport {
205
212
  }
206
213
 
207
214
  const controller = new AbortController()
215
+ // The turn's cancellation and the per-request timeout share one controller,
216
+ // because `fetch` takes one signal. The caller's abort must not be read as
217
+ // "the endpoint never answered": that branch below marks the transport
218
+ // closed, which would turn an interrupt into a dead MCP server.
219
+ const onAbort = (): void => controller.abort()
220
+ signal?.addEventListener('abort', onAbort, { once: true })
208
221
  const timer = setTimeout(() => controller.abort(), this.requestTimeoutMs)
209
222
 
210
223
  // Did an HTTP response come back at all? A rejected fetch or a timeout means
@@ -251,6 +264,11 @@ export class HttpTransport implements Transport {
251
264
  }
252
265
  return json.result
253
266
  } catch (err) {
267
+ if (signal?.aborted) {
268
+ // The caller cancelled. The server is fine — aborting the fetch says
269
+ // nothing about it — so the transport stays connected.
270
+ throw new DOMException('Aborted', 'AbortError')
271
+ }
254
272
  if (controller.signal.aborted) {
255
273
  // The endpoint never answered. Every later request would hang the same
256
274
  // way, so the transport reports itself disconnected — the same state a
@@ -265,6 +283,7 @@ export class HttpTransport implements Transport {
265
283
  throw err
266
284
  } finally {
267
285
  clearTimeout(timer)
286
+ signal?.removeEventListener('abort', onAbort)
268
287
  }
269
288
  }
270
289
 
@@ -135,11 +135,19 @@ export class McpProtocol {
135
135
  return result.tools || []
136
136
  }
137
137
 
138
- async callTool(name: string, args?: Record<string, unknown>): Promise<ToolCallResult> {
139
- const result = (await this.transport.sendRequest('tools/call', {
140
- name,
141
- arguments: args || {},
142
- })) as ToolCallResult
138
+ async callTool(
139
+ name: string,
140
+ args?: Record<string, unknown>,
141
+ signal?: AbortSignal,
142
+ ): Promise<ToolCallResult> {
143
+ const result = (await this.transport.sendRequest(
144
+ 'tools/call',
145
+ {
146
+ name,
147
+ arguments: args || {},
148
+ },
149
+ signal,
150
+ )) as ToolCallResult
143
151
  return result
144
152
  }
145
153
 
@@ -105,7 +105,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
105
105
  category: 'system',
106
106
  permission: 'ask',
107
107
  parameters,
108
- async execute(params: Record<string, unknown>, _ctx: ToolContext): Promise<ToolResult> {
108
+ async execute(params: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult> {
109
109
  const client = McpClient.getInstance()
110
110
 
111
111
  // Startup connects servers without blocking, and a resumed session re-attaches
@@ -114,7 +114,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
114
114
  // the only thing missing is patience. Same wait the `mcp_tool` hook already
115
115
  // does (`core/hooks-executor.ts`), so both entry points treat a connecting
116
116
  // server identically. A server that is *not* connecting returns immediately.
117
- await client.waitUntilReady(serverName)
117
+ await client.waitUntilReady(serverName, undefined, ctx.signal)
118
118
 
119
119
  const conn = client.getConnection(serverName)
120
120
  if (!conn || conn.status !== 'connected') {
@@ -125,7 +125,12 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
125
125
  }
126
126
  }
127
127
 
128
- const result: ToolCallResult = await client.callTool(serverName, mcpTool.name, params)
128
+ const result: ToolCallResult = await client.callTool(
129
+ serverName,
130
+ mcpTool.name,
131
+ params,
132
+ ctx.signal,
133
+ )
129
134
 
130
135
  const text = result.content
131
136
  .map((c) => {
@@ -12,7 +12,11 @@ export type NotificationHandler = (notification: JsonRpcNotification) => void
12
12
  * interface — callers invoke the concrete `start(...)` before use.
13
13
  */
14
14
  export interface Transport {
15
- sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown>
15
+ sendRequest(
16
+ method: string,
17
+ params?: Record<string, unknown>,
18
+ signal?: AbortSignal,
19
+ ): Promise<unknown>
16
20
  sendNotification(method: string, params?: Record<string, unknown>): void
17
21
  onNotification(handler: NotificationHandler): void
18
22
  close(): Promise<void>
@@ -214,10 +218,17 @@ export class StdioTransport implements Transport {
214
218
  })
215
219
  }
216
220
 
217
- async sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown> {
221
+ async sendRequest(
222
+ method: string,
223
+ params?: Record<string, unknown>,
224
+ signal?: AbortSignal,
225
+ ): Promise<unknown> {
218
226
  if (!this.proc || this.closed) {
219
227
  throw new Error('Transport not connected')
220
228
  }
229
+ if (signal?.aborted) {
230
+ throw new DOMException('Aborted', 'AbortError')
231
+ }
221
232
 
222
233
  const id = ++this.msgId
223
234
  const request: JsonRpcRequest = {
@@ -228,12 +239,38 @@ export class StdioTransport implements Transport {
228
239
  }
229
240
 
230
241
  return new Promise((resolve, reject) => {
242
+ // Cancellation has to reach the request itself: the caller's turn-level
243
+ // signal used to stop at the tool boundary, so a server that never
244
+ // answered held the turn until the 60s request timeout. Clearing the
245
+ // timer and deleting the pending entry keeps that timer from firing a
246
+ // second rejection on an already-settled promise.
247
+ const onAbort = (): void => {
248
+ const entry = this.pending.get(id)
249
+ if (!entry) return
250
+ this.pending.delete(id)
251
+ clearTimeout(entry.timer)
252
+ reject(new DOMException('Aborted', 'AbortError'))
253
+ }
254
+ signal?.addEventListener('abort', onAbort, { once: true })
255
+ const cleanup = (): void => signal?.removeEventListener('abort', onAbort)
256
+
231
257
  const timer = setTimeout(() => {
232
258
  this.pending.delete(id)
259
+ cleanup()
233
260
  reject(requestTimeoutError(method, this.requestTimeoutMs))
234
261
  }, this.requestTimeoutMs)
235
262
 
236
- this.pending.set(id, { resolve, reject, timer })
263
+ this.pending.set(id, {
264
+ resolve: (v) => {
265
+ cleanup()
266
+ resolve(v)
267
+ },
268
+ reject: (e) => {
269
+ cleanup()
270
+ reject(e)
271
+ },
272
+ timer,
273
+ })
237
274
 
238
275
  // Write to stdin
239
276
  this.proc!.stdin!.write(JSON.stringify(request) + '\n')
@@ -345,11 +345,32 @@ export class PluginManager {
345
345
  // plugin command instead of starting empty.
346
346
  this.plugins = Array.isArray(parsed) ? (parsed as InstalledPlugin[]) : []
347
347
  if (!Array.isArray(parsed)) {
348
- this.loadWarning = `Plugin state file is not a list; starting empty (${this.statePath})`
348
+ this.quarantineState('Plugin state file is not a list;')
349
349
  }
350
350
  } catch (err) {
351
351
  this.plugins = []
352
- this.loadWarning = `Could not read plugin state (${this.statePath}): ${String(err)}`
352
+ this.quarantineState(`Could not read plugin state (${this.statePath}): ${String(err)}.`)
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Move an unusable `state.json` aside before continuing with an empty list.
358
+ *
359
+ * Warning alone is not enough: the next `saveState` persists `[]` over the
360
+ * same path, so a file we could not read becomes a file whose records are
361
+ * gone. Renaming keeps the bytes for hand recovery — and if the rename fails
362
+ * the warning says so, because that is exactly the case where the next save
363
+ * destroys the only copy.
364
+ */
365
+ private quarantineState(reason: string): void {
366
+ const backup = `${this.statePath}.corrupt-${Date.now()}`
367
+ try {
368
+ renameSync(this.statePath, backup)
369
+ this.loadWarning = `${reason} Moved to ${backup}; starting with an empty plugin list.`
370
+ } catch (err) {
371
+ this.loadWarning =
372
+ `${reason} Could not move it aside (${String(err)}); starting with an empty ` +
373
+ `plugin list — the next change overwrites ${this.statePath}.`
353
374
  }
354
375
  }
355
376
 
@@ -199,7 +199,9 @@ export class AnthropicProvider implements ProviderInstance {
199
199
  yield {
200
200
  type: 'error',
201
201
  error: `Anthropic API error ${response.status}: ${errText}`,
202
- retryable: isRetryableFailure(response.status),
202
+ // 服务端给了 `x-should-retry` 就以它为准:429/5xx 上是「这件事不会有
203
+ // 下一次」,而只看状态会把这一轮挂在一架不可能成功的重试梯子上。
204
+ retryable: isRetryableFailure(response.status, undefined, response.headers),
203
205
  }
204
206
  return
205
207
  }
@@ -93,15 +93,42 @@ const NON_RETRYABLE_ERROR_TYPES = new Set([
93
93
  'content_policy_violation',
94
94
  ])
95
95
 
96
+ /**
97
+ * The provider's own verdict on whether this response may be re-sent, if it gave one.
98
+ *
99
+ * Anthropic answers some 429/5xx responses with `x-should-retry: false` — it is
100
+ * saying the failure will repeat (an exhausted quota, not a burst). A status-only
101
+ * rule sends it again anyway, and a turn sitting on a retry ladder that cannot
102
+ * succeed looks exactly like a slow response. `true` is honoured the same way, in
103
+ * the opposite direction: the server knows things the status code does not.
104
+ *
105
+ * Absent or unrecognised ⇒ `undefined`, i.e. no opinion: status rules decide, so a
106
+ * provider (or a test double) that never sends the header behaves as before.
107
+ */
108
+ export function parseShouldRetry(headers: Headers): boolean | undefined {
109
+ const raw = headers.get('x-should-retry')?.trim().toLowerCase()
110
+ if (raw === 'true') return true
111
+ if (raw === 'false') return false
112
+ return undefined
113
+ }
114
+
96
115
  /**
97
116
  * Should the engine re-send a turn the provider reported as failed?
98
117
  *
99
- * Two call shapes: an HTTP status, or a provider error object's `type`/`code`.
118
+ * Three call shapes: an HTTP status (optionally with the response headers, so the
119
+ * server's `x-should-retry` verdict wins over the status rule), or a provider
120
+ * error object's `type`/`code`.
100
121
  * Statuses follow the same rule as `fetchWithRetry` (429 and 5xx are transient).
101
122
  * For an error type, only the *known* deterministic ones say no — an unrecognised
102
123
  * type stays retryable, because guessing "final" would lose a recoverable turn.
103
124
  */
104
- export function isRetryableFailure(status: number | undefined, errorType?: string): boolean {
125
+ export function isRetryableFailure(
126
+ status: number | undefined,
127
+ errorType?: string,
128
+ headers?: Headers,
129
+ ): boolean {
130
+ const verdict = headers ? parseShouldRetry(headers) : undefined
131
+ if (verdict !== undefined) return verdict
105
132
  if (status !== undefined) return RETRYABLE_STATUSES.has(status) || status >= 500
106
133
  if (errorType === undefined) return true
107
134
  return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
@@ -187,10 +214,17 @@ export async function fetchWithRetry(
187
214
  try {
188
215
  const response = await fetch(url, { ...init, signal })
189
216
 
190
- // 429 / 5xx → retry
191
- if (RETRYABLE_STATUSES.has(response.status) && attempt < maxRetries) {
192
- await sleep(retryDelayMs(response.headers.get('Retry-After'), attempt, baseDelay))
193
- continue
217
+ // 429 / 5xx → retry, unless the server itself said which way to go.
218
+ // `x-should-retry: false` on a 503 means "this will fail again"; re-sending
219
+ // it only holds the turn. Only error statuses are eligible either way — a
220
+ // 200 carrying `true` is not a failure to re-issue.
221
+ if (!response.ok) {
222
+ const verdict = parseShouldRetry(response.headers)
223
+ const retryable = verdict ?? RETRYABLE_STATUSES.has(response.status)
224
+ if (retryable && attempt < maxRetries) {
225
+ await sleep(retryDelayMs(response.headers.get('Retry-After'), attempt, baseDelay))
226
+ continue
227
+ }
194
228
  }
195
229
 
196
230
  return response
@@ -59,7 +59,8 @@ export class OpenAICompatProvider implements ProviderInstance {
59
59
  yield {
60
60
  type: 'error',
61
61
  error: `OpenAI API error ${response.status}: ${errText}`,
62
- retryable: isRetryableFailure(response.status),
62
+ // 网关可能替上游把 `x-should-retry` 带回来;给了就压过状态规则。
63
+ retryable: isRetryableFailure(response.status, undefined, response.headers),
63
64
  }
64
65
  return
65
66
  }
@@ -8,6 +8,9 @@ import { getMetrics } from '../core/metrics'
8
8
  * active. Exported so the permission classifier and `self-critique` pick the
9
9
  * same model — two private copies of this heuristic would drift apart silently.
10
10
  */
11
+ /** Tier shorthands an agent definition may use instead of a concrete model id. */
12
+ const MODEL_TIER_ALIASES = new Set(['haiku', 'sonnet', 'opus'])
13
+
11
14
  export function pickFastestModel(registry: ProviderRegistry): string {
12
15
  const models = registry.listModels?.() ?? []
13
16
  const flash = models.find(
@@ -120,12 +123,31 @@ export class ProviderRegistry implements Llm {
120
123
  return provider.config.models.filter((m) => m.status === 'active')
121
124
  }
122
125
 
126
+ /**
127
+ * `haiku` / `sonnet` / `opus` are **tiers, not ids** — agent definitions
128
+ * (`AgentDefinition.model`) and `--model` spell them that way to mean "the
129
+ * current model of this tier". An exact id always wins, so a provider that
130
+ * really ships a model with that name is unaffected. Otherwise the tier is
131
+ * resolved against the **active provider only**: returning another provider's
132
+ * model would pair an id with a provider that cannot serve it, since the
133
+ * caller passes the resolved id back to the active provider's `chat()`.
134
+ *
135
+ * Within the tier the **last listed** active model wins — provider configs
136
+ * enumerate a family in ascending version order (`…-sonnet-4-6` before
137
+ * `…-sonnet-5`).
138
+ */
123
139
  findModel(modelId: string): ModelInfo | undefined {
124
140
  for (const provider of this.providers.values()) {
125
141
  const model = provider.config.models.find((m) => m.id === modelId)
126
142
  if (model) return model
127
143
  }
128
- return undefined
144
+ if (!MODEL_TIER_ALIASES.has(modelId)) return undefined
145
+ const active = this.providers.get(this.activeProviderId)
146
+ if (!active) return undefined
147
+ const tier = active.config.models.filter(
148
+ (m) => m.status === 'active' && m.id.toLowerCase().includes(`-${modelId}-`),
149
+ )
150
+ return tier.at(-1)
129
151
  }
130
152
 
131
153
  /**
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Environment for git commands **this program runs on its own behalf** (creating
3
+ * a worktree, reading the branch, …) — as opposed to commands the model asked to
4
+ * run in the user's shell.
5
+ *
6
+ * `GIT_NO_REPLACE_OBJECTS=1` makes git ignore `refs/replace/*`. A replace ref
7
+ * rewrites what a commit *appears to be*: `git replace <a> <b>` makes every
8
+ * reader of `<a>` see `<b>`'s tree, so a checkout / `worktree add` produced from
9
+ * that view contains different files than the real object graph. These are local
10
+ * refs that any process in the repository can write, and this program derives no
11
+ * correctness from replaying them — the isolation boundary (`enter-worktree`,
12
+ * workflow agents, `/fork`, the CRSI sandbox) has to be built from true history.
13
+ * `git` itself still accepts the env var as an escape hatch, so nothing here
14
+ * breaks a repository that genuinely relies on replacements in a user's shell.
15
+ */
16
+ export function internalGitEnv(): NodeJS.ProcessEnv {
17
+ return { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' }
18
+ }