@miphamai/cli 0.85.11 → 0.85.13
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 +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +22 -0
- package/src/config/loader.ts +101 -6
- package/src/core/context-microcompact.ts +3 -5
- package/src/core/context.ts +17 -11
- package/src/core/credential-masker/output-scrub.ts +7 -1
- package/src/core/crsi-sandbox.ts +101 -49
- package/src/core/engine.ts +22 -2
- package/src/core/hooks-executor.ts +165 -16
- package/src/core/permission-classifier.ts +36 -12
- package/src/core/permission.ts +45 -0
- package/src/core/self-critique.ts +3 -15
- package/src/core/task-performance.ts +32 -4
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +15 -1
- package/src/plugin/plugin-loader.ts +10 -9
- package/src/providers/anthropic.ts +11 -3
- package/src/providers/fetch-utils.ts +29 -0
- package/src/providers/openai-compat.ts +24 -2
- package/src/providers/registry.ts +38 -0
- package/src/security/world-writable-chmod.ts +157 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +33 -0
- package/src/shared/types.ts +30 -0
- package/src/tools/agent/agent.ts +18 -3
- package/src/tools/agent/exit-plan.ts +49 -9
- package/src/tools/artifact/artifact.ts +0 -1
- package/src/tools/exec/bash.ts +28 -3
- package/src/tools/index.ts +7 -1
- package/src/tools/network/web-fetch.ts +2 -1
- package/src/ui/chat.tsx +2 -1
- package/src/ui/commands.ts +7 -6
- package/src/ui/input.tsx +5 -0
- package/src/workflow/event-bus.ts +13 -0
- package/src/workflow/journal.ts +8 -0
- package/src/workflow/runtime.ts +59 -11
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
2
|
import { McpClient } from '../mcp/client'
|
|
3
3
|
import type { ToolCallResult } from '../mcp/types'
|
|
4
4
|
import type { HookConfig, HookContext, HookResult } from '../shared/index.ts'
|
|
@@ -115,9 +115,9 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
|
|
|
115
115
|
/**
|
|
116
116
|
* Why the hook subprocess failed to run to completion, or `null` if it did exit.
|
|
117
117
|
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
118
|
+
* The spawn does **not** throw for a failed spawn or a timeout — it reports them on
|
|
119
|
+
* the result, and all three shapes arrive with **empty stderr**: `error.code` is
|
|
120
|
+
* `ETIMEDOUT` for the timeout, `ENOENT` when the command does not exist, and an
|
|
121
121
|
* externally killed child comes back as `status: null` + `signal` with no `error`
|
|
122
122
|
* at all. Empty stderr is what made them one string with a benign non-zero exit
|
|
123
123
|
* that printed nothing — `Hook warning (<cmd>): ` with the reason left blank.
|
|
@@ -133,7 +133,7 @@ export function parseHookStdout(stdout: string | null | undefined, _ctx: HookCon
|
|
|
133
133
|
* is exempt from the two decisions below, and speaks only when nothing else can.
|
|
134
134
|
*
|
|
135
135
|
* Named here rather than in the caller's `catch`, which cannot see any of them:
|
|
136
|
-
* it runs only when
|
|
136
|
+
* it runs only when the spawn machinery itself throws.
|
|
137
137
|
*/
|
|
138
138
|
function spawnFailureCause(
|
|
139
139
|
result: { status?: number | null; signal?: string | null; error?: unknown },
|
|
@@ -176,6 +176,156 @@ function failingLabel(command: string | undefined, source?: string): string {
|
|
|
176
176
|
return `(${command})${source ? ` from "${source}"` : ''}`
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
/** Grace given to a descendant still holding a stdio pipe after the hook itself exited. */
|
|
180
|
+
const HOOK_PIPE_GRACE_MS = 1_000
|
|
181
|
+
|
|
182
|
+
/** The `spawnSync`-shaped outcome `spawnFailureCause` and the caller already read. */
|
|
183
|
+
interface HookProcessResult {
|
|
184
|
+
status: number | null
|
|
185
|
+
signal: string | null
|
|
186
|
+
stdout: string
|
|
187
|
+
stderr: string
|
|
188
|
+
error?: { code?: string; message?: string }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Run a hook command to completion, bounding **both** halves of the wait.
|
|
193
|
+
*
|
|
194
|
+
* `spawnSync` was the wrong tool here. It returns only when the child's stdout and
|
|
195
|
+
* stderr reach EOF — not when the child exits — so a hook that backgrounds anything
|
|
196
|
+
* (`daemon &`, a watcher, an ssh tunnel) leaves a descendant holding the pipe and
|
|
197
|
+
* the read never sees EOF. Because `spawnSync` blocks the thread, the whole event
|
|
198
|
+
* loop froze with it: the terminal stopped responding for the full 60s default, and
|
|
199
|
+
* the error that finally surfaced (`timed out after 60s`) was a misdiagnosis — the
|
|
200
|
+
* hook itself had already exited. Measured on this host with a grandchild holding
|
|
201
|
+
* the pipe: 60,0xx ms with the default timeout, and no return at all without one.
|
|
202
|
+
*
|
|
203
|
+
* The async version keeps the event loop live (Escape and Ctrl+C keep working) and
|
|
204
|
+
* gives a pipe-holding descendant the same grace-then-group-kill that the Bash tool
|
|
205
|
+
* already uses, so the wait is bounded by the hook, not by whatever it left behind.
|
|
206
|
+
* `detached` makes the child a process-group leader, which is what lets the group
|
|
207
|
+
* kill reach descendants rather than only the direct child.
|
|
208
|
+
*/
|
|
209
|
+
async function runHookCommand(
|
|
210
|
+
command: string,
|
|
211
|
+
args: string[],
|
|
212
|
+
opts: { input: string; cwd: string; env: NodeJS.ProcessEnv | undefined; timeoutMs: number },
|
|
213
|
+
): Promise<HookProcessResult> {
|
|
214
|
+
return await new Promise<HookProcessResult>((resolve) => {
|
|
215
|
+
let stdout = ''
|
|
216
|
+
let stderr = ''
|
|
217
|
+
let status: number | null = null
|
|
218
|
+
let signal: string | null = null
|
|
219
|
+
let spawnError: { code?: string; message?: string } | undefined
|
|
220
|
+
let timedOut = false
|
|
221
|
+
let settled = false
|
|
222
|
+
// `finish()` 先于计时器存在(它读 `timer`),而计时器只能在 `spawn` 之后开 ——
|
|
223
|
+
// 顺序反过来就是「还没起进程就先超时」。所以这里必须是 `let`。
|
|
224
|
+
// eslint-disable-next-line prefer-const -- 唯一那次赋值在 `finish` 之后
|
|
225
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
226
|
+
let graceTimer: ReturnType<typeof setTimeout> | undefined
|
|
227
|
+
|
|
228
|
+
const child = spawn(command, args, {
|
|
229
|
+
cwd: opts.cwd,
|
|
230
|
+
env: opts.env,
|
|
231
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
232
|
+
detached: true,
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
const killGroup = () => {
|
|
236
|
+
if (child.pid === undefined) return
|
|
237
|
+
try {
|
|
238
|
+
process.kill(-child.pid, 'SIGKILL')
|
|
239
|
+
} catch {
|
|
240
|
+
try {
|
|
241
|
+
child.kill('SIGKILL')
|
|
242
|
+
} catch {
|
|
243
|
+
// Already gone.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const finish = () => {
|
|
249
|
+
if (settled) return
|
|
250
|
+
settled = true
|
|
251
|
+
clearTimeout(timer)
|
|
252
|
+
clearTimeout(graceTimer)
|
|
253
|
+
// Keep the timeout distinguishable from an external kill: both arrive as
|
|
254
|
+
// `status: null`, and only this flag separates "the hook was too slow" from
|
|
255
|
+
// "something killed it" for the message the operator reads.
|
|
256
|
+
if (timedOut && !spawnError) {
|
|
257
|
+
spawnError = {
|
|
258
|
+
code: 'ETIMEDOUT',
|
|
259
|
+
message: `timed out after ${Math.round(opts.timeoutMs / 1000)}s`,
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
resolve({ status, signal, stdout, stderr, ...(spawnError ? { error: spawnError } : {}) })
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
timer = setTimeout(() => {
|
|
266
|
+
timedOut = true
|
|
267
|
+
killGroup()
|
|
268
|
+
// Resolve on the decision, not on a `close` the killed group may never
|
|
269
|
+
// produce: a descendant can outlive the SIGKILL's delivery and keep holding
|
|
270
|
+
// the pipe, and the old `spawnSync` had a hard bound here (a misdiagnosed
|
|
271
|
+
// one, but a bound). Without this, the pipe-holding case would wait forever
|
|
272
|
+
// instead of for the timeout.
|
|
273
|
+
finish()
|
|
274
|
+
}, opts.timeoutMs)
|
|
275
|
+
|
|
276
|
+
// The hook exited, but its stdio may still be held by a descendant it spawned.
|
|
277
|
+
// Give that descendant a short grace, then take the group down — otherwise the
|
|
278
|
+
// caller waits out the full timeout and blames the hook for a timeout it never had.
|
|
279
|
+
const startPipeGrace = () => {
|
|
280
|
+
graceTimer = setTimeout(killGroup, HOOK_PIPE_GRACE_MS)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
child.stdout.on('data', (chunk: Buffer) => {
|
|
284
|
+
stdout += chunk.toString()
|
|
285
|
+
})
|
|
286
|
+
child.stderr.on('data', (chunk: Buffer) => {
|
|
287
|
+
stderr += chunk.toString()
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
child.on('error', (err: NodeJS.ErrnoException) => {
|
|
291
|
+
// A failed spawn (ENOENT, EACCES) never produces an exit or a close.
|
|
292
|
+
spawnError = { code: err.code, message: err.message }
|
|
293
|
+
finish()
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
child.on('exit', (code, sig) => {
|
|
297
|
+
status = code
|
|
298
|
+
signal = sig
|
|
299
|
+
startPipeGrace()
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
// `close` fires once stdio is closed *and* the child has exited — the exact
|
|
303
|
+
// event `spawnSync` was waiting on, minus the frozen thread.
|
|
304
|
+
child.on('close', (code, sig) => {
|
|
305
|
+
status = code
|
|
306
|
+
signal = sig
|
|
307
|
+
finish()
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
// The payload races the child's exit: a child that ignores stdin is gone before
|
|
311
|
+
// the write lands, and the EPIPE that results is a scheduler property, not a hook
|
|
312
|
+
// failure (see `spawnFailureCause`). Recorded as the result's `error` so the
|
|
313
|
+
// existing EPIPE exemption still applies.
|
|
314
|
+
child.stdin.on('error', (err: NodeJS.ErrnoException) => {
|
|
315
|
+
// Only EPIPE is recorded: any other failure here has already been reported by
|
|
316
|
+
// the `error` handler above with a more useful code.
|
|
317
|
+
if (err.code === 'EPIPE' && !spawnError) {
|
|
318
|
+
spawnError = { code: 'EPIPE', message: err.message }
|
|
319
|
+
}
|
|
320
|
+
})
|
|
321
|
+
try {
|
|
322
|
+
child.stdin.end(opts.input)
|
|
323
|
+
} catch {
|
|
324
|
+
// The stream surfaced it through the `error` handler.
|
|
325
|
+
}
|
|
326
|
+
})
|
|
327
|
+
}
|
|
328
|
+
|
|
179
329
|
async function executeCommand(
|
|
180
330
|
cfg: HookConfig,
|
|
181
331
|
ctx: HookContext,
|
|
@@ -186,8 +336,8 @@ async function executeCommand(
|
|
|
186
336
|
try {
|
|
187
337
|
const args = cfg.args ? cfg.args.map((a) => substituteVars(a, ctx)) : []
|
|
188
338
|
|
|
189
|
-
// A hook command is a child of this process, so
|
|
190
|
-
//
|
|
339
|
+
// A hook command is a child of this process, so inheriting the environment
|
|
340
|
+
// would hand it everything — every provider key and bot secret included. Bash
|
|
191
341
|
// has been masking these since E1; hooks were the remaining door, so they use
|
|
192
342
|
// the same policy. Resolved at **user level** — the same choice E1 made for
|
|
193
343
|
// every spawn it could not scope to one session's project section
|
|
@@ -207,13 +357,10 @@ async function executeCommand(
|
|
|
207
357
|
// hand, and is exactly right for the one-shot CLI.
|
|
208
358
|
const cwd = ctx.cwd ?? process.cwd()
|
|
209
359
|
|
|
210
|
-
//
|
|
211
|
-
//
|
|
360
|
+
// Array args — no shell, so no command injection. The Claude-protocol stdin JSON
|
|
361
|
+
// goes in so scripts can read structured context.
|
|
212
362
|
const input = JSON.stringify(buildHookStdin(ctx, cwd))
|
|
213
|
-
const result =
|
|
214
|
-
timeout: (cfg.timeout ?? 60) * 1000,
|
|
215
|
-
encoding: 'utf-8',
|
|
216
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
363
|
+
const result = await runHookCommand(cfg.command, args, {
|
|
217
364
|
input,
|
|
218
365
|
// Both halves of "where is this hook": the directory it runs in, and the
|
|
219
366
|
// `cwd` it reads off stdin. Fixing only one leaves the hook told it is
|
|
@@ -222,6 +369,7 @@ async function executeCommand(
|
|
|
222
369
|
// `undefined` = inherit, which is what node does by default; passing it
|
|
223
370
|
// explicitly keeps the two branches visible at one site.
|
|
224
371
|
env,
|
|
372
|
+
timeoutMs: (cfg.timeout ?? 60) * 1000,
|
|
225
373
|
})
|
|
226
374
|
|
|
227
375
|
// Exit code 0 = success — parse the stdout JSON for structured decisions.
|
|
@@ -255,9 +403,10 @@ async function executeCommand(
|
|
|
255
403
|
additionalContext: `Hook warning ${failingLabel(cfg.command, source)}: ${stderr.trim()}`,
|
|
256
404
|
}
|
|
257
405
|
} catch (err) {
|
|
258
|
-
// Only reached when
|
|
259
|
-
// filter, or an option
|
|
260
|
-
//
|
|
406
|
+
// Only reached when the setup around the spawn throws — masking-policy load,
|
|
407
|
+
// env filter, or an option `spawn` rejects synchronously. A failed exec or a
|
|
408
|
+
// timeout is *not* a throw here: both are reported on the result (see
|
|
409
|
+
// `spawnFailureCause`), which is why this comment used to name them wrongly.
|
|
261
410
|
const message = (err as { message?: string }).message || String(err)
|
|
262
411
|
|
|
263
412
|
return {
|
|
@@ -68,18 +68,30 @@ export const PROMPT_VERSION = 'mipham-auto-classifier/1'
|
|
|
68
68
|
* refused for". A budget derived from the fail-open side would be a budget
|
|
69
69
|
* derived from the wrong question.
|
|
70
70
|
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
71
|
+
* 30s is measured, not picked: 24 realistic `ask`-worthy calls per pass, same
|
|
72
|
+
* machine and minute, each request's model read back off the wire rather than
|
|
73
|
+
* trusted from a label.
|
|
74
|
+
*
|
|
75
|
+
* active (reasoning) median 7.6s p90 35.6s max 120.0s over the old 2s: 23/24
|
|
76
|
+
* fast (flash) median 1.3s p90 3.7s max 16.5s over the old 2s: 9/24
|
|
77
|
+
*
|
|
78
|
+
* So the old bound was wrong for **both** models — and since a timeout here is
|
|
79
|
+
* indistinguishable from a denial, "too tight" does not mean slow: every ruled
|
|
80
|
+
* call pays the full wait and the gate then says no to work it should have
|
|
81
|
+
* allowed.
|
|
82
|
+
*
|
|
83
|
+
* The fast model is not the free win its 6× median suggests: over the 20
|
|
84
|
+
* borderline calls sampled against both, it allowed 8 the reasoning model
|
|
85
|
+
* blocked (2 the other way). Speed there is bought with leak, so the default
|
|
86
|
+
* stays the operator's own model (`resolveClassifierModel`), and the number
|
|
87
|
+
* above is the active model's p90 with room for the tail it measured —
|
|
88
|
+
* `permissions.classifierTimeoutMs` exists for a user who has decided otherwise.
|
|
89
|
+
*
|
|
90
|
+
* A longer budget is not the lever it looks like either: both models answer
|
|
91
|
+
* clear-cut calls stably and coin-flip on borderline ones, so what is left here
|
|
92
|
+
* is judgement quality, not patience. Re-measure before re-basing this.
|
|
81
93
|
*/
|
|
82
|
-
export const DEFAULT_CLASSIFIER_TIMEOUT_MS =
|
|
94
|
+
export const DEFAULT_CLASSIFIER_TIMEOUT_MS = 30_000
|
|
83
95
|
|
|
84
96
|
/**
|
|
85
97
|
* Per-value cap on serialized tool input. Truncation is a real boundary here,
|
|
@@ -452,7 +464,19 @@ export class LlmPermissionClassifier implements PermissionClassifier {
|
|
|
452
464
|
}
|
|
453
465
|
|
|
454
466
|
if (streamError) {
|
|
455
|
-
|
|
467
|
+
// The provider surfaces its abort as a *yielded* error chunk, not a throw
|
|
468
|
+
// (`providers/openai-compat.ts`), so a timeout we caused arrives here — and
|
|
469
|
+
// a naive read of `streamError` reports it as "Stream stalled", sending the
|
|
470
|
+
// reader hunting for a network problem. Our own budget expiring is the one
|
|
471
|
+
// cause we already know; name it. (`timedOut` is false for an external
|
|
472
|
+
// abort, so a user interrupt still reads as "unavailable", not "timed out".)
|
|
473
|
+
return {
|
|
474
|
+
allow: false,
|
|
475
|
+
reason: timedOut
|
|
476
|
+
? `classifier timed out after ${this.timeoutMs}ms`
|
|
477
|
+
: `classifier unavailable: ${streamError}`,
|
|
478
|
+
retryable: true,
|
|
479
|
+
}
|
|
456
480
|
}
|
|
457
481
|
|
|
458
482
|
const parsed = parseClassifierResponse(text)
|
package/src/core/permission.ts
CHANGED
|
@@ -9,6 +9,8 @@ import type { PermissionRuleEntry } from '../shared/index.ts'
|
|
|
9
9
|
import { matchBashRule, compileRule } from './permission-rules'
|
|
10
10
|
import { detectDangerousRm } from '../security/dangerous-rm'
|
|
11
11
|
import type { DangerousRm } from '../security/dangerous-rm'
|
|
12
|
+
import { detectWorldWritableChmod } from '../security/world-writable-chmod'
|
|
13
|
+
import type { WorldWritableChmod } from '../security/world-writable-chmod'
|
|
12
14
|
import {
|
|
13
15
|
loadPermissionConfig,
|
|
14
16
|
nextMode,
|
|
@@ -127,6 +129,7 @@ export type PermissionDenialReason =
|
|
|
127
129
|
| 'system-default' // no rule, no tool permission → fallback ask
|
|
128
130
|
| 'classifier-deny' // `auto` mode's classifier ruled against the call
|
|
129
131
|
| 'dangerous-rm' // recursive rm whose target is not a path in the command text
|
|
132
|
+
| 'world-writable-chmod' // recursive chmod granting world-write to an unbounded target
|
|
130
133
|
|
|
131
134
|
/**
|
|
132
135
|
* Which denial reasons `auto` mode's classifier is allowed to rule on — an
|
|
@@ -147,6 +150,11 @@ export type PermissionDenialReason =
|
|
|
147
150
|
* reason answers. Every other reason here is "the mode was not sure, let a second
|
|
148
151
|
* opinion decide"; this one is "the command does not say what it will delete", and
|
|
149
152
|
* a second opinion reading the same command is reading the same missing text.
|
|
153
|
+
*
|
|
154
|
+
* `world-writable-chmod` is absent for that same reason, and the measurement says
|
|
155
|
+
* so out loud: the gate was asked it anyway, and answered by coin flip (1/5 vs
|
|
156
|
+
* 4/5 across the two models, 2026-09-30). Both halves — is the grant world-write,
|
|
157
|
+
* is the target bounded — are in the text, so the ruling belongs to the text.
|
|
150
158
|
*/
|
|
151
159
|
const CLASSIFIABLE: ReadonlySet<PermissionDenialReason> = new Set<PermissionDenialReason>([
|
|
152
160
|
'mode-baseline',
|
|
@@ -532,6 +540,16 @@ export class PermissionSystem {
|
|
|
532
540
|
return 'ask'
|
|
533
541
|
}
|
|
534
542
|
|
|
543
|
+
// ── A recursive `chmod` granting world-write to an unbounded target ──
|
|
544
|
+
// Same placement and the same two reasons, so it is spelled once and read
|
|
545
|
+
// once: it sits ahead of the allow rules and every mode baseline (including
|
|
546
|
+
// `auto`, whose classifier was measured answering this one 1/5 versus 4/5),
|
|
547
|
+
// and it is also uncached because the escape hatch is read from the
|
|
548
|
+
// environment on each call.
|
|
549
|
+
if (this.worldWritableChmod(tool, input)) {
|
|
550
|
+
return 'ask'
|
|
551
|
+
}
|
|
552
|
+
|
|
535
553
|
// ── Cache lookup (P2): reuse decision for same tool+mode+input ──
|
|
536
554
|
const cacheKey = this.cacheKey(tool, input)
|
|
537
555
|
if (this.cacheMode === this.mode) {
|
|
@@ -635,6 +653,10 @@ export class PermissionSystem {
|
|
|
635
653
|
if (dangerous) {
|
|
636
654
|
return { reason: 'dangerous-rm', target: dangerous.target }
|
|
637
655
|
}
|
|
656
|
+
const worldWritable = this.worldWritableChmod(tool, input)
|
|
657
|
+
if (worldWritable) {
|
|
658
|
+
return { reason: 'world-writable-chmod', target: worldWritable.target }
|
|
659
|
+
}
|
|
638
660
|
if (this.legacyRules.has(tool.name)) {
|
|
639
661
|
return { reason: 'legacy-rule' }
|
|
640
662
|
}
|
|
@@ -678,6 +700,29 @@ export class PermissionSystem {
|
|
|
678
700
|
return detectDangerousRm(command)
|
|
679
701
|
}
|
|
680
702
|
|
|
703
|
+
/**
|
|
704
|
+
* A recursive `chmod` handing world-write to a target the command does not bound.
|
|
705
|
+
*
|
|
706
|
+
* Only the Bash tool, and the escape hatch is read from the **environment**
|
|
707
|
+
* rather than from tool parameters — both for the same reasons as `dangerousRm`
|
|
708
|
+
* above. A parameter the call can set is a guard the call can turn off, so the
|
|
709
|
+
* opt-out has to come from whoever started the process.
|
|
710
|
+
*
|
|
711
|
+
* The measured case for making this structural is in the module's own header:
|
|
712
|
+
* the gate was asked this question and answered it 1/5 versus 4/5 depending on
|
|
713
|
+
* which model happened to be active.
|
|
714
|
+
*/
|
|
715
|
+
private worldWritableChmod(
|
|
716
|
+
tool: ToolDefinition,
|
|
717
|
+
input: Record<string, unknown>,
|
|
718
|
+
): WorldWritableChmod | null {
|
|
719
|
+
if (tool.name !== 'Bash') return null
|
|
720
|
+
if (process.env.MIPHAM_DISABLE_CHMOD_PROMPT === '1') return null
|
|
721
|
+
const command = input.command
|
|
722
|
+
if (typeof command !== 'string') return null
|
|
723
|
+
return detectWorldWritableChmod(command)
|
|
724
|
+
}
|
|
725
|
+
|
|
681
726
|
/**
|
|
682
727
|
* Resolve a call to a decision, consulting `auto` mode's classifier when — and
|
|
683
728
|
* only when — the static chain answered `'ask'` for a reason a classifier is
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* on every tool call — making it auditable on a per-action basis.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
import type
|
|
24
|
+
import { pickFastestModel, type ProviderRegistry } from '../providers/registry'
|
|
25
25
|
import type { Llm } from '../providers/llm'
|
|
26
26
|
import { DEFAULT_CONSTITUTION } from './constitution-loader'
|
|
27
27
|
|
|
@@ -62,7 +62,7 @@ export const DEFAULT_SELF_CRITIQUE_CONFIG: SelfCritiqueConfig = {
|
|
|
62
62
|
threshold: 0.6,
|
|
63
63
|
targetTools: ['Bash', 'Write', 'Edit', 'Agent'],
|
|
64
64
|
// Measured, not chosen: 30 real critiques against the configured provider
|
|
65
|
-
// (`
|
|
65
|
+
// (`pickFastestModel` → `deepseek-v4-flash`; default model is the slower
|
|
66
66
|
// `-pro`) took min 1.85s / median 3.95s / max 17.9s, and **28 of 30 exceeded
|
|
67
67
|
// 2s** — the value this replaced. At 2s the budget would have skipped 93% of
|
|
68
68
|
// critiques, and since `critique()` fails *open* (null ⇒ the tool runs
|
|
@@ -175,7 +175,7 @@ export class SelfCritique {
|
|
|
175
175
|
)
|
|
176
176
|
|
|
177
177
|
try {
|
|
178
|
-
const critiqueModel = this.config.model ||
|
|
178
|
+
const critiqueModel = this.config.model || pickFastestModel(registry)
|
|
179
179
|
|
|
180
180
|
const controller = new AbortController()
|
|
181
181
|
const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs)
|
|
@@ -219,18 +219,6 @@ export class SelfCritique {
|
|
|
219
219
|
|
|
220
220
|
// ── Private ──
|
|
221
221
|
|
|
222
|
-
/** Find the fastest available model for low-latency critique. */
|
|
223
|
-
private findFastestModel(registry: ProviderRegistry): string {
|
|
224
|
-
// Prefer Flash models (Qwen2.5-1.5B or similar small models)
|
|
225
|
-
const models = registry.listModels?.() || []
|
|
226
|
-
const flashModel = models.find(
|
|
227
|
-
(m) => m.id.toLowerCase().includes('flash') || m.id.toLowerCase().includes('1.5b'),
|
|
228
|
-
)
|
|
229
|
-
if (flashModel) return flashModel.id
|
|
230
|
-
// Fall back to whatever's active
|
|
231
|
-
return registry.getActiveModel()
|
|
232
|
-
}
|
|
233
|
-
|
|
234
222
|
/** Extract JSON object from model response (may have markdown fences). */
|
|
235
223
|
private extractJson(text: string): Record<string, unknown> | null {
|
|
236
224
|
// Try direct parse
|
|
@@ -60,14 +60,26 @@ export interface TaskPerformanceResult {
|
|
|
60
60
|
description: string
|
|
61
61
|
passed: boolean
|
|
62
62
|
detail?: string
|
|
63
|
+
/**
|
|
64
|
+
* The generation hit the output cap, so the code is incomplete by construction and
|
|
65
|
+
* a failing test cannot distinguish "did not solve it" from "was cut off". Kept on
|
|
66
|
+
* the result and excluded from `score` — mixing the two biases the readout low.
|
|
67
|
+
*/
|
|
68
|
+
truncated?: boolean
|
|
63
69
|
}
|
|
64
70
|
|
|
65
71
|
export interface TaskPerformanceReport {
|
|
66
72
|
total: number
|
|
67
73
|
passed: number
|
|
74
|
+
/**
|
|
75
|
+
* Percent of **non-truncated** tasks that passed (100 when there are none). A
|
|
76
|
+
* truncated task is reported in `total`/`truncated` but never scored.
|
|
77
|
+
*/
|
|
68
78
|
score: number
|
|
69
79
|
results: TaskPerformanceResult[]
|
|
70
80
|
failures: string[]
|
|
81
|
+
/** Tasks whose generation was cut off at the output cap; counted, not scored. */
|
|
82
|
+
truncated: number
|
|
71
83
|
/** B2 代价维:整轮(LLM 生成 + 冻结测试判定)的墙钟耗时。只记录,不参与任何判定。 */
|
|
72
84
|
durationMs: number
|
|
73
85
|
}
|
|
@@ -82,8 +94,9 @@ async function collectGeneratedCode(
|
|
|
82
94
|
llm: Llm,
|
|
83
95
|
prompt: string,
|
|
84
96
|
systemPrompt?: string,
|
|
85
|
-
): Promise<string> {
|
|
97
|
+
): Promise<{ code: string; truncated: boolean }> {
|
|
86
98
|
let text = ''
|
|
99
|
+
let truncated = false
|
|
87
100
|
const req = {
|
|
88
101
|
model: '', // falsy → registry 回退到 active model
|
|
89
102
|
messages: [{ role: 'user' as const, content: prompt }],
|
|
@@ -92,8 +105,11 @@ async function collectGeneratedCode(
|
|
|
92
105
|
}
|
|
93
106
|
for await (const chunk of llm.chat(req)) {
|
|
94
107
|
if (chunk.type === 'text' && chunk.content) text += chunk.content
|
|
108
|
+
// Both providers already emit `truncated` on the stop chunk; reading it here is
|
|
109
|
+
// what turns the signal into something the score can act on.
|
|
110
|
+
if (chunk.truncated) truncated = true
|
|
95
111
|
}
|
|
96
|
-
return stripCodeFences(text)
|
|
112
|
+
return { code: stripCodeFences(text), truncated }
|
|
97
113
|
}
|
|
98
114
|
|
|
99
115
|
export async function runTaskPerformance(
|
|
@@ -105,13 +121,14 @@ export async function runTaskPerformance(
|
|
|
105
121
|
const results: TaskPerformanceResult[] = []
|
|
106
122
|
const startedAt = Date.now()
|
|
107
123
|
for (const task of tasks) {
|
|
108
|
-
const code = await collectGeneratedCode(llm, task.prompt, opts?.skill?.text)
|
|
124
|
+
const { code, truncated } = await collectGeneratedCode(llm, task.prompt, opts?.skill?.text)
|
|
109
125
|
if (!code) {
|
|
110
126
|
results.push({
|
|
111
127
|
id: task.id,
|
|
112
128
|
description: task.prompt,
|
|
113
129
|
passed: false,
|
|
114
130
|
detail: 'LLM 未生成代码',
|
|
131
|
+
...(truncated ? { truncated: true } : {}),
|
|
115
132
|
})
|
|
116
133
|
continue
|
|
117
134
|
}
|
|
@@ -121,15 +138,26 @@ export async function runTaskPerformance(
|
|
|
121
138
|
description: task.prompt,
|
|
122
139
|
passed: verdict.passed,
|
|
123
140
|
detail: verdict.detail,
|
|
141
|
+
...(truncated ? { truncated: true } : {}),
|
|
124
142
|
})
|
|
125
143
|
}
|
|
126
144
|
const passed = results.filter((r) => r.passed).length
|
|
145
|
+
// Score only what the model was actually given a chance to finish. A truncated
|
|
146
|
+
// generation is incomplete by construction; folding those failures into the mean
|
|
147
|
+
// makes the readout (and any improved/regressed verdict derived from it) depend on
|
|
148
|
+
// the output cap rather than on the work.
|
|
149
|
+
const scored = results.filter((r) => !r.truncated)
|
|
150
|
+
const truncated = results.length - scored.length
|
|
127
151
|
return {
|
|
128
152
|
total: results.length,
|
|
129
153
|
passed,
|
|
130
|
-
score:
|
|
154
|
+
score:
|
|
155
|
+
scored.length > 0
|
|
156
|
+
? Math.round((scored.filter((r) => r.passed).length / scored.length) * 100)
|
|
157
|
+
: 100,
|
|
131
158
|
results,
|
|
132
159
|
failures: results.filter((r) => !r.passed).map((r) => r.id),
|
|
160
|
+
truncated,
|
|
133
161
|
durationMs: Date.now() - startedAt,
|
|
134
162
|
}
|
|
135
163
|
}
|
|
@@ -938,6 +938,7 @@
|
|
|
938
938
|
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\") Treat this denial as covering the outcome, not only this exact command.",
|
|
939
939
|
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule, or allow it outright with: /permissions allow \"{name}\" Treat this denial as covering the outcome, not only this exact command.",
|
|
940
940
|
"tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
941
|
+
"tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
941
942
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
942
943
|
"tool_blocked": "Tool \"{name}\" blocked by hook",
|
|
943
944
|
"tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
|
|
@@ -938,6 +938,7 @@
|
|
|
938
938
|
"tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可) 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
939
939
|
"tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则,或直接放行:/permissions allow \"{name}\" 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
940
940
|
"tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
941
|
+
"tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
941
942
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
942
943
|
"tool_blocked": "工具 \"{name}\" 被钩子拦截",
|
|
943
944
|
"tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
|
package/src/index.tsx
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
discoverSessions,
|
|
22
22
|
} from './agent/cross-session/discovery'
|
|
23
23
|
import { bootstrapProviders } from './providers/bootstrap'
|
|
24
|
+
import { resolveClassifierModel } from './providers/registry'
|
|
24
25
|
import { InstructionsLoader, formatInstructionSizeNotice } from './core/instructions'
|
|
25
26
|
import { loadSessionMemories, getMemoryManager } from './core/memory/memory-loader'
|
|
26
27
|
import { ContextManager } from './core/context'
|
|
@@ -460,6 +461,15 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
460
461
|
` (an allow rule widens the gate — move the rules to ${settingsPathFor('user', process.cwd())})\n`,
|
|
461
462
|
)
|
|
462
463
|
}
|
|
464
|
+
// Same reason, one key group over: these two choose **how** the `auto` gate
|
|
465
|
+
// rules, and both directions of that choice widen it (a weaker judge, or enough
|
|
466
|
+
// time that a ruling no longer times out into a denial).
|
|
467
|
+
if (settingsJson.projectClassifierSkipped) {
|
|
468
|
+
process.stderr.write(
|
|
469
|
+
`⚠ Mipham Code: ignored permissions.classifierModel / classifierTimeoutMs from ${settingsPathFor('project', process.cwd())}\n` +
|
|
470
|
+
` (a repository must not choose how the approval gate rules — set them in ${settingsPathFor('user', process.cwd())})\n`,
|
|
471
|
+
)
|
|
472
|
+
}
|
|
463
473
|
// Apply org-level permission restrictions (P0: bypassPermissions policy gap)
|
|
464
474
|
if (config.permissionRestrictions) {
|
|
465
475
|
permission.setRestrictions(config.permissionRestrictions)
|
|
@@ -486,7 +496,11 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
486
496
|
// here would freeze it at whatever was active at startup, so a user who switches to
|
|
487
497
|
// a cheaper model would keep paying for the old one with nothing on screen to say so.
|
|
488
498
|
permission.setClassifier(
|
|
489
|
-
new LlmPermissionClassifier(registry, {
|
|
499
|
+
new LlmPermissionClassifier(registry, {
|
|
500
|
+
resolveModel: () =>
|
|
501
|
+
resolveClassifierModel(settingsJson.permissions.classifierModel, registry),
|
|
502
|
+
timeoutMs: settingsJson.permissions.classifierTimeoutMs,
|
|
503
|
+
}),
|
|
490
504
|
)
|
|
491
505
|
|
|
492
506
|
// Load instructions
|
|
@@ -5,7 +5,7 @@ import type { AgentRegistry } from '../agent/agent-registry'
|
|
|
5
5
|
import type { SkillsLoader } from '../skills/loader'
|
|
6
6
|
import type { HookEngine } from '../core/hooks'
|
|
7
7
|
import type { McpClient } from '../mcp/client'
|
|
8
|
-
import { registerMcpServerTools } from '../mcp/registry'
|
|
8
|
+
import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
|
|
9
9
|
import { executeHook } from '../core/hooks-executor'
|
|
10
10
|
import { detectPluginFormat, isLoadableMcpConfig } from './plugin-validator'
|
|
11
11
|
import { loadClaudePlugin } from './claude-plugin'
|
|
@@ -37,10 +37,12 @@ export function loadPlugins(
|
|
|
37
37
|
pluginManager.onRemove(plugin.name, () => {
|
|
38
38
|
for (const serverName of claudeMcpServers) {
|
|
39
39
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
40
|
+
mcpClient.disconnect(serverName)
|
|
41
|
+
// Register-time names go through `sanitizeName`; deleting by a raw
|
|
42
|
+
// `mcp__<serverName>__<toolName>` key silently missed every tool whose
|
|
43
|
+
// server name needed sanitizing, leaving orphans in the registry. The
|
|
44
|
+
// shared helper deletes by the same sanitized prefix registration used.
|
|
45
|
+
unregisterMcpServerTools(serverName, toolsMap)
|
|
44
46
|
} catch {
|
|
45
47
|
/* best effort */
|
|
46
48
|
}
|
|
@@ -163,10 +165,9 @@ export function loadPlugins(
|
|
|
163
165
|
// Disconnect MCP servers and unregister their tools
|
|
164
166
|
for (const serverName of mcpServers) {
|
|
165
167
|
try {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
168
|
+
mcpClient.disconnect(serverName)
|
|
169
|
+
// Same sanitized-prefix deletion as the Claude-format branch above.
|
|
170
|
+
unregisterMcpServerTools(serverName, toolsMap)
|
|
170
171
|
} catch {
|
|
171
172
|
/* best effort */
|
|
172
173
|
}
|
|
@@ -6,7 +6,7 @@ import type {
|
|
|
6
6
|
ContentBlock,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
9
|
-
import { fetchWithRetry, streamIdleTimeoutMs } from './fetch-utils'
|
|
9
|
+
import { fetchWithRetry, streamIdleTimeoutMs, isRetryableFailure } from './fetch-utils'
|
|
10
10
|
|
|
11
11
|
interface AnthropicContentBlock {
|
|
12
12
|
type: string
|
|
@@ -139,7 +139,11 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
139
139
|
|
|
140
140
|
if (!response.ok) {
|
|
141
141
|
const errText = await response.text()
|
|
142
|
-
yield {
|
|
142
|
+
yield {
|
|
143
|
+
type: 'error',
|
|
144
|
+
error: `Anthropic API error ${response.status}: ${errText}`,
|
|
145
|
+
retryable: isRetryableFailure(response.status),
|
|
146
|
+
}
|
|
143
147
|
return
|
|
144
148
|
}
|
|
145
149
|
|
|
@@ -304,7 +308,11 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
304
308
|
}
|
|
305
309
|
|
|
306
310
|
case 'error': {
|
|
307
|
-
yield {
|
|
311
|
+
yield {
|
|
312
|
+
type: 'error',
|
|
313
|
+
error: event.error?.message || 'Unknown Anthropic error',
|
|
314
|
+
retryable: isRetryableFailure(undefined, event.error?.type),
|
|
315
|
+
}
|
|
308
316
|
return
|
|
309
317
|
}
|
|
310
318
|
}
|