@miphamai/cli 0.85.22 → 0.85.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +1 -1
  2. package/bin/mipham.ts +40 -13
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +19 -6
  5. package/src/agent/agent-registry.ts +42 -2
  6. package/src/agent/message-router.ts +30 -0
  7. package/src/agent/sub-agent.ts +17 -0
  8. package/src/config/loader.ts +41 -0
  9. package/src/core/context-microcompact.ts +1 -1
  10. package/src/core/context.ts +167 -10
  11. package/src/core/cron-poller.ts +74 -6
  12. package/src/core/engine.ts +34 -7
  13. package/src/core/hooks-config.ts +4 -0
  14. package/src/core/hooks-executor.ts +96 -28
  15. package/src/core/hooks.ts +49 -3
  16. package/src/core/permission-rules.ts +32 -2
  17. package/src/core/safe-mode.ts +11 -0
  18. package/src/core/session-exit.ts +73 -0
  19. package/src/core/session-log.ts +36 -1
  20. package/src/daemon/engine-capabilities.ts +13 -4
  21. package/src/daemon/launch.ts +37 -0
  22. package/src/daemon/server.ts +9 -1
  23. package/src/i18n-core/locales/en-US.json +1 -0
  24. package/src/i18n-core/locales/zh-CN.json +1 -0
  25. package/src/index.tsx +68 -27
  26. package/src/mcp/client.ts +22 -8
  27. package/src/mcp/http-transport.ts +19 -4
  28. package/src/mcp/registry.ts +40 -5
  29. package/src/plugin/plugin-loader.ts +4 -0
  30. package/src/providers/anthropic.ts +8 -2
  31. package/src/providers/openai-compat.ts +14 -2
  32. package/src/shared/arg-validation.ts +2 -1
  33. package/src/shared/package-info.ts +2 -2
  34. package/src/shared/types.ts +18 -0
  35. package/src/skills/loader.ts +86 -4
  36. package/src/tools/agent/workflow.ts +9 -2
  37. package/src/tools/exec/bash.ts +38 -11
  38. package/src/tools/exec/exit-worktree.ts +45 -4
  39. package/src/tools/file/read.ts +16 -2
  40. package/src/tools/network/web-fetch.ts +11 -3
  41. package/src/tools/network/web-search.ts +5 -1
  42. package/src/tools/scheduling/cron.ts +2 -1
  43. package/src/tools/scheduling/schedule-wakeup.ts +23 -8
  44. package/src/tools/validation.ts +11 -0
  45. package/src/ui/app.tsx +6 -5
  46. package/src/ui/commands.ts +17 -8
  47. package/src/workflow/primitives/agent.ts +34 -5
  48. package/src/workflow/primitives/verify.ts +36 -20
  49. package/src/workflow/runtime.ts +10 -2
@@ -5,9 +5,10 @@
5
5
  // (which re-invokes it into the current session) and then advances the job
6
6
  // (recurring → next fire; one-shot → deleted).
7
7
 
8
+ import { mkdirSync, rmSync, statSync } from 'node:fs'
8
9
  import { computeNextFire } from './cron'
9
10
  import type { CronJob } from '../tools/scheduling/cron'
10
- import { readAllJobs, writeJob, deleteJobFile } from '../tools/scheduling/cron'
11
+ import { readAllJobs, writeJob, deleteJobFile, jobPath } from '../tools/scheduling/cron'
11
12
 
