@miphamai/cli 0.85.41 → 0.85.43

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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.41
1
+ # Mipham Code v0.85.43
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.41",
3
+ "version": "0.85.43",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -72,6 +72,7 @@ const BUILTIN_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
72
72
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
73
73
  'code-review':
74
74
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
75
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
75
76
  }
76
77
 
77
78
  const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
@@ -79,6 +80,7 @@ const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
79
80
  explore: 'Read-only search agent for broad fan-out searches across files.',
80
81
  plan: 'Software architect agent for designing implementation plans.',
81
82
  'code-review': 'Code review agent for finding bugs and quality issues.',
83
+ fork: 'Sub-agent that inherits the current conversation and continues from it.',
82
84
  }
83
85
 
84
86
  export class AgentRegistry {
@@ -35,7 +35,10 @@ export class FileInboxTransport implements CrossSessionTransport {
35
35
  private initialized = false
36
36
 
37
37
  private ensureDir(dir: string): void {
38
- mkdirSync(dir, { recursive: true })
38
+ // Owner-only. The inbox carries other sessions' message bodies; the default
39
+ // 0755 directory makes them readable by every local account on a machine
40
+ // whose home directory is world-traversable.
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
39
42
  }
40
43
 
41
44
  /** Ensure the inbox root directory exists (call on first use). */
@@ -69,7 +72,7 @@ export class FileInboxTransport implements CrossSessionTransport {
69
72
 
70
73
  // Atomic write: temp file then rename
71
74
  const tmpPath = filePath + '.tmp'
72
- atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o644 })
75
+ atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o600 })
73
76
  renameSync(tmpPath, filePath)
74
77
 
75
78
  return true
@@ -55,6 +55,7 @@ const TYPE_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
55
55
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
56
56
  'code-review':
57
57
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
58
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
58
59
  }
59
60
 
60
61
  /**
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { Message, ToolContext } from '../shared/index.ts'
4
4
 
5
- export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review'
5
+ export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review' | 'fork'
6
6
 
7
7
  export interface AgentFrontmatter {
8
8
  name: string
@@ -924,7 +924,9 @@ Current directory: ${process.cwd()}`,
924
924
  Nothing was registered — this build has no workspace-directory allowlist.
925
925
 
926
926
  How access is actually decided:
927
- • Reads — not limited by directory. What refuses a file is a deny rule
927
+ • Reads — must resolve inside the session directory. Read/Grep/Glob/Edit/
928
+ Write all go through the same workspace check, so a path outside
929
+ it is rejected. Inside it, a deny rule can still refuse a file
928
930
  (\`Read(<path>)\`, which also covers Bash readers like cat/head).
929
931
  • Writes — gated by the permission mode (Shift+Tab cycles:
930
932
  ${renderCycleLine()}).
@@ -466,6 +466,13 @@ function loadMcpJson(cwd: string, warn?: (message: string) => void): McpServerCo
466
466
  */
467
467
  export interface SettingsJson {
468
468
  hooks: SettingsHooks
469
+ /**
470
+ * `disableAllHooks: true` — the Claude Code setting name, honoured for the
471
+ * hooks this file can configure (settings.json's own list). Omitted unless
472
+ * true, so the absent/`false` distinction stays visible. Built-in product
473
+ * hooks are not user-configured and are disabled only by `--safe-mode`.
474
+ */
475
+ disableAllHooks?: true
469
476
  /**
470
477
  * `allow` is the **user-level** file's list; a project-level one is withheld
471
478
  * (`projectAllowSkipped`) because a rule that widens is the approval gate by
@@ -591,6 +598,7 @@ export function loadSettingsJson(
591
598
  let projectModeSkipped = false
592
599
  let projectAllowSkipped = false
593
600
  let projectClassifierSkipped = false
601
+ let disableAllHooks = false
594
602
  // The project file's entries, kept out of the merge so provenance survives it.
595
603
  const projectHooks: SettingsHooks = {}
596
604
 
@@ -636,6 +644,7 @@ export function loadSettingsJson(
636
644
  }
637
645
  const parsed = JSON.parse(raw) as {
638
646
  hooks?: Record<string, unknown>
647
+ disableAllHooks?: unknown
639
648
  permissions?: {
640
649
  allow?: unknown
641
650
  deny?: unknown
@@ -645,6 +654,19 @@ export function loadSettingsJson(
645
654
  }
646
655
  }
647
656
 
657
+ if (parsed.disableAllHooks !== undefined) {
658
+ if (parsed.disableAllHooks === true) {
659
+ // Additive across levels and narrowing in every direction: whichever
660
+ // file said it, fewer shell commands run. A project file therefore may
661
+ // say it too — unlike `allow`, this is not a widening.
662
+ disableAllHooks = true
663
+ } else if (parsed.disableAllHooks !== false) {
664
+ process.stderr.write(
665
+ `⚠ Mipham Code: ignoring disableAllHooks from ${path} — expected true or false.\n`,
666
+ )
667
+ }
668
+ }
669
+
648
670
  if (!readHooks) {
649
671
  // "Was anything actually withheld?" is answered from the same parse that
650
672
  // would have read it, so the skip notice cannot outrun the fact.
@@ -686,8 +708,22 @@ export function loadSettingsJson(
686
708
  }
687
709
  for (const key of ['allow', 'deny'] as const) {
688
710
  const list = parsed.permissions[key]
689
- if (!Array.isArray(list)) continue
711
+ if (list === undefined) continue
712
+ // A hand-written `"deny": "Read(**/.env)"` (the YAML habit) used to be
713
+ // dropped here without a word. For `deny` that is fail-open: the user
714
+ // wrote a rule, believes it is in force, and nothing is. Say it.
715
+ if (!Array.isArray(list)) {
716
+ process.stderr.write(
717
+ `⚠ Mipham Code: ignoring permissions.${key} from ${path} — expected an array of rule strings, got ${typeof list}.\n`,
718
+ )
719
+ continue
720
+ }
690
721
  const strings = list.filter((p): p is string => typeof p === 'string')
722
+ if (strings.length !== list.length) {
723
+ process.stderr.write(
724
+ `⚠ Mipham Code: ignoring ${list.length - strings.length} non-string entry(s) in permissions.${key} from ${path}.\n`,
725
+ )
726
+ }
691
727
  // `deny` narrows, so a repository may ship it. `allow` widens — and the
692
728
  // question "does it widen past what is permitted?" is **not** answered by
693
729
  // the mode ceiling unless someone configured one: `allowRuleDecision`
@@ -756,6 +792,7 @@ export function loadSettingsJson(
756
792
  // "nothing to report" — an empty marker would let a caller tag user hooks as
757
793
  // gated on the strength of a file with nothing in it.
758
794
  const result: SettingsJson = { hooks, permissions }
795
+ if (disableAllHooks) result.disableAllHooks = true
759
796
  if (projectHooksSkipped) result.projectHooksSkipped = true
760
797
  if (projectModeSkipped) result.projectModeSkipped = true
761
798
  if (projectAllowSkipped) result.projectAllowSkipped = true
@@ -6,10 +6,19 @@ import { SecurityGate } from '../../security/gate'
6
6
  * Well-known secret token prefixes. These are high-signal formats that must
7
7
  * never leak into output, independent of the configured patterns.
8
8
  * - GitHub: ghp_ (personal access), gho_ (OAuth), ghs_ (server), ghu_/ghr_ (user/server-to-server), github_pat_ (fine-grained)
9
- * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app)
9
+ * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app),
10
+ * glptt- (pipeline trigger), glagent- (agent), glimt- (incoming mail),
11
+ * glsoat- (SCIM OAuth), glcbt- (CI build), glft- (feed), glffct- (feature flags)
12
+ *
13
+ * GitLab "routable" tokens carry a `.` between a short routing segment and the
14
+ * secret (e.g. `glpat-abcde.0123456789abcdef`). A body class without `.` stops
15
+ * at the first segment, redacting the routing prefix and leaving the secret in
16
+ * the clear — the dot-separated tail is part of the credential, not punctuation.
17
+ * Each dot segment must be at least five characters, so a sentence-ending period
18
+ * after a token is not swallowed.
10
19
  */
