@miphamai/cli 0.85.11 → 0.85.12
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 +23 -3
- 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 +20 -2
- package/src/core/hooks-executor.ts +165 -16
- package/src/core/task-performance.ts +32 -4
- 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/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 {
|
|
@@ -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
|
}
|
|
@@ -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
|
}
|
|
@@ -77,6 +77,35 @@ function isRetryableError(err: unknown): boolean {
|
|
|
77
77
|
return true
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Provider error types that are decided, not transient. A content filter or a
|
|
82
|
+
* malformed request answers the same way on every attempt, so re-sending it only
|
|
83
|
+
* makes the user wait for an error that was final the first time.
|
|
84
|
+
*/
|
|
85
|
+
const NON_RETRYABLE_ERROR_TYPES = new Set([
|
|
86
|
+
'invalid_request_error',
|
|
87
|
+
'authentication_error',
|
|
88
|
+
'permission_error',
|
|
89
|
+
'not_found_error',
|
|
90
|
+
'request_too_large',
|
|
91
|
+
'content_filter',
|
|
92
|
+
'content_policy_violation',
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Should the engine re-send a turn the provider reported as failed?
|
|
97
|
+
*
|
|
98
|
+
* Two call shapes: an HTTP status, or a provider error object's `type`/`code`.
|
|
99
|
+
* Statuses follow the same rule as `fetchWithRetry` (429 and 5xx are transient).
|
|
100
|
+
* For an error type, only the *known* deterministic ones say no — an unrecognised
|
|
101
|
+
* type stays retryable, because guessing "final" would lose a recoverable turn.
|
|
102
|
+
*/
|
|
103
|
+
export function isRetryableFailure(status: number | undefined, errorType?: string): boolean {
|
|
104
|
+
if (status !== undefined) return RETRYABLE_STATUSES.has(status) || status >= 500
|
|
105
|
+
if (errorType === undefined) return true
|
|
106
|
+
return !NON_RETRYABLE_ERROR_TYPES.has(errorType)
|
|
107
|
+
}
|
|
108
|
+
|
|
80
109
|
/**
|
|
81
110
|
* Fetch with optional timeout and retry with exponential backoff.
|
|
82
111
|
*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execSync } from 'node:child_process'
|
|
2
2
|
import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
|
|
3
3
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
4
|
-
import { fetchWithRetry, streamIdleTimeoutMs } from './fetch-utils'
|
|
4
|
+
import { fetchWithRetry, streamIdleTimeoutMs, isRetryableFailure } from './fetch-utils'
|
|
5
5
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
6
6
|
|
|
7
7
|
export class OpenAICompatProvider implements ProviderInstance {
|
|
@@ -46,7 +46,11 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
46
46
|
|
|
47
47
|
if (!response.ok) {
|
|
48
48
|
const errText = await response.text()
|
|
49
|
-
yield {
|
|
49
|
+
yield {
|
|
50
|
+
type: 'error',
|
|
51
|
+
error: `OpenAI API error ${response.status}: ${errText}`,
|
|
52
|
+
retryable: isRetryableFailure(response.status),
|
|
53
|
+
}
|
|
50
54
|
return
|
|
51
55
|
}
|
|
52
56
|
|
|
@@ -141,6 +145,24 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
141
145
|
}
|
|
142
146
|
}
|
|
143
147
|
|
|
148
|
+
// A mid-stream error arrives as `data: {"error": {...}}` — no `choices`.
|
|
149
|
+
// Previously it fell through `if (!choice) continue`, the loop ran to its
|
|
150
|
+
// end, and the trailing `yield { type: 'stop' }` below made the turn look
|
|
151
|
+
// like a clean finish: no error surfaced, so the engine neither retried
|
|
152
|
+
// nor fell back and the user got a silently empty answer. Surface it as
|
|
153
|
+
// an error chunk instead, which is also what feeds the "name the model and
|
|
154
|
+
// offer a way out" path.
|
|
155
|
+
if (parsed.error) {
|
|
156
|
+
const e = parsed.error as { message?: string; code?: string; type?: string }
|
|
157
|
+
const detail = e.message ?? JSON.stringify(parsed.error)
|
|
158
|
+
yield {
|
|
159
|
+
type: 'error',
|
|
160
|
+
error: `${this.config.id}: ${detail}`,
|
|
161
|
+
retryable: isRetryableFailure(undefined, e.type ?? e.code),
|
|
162
|
+
}
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
|
|
144
166
|
if (!choice) continue
|
|
145
167
|
|
|
146
168
|
const delta = choice.delta
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export const PACKAGE_NAME = '@miphamai/cli' as const
|
|
10
10
|
|
|
11
11
|
/** 当前发布版本 */
|
|
12
|
-
export const PACKAGE_VERSION = '0.85.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.12' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 3839 as const
|
package/src/shared/sanitize.ts
CHANGED
|
@@ -213,6 +213,39 @@ export function stripControlCharsForCheck(input: string): string {
|
|
|
213
213
|
return result
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
+
/**
|
|
217
|
+
* Decode ` ` in assistant text for terminal display.
|
|
218
|
+
*
|
|
219
|
+
* The terminal has no markdown/entity layer, so a reply that uses ` ` to indent
|
|
220
|
+
* — row labels in a table, most often — shows the literal characters. Only this one
|
|
221
|
+
* entity is decoded, deliberately: `<`/`&`/`>` appear in code the assistant
|
|
222
|
+
* is *showing*, where decoding would corrupt the sample, whereas a literal ` `
|
|
223
|
+
* meant to be read as text is rare enough to accept. This is a narrow fix for the
|
|
224
|
+
* common case, not a general entity decoder.
|
|
225
|
+
*/
|
|
226
|
+
export function decodeDisplayEntities(input: string): string {
|
|
227
|
+
if (!input.includes('&')) return input
|
|
228
|
+
return input.replace(/ /gi, ' ')
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Make an untrusted **single-line** value safe to interpolate into terminal output.
|
|
233
|
+
*
|
|
234
|
+
* Config-sourced strings (an MCP server's name, URL, or command line) are rendered
|
|
235
|
+
* straight into the transcript. `stripDangerousUnicode` covers the invisible
|
|
236
|
+
* characters but **not** C0 controls, and ESC (U+001B) is one of those — a name
|
|
237
|
+
* carrying `\x1b[2J` is read by the terminal as a clear-screen sequence, not shown
|
|
238
|
+
* as text. DEL (U+007F) goes too.
|
|
239
|
+
*
|
|
240
|
+
* Newlines are stripped as well, unlike `stripControlCharsForCheck` (which keeps
|
|
241
|
+
* `\n` for multi-line shell commands): these values sit on one output line, so an
|
|
242
|
+
* embedded newline forges an extra row in the listing.
|
|
243
|
+
*/
|
|
244
|
+
export function sanitizeInlineField(input: string): string {
|
|
245
|
+
if (!input) return input
|
|
246
|
+
return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f]/g, '')
|
|
247
|
+
}
|
|
248
|
+
|
|
216
249
|
/**
|
|
217
250
|
* Full command sanitization pipeline for permission checks.
|
|
218
251
|
* Applies in order:
|
package/src/shared/types.ts
CHANGED
|
@@ -135,6 +135,14 @@ export interface StreamChunk {
|
|
|
135
135
|
*/
|
|
136
136
|
isError?: boolean
|
|
137
137
|
error?: string
|
|
138
|
+
/**
|
|
139
|
+
* `type: 'error'` only. `false` means the provider knows the failure is
|
|
140
|
+
* deterministic (a content filter, a malformed request, a bad key) and re-sending
|
|
141
|
+
* it will produce the same answer. The engine then skips both its in-place retry
|
|
142
|
+
* and the fallback provider, so a final error is shown once instead of three
|
|
143
|
+
* times. Absent means "unknown" and preserves the retry.
|
|
144
|
+
*/
|
|
145
|
+
retryable?: boolean
|
|
138
146
|
/** DeepSeek reasoning tokens accumulated during this stream. */
|
|
139
147
|
reasoning_content?: string
|
|
140
148
|
/** Anthropic thinking block content (DeepSeek Anthropic endpoint). */
|
|
@@ -565,6 +573,28 @@ export interface ToolContext {
|
|
|
565
573
|
llm?: import('../providers/llm').Llm
|
|
566
574
|
/** Files read this session — used by Write tool to check read-before-write */
|
|
567
575
|
readFiles?: Set<string>
|
|
576
|
+
/**
|
|
577
|
+
* Cancellation for the turn this tool call belongs to.
|
|
578
|
+
*
|
|
579
|
+
* Carried on the context, not on `execute`'s signature, so every tool can reach it
|
|
580
|
+
* without changing the `ToolDefinition.execute` contract. Before this field existed
|
|
581
|
+
* the signal stopped at `permission.resolveApproval` and the LLM stream: a long
|
|
582
|
+
* Bash command could not be cancelled at all, because nothing it received ever
|
|
583
|
+
* changed. Absent means "no cancellation in effect" — tools must treat that as
|
|
584
|
+
* "run to completion", not as "abort".
|
|
585
|
+
*/
|
|
586
|
+
signal?: AbortSignal
|
|
587
|
+
/**
|
|
588
|
+
* True when this tool call is being executed *by a sub-agent*, not by the main
|
|
589
|
+
* loop.
|
|
590
|
+
*
|
|
591
|
+
* Set by `SubAgent.runExecution` on the context it hands its own tools, so a
|
|
592
|
+
* tool whose behaviour must differ one level down can see where it is instead of
|
|
593
|
+
* inferring it (`sessionId` is `'sub-agent'` there, but that is a display string,
|
|
594
|
+
* not a contract). The only reader today is the Agent tool: a nested call cannot
|
|
595
|
+
* consume a background handle, so its default flips to synchronous.
|
|
596
|
+
*/
|
|
597
|
+
isSubAgent?: boolean
|
|
568
598
|
}
|
|
569
599
|
|
|
570
600
|
export interface ToolDefinition {
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -7,14 +7,28 @@ const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review'
|
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Resolve whether a sub-agent should run in the background.
|
|
10
|
-
*
|
|
11
|
-
* `
|
|
10
|
+
*
|
|
11
|
+
* Precedence: explicit `run_in_background` param > nested-call rule > agent
|
|
12
|
+
* frontmatter `background` field > default (background, Claude Code 2.1.232 parity).
|
|
13
|
+
*
|
|
14
|
+
* `nested` is true when the caller is itself a sub-agent. `[background-task:<id>]`
|
|
15
|
+
* is a *handle*, not an answer: the child's result goes to the background registry
|
|
16
|
+
* and the hook/experience logs, and nothing ever hands it back to the agent that
|
|
17
|
+
* asked. So one level down, the ordinary fan-out shape — "ask a child, then use its
|
|
18
|
+
* answer" — cannot work at all: the caller sees a placeholder where its input
|
|
19
|
+
* should be. A *default* of background turns that from an option into a hole, which
|
|
20
|
+
* is why the default flips here. An explicit `run_in_background: true` is still
|
|
21
|
+
* honoured, in both directions: that is a request, not a default chosen on the
|
|
22
|
+
* caller's behalf.
|
|
12
23
|
*/
|
|
13
24
|
export function resolveRunInBackground(
|
|
14
25
|
runInBackground: boolean | undefined,
|
|
15
26
|
agentDef?: { background?: boolean },
|
|
27
|
+
nested = false,
|
|
16
28
|
): boolean {
|
|
17
|
-
|
|
29
|
+
if (runInBackground !== undefined) return runInBackground
|
|
30
|
+
if (nested) return false
|
|
31
|
+
return agentDef?.background ?? true
|
|
18
32
|
}
|
|
19
33
|
|
|
20
34
|
export const agentTool: ToolDefinition = {
|
|
@@ -73,6 +87,7 @@ export const agentTool: ToolDefinition = {
|
|
|
73
87
|
const runInBackground = resolveRunInBackground(
|
|
74
88
|
params.run_in_background as boolean | undefined,
|
|
75
89
|
agentDef,
|
|
90
|
+
ctx.isSubAgent === true,
|
|
76
91
|
)
|
|
77
92
|
|
|
78
93
|
try {
|