12
13
  /**
13
14
  * Whether a job belongs to `cwd`.
@@ -37,6 +38,51 @@ export function advanceJob(job: CronJob, now: Date): CronJob | null {
37
38
  }
38
39
  }
39
40
 
41
+ /**
42
+ * A claim older than this belonged to a poller that died mid-fire. Firing a job
43
+ * twice is recoverable; never firing it again is not, so stale claims are
44
+ * reclaimed rather than trusted forever.
45
+ */
46
+ export const CLAIM_STALE_MS = 5 * 60_000
47
+
48
+ function claimPath(id: string): string {
49
+ return `${jobPath(id)}.lock`
50
+ }
51
+
52
+ /** Atomic across processes: `mkdir` fails with EEXIST for every loser. */
53
+ function makeClaim(path: string): boolean {
54
+ try {
55
+ mkdirSync(path)
56
+ return true
57
+ } catch {
58
+ return false
59
+ }
60
+ }
61
+
62
+ /** Take one job's claim. False = another poller is (or was) on it. */
63
+ function tryClaim(id: string): boolean {
64
+ const path = claimPath(id)
65
+ if (makeClaim(path)) return true
66
+ try {
67
+ if (Date.now() - statSync(path).mtimeMs < CLAIM_STALE_MS) return false
68
+ rmSync(path, { recursive: true, force: true })
69
+ } catch {
70
+ // It vanished between the two calls (the holder released or another poller
71
+ // reclaimed it) — that poller fires this tick. Skip rather than risk a
72
+ // second one firing too.
73
+ return false
74
+ }
75
+ return makeClaim(path)
76
+ }
77
+
78
+ function releaseClaim(id: string): void {
79
+ try {
80
+ rmSync(claimPath(id), { recursive: true, force: true })
81
+ } catch {
82
+ /* Best effort — a leftover claim goes stale and is reclaimed. */
83
+ }
84
+ }
85
+
40
86
  /**
41
87
  * Read due jobs, enqueue their prompts, and advance/delete. Returns fired count.
42
88
  *
@@ -44,6 +90,19 @@ export function advanceJob(job: CronJob, now: Date): CronJob | null {
44
90
  * `ToolContext.cwd` comes from — because the enqueued prompt lands in *this*
45
91
  * session and is executed here. Without the filter, a schedule created in one
46
92
  * project would be run by whatever session happened to be open in another.
93
+ *
94
+ * The store is global and every open CLI in the same directory runs its own
95
+ * poller, so two of them can read the same due job before either writes it
96
+ * back — the prompt would run twice. Each job is claimed with an exclusive
97
+ * directory before firing, and the file is re-read under that claim: a poller
98
+ * whose snapshot has gone stale (the job was advanced or deleted meanwhile)
99
+ * skips it.
100
+ *
101
+ * Delivery is at-least-once, not exactly-once: a process killed between
102
+ * `enqueue` and `writeJob` leaves the claim behind, and once it goes stale the
103
+ * job fires again. Two pollers reclaiming the same stale claim can likewise
104
+ * both proceed. The claim closes the concurrent-poller window, not the crash
105
+ * window — the prompt has already been handed to the session by then.
47
106
  */