11
20
  const TOKEN_REDACTION_PATTERN =
12
- /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-)[A-Za-z0-9_-]{8,}/g
21
+ /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-|glptt-|glagent-|glimt-|glsoat-|glcbt-|glft-|glffct-)[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})*/g
13
22
 
14
23
  /**
15
24
  * Credentials embedded in a URL's userinfo — `scheme://user:password@host`.
@@ -762,6 +762,11 @@ export class QueryEngine {
762
762
  // Fire UserPromptSubmit hooks before processing
763
763
  if (this.hookEngine) {
764
764
  const submitResult = await this.hookEngine.executeUserPromptSubmit(userInput, this.sessionId)
765
+ // `systemMessage` is the hook's channel to the operator — show it here
766
+ // rather than folding it into model context.
767
+ if (submitResult.systemMessage) {
768
+ yield { type: 'warning', content: submitResult.systemMessage }
769
+ }
765
770
  if (submitResult.additionalContext) {
766
771
  this.context.addMessage({
767
772
  role: 'user',
@@ -1241,6 +1246,15 @@ export class QueryEngine {
1241
1246
  signal?: AbortSignal,
1242
1247
  roundsLeft: number = MAX_TOOL_TURNS,
1243
1248
  ): AsyncGenerator<StreamChunk> {
1249
+ // No rounds left: the turn ends here. `Stop` means "the agent finished
1250
+ // responding", and a turn whose tool-round budget ran out finished too. It
1251
+ // used to return silently, so a hook was never told — and a hook asking for
1252
+ // more work gets the budget-spent notice instead of being ignored.
1253
+ if (roundsLeft <= 0) {
1254
+ yield* this.checkStopHook(signal, 0)
1255
+ return
1256
+ }
1257
+
1244
1258
  // Task-level stall guard: a turn that produces no text or tool result for
1245
1259
  // this long is considered stalled and stopped (prevents ~40-min idle spins).
1246
1260
  //
@@ -1407,6 +1421,9 @@ export class QueryEngine {
1407
1421
  error: t('errors.max_tool_turns', { max: String(MAX_TOOL_TURNS) }),
1408
1422
  }
1409
1423
  }
1424
+ // The forced summary *is* the final answer for this turn, so Stop fires
1425
+ // here too. With no rounds left, a blocking hook can only be told so.
1426
+ yield* this.checkStopHook(signal, 0)
1410
1427
  return
1411
1428
  }
1412
1429
 
@@ -1572,6 +1589,9 @@ export class QueryEngine {
1572
1589
  llm: this.llm,
1573
1590
  readFiles: this.readFiles,
1574
1591
  readFilesComplete: this.readFilesComplete,
1592
+ // A copy: the sub-agent seeds its own context from this prefix while the
1593
+ // parent turn keeps appending to its list.
1594
+ parentMessages: this.context.getMessages().slice(),
1575
1595
  })
1576
1596
 
1577
1597
  // Track touched files for rules matching
@@ -1854,6 +1874,21 @@ export class QueryEngine {
1854
1874
  }
1855
1875
  continue
1856
1876
  }
1877
+ // Compaction has already run and the request is *still* too large.
1878
+ // Re-sending it — here or to a fallback provider — cannot change the
1879
+ // answer: the messages themselves are the oversized part and there is
1880
+ // nothing left to strip. Say why once instead of spending the retry and
1881
+ // fallback budget on a request that is guaranteed to fail the same way.
1882
+ if (compactedForOverflow && ownsFlow && isContextOverflowError(failure)) {
1883
+ yield {
1884
+ type: 'error',
1885
+ error:
1886
+ `${activeId} rejected the request as too large even after compacting — ` +
1887
+ `the conversation itself exceeds the request size limit, so retrying cannot help. ` +
1888
+ `Start a new session (/clear) or remove large attachments.`,
1889
+ }
1890
+ return
1891
+ }
1857
1892
  if (!retryable || !ownsFlow || attempt >= 1) break
1858
1893
  // `restart: true` tells the consumer to drop what the failed attempt already
1859
1894
  // yielded. Without it the retry's tool calls are *added* to the failed
@@ -2283,7 +2318,8 @@ export class QueryEngine {
2283
2318
  signal?: AbortSignal,
2284
2319
  roundsLeft: number = MAX_TOOL_TURNS,
2285
2320
  ): AsyncGenerator<StreamChunk> {
2286
- const block = await this.stopBlock()
2321
+ const { block, systemMessage } = await this.stopCheck()
2322
+ if (systemMessage) yield { type: 'warning', content: systemMessage }
2287
2323
  if (!block) return
2288
2324
 
2289
2325
  // A block asks for more work, and more work means another round — which the
@@ -2311,27 +2347,38 @@ export class QueryEngine {
2311
2347
  * 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
2312
2348
  * 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
2313
2349
  */
