@miphamai/cli 0.85.43 → 0.85.45

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.
@@ -544,43 +544,176 @@ function skipEnvAssignment(tokens: string[], start: number): number {
544
544
  * `bash -c 'rm -rf /'`. Over-matching is the safe direction for a deny rule.
545
545
  */
546
546
  export function flattenCommand(command: string, depth = 0): string[] {
547
- const out: string[] = []
548
- for (const seg of splitShellSegments(command)) {
549
- out.push(seg)
547
+ return flattenCommandGroups(command, depth).flatMap((group) => group.variants)
548
+ }
549
+
550
+ /** One shell segment plus every normalized reading of it. */
551
+ export interface CommandSegmentGroup {
552
+ /** The segment as written — guards about what the command *really* runs judge this. */
553
+ raw: string
554
+ /** Readings of the same segment; a rule matching **any** of them matches the segment. */
555
+ variants: string[]
556
+ }
557
+
558
+ /**
559
+ * Like `flattenCommand`, but keeps each command segment's normalizations
560
+ * together.
561
+ *
562
+ * Why the grouping matters for an **allow** rule: a rule is a grant, and a
563
+ * compound command must satisfy it in every segment. The normalizations of one
564
+ * segment are alternative readings of the *same* command, so the grant needs
565
+ * only one of them to match — flattening everything into one list made the raw
566
+ * spelling mandatory too, and `NODE_ENV=production npm run build` stopped
567
+ * matching `Bash(npm:*)` (nor did `sudo npm run build`).
568
+ *
569
+ * The raw spelling is still what the foreign-command guard reads (see
570
+ * `matchBashRule`): stripping `--exec-path=…` must not let the normalized form
571
+ * pass a grant the raw form was refused.
572
+ */
573
+ export function flattenCommandGroups(command: string, depth = 0): CommandSegmentGroup[] {
574
+ const groups: CommandSegmentGroup[] = []
575
+ for (const seg of splitShellSegments(joinLineContinuations(command))) {
576
+ const variants: string[] = [seg]
550
577
  // The shell removes quotes before running the command, so `rm "-rf" /tmp`
551
578
  // *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
552
579
  // quoted spelling used to slip past `Bash(rm -rf *)`.
553
- const unquoted = dequoteSimpleTokens(seg)
554
- if (unquoted !== seg) out.push(unquoted)
555
- const stripped = stripPrefixCommand(seg)
556
- if (stripped !== seg) out.push(stripped)
580
+ const push = (v: string) => {
581
+ if (v !== seg && !variants.includes(v)) variants.push(v)
582
+ }
583
+ push(dequoteSimpleTokens(seg))
584
+ push(stripPrefixCommand(seg))
557
585
  // 剥掉前导噪声后的形态也要参与匹配:`IFS=x rm -rf x` / `( rm -rf x )` /
558
586
  // `for …; do rm -rf x; done` 执行的仍是 `rm`,规则必须看得见它。同一个函数
559
587
  // 也被 scanReaderWriterCommands 用(Read/Write/Edit 桥接那条路径)—— 两条
560
588
  // 路径共用一份归一化,只接一条就是只修一半。
561
- const denoised = stripLeadingShellNoise(seg)
562
- if (denoised !== seg) out.push(denoised)
563
- for (const inner of extractSubstitutions(seg)) {
564
- out.push(...flattenCommand(inner, depth + 1))
565
- }
589
+ push(stripLeadingShellNoise(seg))
566
590
  // Wrapper prefixes (`env`, `sudo`, `timeout`, …) are not the command being
567
591
  // run. Without their removal `env X="a b" rm -rf /` matched no `rm …`
568
592
  // rule at all, because the matcher never saw past the assignment.
569
593
  const { base, args, payload } = effectiveCommand(seg.split(/\s+/).filter(Boolean))
570
- if (base) {
571
- const unwrapped = [base, ...args].join(' ')
572
- if (unwrapped !== seg) out.push(unwrapped)
594
+ if (base) push([base, ...args].join(' '))
595
+ // Global options before a subcommand (`git -C /path log`). The allow rule
596
+ // `Bash(git log:*)` names the subcommand, and the option only decides where
597
+ // it runs — not which program does. Guarded variants are judged on `raw`.
598
+ const subcommand = stripGlobalOptions(seg)
599
+ if (subcommand) push(subcommand)
600
+
601
+ groups.push({ raw: seg, variants })
602
+
603
+ for (const inner of extractSubstitutions(seg)) {
604
+ groups.push(...flattenCommandGroups(inner, depth + 1))
573
605
  }
574
606
  // A shell `-c` payload is a command line in its own right, so `Bash(rm *)`
575
607
  // must also match `bash -c 'rm -rf /'`. Past the depth bound recursion stops
576
608
  // outright rather than pushing the raw payload: the raw text
577
609
  // (`bash -c 'rm -rf /'`) matches no `rm …` pattern anyway, and stopping
578
610
  // keeps the boundary predictable.
579
- if (payload && depth < MAX_COMMAND_DEPTH) out.push(...flattenCommand(payload, depth + 1))
611
+ if (payload && depth < MAX_COMMAND_DEPTH)
612
+ groups.push(...flattenCommandGroups(payload, depth + 1))
613
+ }
614
+ return groups
615
+ }
616
+
617
+ /**
618
+ * Remove backslash-newline continuations before splitting a command into
619
+ * segments.
620
+ *
621
+ * `splitShellSegments` splits on `\n`, but a shell removes `\` + newline
622
+ * *before* parsing, so `npm install \⏎left-pad` is one command. Splitting first
623
+ * produced two segments — the first (`npm install \`) matched no allow rule and
624
+ * the whole command fell back to "ask". Inside single quotes the backslash is
625
+ * literal, so the pair stays.
626
+ */
627
+ export function joinLineContinuations(command: string): string {
628
+ let out = ''
629
+ let quote: "'" | '"' | null = null
630
+ for (let i = 0; i < command.length; i++) {
631
+ const ch = command[i]!
632
+ if (ch === '\\' && quote !== "'") {
633
+ if (command[i + 1] === '\n') {
634
+ i += 1
635
+ continue
636
+ }
637
+ if (command[i + 1] === '\r' && command[i + 2] === '\n') {
638
+ i += 2
639
+ continue
640
+ }
641
+ // Any other escaped character: keep both, and do not let the escaped
642
+ // character toggle quote state (`\"` is a literal quote).
643
+ out += ch
644
+ if (i + 1 < command.length) {
645
+ out += command[i + 1]
646
+ i += 1
647
+ }
648
+ continue
649
+ }
650
+ if (ch === "'" && quote !== '"') {
651
+ quote = quote === "'" ? null : "'"
652
+ } else if (ch === '"' && quote !== "'") {
653
+ quote = quote === '"' ? null : '"'
654
+ }
655
+ out += ch
580
656
  }
581
657
  return out
582
658
  }
583
659
 
660
+ /** git global options that consume the next token. */
661
+ const GIT_GLOBAL_WITH_ARG = new Set([
662
+ '-C',
663
+ '-c',
664
+ '--git-dir',
665
+ '--work-tree',
666
+ '--namespace',
667
+ '--exec-path',
668
+ '--config-env',
669
+ '--super-prefix',
670
+ ])
671
+ /** git global options that stand alone. */
672
+ const GIT_GLOBAL_FLAGS = new Set([
673
+ '-p',
674
+ '--paginate',
675
+ '-P',
676
+ '--no-pager',
677
+ '--bare',
678
+ '--no-replace-objects',
679
+ '--literal-pathspecs',
680
+ '--no-optional-locks',
681
+ '--no-advice',
682
+ '--no-lazy-fetch',
683
+ ])
684
+
685
+ /**
686
+ * Normalize a known command by dropping global options that precede its
687
+ * subcommand (`git -C /path log` → `git log`).
688
+ *
689
+ * Only commands whose global-option grammar is known are normalized — a generic
690
+ * "skip everything that starts with -" would drop flags that *are* the command's
691
+ * behaviour. Returns null when there is nothing to strip.
692
+ */
693
+ export function stripGlobalOptions(segment: string): string | null {
694
+ const tokens = segment.trim().split(/\s+/)
695
+ if (tokens[0] !== 'git') return null
696
+ let i = 1
697
+ while (i < tokens.length) {
698
+ const token = tokens[i]!
699
+ if (GIT_GLOBAL_FLAGS.has(token)) {
700
+ i += 1
701
+ continue
702
+ }
703
+ if (GIT_GLOBAL_WITH_ARG.has(token)) {
704
+ i += 2
705
+ continue
706
+ }
707
+ if ([...GIT_GLOBAL_WITH_ARG].some((opt) => token.startsWith(`${opt}=`))) {
708
+ i += 1
709
+ continue
710
+ }
711
+ break
712
+ }
713
+ if (i === 1 || i >= tokens.length) return null
714
+ return ['git', ...tokens.slice(i)].join(' ')
715
+ }
716
+
584
717
  /**
585
718
  * Resolve the effective command and its arguments after any wrapper prefix
586
719
  * commands (`sudo`, `env`, `timeout`, …). Skips the wrapper and its own options
@@ -1016,7 +1149,7 @@ export function matchBashRule(
1016
1149
  // The `length > 0` guard is load-bearing: `[].every()` is `true`, so a
1017
1150
  // command with no matchable segment (or no extracted file access) would
1018
1151
  // otherwise satisfy **any** allow rule — a fail-open of its own.
1019
- const qualifies = (items: string[], match: (s: string) => boolean): boolean =>
1152
+ const qualifies = <T>(items: T[], match: (item: T) => boolean): boolean =>
1020
1153
  segmentMode === 'all' ? items.length > 0 && items.every(match) : items.some(match)
1021
1154
 
1022
1155
  // A Read/Write/Edit rule must also refuse a Bash command that touches the
@@ -1066,24 +1199,30 @@ export function matchBashRule(
1066
1199
  // the safe direction.
1067
1200
  const anchored = segmentMode === 'all' ? /^([\w./-]+)\*/.exec(subPattern!) : null
1068
1201
  const firstWord = anchored?.[1]
1069
- return qualifies(flattenCommand(cmd), (seg) => {
1070
- if (firstWord) {
1071
- // The wildcard has to start at a word boundary in the command: `ls`
1072
- // exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
1073
- // `lsof`.
1074
- const boundary = new RegExp(
1075
- '^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])',
1076
- )
1077
- if (!boundary.test(seg)) return false
1078
- }
1202
+ // The wildcard has to start at a word boundary in the command: `ls`
1203
+ // exactly, or `ls` followed by whitespace/`:` — not the `ls` inside
1204
+ // `lsof`.
1205
+ const boundary = firstWord
1206
+ ? new RegExp('^' + firstWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?:$|[:\\s])')
1207
+ : null
1208
+ return qualifies(flattenCommandGroups(cmd), (group) => {
1079
1209
  // An allow rule names a program; these options make that program run a
1080
1210
  // **different** one (`find -exec rm`, `git --upload-pack=…`,
1081
1211
  // `awk system(…)`). Matching the outer word alone would hand over the
1082
1212
  // inner command too, so the segment is not covered by the grant. This
1083
1213
  // list is a floor, not a ceiling — every entry is a construct that
1084
1214
  // executes a command the rule did not name.
1085
- if (segmentMode === 'all' && embedsForeignCommand(seg)) return false
1086
- return wildcardMatch(subPattern!, seg)
1215
+ //
1216
+ // Judged on the segment **as written**: the normalized variants exist to
1217
+ // let benign prefixes match, and letting them carry a stripped
1218
+ // `--exec-path=…` past this guard would turn the fix into a bypass.
1219
+ if (segmentMode === 'all' && embedsForeignCommand(group.raw)) return false
1220
+ // The variants are alternative readings of *this* command — any one of
1221
+ // them matching is enough. (Across segments the caller still applies
1222
+ // 'all' / 'any'; this is the within-segment OR.)
1223
+ return group.variants.some(
1224
+ (seg) => (!boundary || boundary.test(seg)) && wildcardMatch(subPattern!, seg),
1225
+ )
1087
1226
  })
1088
1227
  }
1089
1228
 
@@ -514,6 +514,26 @@ export class PermissionSystem {
514
514
  return this.agentCapWarnings
515
515
  }
516
516
 
517
+ /**
518
+ * Does a deny rule name this tool **outright**?
519
+ *
520
+ * A rule with an input pattern (`Bash(rm:*)`, a path-scoped `Read`) denies
521
+ * *some* invocations, not the tool — those stay visible. A bare name, or a
522
+ * server wildcard (`mcp__srv__*`), denies every call; a tool the model can
523
+ * never run is not worth offering, and naming it in the request only invites
524
+ * calls that are guaranteed to fail.
525
+ *
526
+ * Read by `QueryEngine.getToolDefinitions()` to keep denied tools out of the
527
+ * model-facing list (the rule itself still decides at call time — this is a
528
+ * visibility filter, not a second gate).
529
+ */
530
+ isToolNameDenied(toolName: string): boolean {
531
+ return this.denyRules.some(
532
+ (rule) =>
533
+ !rule.pattern.includes('(') && (rule.pattern === toolName || rule.compiled.test(toolName)),
534
+ )
535
+ }
536
+
517
537
  // ── Rule management ──
518
538
 
519
539
  allow(rule: string): void {
@@ -1,4 +1,4 @@
1
- import { mkdirSync, openSync, readSync, closeSync, statSync } from 'node:fs'
1
+ import { mkdirSync, openSync, readSync, closeSync, statSync, existsSync, renameSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { createHash } from 'node:crypto'
4
4
  import type { Message, ToolUseContent, ToolResultContent, ToolResult } from '../shared/types'
@@ -278,6 +278,44 @@ export class SessionLog {
278
278
  this.save()
279
279
  }
280
280
 
281
+ /** 当前会话名(`/rename` 之后是**新**名字 —— 落盘路径按它推导)。 */
282
+ getName(): string {
283
+ return this.name
284
+ }
285
+
286
+ /**
287
+ * 把会话日志改名 —— 让 `/rename` 与 `/resume <name>` 落在**同一个命名空间**。
288
+ *
289
+ * 从前 `/rename` 只改内存标题与跨会话登记表,`<旧名>.jsonl` 原封不动:用户
290
+ * `/rename Bug Fix` 之后 `/resume Bug Fix` 找不到任何东西,而 `/resume <旧名>`
291
+ * 又读得到 —— 两个名字指向同一段对话,却只有一个是活的。
292
+ *
293
+ * 必须改 `this.name` 而不是只搬文件:`save()` 每次都按名字重算路径,文件搬走了
294
+ * 而字段没变,下一次 `append` 会**新建一个旧名字的空文件**,历史当场分叉。
295
+ *
296
+ * 返回 `'conflict'` 时什么都没动(目标名已有别的会话),调用方必须如实说出来:
297
+ * 静默覆盖别人的会话,或静默假称已改名,都是把「失败」渲染成「成功」。
298
+ */
299
+ rename(newName: string): 'renamed' | 'unchanged' | 'conflict' {
300
+ if (newName === this.name) return 'unchanged'
301
+ const oldPath = join(this.dir, `${sanitizeSessionName(this.name)}.jsonl`)
302
+ const newPath = join(this.dir, `${sanitizeSessionName(newName)}.jsonl`)
303
+ // 两个不同名字可能消毒到同一个文件名(`a/b` 与 `a_b`):此时文件已经是
304
+ // 目标路径,不需要也不能 rename。
305
+ if (oldPath !== newPath) {
306
+ if (existsSync(newPath)) return 'conflict'
307
+ if (existsSync(oldPath)) {
308
+ try {
309
+ renameSync(oldPath, newPath)
310
+ } catch {
311
+ return 'conflict'
312
+ }
313
+ }
314
+ }
315
+ this.name = newName
316
+ return 'renamed'
317
+ }
318
+
281
319
  /** 不可变快照(浅拷贝,事件本身视为不可变)。 */
282
320
  events(): SessionEvent[] {
283
321
  return [...this.buf]
@@ -1,4 +1,4 @@
1
- import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync } from 'node:fs'
1
+ import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync, renameSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { createHash } from 'node:crypto'
4
4
  import type { Message } from '../shared/types'
@@ -333,6 +333,38 @@ export class SessionStore {
333
333
  atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
334
334
  }
335
335
 
336
+ /**
337
+ * Move a session's **index entry** (and its saved summary) to a new name.
338
+ *
339
+ * `/rename` renames the transcript file via `SessionLog.rename`; the index is a
340
+ * separate store, and leaving the old row behind makes `/resume last` point at
341
+ * a file that no longer exists. Returns false when there is no old entry or the
342
+ * new name is already taken — in both cases *nothing* is changed, so a caller
343
+ * that reports failure is telling the truth.
344
+ */
345
+ static renameEntry(oldName: string, newName: string): boolean {
346
+ ensureDir()
347
+ const index = SessionStore.loadIndexRaw()
348
+ const entry = index.find((e) => e.name === oldName)
349
+ if (!entry) return false
350
+ if (index.some((e) => e.name === newName)) return false
351
+ entry.name = newName
352
+ atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
353
+
354
+ // The summary file is named after the session, so it has to follow too —
355
+ // otherwise the renamed session silently loses the recap the user generated.
356
+ const oldSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(oldName)}.md`)
357
+ const newSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(newName)}.md`)
358
+ if (oldSummary !== newSummary && existsSync(oldSummary) && !existsSync(newSummary)) {
359
+ try {
360
+ renameSync(oldSummary, newSummary)
361
+ } catch {
362
+ // Summary is a cache; a failed move must not fail the rename.
363
+ }
364
+ }
365
+ return true
366
+ }
367
+
336
368
  /**
337
369
  * Persist an LLM-generated summary for a session.
338
370
  * Writes a markdown file to .summaries/ and updates the index entry.
@@ -95,10 +95,16 @@ export async function runPreToolGate(
95
95
  // key name. `defer` (and an absent decision) means "no override", which is
96
96
  // exactly what happens when we do nothing.
97
97
  if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
98
+ // A hook that also supplied `updatedInput` proposed a rewrite; there is no
99
+ // approval path to carry it through, so we refuse — but say the rewrite
100
+ // existed. Silently discarding it is the failure mode this note removes.
101
+ const rewriteNote = preResult.modifiedInput
102
+ ? ` ${t('errors.tool_hook_ask_rewrite', { name })}`
103
+ : ''
98
104
  return {
99
105
  ok: false,
100
106
  content: '',
101
- error: preResult.reason || t('errors.tool_hook_ask', { name }),
107
+ error: (preResult.reason || t('errors.tool_hook_ask', { name })) + rewriteNote,
102
108
  notRun: true,
103
109
  }
104
110
  }
@@ -79,6 +79,10 @@ function skillsFor(cwd: string, paths?: string[]): SkillsLoader {
79
79
  loader.loadBuiltinFromPackage()
80
80
  if (!isSafeMode()) {
81
81
  loader.loadUserSkills()
82
+ // Project scope follows the workspace (`<cwd>/.mipham/skills`), same as the
83
+ // CLI — the two entry points must load the same set or a skill works in one
84
+ // and silently not in the other.
85
+ loader.loadProjectSkills(cwd)
82
86
  if (paths && paths.length > 0) loader.loadExternal(paths)
83
87
  }
84
88
  skillsCache.set(cwd, loader)
@@ -92,7 +92,8 @@
92
92
  "rename": {
93
93
  "usage": "Usage: /rename <session-name>\nExample: /rename Bug Fix Session",
94
94
  "confirmed": "✓ Session renamed to \"{name}\"",
95
- "unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last."
95
+ "unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last.",
96
+ "log_conflict": "⚠ Title set to \"{name}\", but a saved session already uses that name — the transcript stays under \"{old}\" (/resume {old})."
96
97
  },
97
98
  "plan": {
98
99
  "entered": "Entered plan mode.",
@@ -512,7 +513,12 @@
512
513
  "skills_unavailable": " (skills info unavailable)",
513
514
  "audit_section": "── CLAUDE.md Audit ──",
514
515
  "audit_clean": " ✓ no code-derivable sections found",
515
- "audit_found": "Add the sections above to the `prompt-exclude` frontmatter to stop sending them to the model."
516
+ "audit_found": "Add the sections above to the `prompt-exclude` frontmatter to stop sending them to the model.",
517
+ "api_section": "── API ──",
518
+ "api_target": " {provider} ({model})",
519
+ "api_not_tested": " ⚪ not tested — {reason}",
520
+ "api_reachable": " 🟢 reachable — {detail}",
521
+ "api_unreachable": " 🔴 unreachable — {detail}"
516
522
  },
517
523
  "skillDoctor": {
518
524
  "title": "── Skill Doctor ──",
@@ -960,6 +966,7 @@
960
966
  "tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
961
967
  "tool_blocked": "Tool \"{name}\" blocked by hook",
962
968
  "tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
969
+ "tool_hook_ask_rewrite": "The hook also proposed a rewritten input for \"{name}\"; it was discarded, because a refusal has no approval path to carry it through.",
963
970
  "user_input_blocked": "User input blocked by hook.",
964
971
  "dlp_blocked": "Request blocked by DLP policy.",
965
972
  "model_error": "Error: {error}",
@@ -985,6 +992,9 @@
985
992
  "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.",
986
993
  "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.",
987
994
  "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.",
995
+ "turn_continuing": "The reply hit the model's output limit — continuing automatically.",
996
+ "turn_truncated_limit": "The reply hit the model's output limit and was cut off; this turn will not be continued further.",
997
+ "continuation_prompt": "Your previous reply was cut off at the output limit. Continue exactly where it stopped — do not repeat anything already written.",
988
998
  "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.",
989
999
  "turn_refused_reason": "The model declined this request: {reason}",
990
1000
  "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.",
@@ -92,7 +92,8 @@
92
92
  "rename": {
93
93
  "usage": "用法: /rename <session-name>\n示例: /rename 修复 Bug 的会话",
94
94
  "confirmed": "✓ 会话重命名为 \"{name}\"",
95
- "unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。"
95
+ "unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。",
96
+ "log_conflict": "⚠ 标题已改为 \"{name}\",但已存在同名会话存档 —— 对话记录仍保存在 \"{old}\" 下(可用 /resume {old} 找回)。"
96
97
  },
97
98
  "plan": {
98
99
  "entered": "已进入计划模式。",
@@ -512,7 +513,12 @@
512
513
  "skills_unavailable": " (技能信息不可用)",
513
514
  "audit_section": "── CLAUDE.md 审计 ──",
514
515
  "audit_clean": " ✓ 未发现可从代码推断的冗余章节",
515
- "audit_found": "将上述章节加入 `prompt-exclude` frontmatter,可停止发送给模型、节省 token。"
516
+ "audit_found": "将上述章节加入 `prompt-exclude` frontmatter,可停止发送给模型、节省 token。",
517
+ "api_section": "── API ──",
518
+ "api_target": " {provider}({model})",
519
+ "api_not_tested": " ⚪ 未测试 — {reason}",
520
+ "api_reachable": " 🟢 可连接 — {detail}",
521
+ "api_unreachable": " 🔴 不可连接 — {detail}"
516
522
  },
517
523
  "skillDoctor": {
518
524
  "title": "── 技能体检 ──",
@@ -960,6 +966,7 @@
960
966
  "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
961
967
  "tool_blocked": "工具 \"{name}\" 被钩子拦截",
962
968
  "tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
969
+ "tool_hook_ask_rewrite": "该钩子同时为 \"{name}\" 提出了改写后的输入;因为本次是拒绝、没有批准通道可以承接它,改写已丢弃。",
963
970
  "user_input_blocked": "用户输入被钩子拦截。",
964
971
  "dlp_blocked": "请求被 DLP 策略阻止。",
965
972
  "model_error": "错误:{error}",
@@ -985,6 +992,9 @@
985
992
  "max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
986
993
  "turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
987
994
  "turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。如果是经代理或公司网关访问提供商,先查那一层;否则检查 VPN 与防火墙规则。",
995
+ "turn_continuing": "回复到达模型输出上限 —— 正在自动续写。",
996
+ "turn_truncated_limit": "回复到达模型输出上限,已被截断;本轮不再继续续写。",
997
+ "continuation_prompt": "你上一条回复在输出上限处被截断了。请从断掉的地方原样接着写 —— 不要重复已经写过的内容。",
988
998
  "turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
989
999
  "turn_refused_reason": "模型拒绝了这次请求:{reason}",
990
1000
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
package/src/index.tsx CHANGED
@@ -554,6 +554,8 @@ export async function runApp(options: RunOptions): Promise<void> {
554
554
  skillsLoader.loadBuiltinFromPackage()
555
555
  if (!safeMode) {
556
556
  skillsLoader.loadUserSkills()
557
+ // The documented project scope (`.mipham/skills/`) — see `loadProjectSkills`.
558
+ skillsLoader.loadProjectSkills(process.cwd())
557
559
  if (config.skills?.paths) {
558
560
  skillsLoader.loadExternal(config.skills.paths)
559
561
  }
@@ -987,7 +989,10 @@ export async function runApp(options: RunOptions): Promise<void> {
987
989
  if (context.getMessageCount() === 0) return
988
990
  const log = context.getLog()
989
991
  if (log) {
990
- SessionStore.saveLog(sessionName, log, {
992
+ // `/rename` moves the transcript file; the index entry must follow the
993
+ // log's *current* name, not the one this process started with — otherwise
994
+ // the row points at a file that was just renamed away.
995
+ SessionStore.saveLog(log.getName(), log, {
991
996
  provider: defaultProvider,
992
997
  model: defaultModel,
993
998
  cwd: process.cwd(),
@@ -222,7 +222,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
222
222
  ctx.signal,
223
223
  )
224
224
 
225
- const text = result.content
225
+ const text = (result.content ?? [])
226
226
  .map((c) => {
227
227
  if (c.type === 'text' && c.text) return c.text
228
228
  if (c.type === 'image') return `[Image: ${c.mimeType || 'unknown'}]`
@@ -230,10 +230,18 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
230
230
  })
231
231
  .join('\n')
232
232
 
233
+ // A server may answer only in `structuredContent` (MCP 2025-06). Dropping
234
+ // it turned a real payload into "(empty result)" — indistinguishable from
235
+ // a tool that genuinely returned nothing.
236
+ const structured =
237
+ text === '' && result.structuredContent !== undefined
238
+ ? JSON.stringify(result.structuredContent, null, 2)
239
+ : ''
240
+
233
241
  return {
234
242
  success: !result.isError,
235
- content: text || '(empty result)',
236
- error: result.isError ? text : undefined,
243
+ content: text || structured || '(empty result)',
244
+ error: result.isError ? text || structured : undefined,
237
245
  }
238
246
  },
239
247
  }
@@ -90,6 +90,25 @@ function killProcessTree(proc: ChildProcess): void {
90
90
  }
91
91
  }
92
92
 
93
+ /**
94
+ * The request id a response line answers, if any.
95
+ *
96
+ * Our requests carry **numeric** ids, but a server is free to stringify them on
97
+ * the way back (`"id": "7"`). That response used to match nothing, so the
98
+ * request stayed pending until the full request timeout — a malformed reply
99
+ * that reads as a slow server. Numeric-string ids are the one spelling we can
100
+ * map back safely; anything else (a non-numeric string, `null`, an object) names
101
+ * a request we never sent and must not settle someone else's promise.
102
+ */
103
+ function matchResponseId(value: unknown): number | null {
104
+ if (typeof value === 'number' && Number.isInteger(value)) return value
105
+ if (typeof value === 'string' && /^\d+$/.test(value)) {
106
+ const id = Number(value)
107
+ return Number.isSafeInteger(id) ? id : null
108
+ }
109
+ return null
110
+ }
111
+
93
112
  /** Every descendant of `root`, parents before children. */
94
113
  function descendantPids(root: number): number[] {
95
114
  let listing: string
@@ -232,12 +251,13 @@ export class StdioTransport implements Transport {
232
251
  const msg = JSON.parse(trimmed)
233
252
 
234
253
  // Check if it's a response (has id and result/error)
235
- if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
236
- const response = msg as JsonRpcResponse
237
- const entry = this.pending.get(response.id)
254
+ const responseId = matchResponseId(msg.id)
255
+ if (responseId !== null && ('result' in msg || 'error' in msg)) {
256
+ const entry = this.pending.get(responseId)
238
257
  if (entry) {
239
258
  clearTimeout(entry.timer)
240
- this.pending.delete(response.id)
259
+ this.pending.delete(responseId)
260
+ const response = msg as JsonRpcResponse
241
261
  if (response.error) {
242
262
  entry.reject(
243
263
  new Error(`MCP error ${response.error.code}: ${response.error.message}`),
package/src/mcp/types.ts CHANGED
@@ -83,6 +83,12 @@ export interface ToolCallContent {
83
83
 
84
84
  export interface ToolCallResult {
85
85
  content: ToolCallContent[]
86
+ /**
87
+ * MCP 2025-06 `structuredContent`: a machine-readable payload some servers
88
+ * return *instead of* (or alongside) text blocks. Ignoring it made such a
89
+ * server look like it answered nothing at all.
90
+ */
91
+ structuredContent?: unknown
86
92
  isError?: boolean
87
93
  }
88
94