48
107
  export function checkCronJobs(
49
108
  enqueue: (prompt: string) => void,
@@ -51,13 +110,22 @@ export function checkCronJobs(
51
110
  cwd = process.cwd(),
52
111
  ): number {
53
112
  const due = findDueJobs(readAllJobs(), now, cwd)
113
+ let fired = 0
54
114
  for (const job of due) {
55
- enqueue(job.prompt)
56
- const next = advanceJob(job, now)
57
- if (next) writeJob(next)
58
- else deleteJobFile(job.id)
115
+ if (!tryClaim(job.id)) continue
116
+ try {
117
+ const current = readAllJobs().find((j) => j.id === job.id)
118
+ if (!current || findDueJobs([current], now, cwd).length === 0) continue
119
+ enqueue(current.prompt)
120
+ const next = advanceJob(current, now)
121
+ if (next) writeJob(next)
122
+ else deleteJobFile(current.id)
123
+ fired++
124
+ } finally {
125
+ releaseClaim(job.id)
126
+ }
59
127
  }
60
- return due.length
128
+ return fired
61
129
  }
62
130
 
63
131
  /**
@@ -43,7 +43,7 @@ import { UsageTracker } from './usage-tracker'
43
43
  import { getMetrics } from './metrics'
44
44
  import { buildRequest, sendInferenceCheck, isInferenceHookEnabled } from './inference-hook'
45
45
  import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
46
- import { registerWakeupHandler } from '../tools/scheduling/schedule-wakeup'
46
+ import { registerWakeupHandler, unregisterWakeupHandler } from '../tools/scheduling/schedule-wakeup'
47
47
  import { accumulateGraftSavings } from '../shared/graft-savings'
48
48
  import { deletedCwdSessionMessage, resolveExistingCwd } from '../shared/deleted-cwd'
49
49
  import {
@@ -144,7 +144,20 @@ export class QueryEngine {
144
144
  ) {
145
145
  this.ruleEngine = ruleEngine
146
146
  // ScheduleWakeup 的 timer 到期后,把 loop prompt 交回本引擎 re-invoke。
147
- registerWakeupHandler((_sessionId, prompt, noop) => this.enqueueWakeup(prompt, noop))
147
+ this.bindWakeupHandler()
148
+ }
149
+
150
+ /**
151
+ * Route this engine's session wakeups to itself.
152
+ *
153
+ * Keyed by session, not global: several engines live in the same daemon process
154
+ * (one per session), and a single shared slot meant the engine built last
155
+ * received every session's wakeups.
156
+ */
157
+ private bindWakeupHandler(): void {
158
+ registerWakeupHandler(this.sessionId, (_sessionId, prompt, noop) => {
159
+ this.enqueueWakeup(prompt, noop)
160
+ })
148
161
  }
149
162
 
150
163
  /** Enqueue a loop prompt for later re-invocation (keep-latest — drops older wakeups). */
@@ -224,7 +237,12 @@ export class QueryEngine {
224
237
 
225
238
  /** Set the session identifier (called from index.tsx at startup with the actual session name). */
226
239
  setSessionId(id: string): void {
240
+ if (id === this.sessionId) return
241
+ // The wakeup registry is keyed by session, so a rename has to move the entry:
242
+ // leaving the old one behind would hand this engine another session's wakeups.
243
+ unregisterWakeupHandler(this.sessionId)
227
244
  this.sessionId = id
245
+ this.bindWakeupHandler()
228
246
  }
229
247
 
230
248
  /** Get the current session identifier. */
@@ -567,12 +585,16 @@ export class QueryEngine {
567
585
 
568
586
  /** Wire LLM-based conversation summarization into the context manager. */
569
587
  setupContextSummarizer(): void {
570
- this.context.setSummarizer(async (messages, heading) => {
588
+ this.context.setSummarizer(async (messages, heading, signal) => {
571
589
  const text = messages
572
590
  .map((m) => {
573
591
  const role = m.role
574
592
  const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content)
575
- return `[${role}]: ${content.slice(0, 2000)}`
593
+ // 2000 字符是摘要器读得到的上限,但不能是**静默**上限:被切掉的那半里
594
+ // 常是工具结果的结论部分,摘要据此写成「做了什么」而漏掉「结果如何」。
595
+ // 写明省略了多少,摘要器才知道这条不完整。
596
+ if (content.length <= 2000) return `[${role}]: ${content}`
597
+ return `[${role}]: ${content.slice(0, 2000)} … [${content.length - 2000} characters omitted]`
576
598
  })
577
599
  .join('\n')
578
600
 
@@ -594,6 +616,11 @@ export class QueryEngine {
594
616
  systemPrompt: summaryPrompt,
595
617
  messages: [{ role: 'user', content: text }],
596
618
  maxTokens: 2000,
619
+ // An interrupt has to reach *this* call too. Summarising a long
620
+ // conversation is a full model round trip; without the signal, Ctrl+C
621
+ // arrives at the compaction step and simply waits for it to finish
622
+ // before the turn can stop.
623
+ signal,
597
624
  })) {
598
625
  if (chunk.type === 'text' && chunk.content) {
599
626
  summary += chunk.content
@@ -660,7 +687,7 @@ export class QueryEngine {
660
687
 
661
688
  // Check compaction before processing
662
689
  if (this.context.needsCompaction()) {
663
- await this.compactWithHooks('conversation summary')
690
+ await this.compactWithHooks('conversation summary', signal)
664
691
  }
665
692
 
666
693
  const systemPrompt = this.context.getSystemPrompt()
@@ -2055,7 +2082,7 @@ export class QueryEngine {
2055
2082
  }
2056
2083
 
2057
2084
  /** Wrap context compaction with PreCompact/PostCompact hooks. */
2058
- private async compactWithHooks(heading: string): Promise<void> {
2085
+ private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
2059
2086
  if (this.hookEngine) {
2060
2087
  const preResult = await this.hookEngine.executePreCompact(this.sessionId)
2061
2088
  if (preResult.additionalContext) {
@@ -2066,7 +2093,7 @@ export class QueryEngine {
2066
2093
  }
2067
2094
  }
2068
2095
 
2069
- await this.context.compact(heading)
2096
+ await this.context.compact(heading, signal)
2070
2097
 
2071
2098
  if (this.hookEngine) {
2072
2099
  const postResult = await this.hookEngine.executePostCompact(this.sessionId)
@@ -60,6 +60,10 @@ export function loadHookConfigs(configs: SettingsHooks): HookDefinition[] {
60
60
  definitions.push({
61
61
  event: eventName as HookEvent,
62
62
  toolName: entry.matcher || undefined,
63
+ // The engine's own failure paths (a handler that throws, a hook
64
+ // auto-disabled for repeated failures) see the definition, not the
65
+ // config, and an opted-open guard must stay open there too.
66
+ failureMode: hookCfg.failureMode,
63
67
  handler: async (ctx: HookContext) => {
64
68
  // Check matcher if tool-specific
65
69
  if (matcherRegex && ctx.toolName && !matcherRegex.test(ctx.toolName)) {
@@ -1,7 +1,46 @@
1
1
  import { spawn } from 'node:child_process'
2
2
  import { McpClient } from '../mcp/client'
3
3
  import type { ToolCallResult } from '../mcp/types'
4
- import type { HookConfig, HookContext, HookResult } from '../shared/index.ts'
4
+ import type { HookConfig, HookContext, HookEvent, HookResult } from '../shared/index.ts'
5
+
6
+ /**
7
+ * Does a failure to *run* this hook block the call?
8
+ *
9
+ * A `PreToolUse` hook is a guard: it exists to decide before the tool runs. If
10
+ * it cannot start, times out, or cannot hand back an answer, there is no
11
+ * decision — and treating that as "allow" turns a broken guard into a silent
12
+ * bypass. Every other event observes something that already happened, so there
13
+ * is nothing left to refuse and their failures stay context.
14
+ *
15
+ * `failureMode: 'open'` opts one hook back into the old fail-open behaviour.
16
+ */
17
+ export function hookFailureBlocks(
18
+ event: HookEvent,
19
+ failureMode: 'open' | 'closed' | undefined,
20
+ ): boolean {
21
+ return event === 'PreToolUse' && failureMode !== 'open'
22
+ }
23
+
24
+ /**
25
+ * The result for a hook that could not run.
26
+ *
27
+ * Blocking and non-blocking results carry the same message in `reason` /
28
+ * `additionalContext`: a guard's block is read by the model, and a non-guard's
29
+ * context is shown as a warning, so neither may lose the diagnosis.
30
+ */
31
+ function failureResult(cfg: HookConfig, ctx: HookContext, text: string, error: string): HookResult {
32
+ if (hookFailureBlocks(ctx.event, cfg.failureMode)) {
33
+ return {
34
+ allowed: false,
35
+ reason:
36
+ `${text} — the ${ctx.event} hook could not run, so the call was blocked ` +
37
+ `(set "failureMode": "open" on this hook to allow instead).`,
38
+ additionalContext: text,
39
+ hookError: error,
40
+ }
41
+ }
42
+ return { allowed: true, hookError: error, additionalContext: text }
43
+ }
5
44
 
6
45
  /**
7
46
  * Execute a hook based on its type, returning a HookResult.
@@ -331,7 +370,16 @@ async function executeCommand(
331
370
  ctx: HookContext,
332
371
  source?: string,
333
372
  ): Promise<HookResult> {
334
- if (!cfg.command) return { allowed: true }
373
+ if (!cfg.command) {
374
+ // A guard with no command cannot decide. For other events this stays a
375
+ // silent allow, as it always was.
376
+ return failureResult(
377
+ cfg,
378
+ ctx,
379
+ 'Hook error: no command configured for this hook',
380
+ 'no command configured',
381
+ )
382
+ }
335
383
 
336
384
  try {
337
385
  const args = cfg.args ? cfg.args.map((a) => substituteVars(a, ctx)) : []
@@ -391,11 +439,12 @@ async function executeCommand(
391
439
 
392
440
  const failure = spawnFailureCause(result, cfg.timeout ?? 60)
393
441
  if (failure) {
394
- return {
395
- allowed: true,
396
- hookError: failure,
397
- additionalContext: `Hook error ${failingLabel(cfg.command, source)}: ${failure}`,
398
- }
442
+ return failureResult(
443
+ cfg,
444
+ ctx,
445
+ `Hook error ${failingLabel(cfg.command, source)}: ${failure}`,
446
+ failure,
447
+ )
399
448
  }
400
449
 
401
450
  // Other non-zero exit: don't block, log the error as context
@@ -410,16 +459,24 @@ async function executeCommand(
410
459
  // `spawnFailureCause`), which is why this comment used to name them wrongly.
411
460
  const message = (err as { message?: string }).message || String(err)
412
461
 
413
- return {
414
- allowed: true,
415
- hookError: message,
416
- additionalContext: `Hook error ${failingLabel(cfg.command, source)}: ${message}`,
417
- }
462
+ return failureResult(
463
+ cfg,
464
+ ctx,
465
+ `Hook error ${failingLabel(cfg.command, source)}: ${message}`,
466
+ message,
467
+ )
418
468
  }
419
469
  }
420
470
 
421
471
  async function executeHttp(cfg: HookConfig, ctx: HookContext): Promise<HookResult> {
422
- if (!cfg.url) return { allowed: true }
472
+ if (!cfg.url) {
473
+ return failureResult(
474
+ cfg,
475
+ ctx,
476
+ 'Hook error: no url configured for this HTTP hook',
477
+ 'no url configured',
478
+ )
479
+ }
423
480
 
424
481
  try {
425
482
  const response = await fetch(cfg.url, {
@@ -450,11 +507,9 @@ async function executeHttp(cfg: HookConfig, ctx: HookContext): Promise<HookResul
450
507
  additionalContext: body.slice(0, 2000) || undefined,
451
508
  }
452
509
  } catch (err) {
453
- // HTTP hook failures should not block
454
- return {
455
- allowed: true,
456
- additionalContext: `HTTP hook error (${cfg.url}): ${String(err)}`,
457
- }
510
+ // An unreachable guard cannot decide; other events keep reporting it as context.
511
+ const message = `HTTP hook error (${cfg.url}): ${String(err)}`
512
+ return failureResult(cfg, ctx, message, String(err))
458
513
  }
459
514
  }
460
515
 
@@ -466,19 +521,30 @@ async function executeHttp(cfg: HookConfig, ctx: HookContext): Promise<HookResul
466
521
  * structured decision decides, plain prose is context — so a tool that guards a
467
522
  * tool call can block it the way a script would. An `isError` result is *not* a
468
523
  * decision: it means the call did not speak, and an unreachable server reports
469
- * the same way, so its message is reported rather than read as a verdict.
524
+ * the same way, so its message is reported rather than read as a verdict. On a
525
+ * `PreToolUse` guard, "not a verdict" still means "no answer" — and no answer
526
+ * blocks (see `hookFailureBlocks`).
470
527
  */
471
528
  async function executeMcpTool(cfg: HookConfig, ctx: HookContext): Promise<HookResult> {
472
- if (!cfg.mcpServer || !cfg.mcpTool) return { allowed: true }
529
+ if (!cfg.mcpServer || !cfg.mcpTool) {
530
+ return failureResult(
531
+ cfg,
532
+ ctx,
533
+ 'Hook error: no mcpServer/mcpTool configured for this MCP hook',
534
+ 'no mcpServer/mcpTool configured',
535
+ )
536
+ }
473
537
 
474
538
  const client = McpClient.getInstance()
475
539
 
476
540
  // Startup connects servers without blocking; this hook can arrive first.
477
541
  if (!(await client.waitUntilReady(cfg.mcpServer))) {
478
- return {
479
- allowed: true,
480
- additionalContext: `MCP hook (${cfg.mcpServer}/${cfg.mcpTool}): server "${cfg.mcpServer}" was still connecting — the tool was not called.`,
481
- }
542
+ return failureResult(
543
+ cfg,
544
+ ctx,
545
+ `MCP hook (${cfg.mcpServer}/${cfg.mcpTool}): server "${cfg.mcpServer}" was still connecting — the tool was not called.`,
546
+ 'server still connecting',
547
+ )
482
548
  }
483
549
 
484
550
  const result = await client.callTool(cfg.mcpServer, cfg.mcpTool, {
@@ -490,10 +556,12 @@ async function executeMcpTool(cfg: HookConfig, ctx: HookContext): Promise<HookRe
490
556
  const body = mcpResultText(result)
491
557
 
492
558
  if (result.isError) {
493
- return {
494
- allowed: true,
495
- additionalContext: `MCP hook error (${cfg.mcpServer}/${cfg.mcpTool}): ${body.slice(0, 2000)}`,
496
- }
559
+ return failureResult(
560
+ cfg,
561
+ ctx,
562
+ `MCP hook error (${cfg.mcpServer}/${cfg.mcpTool}): ${body.slice(0, 2000)}`,
563
+ body.slice(0, 2000) || 'MCP tool returned an error',
564
+ )
497
565
  }
498
566
 
499
567
  const parsed = parseHookStdout(body, ctx)
package/src/core/hooks.ts CHANGED
@@ -33,6 +33,17 @@ const COOLDOWN_MS = 5 * 60 * 1000
33
33
  * Merge two permission decisions, keeping the more restrictive one.
34
34
  * Priority: deny > defer > ask > allow
35
35
  */
36
+ /**
37
+ * Does a failure to run this hook block the call?
38
+ *
39
+ * Same rule as `hookFailureBlocks` in `hooks-executor.ts`, kept local so the
40
+ * engine's own failure paths — a handler that throws, a hook auto-disabled after
41
+ * repeated failures — do not import the executor module to ask.
42
+ */
43
+ function guardFailureBlocks(hook: HookDefinition): boolean {
44
+ return hook.event === 'PreToolUse' && hook.failureMode !== 'open'
45
+ }
46
+
36
47
  export function mergePermissionDecision(
37
48
  current: HookResult['permissionDecision'],
38
49
  incoming: NonNullable<HookResult['permissionDecision']>,
@@ -350,11 +361,35 @@ export class HookEngine {
350
361
 
351
362
  const result: HookResult = { allowed: true }
352
363
 
364
+ // A guard that could not run denies — but the denial is *remembered* rather
365
+ // than returned on the spot. Returning early would end the loop, and every
366
+ // later hook is a hook the call never got to consult: an explicit deny
367
+ // written after the broken one would never be reached, so the model gets
368
+ // "hook broke" where the real answer is "this was refused, here is why".
369
+ // Keep going, keep the first guard failure, and let an explicit deny
370
+ // (which returns immediately at its own branch) outweigh it.
371
+ let guardDenial: HookResult | undefined
372
+
353
373
  for (const hook of matching) {
354
374
  const key = this.healthKey(hook)
355
375
 
356
376
  // ── Resilience: skip disabled hooks ──
357
377
  if (this.shouldSkip(key)) {
378
+ // A disabled guard is still a guard. Auto-disable exists so a broken
379
+ // hook stops being retried, not so it quietly stops guarding: skipping
380
+ // it for `PreToolUse` would turn five failures into a permanent allow
381
+ // for the rest of the cooldown — the same fail-open hole, delayed.
382
+ if (guardFailureBlocks(hook)) {
383
+ guardDenial ??= {
384
+ allowed: false,
385
+ reason:
386
+ `Hook "${key}" is temporarily disabled after repeated failures; ` +
387
+ `a PreToolUse guard that cannot run blocks the call. ` +
388
+ `Fix the hook, re-enable it with /hooks enable "${key}", or set ` +
389
+ `"failureMode": "open" to allow instead.`,
390
+ }
391
+ continue
392
+ }
358
393
  result.additionalContext = result.additionalContext
359
394
  ? result.additionalContext +
360
395
  `\n[Hook "${key}" skipped — temporarily disabled after repeated failures]`
@@ -414,14 +449,25 @@ export class HookEngine {
414
449
  if (hookResult.updatedOutput) {
415
450
  result.updatedOutput = hookResult.updatedOutput
416
451
  }
417
- } catch {
452
+ } catch (err) {
418
453
  // Record failure — may trigger auto-disable
419
454
  this.recordFailure(key)
420
- // Hook failures do not block execution
455
+ // A handler that throws is a hook that could not answer. For a guard
456
+ // that is not "allow" — see `guardFailureBlocks`.
457
+ if (guardFailureBlocks(hook)) {
458
+ const message = (err as { message?: string }).message || String(err)
459
+ guardDenial ??= {
460
+ allowed: false,
461
+ reason:
462
+ `Hook "${key}" failed and the PreToolUse guard is fail-closed: ${message} ` +
463
+ `(set "failureMode": "open" on this hook to allow instead).`,
464
+ }
465
+ }
466
+ // Other events observe what already happened; the failure stays diagnostic.
421
467
  }
422
468
  }
423
469
 
424
- return result
470
+ return guardDenial ?? result
425
471
  }
426
472
 
427
473
  listHooks(): HookDefinition[] {
@@ -821,6 +821,12 @@ export function validateRulePattern(
821
821
  return null
822
822
  }
823
823
 
824
+ // Whole-server MCP rules (`mcp__server`, `mcp__server__*`) are valid and are
825
+ // compiled as a prefix match — see `mcpServerPrefix`. Before this they either
826
+ // failed `^\w+$` (the wildcard form, warned as invalid) or compiled to an
827
+ // exact regex that could never equal `mcp__server__tool` (silent dead rule).
828
+ if (mcpServerPrefix(pattern)) return null
829
+
824
830
  // No parenthesis → must be a plain tool name (matched via `pattern === tool.name`).
825
831
  if (!/^\w+$/.test(pattern)) return 'not a single tool name'
826
832
  if (knownTools && !pattern.startsWith('mcp__')) {
@@ -836,16 +842,40 @@ export function validateRulePattern(
836
842
  return null
837
843
  }
838
844
 
839
- /** Compile a rule pattern string into a PermissionRuleEntry. */
845
+ /**
846
+ * Recognize an **MCP whole-server** rule and return its tool-name prefix.
847
+ *
848
+ * `mcp__server` and `mcp__server__*` both mean "every tool on that server".
849
+ * Full tool names (`mcp__server__tool`) are not whole-server rules and return
850
+ * null — they stay exact matches. Server names are lowercased because
851
+ * `sanitizeName` (mcp/registry.ts) lowercases them when building tool names;
852
+ * without this, `mcp__MyServer` would compile to a rule that can never match.
853
+ */
854
+ export function mcpServerPrefix(pattern: string): string | null {
855
+ const base = pattern.endsWith('__*') ? pattern.slice(0, -3) : pattern
856
+ if (!base.startsWith('mcp__')) return null
857
+ const server = base.slice('mcp__'.length)
858
+ // A second `__` means this is a full tool name, not a whole-server rule.
859
+ if (!server || server.includes('__')) return null
860
+ // Same charset `sanitizeName` leaves intact (it maps everything else to `_`).
861
+ if (!/^[A-Za-z0-9-]+$/.test(server)) return null
862
+ return `mcp__${server.toLowerCase()}__`
863
+ }
864
+
865
+ /**
866
+ * Compile a rule pattern string into a PermissionRuleEntry.
867
+ */
840
868
  export function compileRule(
841
869
  pattern: string,
842
870
  level: 'allow' | 'deny' | 'ask',
843
871
  knownTools?: ReadonlySet<string>,
844
872
  ): PermissionRuleEntry {
845
873
  const invalid = validateRulePattern(pattern, knownTools)
874
+ const serverPrefix = mcpServerPrefix(pattern)
875
+ const source = serverPrefix ? `${serverPrefix}*` : pattern
846
876
  const regexStr =
847
877
  '^' +
848
- pattern
878
+ source
849
879
  .replace(/[.+^${}()|[\]\\*?]/g, '\\$&')
850
880
  .replace(/:/g, '[:\\s]')
851
881
  .replace(/\\\*/g, '.*')
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `--safe-mode` gate.
3
+ *
4
+ * Read at call time, not at import time: `bin/mipham.ts` sets
5
+ * `MIPHAM_SAFE_MODE=1` while parsing argv, which happens after the module
6
+ * graph is evaluated. Only the exact value `1` enables it — an inherited
7
+ * empty string or `0` must not silently disable the user's customizations.
8
+ */
9
+ export function isSafeMode(): boolean {
10
+ return process.env.MIPHAM_SAFE_MODE === '1'
11
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The one way out of a session.
3
+ *
4
+ * `SessionEnd` hooks are asynchronous, while `process.exit()` is immediate. The
5
+ * exit path used to start the hooks and call `process.exit()` in the same tick,
6
+ * so a hook registered for SessionEnd could never finish — and `/exit`, `/quit`
7
+ * and the second Ctrl+C left through `process.exit()` directly, never starting
8
+ * them at all. Every user-initiated exit now goes through `exitSession()`, which
9
+ * runs the registered shutdown callback once and then exits.
10
+ *
11
+ * The callback owns its own bounds (a session must not hang on exit); this module
12
+ * only guarantees ordering and that a broken callback cannot trap the user.
13
+ */
14
+
15
+ let handler: (() => void | Promise<void>) | null = null
16
+ let exitPromise: Promise<void> | null = null
17
+
18
+ /**
19
+ * SessionEnd is best-effort: a hook that is slow, hung, or waiting on a server
20
+ * that never answers must not hold the terminal open. The caller uses this as
21
+ * the upper bound for the hook phase.
22
+ */
23
+ export const SESSION_END_HOOK_TIMEOUT_MS = 1_500
24
+
25
+ export function registerExitHandler(fn: () => void | Promise<void>): void {
26
+ handler = fn
27
+ }
28
+
29
+ /** Test hook — the process-global handler otherwise leaks between test files. */
30
+ export function resetExitHandler(): void {
31
+ handler = null
32
+ exitPromise = null
33
+ }
34
+
35
+ /**
36
+ * Run `promise`, giving up after `ms`. Used to bound SessionEnd hooks without
37
+ * cancelling the work they may still be doing in the background.
38
+ */
39
+ export async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {
40
+ let timer: unknown
41
+ try {
42
+ return await Promise.race([
43
+ promise,
44
+ new Promise<undefined>((resolve) => {
45
+ timer = setTimeout(resolve, ms)
46
+ // A pending timeout must not keep a test process (or a stuck session)
47
+ // alive by itself. Bun's timer is a number; Node's has `unref`.
48
+ ;(timer as { unref?: () => void }).unref?.()
49
+ }),
50
+ ])
51
+ } finally {
52
+ if (timer !== undefined) clearTimeout(timer as ReturnType<typeof setTimeout>)
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Run the registered shutdown callback (once, across every caller) and exit.
58
+ *
59
+ * Concurrent or repeated calls — a signal arriving while `/exit` is already
60
+ * shutting down — await the same work and share the same exit.
61
+ */
62
+ export function exitSession(code = 0): Promise<never> {
63
+ if (!exitPromise) {
64
+ exitPromise = Promise.resolve()
65
+ .then(() => handler?.())
66
+ .then(() => undefined)
67
+ .catch(() => {
68
+ // Shutdown is best effort. A callback that throws must not leave the
69
+ // user with a session they cannot close.
70
+ })
71
+ }
72
+ return exitPromise.then(() => process.exit(code))
73
+ }