2314
- private async stopBlock(): Promise<{ source: string; text: string; reason: string } | null> {
2350
+ private async stopCheck(): Promise<{
2351
+ block: { source: string; text: string; reason: string } | null
2352
+ systemMessage?: string
2353
+ }> {
2354
+ let systemMessage: string | undefined
2315
2355
  if (this.hookEngine) {
2316
2356
  const stopResult = await this.hookEngine.executeStop(this.sessionId)
2357
+ systemMessage = stopResult.systemMessage
2317
2358
  if (stopResult.decision === 'block') {
2318
2359
  const reason = stopResult.reason || 'Continue working.'
2319
2360
  return {
2320
- source: 'stop-hook',
2321
- text: t('system.context.stop_blocked', { reason }),
2322
- reason,
2361
+ block: {
2362
+ source: 'stop-hook',
2363
+ text: t('system.context.stop_blocked', { reason }),
2364
+ reason,
2365
+ },
2366
+ systemMessage,
2323
2367
  }
2324
2368
  }
2325
2369
  }
2326
2370
 
2327
2371
  const claims = this.unprovenNumbers()
2328
- if (!claims) return null
2372
+ if (!claims) return { block: null, systemMessage }
2329
2373
  // 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
2330
2374
  // 把整段问话塞进 warning 只会让人读一屏。
2331
2375
  return {
2332
- source: 'number-provenance',
2333
- text: t('system.context.numbers_unproven', { claims }),
2334
- reason: claims,
2376
+ block: {
2377
+ source: 'number-provenance',
2378
+ text: t('system.context.numbers_unproven', { claims }),
2379
+ reason: claims,
2380
+ },
2381
+ systemMessage,
2335
2382
  }
2336
2383
  }
2337
2384
 
@@ -99,7 +99,25 @@ export function buildHookStdin(ctx: HookContext, cwd: string): Record<string, un
99
99
  * (permissionDecision / updatedInput / additionalContext) plus the legacy
100
100
  * root-level `decision` and `continue` fields. Non-JSON or empty stdout = allow.
101
101
  */
102
- export function parseHookStdout(stdout: string | null | undefined, _ctx: HookContext): HookResult {
102
+ export function parseHookStdout(stdout: string | null | undefined, ctx: HookContext): HookResult {
103
+ const result = parseHookStdoutFields(stdout, ctx)
104
+ if (!stdout) return result
105
+ // Root-level `systemMessage` is common to every event in the Claude hook
106
+ // contract — it is the one output meant for the *user*, not the model. It sat
107
+ // unread here: a hook could warn the operator and the message went nowhere.
108
+ try {
109
+ const parsed = JSON.parse(stdout) as Record<string, unknown>
110
+ const message = parsed.systemMessage
111
+ if (typeof message === 'string' && message.trim() !== '') {
112
+ return { ...result, systemMessage: message }
113
+ }
114
+ } catch {
115
+ // Non-JSON stdout already parsed as "allow"; there is nothing to attach.
116
+ }
117
+ return result
118
+ }
119
+
120
+ function parseHookStdoutFields(stdout: string | null | undefined, _ctx: HookContext): HookResult {
103
121
  if (!stdout) return { allowed: true }
104
122
 
105
123
  let parsed: Record<string, unknown>
@@ -414,10 +432,6 @@ async function executeCommand(
414
432
  const { loadUserCredentialMaskingConfig } = await import('../config/loader')
415
433
  const { filterEnv } = await import('./credential-masker')
416
434
  const masking = loadUserCredentialMaskingConfig()
417
- const env =
418
- masking.enabled && masking.env_filter.enabled
419
- ? filterEnv(process.env as Record<string, string | undefined>, masking)
420
- : undefined
421
435
 
422
436
  // Which workspace the hook is *for* is the session's business, not this
423
437
  // process's — the daemon runs many sessions and its own cwd belongs to none of
@@ -425,6 +439,16 @@ async function executeCommand(
425
439
  // hand, and is exactly right for the one-shot CLI.
426
440
  const cwd = ctx.cwd ?? process.cwd()
427
441
 
442
+ // A copy, not `undefined`: the CC hook contract exposes the project
443
+ // directory as `$CLAUDE_PROJECT_DIR`, and migrated scripts read it. With
444
+ // `undefined` the child inherited `process.env` and the variable expanded to
445
+ // empty. Copying also keeps the injected value out of this process's env.
446
+ const env =
447
+ masking.enabled && masking.env_filter.enabled
448
+ ? filterEnv(process.env as Record<string, string | undefined>, masking)
449
+ : ({ ...process.env } as Record<string, string | undefined>)
450
+ env.CLAUDE_PROJECT_DIR = cwd
451
+
428
452
  // Array args — no shell, so no command injection. The Claude-protocol stdin JSON
429
453
  // goes in so scripts can read structured context.
430
454
  const input = JSON.stringify(buildHookStdin(ctx, cwd))
package/src/core/hooks.ts CHANGED
@@ -455,6 +455,14 @@ export class HookEngine {
455
455
  : hookResult.additionalContext
456
456
  }
457
457
 
458
+ // `systemMessage` is addressed to the user, so collect it too instead of
459
+ // letting the last hook's warning win.
460
+ if (hookResult.systemMessage) {
461
+ result.systemMessage = result.systemMessage
462
+ ? result.systemMessage + '\n' + hookResult.systemMessage
463
+ : hookResult.systemMessage
464
+ }
465
+
458
466
  // PostToolUse: replace output if provided
459
467
  if (hookResult.updatedOutput) {
460
468
  result.updatedOutput = hookResult.updatedOutput
@@ -117,7 +117,11 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
117
117
  const projectHooksTrusted = getWorkspaceTrust().isTrusted(cwd)
118
118
  const settings = loadSettingsJson(cwd, { includeProjectHooks: projectHooksTrusted })
119
119
  if (settings.projectHooksSkipped) warnProjectHooksSkipped(cwd)
120
- for (const def of loadHookConfigs(settings.hooks)) engine.register(def)
120
+ // Same setting, same meaning on the daemon path — a session started by the
121
+ // daemon must not run hooks the CLI would have skipped.
122
+ if (!settings.disableAllHooks) {
123
+ for (const def of loadHookConfigs(settings.hooks)) engine.register(def)
124
+ }
121
125
  hookCache.set(cwd, engine)
122
126
  return engine
123
127
  }
@@ -122,7 +122,9 @@
122
122
  "footer": "Token counting is approximate (chars/4).\nActual API usage depends on provider and model."
123
123
  },
124
124
  "model": {
125
- "current": "Current model: {model}\nProvider: {provider}\n\nUse /switch <provider> <model> to change."
125
+ "current": "Current model: {model}\nProvider: {provider}\n\nUse /model <model> or /switch <provider> <model> to change.",
126
+ "unknown": "Unknown model: {model}. Use /models to list the available models.",
127
+ "ambiguous": "Model \"{model}\" is available from more than one provider ({providers}). Use /switch <provider> {model}."
126
128
  },
127
129
  "models": {
128
130
  "title": "Available models ({count} active):",
@@ -483,6 +485,7 @@
483
485
  "source_project": "project",
484
486
  "gated": "⚠️ workspace not trusted — will not run",
485
487
  "undispatched": "⚠️ no dispatch point in this version — will not run",
488
+ "disabled_all": "⚠️ disableAllHooks is set — will not run",
486
489
  "found": "{count} hook(s) found.",
487
490
  "error": "── Hooks ──\n\nCould not read hooks directory."
488
491
  },
@@ -122,7 +122,9 @@
122
122
  "footer": "Token 计数为近似值(字符数/4)。\n实际 API 用量取决于提供商和模型。"
123
123
  },
124
124
  "model": {
125
- "current": "当前模型: {model}\n提供商: {provider}\n\n使用 /switch <provider> <model> 切换。"
125
+ "current": "当前模型: {model}\n提供商: {provider}\n\n使用 /model <model> 或 /switch <provider> <model> 切换。",
126
+ "unknown": "未知模型: {model}。用 /models 查看可用模型。",
127
+ "ambiguous": "模型 \"{model}\" 在多个提供商下都有({providers})。请用 /switch <provider> {model}。"
126
128
  },
127
129
  "models": {
128
130
  "title": "可用模型({count} 个活跃):",
@@ -483,6 +485,7 @@
483
485
  "source_project": "项目级",
484
486
  "gated": "⚠️ 工作区未受信任,不会运行",
485
487
  "undispatched": "⚠️ 本版本没有派发点,不会运行",
488
+ "disabled_all": "⚠️ 已设 disableAllHooks,不会运行",
486
489
  "found": "找到 {count} 个钩子。",
487
490
  "error": "── 钩子 ──\n\n无法读取钩子目录。"
488
491
  },
package/src/index.tsx CHANGED
@@ -819,7 +819,10 @@ export async function runApp(options: RunOptions): Promise<void> {
819
819
  // skip is announced, since silence would look the same as having passed.
820
820
  // `settingsJson` itself was read up top, next to the permission it also feeds.
821
821
  if (settingsJson.projectHooksSkipped) warnProjectHooksSkipped(process.cwd())
822
- if (!safeMode) {
822
+ // `disableAllHooks` is the Claude Code setting name; honour it at the same
823
+ // wiring point as `--safe-mode` so a migrated settings file cannot keep
824
+ // spawning hook commands the operator believes are off.
825
+ if (!safeMode && !settingsJson.disableAllHooks) {
823
826
  for (const def of loadHookConfigs(settingsJson.hooks)) {
824
827
  hookEngine.register(def)
825
828
  }
@@ -963,9 +966,16 @@ export async function runApp(options: RunOptions): Promise<void> {
963
966
  }
964
967
 
965
968
  // P2-1: Trigger SessionStart hooks after full initialization
966
- hookEngine.executeSessionStart(sessionName).catch(() => {
967
- // Hook failures never block session startup
968
- })
969
+ hookEngine
970
+ .executeSessionStart(sessionName)
971
+ .then((result) => {
972
+ // No live stream exists yet at startup, so a user-facing `systemMessage`
973
+ // goes to stderr — the same channel the hook's other startup warnings use.
974
+ if (result.systemMessage) process.stderr.write(`⚠ ${result.systemMessage}\n`)
975
+ })
976
+ .catch(() => {
977
+ // Hook failures never block session startup
978
+ })
969
979
 
970
980
  // Auto-save session on exit
971
981
  let saved = false
@@ -998,11 +1008,18 @@ export async function runApp(options: RunOptions): Promise<void> {
998
1008
  // hooks and exiting in the same tick meant they never ran — the await is
999
1009
  // the difference between "best effort" and "never". Bounded, because a
1000
1010
  // hook waiting on an unreachable server must not hold the terminal open.
1001
- await withTimeout(
1011
+ const endResult = await withTimeout(
1002
1012
  hookEngine.executeSessionEnd(sessionName).catch(() => undefined),
1003
1013
  SESSION_END_HOOK_TIMEOUT_MS,
1004
1014
  )
1015
+ // The Ink tree is being torn down; stderr is the only channel left that the
1016
+ // operator will still see.
1017
+ if (endResult?.systemMessage) process.stderr.write(`⚠ ${endResult.systemMessage}\n`)
1005
1018
  artifactServer.stop()
1019
+ // MCP servers are our children. `closeAll()` waits for stdin EOF, which is
1020
+ // the right thing during `/mcp reload`; at exit there is no time to wait,
1021
+ // and a server that ignores EOF would outlive the CLI.
1022
+ McpClient.shutdownSync()
1006
1023
  persistSession()
1007
1024
  // Finalize the session — write session summary + flush CRSI effectiveness
1008
1025
  // (evaluate rules and apply auto-degrade/disable). Best-effort: the
@@ -1036,6 +1053,9 @@ export async function runApp(options: RunOptions): Promise<void> {
1036
1053
  process.on('exit', () => {
1037
1054
  clearInterval(heartbeatInterval)
1038
1055
  unregisterSession(sessionName)
1056
+ // The last synchronous word on MCP children — `shutdown` covers the normal
1057
+ // paths; this covers `process.exit()` called from code that never saw it.
1058
+ McpClient.shutdownSync()
1039
1059
  // Finalize the session on non-interactive exit paths
1040
1060
  // (daemon worker / crash / kill) that bypass saveAndExit.
1041
1061
  if (!saved) {
package/src/mcp/client.ts CHANGED
@@ -651,6 +651,33 @@ export class McpClient {
651
651
  McpClient.instance = null
652
652
  }
653
653
 
654
+ /**
655
+ * Last-resort teardown for the `exit` event, where awaiting is impossible.
656
+ *
657
+ * `closeAll()` gives each server the stdin-EOF grace period; this one kills
658
+ * the process trees immediately. Without it, a server that ignores EOF
659
+ * survives the CLI — and the process group is not ours to rely on, since MCP
660
+ * children are deliberately not spawned detached.
661
+ */
662
+ closeAllSync(): void {
663
+ this.closing = true
664
+ for (const [name, conn] of this.connections) {
665
+ try {
666
+ const transport = conn.transport as { closeSync?: () => void }
667
+ transport.closeSync?.()
668
+ } catch {
669
+ /* best effort */
670
+ }
671
+ this.connections.delete(name)
672
+ }
673
+ McpClient.instance = null
674
+ }
675
+
676
+ /** No-op when no client was ever created — the exit path must not create one. */
677
+ static shutdownSync(): void {
678
+ McpClient.instance?.closeAllSync()
679
+ }
680
+
654
681
  getConnection(name: string): ConnectionInfo | undefined {
655
682
  const conn = this.connections.get(name)
656
683
  if (!conn) return undefined
package/src/mcp/oauth.ts CHANGED
@@ -16,6 +16,17 @@ const bundles: Record<string, TranslationMap> = {
16
16
  }
17
17
  const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
18
18
 
19
+ /**
20
+ * The one spelling used for both the loopback listener and its redirect URI.
21
+ *
22
+ * `localhost` is resolved by the *browser*, and on many systems that resolves
23
+ * to `::1` first while this server listens on IPv4 only — the browser then
24
+ * fails to reach the callback. Strict authorization servers also compare the
25
+ * redirect URI against the client registration byte-for-byte, and `127.0.0.1`
26
+ * is the spelling registrations use. Both sides therefore name the same host.
27
+ */
28
+ const OAUTH_CALLBACK_HOST = '127.0.0.1'
29
+
19
30
  interface TokenResponse {
20
31
  accessToken: string
21
32
  refreshToken?: string
@@ -68,7 +79,7 @@ export class OAuthClient {
68
79
 
69
80
  const code = await new Promise<string>((resolve, reject) => {
70
81
  const server: Server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
71
- const url = new URL(req.url || '/', `http://localhost:${port}`)
82
+ const url = new URL(req.url || '/', `http://${OAUTH_CALLBACK_HOST}:${port}`)
72
83
  if (url.pathname === '/callback') {
73
84
  const receivedCode = url.searchParams.get('code')
74
85
  const receivedState = url.searchParams.get('state')
@@ -112,7 +123,7 @@ export class OAuthClient {
112
123
  authUrl.searchParams.set('client_id', auth.clientId)
113
124
  authUrl.searchParams.set('code_challenge', codeChallenge)
114
125
  authUrl.searchParams.set('code_challenge_method', 'S256')
115
- authUrl.searchParams.set('redirect_uri', `http://localhost:${port}/callback`)
126
+ authUrl.searchParams.set('redirect_uri', `http://${OAUTH_CALLBACK_HOST}:${port}/callback`)
116
127
  authUrl.searchParams.set('state', state)
117
128
  if (auth.scopes?.length) {
118
129
  authUrl.searchParams.set('scope', auth.scopes.join(' '))
@@ -148,7 +159,7 @@ export class OAuthClient {
148
159
  grant_type: 'authorization_code',
149
160
  code,
150
161
  code_verifier: codeVerifier,
151
- redirect_uri: `http://localhost:${port}/callback`,
162
+ redirect_uri: `http://${OAUTH_CALLBACK_HOST}:${port}/callback`,
152
163
  client_id: auth.clientId,
153
164
  }).toString(),
154
165
  })
@@ -39,8 +39,14 @@ function sanitizeName(name: string): string {
39
39
  /**
40
40
  * Build a namespaced MCP tool name.
41
41
  * Format: mcp__<sanitizedServerName>__<sanitizedToolName>
42
+ *
43
+ * Exported because every surface that *names* an MCP tool must use this
44
+ * spelling: the registered name is what the model has to call, and a display
45
+ * path that builds its own (`tool-search`) handed back names that did not
46
+ * exist for any server or tool with an uppercase or non-alphanumeric
47
+ * character in its name.
42
48
  */
43
- function buildToolName(serverName: string, toolName: string): string {
49
+ export function buildToolName(serverName: string, toolName: string): string {
44
50
  const base = `${MCP_TOOL_PREFIX}${sanitizeName(serverName)}__${sanitizeName(toolName)}`
45
51
  if (base.length <= MAX_NAME_LENGTH) return base
46
52
  const prefix = `${MCP_TOOL_PREFIX}${sanitizeName(serverName)}__`
@@ -348,6 +348,21 @@ export class StdioTransport implements Transport {
348
348
  this.notificationHandlers.push(handler)
349
349
  }
350
350
 
351
+ /**
352
+ * Synchronous teardown for `process.on('exit')`, where nothing can be
353
+ * awaited and no grace period can run. Kills the process tree now: a server
354
+ * that does not read stdin EOF otherwise outlives the CLI (the shape Claude
355
+ * Code fixed twice: 1.0.21.003 and 1.0.36).
356
+ */
357
+ closeSync(): void {
358
+ this.closed = true
359
+ const proc = this.proc
360
+ this.proc = null
361
+ if (proc && proc.exitCode === null && proc.signalCode === null) {
362
+ killProcessTree(proc)
363
+ }
364
+ }
365
+
351
366
  async close(): Promise<void> {
352
367
  this.closed = true
353
368
 
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.41' as const
12
+ export const PACKAGE_VERSION = '0.85.43' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 5064 as const
93
+ export const TEST_COUNT = 5122 as const
@@ -403,6 +403,15 @@ export interface HookResult {
403
403
  permissionDecision?: 'allow' | 'deny' | 'ask' | 'defer'
404
404
  additionalContext?: string
405
405
  updatedOutput?: string
406
+ /**
407
+ * Warning text the hook wants the **user** to see (Claude Code's root-level
408
+ * `systemMessage`). Distinct from `additionalContext`, which goes into the
409
+ * model's prompt. Only events with a live user channel surface it:
410
+ * UserPromptSubmit and Stop yield a warning chunk; SessionStart/SessionEnd
411
+ * write it to stderr before/at exit. A hook that emits it on an event with
412
+ * no such channel is not silently reinterpreted as model context.
413
+ */
414
+ systemMessage?: string
406
415
  }
407
416
 
408
417
  // ── Instruction Types ──
@@ -656,6 +665,16 @@ export interface ToolContext {
656
665
  * Absent means "no completeness tracking" and is treated as not complete.
657
666
  */
658
667
  readFilesComplete?: Set<string>
668
+ /**
669
+ * The live conversation this tool call belongs to.
670
+ *
671
+ * Set by `Engine.executeTool` on the context it hands every tool. The Agent
672
+ * tool's `fork` subagent type seeds its own context with this prefix so it can
673
+ * act on the conversation without being told about it again. Absent when a
674
+ * context is built by hand (tests, daemon stubs) — `fork` then refuses rather
675
+ * than silently behaving like `general`.
676
+ */
677
+ parentMessages?: Message[]
659
678
  /**
660
679
  * Cancellation for the turn this tool call belongs to.
661
680
  *
@@ -3,7 +3,7 @@ import { SubAgent } from '../../agent/sub-agent'
3
3
  import type { SubAgentType } from '../../agent/types'
4
4
  import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
- const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
6
+ const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review', 'fork']
7
7
 
8
8
  /** Same domain as the session-level `/effort` command (`ui/commands.ts`). */
9
9
  const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
@@ -38,7 +38,8 @@ export const agentTool: ToolDefinition = {
38
38
  name: 'Agent',
39
39
  description:
40
40
  'Launch a sub-agent to handle complex, multi-step tasks independently. ' +
41
- 'Available types: general (default), explore (code search), plan (design), code-review. ' +
41
+ 'Available types: general (default), explore (code search), plan (design), code-review, ' +
42
+ 'fork (inherits this conversation). ' +
42
43
  'Runs in the background by default — returns a task ID immediately; results are ' +
43
44
  'retrievable via the Task tool (output action) or Agent View. ' +
44
45
  'Set run_in_background: false to run synchronously.',
@@ -60,7 +61,8 @@ export const agentTool: ToolDefinition = {
60
61
  prompt: { type: 'string', description: 'The task for the agent to perform' },
61
62
  subagent_type: {
62
63
  type: 'string',
63
- description: 'Type: general (default), explore (code search), plan (design), code-review',
64
+ description:
65
+ 'Type: general (default), explore (code search), plan (design), code-review, fork (inherits this conversation)',
64
66
  },
65
67
  run_in_background: {
66
68
  type: 'boolean',
@@ -116,6 +118,20 @@ export const agentTool: ToolDefinition = {
116
118
 
117
119
  // Resolve agent definition from registry (custom > builtin)
118
120
  const agentDef = ctx.agentRegistry?.resolve(agentType)
121
+
122
+ // `fork` inherits the live conversation. It needs one to inherit: with no
123
+ // parent messages it would behave exactly like `general` while the caller
124
+ // reads the type as proof that context was carried over, so refuse instead.
125
+ const inheritedMessages = agentType === 'fork' ? ctx.parentMessages?.slice() : undefined
126
+ if (agentType === 'fork' && (!inheritedMessages || inheritedMessages.length === 0)) {
127
+ return {
128
+ success: false,
129
+ content: '',
130
+ error:
131
+ 'fork requires an existing conversation to inherit; this session has no messages yet.',
132
+ }
133
+ }
134
+
119
135
  const runInBackground = resolveRunInBackground(
120
136
  params.run_in_background as boolean | undefined,
121
137
  agentDef,
@@ -139,6 +155,9 @@ export const agentTool: ToolDefinition = {
139
155
  agentDef,
140
156
  runInBackground,
141
157
  effort,
158
+ // Byte-identical parent prefix (see SubAgent's `inheritContext`), so the
159
+ // fork starts from the conversation rather than from the prompt alone.
160
+ ...(inheritedMessages ? { inheritContext: { messages: inheritedMessages } } : {}),
142
161
  // Hand the caller's services down: the sub-agent keeps running the same
143
162
  // skills/agents/artifacts, and only the fields it owns are overridden.
144
163
  toolContext: ctx,
@@ -111,12 +111,11 @@ const BLOCKED_PATTERNS = [
111
111
  // command as `bash -c 'rm -rf /'`. `ash`, `fish`, `csh` and `tcsh` are added
112
112
  // because the payload only has to be a POSIX-ish shell, not bash.
113
113
  /\b(?:bash|sh|zsh|dash|ksh|ash|fish|csh|tcsh)\b(?:\s+-{1,2}[\w=.-]+)*\s+-[A-Za-z]*c[A-Za-z]*\b/,
114
- // P0 hardening — eval builtin (obfuscation vector)
115
- /\beval\s+/,
116
114
  // P0 hardening — exec redirect bypass (e.g. exec >/dev/sda)
117
115
  /\bexec\s+\d*>/,
118
- // P0 hardening — source/dot builtin (script sourcing)
119
- /\bsource\s+/,
116
+ // `eval` / `source` are handled by `commandWords()` below, not as substring
117
+ // patterns: the word appearing in an argument is not the builtin running
118
+ // (`git commit -m "source config cleanup"`).
120
119
  // P0 hardening — base64 decode + pipe
121
120
  /\bbase64\s+(?:-d|--decode)\b/,
122
121
  ]
@@ -163,19 +162,18 @@ export function isBlocked(command: string): string | null {
163
162
  // P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
164
163
  const sanitized = sanitizeCommand(command)
165
164
 
166
- // Check exact blocked commands (on normalized + sanitized)
167
- const firstWord = normalized.trim().split(/\s+/)[0]
168
- if (firstWord && BLOCKED_COMMANDS.includes(firstWord)) {
169
- return `Command "${firstWord}" rejected by security policy.`
170
- }
171
- // Also check sanitized first word (catches fullwidth command names after normalization)
172
- const sanitizedFirstWord = sanitized.trim().split(/\s+/)[0]
173
- if (
174
- sanitizedFirstWord &&
175
- sanitizedFirstWord !== firstWord &&
176
- BLOCKED_COMMANDS.includes(sanitizedFirstWord)
177
- ) {
178
- return `Command "${sanitizedFirstWord}" rejected by security policy.`
165
+ // Check every simple command's base word, not a substring of the line: the
166
+ // word may be a quoted argument (`git commit -m "source config cleanup"`),
167
+ // and a compound command may hide it after a separator (`ok && source x`).
168
+ // Command substitutions are scanned too (`echo "$(eval …)"`).
169
+ for (const word of [
170
+ ...commandWords(command),
171
+ ...commandWords(normalized),
172
+ ...commandWords(sanitized),
173
+ ]) {
174
+ if (BLOCKED_COMMANDS.includes(word)) {
175
+ return `Command "${word}" rejected by security policy.`
176
+ }
179
177
  }
180
178
 
181
179
  // Detect dangerous git operations invoked via Bash — anywhere in the command,
@@ -503,6 +501,174 @@ export function shellWords(segment: string): string[] {
503
501
  return words
504
502
  }
505
503
 
504
+ /**
505
+ * Split a command into simple commands on **unquoted** separators.
506
+ *
507
+ * Deliberately different from `splitShellSegments` (permission-rules), which
508
+ * splits regardless of quoting: over-matching is the safe direction for a
509
+ * *deny* rule, but here it is the bug — `rg 'eval|source'` is one command with
510
+ * a quoted argument, not two commands.
511
+ */
512
+ function splitUnquotedSegments(command: string): string[] {
513
+ const segments: string[] = []
514
+ let cur = ''
515
+ let quote: '"' | "'" | null = null
516
+ for (let i = 0; i < command.length; i++) {
517
+ const ch = command[i]!
518
+ if (quote === "'") {
519
+ cur += ch
520
+ if (ch === "'") quote = null
521
+ continue
522
+ }
523
+ if (quote === '"') {
524
+ cur += ch
525
+ if (ch === '\\' && i + 1 < command.length) cur += command[++i]
526
+ else if (ch === '"') quote = null
527
+ continue
528
+ }
529
+ if (ch === "'" || ch === '"') {
530
+ quote = ch
531
+ cur += ch
532
+ continue
533
+ }
534
+ if (ch === '\\' && i + 1 < command.length) {
535
+ cur += ch + command[++i]
536
+ continue
537
+ }
538
+ if (
539
+ ch === ';' ||
540
+ ch === '\n' ||
541
+ ch === '\r' ||
542
+ ch === '|' ||
543
+ ch === '&' ||
544
+ ch === '(' ||
545
+ ch === ')'
546
+ ) {
547
+ segments.push(cur)
548
+ cur = ''
549
+ if ((ch === '&' || ch === '|') && command[i + 1] === ch) i++
550
+ continue
551
+ }
552
+ cur += ch
553
+ }
554
+ segments.push(cur)
555
+ return segments.map((s) => s.trim()).filter((s) => s.length > 0)
556
+ }
557
+
558
+ /**
559
+ * Bodies of command substitutions — `$(…)`, `` `…` ``, `<(…)` and `>(…)`.
560
+ *
561
+ * They run commands too, and they can sit inside double quotes:
562
+ * `echo "$(eval …)"` executes `eval` even though the outer command word is
563
+ * `echo`. Single-quoted text is skipped because it is literal there.
564
+ * Nested groups are left to the caller's recursion.
565
+ */
566
+ function substitutionBodies(command: string): string[] {
567
+ const bodies: string[] = []
568
+ for (let i = 0; i < command.length; i++) {
569
+ const ch = command[i]!
570
+ if (ch === '\\') {
571
+ i++
572
+ continue
573
+ }
574
+ if (ch === "'") {
575
+ const end = command.indexOf("'", i + 1)
576
+ if (end === -1) break
577
+ i = end
578
+ continue
579
+ }
580
+ const isDollarParen = ch === '$' && command[i + 1] === '('
581
+ const isProcSub = (ch === '<' || ch === '>') && command[i + 1] === '('
582
+ if (ch === '`') {
583
+ const end = command.indexOf('`', i + 1)
584
+ if (end === -1) break
585
+ bodies.push(command.slice(i + 1, end))
586
+ i = end
587
+ continue
588
+ }
589
+ if (!isDollarParen && !isProcSub) continue
590
+ let depth = 1
591
+ let j = i + 2
592
+ let quote: '"' | "'" | null = null
593
+ for (; j < command.length; j++) {
594
+ const c = command[j]!
595
+ if (c === '\\') {
596
+ j++
597
+ continue
598
+ }
599
+ if (quote === "'") {
600
+ if (c === "'") quote = null
601
+ continue
602
+ }
603
+ if (quote === '"') {
604
+ if (c === '"') quote = null
605
+ continue
606
+ }
607
+ if (c === "'" || c === '"') {
608
+ quote = c
609
+ continue
610
+ }
611
+ if (c === '(') depth++
612
+ else if (c === ')') {
613
+ depth--
614
+ if (depth === 0) break
615
+ }
616
+ }
617
+ if (j < command.length) {
618
+ bodies.push(command.slice(i + 2, j))
619
+ i = j
620
+ }
621
+ }
622
+ return bodies
623
+ }
624
+
625
+ /**
626
+ * The base command word of every simple command in `command`, including
627
+ * commands run inside substitutions (recursively, depth-limited).
628
+ *
629
+ * This is what tells a *mention* from an *invocation*: `git commit -m "source
630
+ * config cleanup"` has the command word `git`; `echo ok && source /etc/x` has
631
+ * `echo` and `source`. Prior to this, `eval` / `source` were matched anywhere
632
+ * in the string and refused ordinary commands that merely quoted the words
633
+ * (CC 1.0.73: "reduced false security warnings").
634
+ */
635
+ export function commandWords(command: string, depth = 0): string[] {
636
+ const words: string[] = []
637
+ for (const segment of splitUnquotedSegments(command)) {
638
+ const tokens = shellWords(segment)
639
+ let i = 0
640
+ for (;;) {
641
+ while (i < tokens.length && LEADING_ASSIGNMENT.test(tokens[i]!)) i++
642
+ const word = tokens[i]
643
+ if (word === undefined) break
644
+ if (LEADING_SHELL_PUNCT.has(word)) {
645
+ i++
646
+ continue
647
+ }
648
+ if (LEADING_SHELL_KEYWORDS.has(word)) {
649
+ i++
650
+ // A keyword's own flags (`time -p eval …`) are not the command word.
651
+ while (i < tokens.length && /^-[A-Za-z]+$/.test(tokens[i]!)) i++
652
+ continue
653
+ }
654
+ if (WRAPPERS.has(word)) {
655
+ i++
656
+ continue
657
+ }
658
+ break
659
+ }
660
+ if (tokens[i] !== undefined) words.push(tokens[i]!)
661
+ }
662
+ // A substitution can nest (`$( … $( … ) … )`); three levels is enough to
663
+ // reach any spelling a guard needs to see, and bounds the recursion.
664
+ if (depth < 3) {
665
+ for (const body of substitutionBodies(command)) {
666
+ words.push(...commandWords(body, depth + 1))
667
+ }
668
+ }
669
+ return words
670
+ }
671
+
506
672
  /**
507
673
  * Every directory this simple command changes the shell's cwd to.
508
674
  *
@@ -764,14 +930,15 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
764
930
  // ── Sandbox violation detection ──
765
931
  const violations = detectViolations(rawStderr)
766
932
 
933
+ // Mask stderr once, for both outcomes. It used to be masked only on the
934
+ // failure path, so a credential echoed to stderr by a command that then
935
+ // exited 0 would reach the model unmasked.
936
+ const stderr =
937
+ credentialConfig?.enabled && credentialConfig.output_scrubbing.enabled
938
+ ? (await import('../../core/credential-masker')).maskOutput(rawStderr, credentialConfig)
939
+ : rawStderr
940
+
767
941
  if (exitCode !== 0) {
768
- const stderr =
769
- credentialConfig?.enabled && credentialConfig.output_scrubbing.enabled
770
- ? (await import('../../core/credential-masker')).maskOutput(
771
- rawStderr,
772
- credentialConfig,
773
- )
774
- : rawStderr
775
942
  let errorContent = output.slice(0, 5_000)
776
943
  if (violations.length > 0) {
777
944
  errorContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
@@ -814,7 +981,19 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
814
981
  return { success: false, content: output.slice(0, 5_000), error: 'Command cancelled' }
815
982
  }
816
983
 
817
- let successContent = output.slice(0, 100_000) || '(no output)'
984
+ let successContent = output.slice(0, 100_000)
985
+ // Exit 0 does not mean stderr was noise: `git clone` progress, package
986
+ // manager peer warnings and deprecation notices all land there, and the
987
+ // tool advertises "Returns stdout and stderr". Dropping it left the
988
+ // model reading a clean success where the warning it needed sat one
989
+ // stream over (CC 1.0.77 stderr handling).
990
+ const stderrText =
991
+ stderr.length > 5_000 ? stderr.slice(0, 5_000) + '\n[stderr truncated]' : stderr
992
+ if (stderrText.trim().length > 0) {
993
+ successContent +=
994
+ (successContent.length > 0 ? '\n\n' : '') + '── stderr ──\n' + stderrText
995
+ }
996
+ if (successContent.length === 0) successContent = '(no output)'
818
997
  if (violations.length > 0) {
819
998
  successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
820
999
  }
@@ -169,7 +169,11 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
169
169
  if (include) rgArgs.push('--glob', include)
170
170
  rgArgs.push(searchPath)
171
171
  try {
172
- const { stdout, timedOut, exitCode } = await runSearch(rgArgs, ctx.cwd, GREP_TIMEOUT_MS)
172
+ const { stdout, stderr, timedOut, exitCode } = await runSearch(
173
+ rgArgs,
174
+ ctx.cwd,
175
+ GREP_TIMEOUT_MS,
176
+ )
173
177
  if (timedOut) {
174
178
  return {
175
179
  success: false,
@@ -200,6 +204,19 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
200
204
  '\n\n(rg exited 2 — some paths unreadable; narrow scope for complete results)',
201
205
  }
202
206
  }
207
+ // The server's own reason, not a guess. A rejected pattern (a literal
208
+ // line break without multiline mode, an unbalanced bracket) is exit 2
209
+ // with empty stdout exactly like a permission error is — and telling
210
+ // the caller "likely permission denied" sends it to narrow a path when
211
+ // what it has to fix is the pattern.
212
+ const reason = stderr.trim()
213
+ if (reason) {
214
+ return {
215
+ success: false,
216
+ content: '',
217
+ error: `rg rejected the search: ${reason.slice(0, 500)}`,
218
+ }
219
+ }
203
220
  return {
204
221
  success: false,
205
222
  content: '',
@@ -50,6 +50,9 @@ function windowFromString(content: string, offset: number, limit: number): strin
50
50
  let lineNo = 0
51
51
  let start = 0
52
52
  while (out.length < limit) {
53
+ // Nothing follows a terminating newline: `"a\nb\n"` has two lines, not
54
+ // three. An empty string has no lines at all.
55
+ if (start >= content.length) break
53
56
  const nl = content.indexOf('\n', start)
54
57
  const end = nl === -1 ? content.length : nl
55
58
  if (lineNo >= offset) out.push(content.slice(start, end))
@@ -149,7 +152,16 @@ function windowFromFd(
149
152
  if (n <= 0) break
150
153
  got += n
151
154
  }
152
- return { lines: out.toString('utf-8', 0, got).split('\n'), complete }
155
+ // A file that ends with a newline has no line after it. `split('\n')` on
156
+ // `"a\nb\n"` yields `['a','b','']`, and formatting that trailing element
157
+ // printed an extra empty numbered line — the caller asked for the file, not
158
+ // for a line the file does not contain. Only the single element produced by
159
+ // the *final* newline is dropped; blank lines inside the file stay.
160
+ if (got === 0) return { lines: [], complete }
161
+ const text = out.toString('utf-8', 0, got)
162
+ const lines = text.split('\n')
163
+ if (out[got - 1] === 0x0a) lines.pop()
164
+ return { lines, complete }
153
165
  }
154
166
 
155
167
  export function createReadTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
@@ -8,6 +8,7 @@
8
8
 
9
9
  import type { ToolDefinition } from '../../shared/index.ts'
10
10
  import { McpClient } from '../../mcp/client'
11
+ import { buildToolName } from '../../mcp/registry'
11
12
  import { capMcpText } from '../../mcp/instructions'
12
13
 
13
14
  /**
@@ -162,7 +163,7 @@ export const toolSearchTool: ToolDefinition = {
162
163
  lines.push(` ${server} (${tools.length}):`)
163
164
  for (const t of tools) {
164
165
  const desc = t.description ? ` — ${t.description}` : ''
165
- lines.push(` mcp__${server.replace(/[^a-z0-9-]/g, '_')}__${t.tool}${desc}`)
166
+ lines.push(` ${buildToolName(server, t.tool)}${desc}`)
166
167
  }
167
168
  lines.push('')
168
169
  }
@@ -1,7 +1,7 @@
1
1
  import React from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
- import { sanitizeInlineField } from '../shared/sanitize'
4
+ import { safeSlice, sanitizeInlineField } from '../shared/sanitize'
5
5
 
6
6
  /**
7
7
  * 页脚也是本文件通往终端的一道口 —— 且它内插的字全是**模型写出来的**:
@@ -131,7 +131,7 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
131
131
  <Box>
132
132
  <Text color={toolIndicatorColor(activeTool!.name)}>
133
133
  {' '}[{sanitizeInlineField(activeTool!.name)}{' '}
134
- {sanitizeInlineField(activeTool!.detail).slice(0, 60)}
134
+ {safeSlice(sanitizeInlineField(activeTool!.detail), 60)}
135
135
  {animatedDots(tick)}]
136
136
  </Text>
137
137
  <Box flexGrow={1} />
@@ -167,9 +167,13 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
167
167
  const symbol = isRunning ? '◯' : '◼'
168
168
  const symbolColor = isRunning ? 'cyan' : undefined
169
169
 
170
- // Truncate description to keep lines readable
170
+ // Truncate description to keep lines readable. `safeSlice` refuses to end
171
+ // on the high half of a surrogate pair — a plain `slice(0, 80)` there
172
+ // printed a lone surrogate (a garbled glyph) for any emoji on the edge.
171
173
  const desc =
172
- agent.description.length > 80 ? agent.description.slice(0, 80) + '...' : agent.description
174
+ agent.description.length > 80
175
+ ? safeSlice(agent.description, 80) + '...'
176
+ : agent.description
173
177
 
174
178
  return (
175
179
  <Box key={agent.id}>
package/src/ui/chat.tsx CHANGED
@@ -123,7 +123,7 @@ const MessageRow = React.memo(
123
123
  {msg.toolMeta.name ? (
124
124
  <Text color={toolColor(msg.toolMeta.name)}>
125
125
  {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {sanitizeInlineField(msg.toolMeta.name)}
126
- {msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
126
+ {msg.toolMeta.input ? ` (${safeSlice(display(msg.toolMeta.input), 120)})` : ''}
127
127
  </Text>
128
128
  ) : null}
129
129
  {/* Tool result line: ⎿ summary text */}
@@ -604,9 +604,60 @@ const costCmd: CommandHandler = (ctx) => {
604
604
  // Model & Provider
605
605
  // ═══════════════════════════════════════════════════════════════
606
606
 
607
- const modelCmd: CommandHandler = (ctx) => {
607
+ const modelCmd: CommandHandler = (ctx, args) => {
608
608
  const t = resolveT(ctx)
609
- return { content: t('commands.model.current', { model: ctx.modelId, provider: ctx.providerId }) }
609
+ const requested = args[0]?.trim()
610
+ // `/model <name>` used to drop its argument on the floor and print the
611
+ // current model — a request that was refused and a request that was never
612
+ // made looked the same. Validate first, then switch.
613
+ if (!requested) {
614
+ return {
615
+ content: t('commands.model.current', { model: ctx.modelId, provider: ctx.providerId }),
616
+ }
617
+ }
618
+ if (ctx.engine.isRemote) {
619
+ return {
620
+ content:
621
+ `Cannot switch to ${requested}: this session is attached to a daemon, ` +
622
+ 'and the model is chosen on the daemon side. Change it there, or start a local session.',
623
+ }
624
+ }
625
+ const matches = ctx.config.providers
626
+ .filter((p) => p.status !== 'upcoming')
627
+ .flatMap((p) =>
628
+ p.models.filter((m) => m.status === 'active').map((m) => ({ provider: p, model: m })),
629
+ )
630
+ .filter(({ model }) => model.id.toLowerCase() === requested.toLowerCase())
631
+ if (matches.length === 0) {
632
+ return { content: t('commands.model.unknown', { model: requested }) }
633
+ }
634
+ if (matches.length > 1) {
635
+ return {
636
+ content: t('commands.model.ambiguous', {
637
+ model: requested,
638
+ providers: matches.map(({ provider }) => provider.id).join(', '),
639
+ }),
640
+ }
641
+ }
642
+ const { provider, model } = matches[0]!
643
+ if (isApiKeyMissing(provider.apiKey)) {
644
+ return {
645
+ content: t('commands.switch.needs_api_key', { provider: provider.name }),
646
+ needsApiKey: {
647
+ providerId: provider.id,
648
+ modelId: model.id,
649
+ providerName: provider.name,
650
+ },
651
+ }
652
+ }
653
+ const warning = ctx.engine.switchProvider(provider.id, model.id)
654
+ return {
655
+ content:
656
+ t('commands.switch.confirmed', { provider: provider.id, model: model.id }) +
657
+ (warning ? `\n${warning}` : ''),
658
+ nextProvider: provider.id,
659
+ nextModel: model.id,
660
+ }
610
661
  }
611
662
 
612
663
  const modelsCmd: CommandHandler = (ctx) => {
@@ -4847,8 +4898,15 @@ const hooksListCmd: CommandHandler = async (ctx) => {
4847
4898
  // Two calls, one per source: the merged list cannot say which entry came from
4848
4899
  // which file, and the two are not governed alike — only the project file's
4849
4900
  // entries are gated on workspace trust.
4850
- const userHooks = loadSettingsJson(cwd).hooks
4851
- const projectHooks = loadSettingsJson(cwd, { includeProjectHooks: true }).projectHooks ?? {}
4901
+ const userSettings = loadSettingsJson(cwd)
4902
+ const projectSettings = loadSettingsJson(cwd, { includeProjectHooks: true })
4903
+ const userHooks = userSettings.hooks
4904
+ const projectHooks = projectSettings.projectHooks ?? {}
4905
+ // Listing a hook is not the claim that it runs. `disableAllHooks` stops the
4906
+ // wiring at both entry points, and this display reads the files, so it has to
4907
+ // carry the same verdict — otherwise every entry looks installed and
4908
+ // `found N` counts hooks that will never fire.
4909
+ const hooksDisabled = projectSettings.disableAllHooks === true
4852
4910
 
4853
4911
  // Listing them is not the same claim as their running. Project hooks are
4854
4912
  // gated, and this command renders them even when the gate is shut — so the
@@ -4895,13 +4953,14 @@ const hooksListCmd: CommandHandler = async (ctx) => {
4895
4953
  const undispatchable = UNDISPATCHED_EVENTS.has(eventName)
4896
4954
  for (const { entry, project } of bucket) {
4897
4955
  for (const hook of entry.hooks) {
4898
- if (!undispatchable) count++
4956
+ if (!undispatchable && !hooksDisabled) count++
4899
4957
  const matcher = entry.matcher || '*'
4900
4958
  const cmd = hook.type === 'command' && hook.command ? hook.command : hook.type
4901
4959
  const source = t(project ? 'commands.hooks.source_project' : 'commands.hooks.source_user')
4902
4960
  const markers: string[] = []
4903
4961
  if (project && gated) markers.push(t('commands.hooks.gated'))
4904
4962
  if (undispatchable) markers.push(t('commands.hooks.undispatched'))
4963
+ if (hooksDisabled) markers.push(t('commands.hooks.disabled_all'))
4905
4964
  const suffix = markers.map((marker) => ` ${marker}`).join('')
4906
4965
  lines.push(` [${source}] ${eventName} [${matcher}] → ${cmd}${suffix}`)
4907
4966
  }
package/src/ui/input.tsx CHANGED
@@ -401,6 +401,10 @@ export function InputBar({
401
401
  const [value, setValue] = useState('')
402
402
  // Ref mirror of value — used by useInput to read latest without stale closure.
403
403
  const valueRef = useRef(value)
404
+ // Ref mirror of `pickerActive` for the same reason, and one more: the key
405
+ // handler is declared before the picker state below, so it must not read that
406
+ // variable directly.
407
+ const pickerActiveRef = useRef(false)
404
408
  const [verb, setVerb] = useState(() => t(pick(LOADING_KEYS)))
405
409
  const [completionVerb, setCompletionVerb] = useState<string | null>(null)
406
410
  const prevLoading = useRef(isLoading)
@@ -565,8 +569,11 @@ export function InputBar({
565
569
  // History navigation changes value via setValue (no onChange) — clear any
566
570
  // ghost suggestion so a stale one isn't Tab-accepted onto a recalled entry.
567
571
  clearSuggestion()
568
- // Ignore if picker is active (command picker handles its own arrows)
569
- if (value.startsWith('/')) return
572
+ // Ignore only if the picker is actually active (the command picker handles
573
+ // its own arrows). The old test was `value.startsWith('/')`, so after
574
+ // recalling a slash command from history — picker off by default — the
575
+ // Up/Down keys dead-ended and the rest of the history was unreachable.
576
+ if (pickerActiveRef.current) return
570
577
 
571
578
  // A draft Escape cleared is still the user's text, and it is the *only*
572
579
  // copy: unlike a sent message or a slash command it never entered history.
@@ -623,6 +630,11 @@ export function InputBar({
623
630
  valueRef.current = value
624
631
  }, [value])
625
632
 
633
+ // Same for the picker: effects run before the next key event reads the ref.
634
+ useEffect(() => {
635
+ pickerActiveRef.current = pickerActive
636
+ }, [pickerActive])
637
+
626
638
  const handleSubmit = (val: string) => {
627
639
  // Use the latest value from the ref; `val` is the value passed by MiphamTextInput.
628
640
  const finalValue = valueRef.current || val