@miphamai/cli 0.85.21 → 0.85.23

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.21
1
+ # Mipham Code v0.85.23
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 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/bin/mipham.ts CHANGED
@@ -375,18 +375,23 @@ async function runDaemonCLI(): Promise<boolean> {
375
375
 
376
376
  if (subcmd === 'stop') {
377
377
  const { getDaemonStatus } = await import('../src/daemon/index')
378
+ const { terminateDaemonProcess } = await import('../src/daemon/launch')
378
379
  const status = getDaemonStatus()
379
380
  if (!status) {
380
381
  console.log('Daemon is not running.')
381
382
  process.exit(0)
382
383
  }
383
- try {
384
- process.kill(status.pid, 'SIGTERM')
384
+ const started = Date.now()
385
+ // SIGTERM → wait → SIGKILL → wait. "Stopped" is printed only when the
386
+ // process is confirmed gone; the old code printed it right after send().
387
+ if (await terminateDaemonProcess(status.pid)) {
385
388
  console.log(`Daemon stopped (PID: ${status.pid})`)
386
- } catch {
387
- console.log('Daemon is not running.')
389
+ process.exit(0)
388
390
  }
389
- process.exit(0)
391
+ console.error(
392
+ `Failed to stop daemon (PID: ${status.pid}) after ${Date.now() - started}ms — it is still running.`,
393
+ )
394
+ process.exit(1)
390
395
  }
391
396
 
392
397
  if (subcmd === 'status') {
@@ -1214,6 +1219,15 @@ async function main() {
1214
1219
  const { PACKAGE_NAME, PACKAGE_VERSION } = await import('../src/shared/package-info')
1215
1220
  const APP_VERSION = PACKAGE_VERSION
1216
1221
 
1222
+ // ── Safe mode ─────────────────────────────────────────────────────────────
1223
+ // Set the env var before subcommand dispatch: `daemon start` re-execs this
1224
+ // binary with an inherited environment, so parsing the flag after
1225
+ // `runDaemonCLI()` would leave the daemon running with every customization
1226
+ // loaded while the foreground CLI believed it had skipped them.
1227
+ if (process.argv.includes('--safe-mode')) {
1228
+ process.env.MIPHAM_SAFE_MODE = '1'
1229
+ }
1230
+
1217
1231
  // ── Version flag ──────────────────────────────────────────────────────────
1218
1232
  if (
1219
1233
  process.argv.includes('--version') ||
@@ -1356,12 +1370,6 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
1356
1370
  process.exit(1)
1357
1371
  }
1358
1372
 
1359
- // Parse --safe-mode flag: skip custom agents, skills, hooks, plugins
1360
- const safeModeFlag = process.argv.includes('--safe-mode')
1361
- if (safeModeFlag) {
1362
- process.env.MIPHAM_SAFE_MODE = '1'
1363
- }
1364
-
1365
1373
  // Parse --resume <name>: open a saved session instead of starting a new one.
1366
1374
  // `runApp` has accepted `options.resume` all along — it restores the session log
1367
1375
  // and chdirs to the cwd recorded in the session's `session/start` event — but
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.21",
3
+ "version": "0.85.23",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -2,6 +2,7 @@
2
2
  import { readdirSync, readFileSync, existsSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { ContextManager } from '../core/context'
5
+ import { mcpServerPrefix } from '../core/permission-rules'
5
6
  import type { ToolDefinition } from '../shared/index.ts'
6
7
  import type { AgentDefinition } from './types'
7
8
  import type { CrsiConfig } from '../shared/index.ts'
@@ -133,13 +134,25 @@ export function createAgentContext(
133
134
  let allowedTools = Array.from(toolRegistry.values())
134
135
 
135
136
  if (agentDef.tools) {
136
- const allowSet = new Set(
137
- agentDef.tools
138
- .split(',')
139
- .map((s) => s.trim())
140
- .filter(Boolean),
137
+ const allowRules = agentDef.tools
138
+ .split(',')
139
+ .map((s) => s.trim())
140
+ .filter(Boolean)
141
+ // `mcp__server` / `mcp__server__*` mean "every tool on that server".
142
+ // Without expansion these exact-match nothing, so an agent that asks for a
143
+ // whole server silently receives no tools at all.
144
+ const serverPrefixes = allowRules
145
+ .map((r) => mcpServerPrefix(r))
146
+ .filter((p): p is string => p !== null)
147
+ const allowSet = new Set(allowRules.filter((r) => mcpServerPrefix(r) === null))
148
+ allowedTools = allowedTools.filter(
149
+ (t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
141
150
  )
142
- allowedTools = allowedTools.filter((t) => allowSet.has(t.name))
151
+ if (allowedTools.length === 0) {
152
+ process.stderr.write(
153
+ `⚠️ Agent "${agentDef.name}": tools list (${allowRules.join(', ')}) matched no registered tool — the agent will run without tools.\n`,
154
+ )
155
+ }
143
156
  }
144
157
 
145
158
  if (agentDef.disallowedTools) {
@@ -248,17 +248,23 @@ const permissionsCmd: CommandHandler = async (ctx, args) => {
248
248
  }
249
249
  // A rule that can't match is worse than no rule: it reads as protection
250
250
  // that isn't there. Validate every rule before writing any of them.
251
+ //
252
+ // Judged against the permission system's own tool set (`getKnownTools`), not a
253
+ // second copy — that set is what plain-name rules are matched against, so the
254
+ // verdict here and the matching there cannot drift. It is `undefined` in a
255
+ // context nobody told about the registry, in which case the check is structural
256
+ // only, exactly as before.
257
+ const perm = ctx.engine.getPermission()
251
258
  if (verb !== 'remove') {
259
+ const knownTools = perm.getKnownTools()
252
260
  for (const rule of rules) {
253
- const invalid = validateRulePattern(rule)
261
+ const invalid = validateRulePattern(rule, knownTools)
254
262
  if (invalid) {
255
263
  return { content: `Invalid rule "${rule}": ${invalid}.\n\n${usage}` }
256
264
  }
257
265
  }
258
266
  }
259
267
 
260
- const perm = ctx.engine.getPermission()
261
-
262
268
  if (verb === 'remove') {
263
269
  const parts: string[] = []
264
270
  // Both scopes, named one first. `remove` does not know which list holds the
@@ -107,6 +107,44 @@ function mergeProviders(
107
107
  return merged
108
108
  }
109
109
 
110
+ /** Context window assumed for a hand-written model that does not declare one. */
111
+ const DEFAULT_CONTEXT_WINDOW = 128_000
112
+
113
+ /**
114
+ * Ensure every configured model carries a usable `contextWindow`.
115
+ *
116
+ * `ModelInfo.contextWindow` is required in TypeScript but nothing checks the
117
+ * YAML at runtime, and a user-defined provider's `models` reach the registry
118
+ * exactly as written. A model that is found but lacks the field produces
119
+ * `undefined` at `index.tsx`'s `activeModel.contextWindow` — and that becomes
120
+ * `ContextManager.maxTokens`. `needsCompaction()` then compares tokens against
121
+ * `NaN` and is **permanently false**: auto-compaction never runs, and the first
122
+ * sign of trouble is the provider rejecting an oversized request.
123
+ *
124
+ * The fallback is the same 128K `index.tsx` uses for an unknown model. Warn
125
+ * once per model: the whole defect is that this was silent. A value that is
126
+ * present but not a positive finite number (0, negative, a quoted string) is
127
+ * equally unusable and gets the same treatment.
128
+ *
129
+ * Runs on the final provider list — not on an override as it is merged — so a
130
+ * custom provider added wholesale is covered by the same check.
131
+ */
132
+ function normalizeModelContextWindows(providers: ProviderConfig[]): void {
133
+ for (const provider of providers) {
134
+ if (!provider || !Array.isArray(provider.models)) continue
135
+ for (const model of provider.models) {
136
+ if (!model || typeof model !== 'object') continue
137
+ const window = model.contextWindow
138
+ if (typeof window === 'number' && Number.isFinite(window) && window > 0) continue
139
+ model.contextWindow = DEFAULT_CONTEXT_WINDOW
140
+ process.stderr.write(
141
+ `⚠ Mipham Code: model "${model.id ?? '<unnamed>'}" (provider "${provider.id}") ` +
142
+ `has no usable contextWindow — assuming 128K.\n`,
143
+ )
144
+ }
145
+ }
146
+ }
147
+
110
148
  /**
111
149
  * Merge `override` into `base`, recursing into plain objects so that a source
112
150
  * setting one branch of an object does not drop the other source's siblings
@@ -914,6 +952,9 @@ export function loadConfig(cwd: string = process.cwd()): MiphamConfig {
914
952
  // ── Decrypt API keys at rest (enc:v1:) back to plaintext ──
915
953
  decryptProviderApiKeys(config.providers)
916
954
 
955
+ // Last step, so it sees the final merged list from every source.
956
+ normalizeModelContextWindows(config.providers)
957
+
917
958
  return config
918
959
  }
919
960
 
@@ -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. */
@@ -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']>,
@@ -355,6 +366,20 @@ export class HookEngine {
355
366
 
356
367
  // ── Resilience: skip disabled hooks ──
357
368
  if (this.shouldSkip(key)) {
369
+ // A disabled guard is still a guard. Auto-disable exists so a broken
370
+ // hook stops being retried, not so it quietly stops guarding: skipping
371
+ // it for `PreToolUse` would turn five failures into a permanent allow
372
+ // for the rest of the cooldown — the same fail-open hole, delayed.
373
+ if (guardFailureBlocks(hook)) {
374
+ return {
375
+ allowed: false,
376
+ reason:
377
+ `Hook "${key}" is temporarily disabled after repeated failures; ` +
378
+ `a PreToolUse guard that cannot run blocks the call. ` +
379
+ `Fix the hook, re-enable it with /hooks enable "${key}", or set ` +
380
+ `"failureMode": "open" to allow instead.`,
381
+ }
382
+ }
358
383
  result.additionalContext = result.additionalContext
359
384
  ? result.additionalContext +
360
385
  `\n[Hook "${key}" skipped — temporarily disabled after repeated failures]`
@@ -414,10 +439,21 @@ export class HookEngine {
414
439
  if (hookResult.updatedOutput) {
415
440
  result.updatedOutput = hookResult.updatedOutput
416
441
  }
417
- } catch {
442
+ } catch (err) {
418
443
  // Record failure — may trigger auto-disable
419
444
  this.recordFailure(key)
420
- // Hook failures do not block execution
445
+ // A handler that throws is a hook that could not answer. For a guard
446
+ // that is not "allow" — see `guardFailureBlocks`.
447
+ if (guardFailureBlocks(hook)) {
448
+ const message = (err as { message?: string }).message || String(err)
449
+ return {
450
+ allowed: false,
451
+ reason:
452
+ `Hook "${key}" failed and the PreToolUse guard is fail-closed: ${message} ` +
453
+ `(set "failureMode": "open" on this hook to allow instead).`,
454
+ }
455
+ }
456
+ // Other events observe what already happened; the failure stays diagnostic.
421
457
  }
422
458
  }
423
459