@miphamai/cli 0.85.42 → 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.42
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.42",
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",
@@ -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
@@ -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
 
@@ -2301,7 +2318,8 @@ export class QueryEngine {
2301
2318
  signal?: AbortSignal,
2302
2319
  roundsLeft: number = MAX_TOOL_TURNS,
2303
2320
  ): AsyncGenerator<StreamChunk> {
2304
- const block = await this.stopBlock()
2321
+ const { block, systemMessage } = await this.stopCheck()
2322
+ if (systemMessage) yield { type: 'warning', content: systemMessage }
2305
2323
  if (!block) return
2306
2324
 
2307
2325
  // A block asks for more work, and more work means another round — which the
@@ -2329,27 +2347,38 @@ export class QueryEngine {
2329
2347
  * 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
2330
2348
  * 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
2331
2349
  */
2332
- 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
2333
2355
  if (this.hookEngine) {
2334
2356
  const stopResult = await this.hookEngine.executeStop(this.sessionId)
2357
+ systemMessage = stopResult.systemMessage
2335
2358
  if (stopResult.decision === 'block') {
2336
2359
  const reason = stopResult.reason || 'Continue working.'
2337
2360
  return {
2338
- source: 'stop-hook',
2339
- text: t('system.context.stop_blocked', { reason }),
2340
- reason,
2361
+ block: {
2362
+ source: 'stop-hook',
2363
+ text: t('system.context.stop_blocked', { reason }),
2364
+ reason,
2365
+ },
2366
+ systemMessage,
2341
2367
  }
2342
2368
  }
2343
2369
  }
2344
2370
 
2345
2371
  const claims = this.unprovenNumbers()
2346
- if (!claims) return null
2372
+ if (!claims) return { block: null, systemMessage }
2347
2373
  // 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
2348
2374
  // 把整段问话塞进 warning 只会让人读一屏。
2349
2375
  return {
2350
- source: 'number-provenance',
2351
- text: t('system.context.numbers_unproven', { claims }),
2352
- reason: claims,
2376
+ block: {
2377
+ source: 'number-provenance',
2378
+ text: t('system.context.numbers_unproven', { claims }),
2379
+ reason: claims,
2380
+ },
2381
+ systemMessage,
2353
2382
  }
2354
2383
  }
2355
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
@@ -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.42' 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 = 5079 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 ──
@@ -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
  }
@@ -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
  }
@@ -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