@miphamai/cli 0.85.28 → 0.85.29
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 +8 -8
- package/src/agent/sub-agent.ts +1 -0
- package/src/core/engine.ts +48 -11
- package/src/core/hooks-executor.ts +20 -2
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/providers/anthropic.ts +2 -1
- package/src/providers/fetch-utils.ts +31 -0
- package/src/providers/openai-compat.ts +2 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +8 -0
- package/src/tools/exec/bash.ts +39 -0
- package/src/tools/file/grep.ts +45 -11
- package/src/tools/file/read.ts +35 -7
- package/src/tools/file/write.ts +22 -1
- package/src/tools/network/web-fetch.ts +36 -1
- package/src/ui/commands.ts +4 -2
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.29
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@miphamai/cli",
|
|
3
|
-
"version": "0.85.
|
|
3
|
+
"version": "0.85.29",
|
|
4
4
|
"description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -44,23 +44,23 @@
|
|
|
44
44
|
"mutate": "stryker run"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@larksuiteoapi/node-sdk": "^1.
|
|
47
|
+
"@larksuiteoapi/node-sdk": "^1.76.0",
|
|
48
48
|
"commander": "^13.1.0",
|
|
49
49
|
"ink": "^7.1.1",
|
|
50
50
|
"ink-text-input": "^6.0.0",
|
|
51
|
-
"react": "^19.3.
|
|
51
|
+
"react": "^19.3.1",
|
|
52
52
|
"react-devtools-core": "^8.0.0",
|
|
53
53
|
"yaml": "^2.9.1"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@mipham/shared": "workspace:*",
|
|
57
|
-
"@stryker-mutator/core": "10.
|
|
57
|
+
"@stryker-mutator/core": "10.1.1",
|
|
58
58
|
"@stryker-mutator/vitest-runner": "10.0.0",
|
|
59
|
-
"@types/bun": "^1.4.
|
|
60
|
-
"@types/node": "^22.20.
|
|
59
|
+
"@types/bun": "^1.4.4",
|
|
60
|
+
"@types/node": "^22.20.5",
|
|
61
61
|
"@types/react": "^19.3.0",
|
|
62
|
-
"@vitest/coverage-v8": "^5.0.
|
|
62
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
63
63
|
"ink-testing-library": "^4.0.0",
|
|
64
|
-
"vitest": "^5.0.
|
|
64
|
+
"vitest": "^5.0.5"
|
|
65
65
|
}
|
|
66
66
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -484,6 +484,7 @@ export class SubAgent {
|
|
|
484
484
|
ruleEngine: this.ruleEngine,
|
|
485
485
|
llm: this.llm,
|
|
486
486
|
readFiles: new Set<string>(),
|
|
487
|
+
readFilesComplete: new Set<string>(),
|
|
487
488
|
// Every tool call from here on is one level down, and a few tools must know
|
|
488
489
|
// it: `Agent` cannot consume a background handle, so its default flips to
|
|
489
490
|
// synchronous (see `resolveRunInBackground`). Set on the shared literal so it
|
package/src/core/engine.ts
CHANGED
|
@@ -92,6 +92,17 @@ const MAX_TOOL_TURNS = 100
|
|
|
92
92
|
*/
|
|
93
93
|
const TURN_TIMEOUT_MS = 15 * 60 * 1000
|
|
94
94
|
|
|
95
|
+
/**
|
|
96
|
+
* How much of a hook's `additionalContext` may be injected into the prompt.
|
|
97
|
+
*
|
|
98
|
+
* A hook is a shell script this CLI did not write; it can print a whole file or
|
|
99
|
+
* an unbounded grep result. Compaction is the one moment the prompt is supposed
|
|
100
|
+
* to get *smaller* — letting a hook paste megabytes back in defeats it and can
|
|
101
|
+
* push the very next request past the model's window. Truncation is visible in
|
|
102
|
+
* the injected text so the model (and the user) can tell it happened.
|
|
103
|
+
*/
|
|
104
|
+
const MAX_HOOK_CONTEXT_CHARS = 10_000
|
|
105
|
+
|
|
95
106
|
/** The turn's stall clock: when it last moved, and whether it ran out. */
|
|
96
107
|
interface TurnBudget {
|
|
97
108
|
last: number
|
|
@@ -132,6 +143,8 @@ export class QueryEngine {
|
|
|
132
143
|
private _selfCritique?: SelfCritique
|
|
133
144
|
/** Files read this session — tracks what the Read tool has loaded */
|
|
134
145
|
private readFiles = new Set<string>()
|
|
146
|
+
/** Subset of `readFiles` whose reads covered the whole file (no window) */
|
|
147
|
+
private readFilesComplete = new Set<string>()
|
|
135
148
|
private goal?: string
|
|
136
149
|
private maxGoalLoops = 20
|
|
137
150
|
private lastAssistantContent?: string
|
|
@@ -256,6 +269,7 @@ export class QueryEngine {
|
|
|
256
269
|
*/
|
|
257
270
|
resetFileTracking(): void {
|
|
258
271
|
this.readFiles.clear()
|
|
272
|
+
this.readFilesComplete.clear()
|
|
259
273
|
}
|
|
260
274
|
|
|
261
275
|
/** Set the session identifier (called from index.tsx at startup with the actual session name). */
|
|
@@ -1635,6 +1649,7 @@ export class QueryEngine {
|
|
|
1635
1649
|
ruleEngine: this.ruleEngine,
|
|
1636
1650
|
llm: this.llm,
|
|
1637
1651
|
readFiles: this.readFiles,
|
|
1652
|
+
readFilesComplete: this.readFilesComplete,
|
|
1638
1653
|
})
|
|
1639
1654
|
|
|
1640
1655
|
// Track touched files for rules matching
|
|
@@ -2222,18 +2237,30 @@ export class QueryEngine {
|
|
|
2222
2237
|
}
|
|
2223
2238
|
}
|
|
2224
2239
|
|
|
2225
|
-
|
|
2240
|
+
/**
|
|
2241
|
+
* Switch the active provider/model.
|
|
2242
|
+
*
|
|
2243
|
+
* Returns a warning when the model id is not in the registry: the context
|
|
2244
|
+
* window cannot be resized, so compaction keeps the *previous* model's limit.
|
|
2245
|
+
* Saying "✓ Switched" and nothing else made that silent — the user reads
|
|
2246
|
+
* success, then the next request is refused by a model whose window is
|
|
2247
|
+
* smaller than the size we are still willing to send.
|
|
2248
|
+
*/
|
|
2249
|
+
switchProvider(providerId: string, modelId?: string): string | undefined {
|
|
2226
2250
|
this.registry.switchProvider(providerId, modelId)
|
|
2227
2251
|
// Update context manager's max tokens to match the new model's context window
|
|
2228
|
-
if (modelId)
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
}
|
|
2252
|
+
if (!modelId) return undefined
|
|
2253
|
+
const model = this.registry.findModel(modelId)
|
|
2254
|
+
if (!model) {
|
|
2255
|
+
return t('errors.model_window_unknown', {
|
|
2256
|
+
model: modelId,
|
|
2257
|
+
window: this.context.getMaxTokens().toLocaleString('en-US'),
|
|
2258
|
+
})
|
|
2236
2259
|
}
|
|
2260
|
+
const DISABLE_1M = process.env.MIPHAM_DISABLE_1M_CONTEXT === '1'
|
|
2261
|
+
const maxTokens = DISABLE_1M && model.contextWindow > 200_000 ? 200_000 : model.contextWindow
|
|
2262
|
+
this.context.updateMaxTokens(maxTokens, model.contextWindow)
|
|
2263
|
+
return undefined
|
|
2237
2264
|
}
|
|
2238
2265
|
|
|
2239
2266
|
/**
|
|
@@ -2255,6 +2282,16 @@ export class QueryEngine {
|
|
|
2255
2282
|
return n >= 1_000_000 ? `${Math.round(n / 100_000) / 10}M` : `${Math.round(n / 1000)}K`
|
|
2256
2283
|
}
|
|
2257
2284
|
|
|
2285
|
+
/** Bound a hook's `additionalContext` — see `MAX_HOOK_CONTEXT_CHARS`. */
|
|
2286
|
+
private capHookContext(text: string): string {
|
|
2287
|
+
if (text.length <= MAX_HOOK_CONTEXT_CHARS) return text
|
|
2288
|
+
return (
|
|
2289
|
+
`${text.slice(0, MAX_HOOK_CONTEXT_CHARS)}\n` +
|
|
2290
|
+
`[…truncated: hook additionalContext was ${text.length.toLocaleString('en-US')} characters, ` +
|
|
2291
|
+
`only the first ${MAX_HOOK_CONTEXT_CHARS.toLocaleString('en-US')} were kept]`
|
|
2292
|
+
)
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2258
2295
|
/** Wrap context compaction with PreCompact/PostCompact hooks. */
|
|
2259
2296
|
private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
|
|
2260
2297
|
if (this.hookEngine) {
|
|
@@ -2262,7 +2299,7 @@ export class QueryEngine {
|
|
|
2262
2299
|
if (preResult.additionalContext) {
|
|
2263
2300
|
this.context.injectContext(
|
|
2264
2301
|
'pre-compact',
|
|
2265
|
-
`[Pre-compact context]: ${preResult.additionalContext}`,
|
|
2302
|
+
`[Pre-compact context]: ${this.capHookContext(preResult.additionalContext)}`,
|
|
2266
2303
|
)
|
|
2267
2304
|
}
|
|
2268
2305
|
}
|
|
@@ -2280,7 +2317,7 @@ export class QueryEngine {
|
|
|
2280
2317
|
if (postResult.additionalContext) {
|
|
2281
2318
|
this.context.injectContext(
|
|
2282
2319
|
'post-compact',
|
|
2283
|
-
`[Post-compact context]: ${postResult.additionalContext}`,
|
|
2320
|
+
`[Post-compact context]: ${this.capHookContext(postResult.additionalContext)}`,
|
|
2284
2321
|
)
|
|
2285
2322
|
}
|
|
2286
2323
|
}
|
|
@@ -218,6 +218,24 @@ function failingLabel(command: string | undefined, source?: string): string {
|
|
|
218
218
|
/** Grace given to a descendant still holding a stdio pipe after the hook itself exited. */
|
|
219
219
|
const HOOK_PIPE_GRACE_MS = 1_000
|
|
220
220
|
|
|
221
|
+
/**
|
|
222
|
+
* Shortest timeout a hook may be given, in seconds.
|
|
223
|
+
*
|
|
224
|
+
* `"timeout": 0` is a plausible thing to write meaning "no limit" or "as long as
|
|
225
|
+
* it needs", but it arms the kill timer with a zero delay: the hook is torn down
|
|
226
|
+
* before the shell has even exec'd its command, and the operator is told
|
|
227
|
+
* `timed out after 0s` — a hook that never ran, reported as a slow one. One
|
|
228
|
+
* second is the smallest value that can still let a real command finish.
|
|
229
|
+
*/
|
|
230
|
+
const MIN_HOOK_TIMEOUT_SECONDS = 1
|
|
231
|
+
|
|
232
|
+
/** Effective timeout in seconds — configured value floored, defaulting to 60. */
|
|
233
|
+
function hookTimeoutSeconds(cfg: HookConfig): number {
|
|
234
|
+
const configured = cfg.timeout
|
|
235
|
+
if (typeof configured !== 'number' || !Number.isFinite(configured)) return 60
|
|
236
|
+
return Math.max(MIN_HOOK_TIMEOUT_SECONDS, configured)
|
|
237
|
+
}
|
|
238
|
+
|
|
221
239
|
/** The `spawnSync`-shaped outcome `spawnFailureCause` and the caller already read. */
|
|
222
240
|
interface HookProcessResult {
|
|
223
241
|
status: number | null
|
|
@@ -417,7 +435,7 @@ async function executeCommand(
|
|
|
417
435
|
// `undefined` = inherit, which is what node does by default; passing it
|
|
418
436
|
// explicitly keeps the two branches visible at one site.
|
|
419
437
|
env,
|
|
420
|
-
timeoutMs: (cfg
|
|
438
|
+
timeoutMs: hookTimeoutSeconds(cfg) * 1000,
|
|
421
439
|
})
|
|
422
440
|
|
|
423
441
|
// Exit code 0 = success — parse the stdout JSON for structured decisions.
|
|
@@ -437,7 +455,7 @@ async function executeCommand(
|
|
|
437
455
|
}
|
|
438
456
|
}
|
|
439
457
|
|
|
440
|
-
const failure = spawnFailureCause(result, cfg
|
|
458
|
+
const failure = spawnFailureCause(result, hookTimeoutSeconds(cfg))
|
|
441
459
|
if (failure) {
|
|
442
460
|
return failureResult(
|
|
443
461
|
cfg,
|
|
@@ -957,6 +957,7 @@
|
|
|
957
957
|
"model_error": "Error: {error}",
|
|
958
958
|
"model_unavailable": "Model \"{model}\" (provider {provider}) is unavailable, and no default fallback model is configured — this turn produced no model output. Switch models with Ctrl+P, or check that provider's key and network, then retry. Underlying error: {error}",
|
|
959
959
|
"tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
|
|
960
|
+
"model_window_unknown": "⚠ Model \"{model}\" is not in the registry, so the context window could not be resized — compaction keeps using {window} tokens (the previous model's limit). If the new model is smaller, requests will start failing before compaction runs; switch to a known model or add this one to your provider config.",
|
|
960
961
|
"missing_param": "Missing required parameter: \"{param}\"",
|
|
961
962
|
"invalid_params": "Invalid parameters: {errors}",
|
|
962
963
|
"unparseable_args": "The arguments for this tool call were not valid JSON ({detail}). Nothing was executed. Re-issue the call with complete JSON — do not infer the parameters from the fragment.",
|
|
@@ -957,6 +957,7 @@
|
|
|
957
957
|
"model_error": "错误:{error}",
|
|
958
958
|
"model_unavailable": "模型 \"{model}\"(提供商 {provider})当前不可用,且没有可回退的默认模型 —— 本轮没有拿到任何模型输出。用 Ctrl+P 换一个模型,或检查该提供商的密钥与网络后重试。底层错误:{error}",
|
|
959
959
|
"tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
|
|
960
|
+
"model_window_unknown": "⚠ 模型 \"{model}\" 不在注册表中,上下文窗口无法重设 —— 压缩仍按 {window} tokens(上一个模型的限额)判断。新模型若更小,请求会在压缩触发前就开始失败;请切到已知模型,或把该模型加进提供商配置。",
|
|
960
961
|
"missing_param": "缺少必需参数:\"{param}\"",
|
|
961
962
|
"invalid_params": "参数无效:{errors}",
|
|
962
963
|
"unparseable_args": "这次工具调用的参数不是合法 JSON({detail}),没有执行任何操作。请带着完整的 JSON 重新发起调用 —— 不要从这段残片里猜参数。",
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
streamIdleTimeoutMs,
|
|
12
12
|
isRetryableFailure,
|
|
13
13
|
createAwakeTimer,
|
|
14
|
+
readErrorBody,
|
|
14
15
|
} from './fetch-utils'
|
|
15
16
|
|
|
16
17
|
interface AnthropicContentBlock {
|
|
@@ -195,7 +196,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
195
196
|
})
|
|
196
197
|
|
|
197
198
|
if (!response.ok) {
|
|
198
|
-
const errText = await response
|
|
199
|
+
const errText = await readErrorBody(response)
|
|
199
200
|
yield {
|
|
200
201
|
type: 'error',
|
|
201
202
|
error: `Anthropic API error ${response.status}: ${errText}`,
|
|
@@ -259,6 +259,37 @@ function sleep(ms: number): Promise<void> {
|
|
|
259
259
|
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
+
/**
|
|
263
|
+
* Read a provider's error body, bounded in **both** size and time.
|
|
264
|
+
*
|
|
265
|
+
* `await response.text()` on an error path has neither. A gateway that accepts
|
|
266
|
+
* the connection and then streams forever (or a CDN's HTML error page for a
|
|
267
|
+
* multi-MB trace) parks the turn *before* the status code is ever shown — the
|
|
268
|
+
* one thing the caller needed. The body only exists to explain the status, so a
|
|
269
|
+
* truncated prefix is enough; past the deadline an empty string still leaves the
|
|
270
|
+
* status line to report.
|
|
271
|
+
*/
|
|
272
|
+
export async function readErrorBody(
|
|
273
|
+
response: Response,
|
|
274
|
+
maxChars = 2_000,
|
|
275
|
+
timeoutMs = 5_000,
|
|
276
|
+
): Promise<string> {
|
|
277
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
278
|
+
try {
|
|
279
|
+
// `.catch` first so a body that fails *after* the race is lost does not
|
|
280
|
+
// surface as an unhandled rejection.
|
|
281
|
+
const text = await Promise.race([
|
|
282
|
+
response.text().catch(() => ''),
|
|
283
|
+
new Promise<string>((resolve) => {
|
|
284
|
+
timer = setTimeout(() => resolve(''), timeoutMs)
|
|
285
|
+
}),
|
|
286
|
+
])
|
|
287
|
+
return text.length > maxChars ? `${text.slice(0, maxChars)}… (truncated)` : text
|
|
288
|
+
} finally {
|
|
289
|
+
clearTimeout(timer)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
262
293
|
// ── Streaming idle-timeout (stall guard) with effort multiplier ──────────
|
|
263
294
|
//
|
|
264
295
|
// Reasoning models think silently for long stretches. The idle timeout between
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
streamIdleTimeoutMs,
|
|
7
7
|
isRetryableFailure,
|
|
8
8
|
createAwakeTimer,
|
|
9
|
+
readErrorBody,
|
|
9
10
|
} from './fetch-utils'
|
|
10
11
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
11
12
|
|
|
@@ -55,7 +56,7 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
55
56
|
})
|
|
56
57
|
|
|
57
58
|
if (!response.ok) {
|
|
58
|
-
const errText = await response
|
|
59
|
+
const errText = await readErrorBody(response)
|
|
59
60
|
yield {
|
|
60
61
|
type: 'error',
|
|
61
62
|
error: `OpenAI API error ${response.status}: ${errText}`,
|
|
@@ -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.29' 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 = 4612 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -639,6 +639,14 @@ export interface ToolContext {
|
|
|
639
639
|
llm?: import('../providers/llm').Llm
|
|
640
640
|
/** Files read this session — used by Write tool to check read-before-write */
|
|
641
641
|
readFiles?: Set<string>
|
|
642
|
+
/**
|
|
643
|
+
* The subset of `readFiles` whose reads covered the **whole file** (no
|
|
644
|
+
* offset/limit, and not a credential-masked view). Write requires membership
|
|
645
|
+
* to overwrite an existing file: a partial read is context for Edit, not a
|
|
646
|
+
* licence to replace the file with the slice the model happened to see.
|
|
647
|
+
* Absent means "no completeness tracking" and is treated as not complete.
|
|
648
|
+
*/
|
|
649
|
+
readFilesComplete?: Set<string>
|
|
642
650
|
/**
|
|
643
651
|
* Cancellation for the turn this tool call belongs to.
|
|
644
652
|
*
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -631,6 +631,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
631
631
|
// the wrong group and fails (or, worse, hits the parent's).
|
|
632
632
|
detached: true,
|
|
633
633
|
})
|
|
634
|
+
// Tracked until it exits: `detached` also means the group is not taken
|
|
635
|
+
// down when this process goes away (see `liveProcessGroups`).
|
|
636
|
+
trackProcessGroup(proc.pid)
|
|
634
637
|
|
|
635
638
|
// Start reading at once — a child that fills the pipe buffer blocks on
|
|
636
639
|
// write and would then never exit — but do **not** await here: if a
|
|
@@ -663,6 +666,7 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
663
666
|
}
|
|
664
667
|
|
|
665
668
|
const exitCode = await proc.exited
|
|
669
|
+
liveProcessGroups.delete(proc.pid)
|
|
666
670
|
clearTimeout(timer)
|
|
667
671
|
ctx.signal?.removeEventListener('abort', onAbort)
|
|
668
672
|
|
|
@@ -766,6 +770,41 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
766
770
|
/** Grace given to a descendant still holding the output pipe after the shell itself has exited. */
|
|
767
771
|
const PIPE_GRACE_MS = 1_000
|
|
768
772
|
|
|
773
|
+
/**
|
|
774
|
+
* Process groups this tool spawned that have not exited yet.
|
|
775
|
+
*
|
|
776
|
+
* `detached: true` is what makes the group kill work — and it is also what lets
|
|
777
|
+
* the command outlive the CLI: the group is no longer in our process group, so
|
|
778
|
+
* nothing is delivered to it when the parent goes away. A long `build` or
|
|
779
|
+
* `npm test` started a second before Ctrl+C keeps writing to the user's disk
|
|
780
|
+
* with no CLI attached, and the next run finds a locked directory it cannot
|
|
781
|
+
* explain. Killing these on `exit` is the only cleanup that can still run there
|
|
782
|
+
* (the handler must be synchronous, and `killProcessGroup` is).
|
|
783
|
+
*/
|
|
784
|
+
const liveProcessGroups = new Set<number>()
|
|
785
|
+
|
|
786
|
+
/** Kill every still-running group. Registered once against `process.on('exit')`. */
|
|
787
|
+
export function killLiveProcessGroups(): void {
|
|
788
|
+
for (const pid of liveProcessGroups) killProcessGroup(pid)
|
|
789
|
+
liveProcessGroups.clear()
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** How many groups are currently tracked (test observability). */
|
|
793
|
+
export function liveProcessGroupCount(): number {
|
|
794
|
+
return liveProcessGroups.size
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
let exitHookInstalled = false
|
|
798
|
+
|
|
799
|
+
/** Start tracking a freshly spawned group; installs the exit handler on first use. */
|
|
800
|
+
function trackProcessGroup(pid: number | undefined): void {
|
|
801
|
+
if (pid === undefined || pid <= 0) return
|
|
802
|
+
liveProcessGroups.add(pid)
|
|
803
|
+
if (exitHookInstalled) return
|
|
804
|
+
exitHookInstalled = true
|
|
805
|
+
process.on('exit', killLiveProcessGroups)
|
|
806
|
+
}
|
|
807
|
+
|
|
769
808
|
/**
|
|
770
809
|
* Kill a whole process group. `proc.kill()` reaches only the direct child, so a
|
|
771
810
|
* `bash -c` that spawned its own children leaves them orphaned and unnotified.
|
package/src/tools/file/grep.ts
CHANGED
|
@@ -11,6 +11,19 @@ import { maskSearchOutput } from '../../core/credential-masker'
|
|
|
11
11
|
* not hang the session for minutes. Matches the Bash tool's 120s ceiling. */
|
|
12
12
|
const GREP_TIMEOUT_MS = 120_000
|
|
13
13
|
|
|
14
|
+
/** How long `runSearch` waits after SIGTERM before escalating to SIGKILL. */
|
|
15
|
+
const KILL_GRACE_MS = 2_000
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* How long the pipes may stay open after the escalate-to-SIGKILL deadline before
|
|
19
|
+
* the search is abandoned outright.
|
|
20
|
+
*
|
|
21
|
+
* SIGKILL ends the child, but a *grandchild* that inherited the write end keeps
|
|
22
|
+
* EOF from ever arriving, and `new Response(pipe).text()` has no timeout of its
|
|
23
|
+
* own. Without this bound the tool's own "timed out" report would itself hang.
|
|
24
|
+
*/
|
|
25
|
+
const PIPE_DRAIN_GRACE_MS = 2_000
|
|
26
|
+
|
|
14
27
|
/** Run a search command with a kill-timer; report whether the timeout fired. */
|
|
15
28
|
export async function runSearch(
|
|
16
29
|
cmd: string[],
|
|
@@ -19,20 +32,41 @@ export async function runSearch(
|
|
|
19
32
|
): Promise<{ stdout: string; stderr: string; timedOut: boolean; exitCode: number | null }> {
|
|
20
33
|
const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe' })
|
|
21
34
|
let timedOut = false
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
35
|
+
const timers: ReturnType<typeof setTimeout>[] = []
|
|
36
|
+
timers.push(
|
|
37
|
+
setTimeout(() => {
|
|
38
|
+
timedOut = true
|
|
39
|
+
// SIGTERM first: rg releases its walker and flushes what it has. A process
|
|
40
|
+
// that ignores it (or is stuck in uninterruptible I/O) would otherwise keep
|
|
41
|
+
// the pipes open forever — the timeout would never reach the caller.
|
|
42
|
+
proc.kill()
|
|
43
|
+
timers.push(setTimeout(() => proc.kill(9), KILL_GRACE_MS))
|
|
44
|
+
}, timeoutMs),
|
|
45
|
+
)
|
|
26
46
|
// 两条管道必须**并发**读。先读满 stdout 再读 stderr 会在子进程写满
|
|
27
47
|
// stderr(~64 KB 管道缓冲)时死锁:它阻塞在 write 上不退出,stdout 也就
|
|
28
48
|
// 永远读不到 EOF —— 只能等超时兜底,而超时会把「慢」和「错」说成同一件事。
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
49
|
+
const finished = (async () => {
|
|
50
|
+
const [stdout, stderr] = await Promise.all([
|
|
51
|
+
new Response(proc.stdout).text(),
|
|
52
|
+
new Response(proc.stderr).text(),
|
|
53
|
+
])
|
|
54
|
+
await proc.exited
|
|
55
|
+
return { stdout, stderr, exitCode: proc.exitCode }
|
|
56
|
+
})()
|
|
57
|
+
|
|
58
|
+
const abandoned = new Promise<null>((resolve) => {
|
|
59
|
+
timers.push(setTimeout(() => resolve(null), timeoutMs + KILL_GRACE_MS + PIPE_DRAIN_GRACE_MS))
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
const result = await Promise.race([finished, abandoned])
|
|
63
|
+
for (const t of timers) clearTimeout(t)
|
|
64
|
+
if (result === null) {
|
|
65
|
+
// Nothing readable came back and the process would not die. Report it as the
|
|
66
|
+
// timeout it is instead of waiting on fds nobody owns anymore.
|
|
67
|
+
return { stdout: '', stderr: '', timedOut: true, exitCode: null }
|
|
68
|
+
}
|
|
69
|
+
return { ...result, timedOut }
|
|
36
70
|
}
|
|
37
71
|
|
|
38
72
|
/** grep 输出上限:超过则显式截断并附标记(不能静默丢内容——模型会误以为看全了)。 */
|
package/src/tools/file/read.ts
CHANGED
|
@@ -73,14 +73,20 @@ function windowFromString(content: string, offset: number, limit: number): strin
|
|
|
73
73
|
* and the decoded range starts and ends on a newline — so neither pass can split
|
|
74
74
|
* a character. Returns null when the window cannot be located within
|
|
75
75
|
* `MAX_SCAN_BYTES`.
|
|
76
|
+
*
|
|
77
|
+
* `complete` answers a different question from the one the window answers: did
|
|
78
|
+
* this read cover the **whole file**? A 2,000-line window of a 50,000-line file
|
|
79
|
+
* is a correct answer to "show me the start" and a dangerous basis for
|
|
80
|
+
* "overwrite it" — the model would rewrite what it never saw. The Write tool
|
|
81
|
+
* reads this flag (see `ToolContext.readFilesComplete`).
|
|
76
82
|
*/
|
|
77
83
|
function windowFromFd(
|
|
78
84
|
fd: number,
|
|
79
85
|
offset: number,
|
|
80
86
|
limit: number,
|
|
81
87
|
maxScanBytes: number = MAX_SCAN_BYTES,
|
|
82
|
-
): string[] | null {
|
|
83
|
-
if (limit <= 0) return []
|
|
88
|
+
): { lines: string[]; complete: boolean } | null {
|
|
89
|
+
if (limit <= 0) return { lines: [], complete: false }
|
|
84
90
|
|
|
85
91
|
const buf = Buffer.allocUnsafe(CHUNK_BYTES)
|
|
86
92
|
let scanned = 0 // bytes consumed by the scan
|
|
@@ -113,13 +119,28 @@ function windowFromFd(
|
|
|
113
119
|
scanned += n
|
|
114
120
|
}
|
|
115
121
|
|
|
122
|
+
// `complete` = this window is the whole file: it starts at line 0 and nothing
|
|
123
|
+
// follows its last line. The window ended on a terminating newline, which is
|
|
124
|
+
// also what a file whose final byte is that newline looks like — one probe
|
|
125
|
+
// byte past it tells the two apart. A read error here means "unknown", and
|
|
126
|
+
// unknown must not grant overwrite permission.
|
|
127
|
+
let complete: boolean
|
|
116
128
|
if (windowEnd === -1) {
|
|
117
129
|
// Either the file ended (the window is everything that is left) or the scan
|
|
118
130
|
// budget ran out before the window's last line was reached.
|
|
119
131
|
if (!eof) return null
|
|
120
132
|
windowEnd = scanned
|
|
133
|
+
complete = offset <= 0
|
|
134
|
+
} else {
|
|
135
|
+
let hasMore = true
|
|
136
|
+
try {
|
|
137
|
+
hasMore = readSync(fd, Buffer.allocUnsafe(1), 0, 1, windowEnd + 1) > 0
|
|
138
|
+
} catch {
|
|
139
|
+
hasMore = true
|
|
140
|
+
}
|
|
141
|
+
complete = offset <= 0 && !hasMore
|
|
121
142
|
}
|
|
122
|
-
if (windowStart === -1) return [] // `offset` is past the end of the file
|
|
143
|
+
if (windowStart === -1) return { lines: [], complete: false } // `offset` is past the end of the file
|
|
123
144
|
|
|
124
145
|
const out = Buffer.allocUnsafe(windowEnd - windowStart)
|
|
125
146
|
let got = 0
|
|
@@ -128,7 +149,7 @@ function windowFromFd(
|
|
|
128
149
|
if (n <= 0) break
|
|
129
150
|
got += n
|
|
130
151
|
}
|
|
131
|
-
return out.toString('utf-8', 0, got).split('\n')
|
|
152
|
+
return { lines: out.toString('utf-8', 0, got).split('\n'), complete }
|
|
132
153
|
}
|
|
133
154
|
|
|
134
155
|
export function createReadTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
|
|
@@ -199,6 +220,11 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
199
220
|
// *first* is what used to make `offset`/`limit` useless on large files —
|
|
200
221
|
// the size check ran before the window was ever applied.
|
|
201
222
|
let result: string | null = null
|
|
223
|
+
// Did this read see the whole file? Only then may the Write tool replace
|
|
224
|
+
// the file outright; a window is an excerpt, not a basis for overwriting.
|
|
225
|
+
// Credential-masked content is never "whole": what was returned to the
|
|
226
|
+
// model is a sentinel or a redaction of the real bytes.
|
|
227
|
+
let complete = false
|
|
202
228
|
if (credentialConfig) {
|
|
203
229
|
const { matchCredentialFile, maskContent, CREDENTIAL_SENTINEL } =
|
|
204
230
|
await import('../../core/credential-masker')
|
|
@@ -216,8 +242,8 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
216
242
|
if (result === null) {
|
|
217
243
|
const allowLarge = params.allow_large === true
|
|
218
244
|
const scanBudget = allowLarge ? MAX_SCAN_BYTES_LARGE : MAX_SCAN_BYTES
|
|
219
|
-
const
|
|
220
|
-
if (
|
|
245
|
+
const window = windowFromFd(fd, offset, limit, scanBudget)
|
|
246
|
+
if (window === null) {
|
|
221
247
|
return {
|
|
222
248
|
success: false,
|
|
223
249
|
content: '',
|
|
@@ -228,7 +254,8 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
228
254
|
`, or use a shell tool to slice the file.`,
|
|
229
255
|
}
|
|
230
256
|
}
|
|
231
|
-
result = formatLines(lines, offset)
|
|
257
|
+
result = formatLines(window.lines, offset)
|
|
258
|
+
complete = window.complete
|
|
232
259
|
}
|
|
233
260
|
|
|
234
261
|
// ── Binary sniff ──
|
|
@@ -254,6 +281,7 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
254
281
|
|
|
255
282
|
// ── Read tracking: mark file as read for Write tool safety ──
|
|
256
283
|
ctx.readFiles?.add(filePath)
|
|
284
|
+
if (complete) ctx.readFilesComplete?.add(filePath)
|
|
257
285
|
return { success: true, content: result }
|
|
258
286
|
} finally {
|
|
259
287
|
closeSync(fd)
|
package/src/tools/file/write.ts
CHANGED
|
@@ -42,6 +42,25 @@ export const writeTool: ToolDefinition = {
|
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
// ── Whole-file check: a window is not the file ──
|
|
46
|
+
// `offset`/`limit` exist so a huge file can be inspected a slice at a time.
|
|
47
|
+
// Treating that slice as "the file has been read" lets the next Write erase
|
|
48
|
+
// every line outside it without a trace — the model rewrites a file it only
|
|
49
|
+
// half-saw. Only a read that covered the whole file grants overwrite;
|
|
50
|
+
// anything less must go through Edit, which is anchored on content the model
|
|
51
|
+
// actually has.
|
|
52
|
+
const completelyRead = ctx.readFilesComplete?.has(filePath) ?? false
|
|
53
|
+
if (fileExists && wasRead && !completelyRead) {
|
|
54
|
+
return {
|
|
55
|
+
success: false,
|
|
56
|
+
content: '',
|
|
57
|
+
error:
|
|
58
|
+
`File "${filePath}" was only partially read (an offset/limit window). ` +
|
|
59
|
+
'Overwriting it would discard the rest of the file. Use Edit for targeted ' +
|
|
60
|
+
'changes, or Read the whole file first (no offset/limit).',
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
45
64
|
// ── Non-UTF-8 guard: refuse to clobber a file we cannot represent ──
|
|
46
65
|
// A Windows-1252 / Shift-JIS / GBK file read into the model came back as
|
|
47
66
|
// U+FFFD garbage; writing UTF-8 content over it would erase the originals
|
|
@@ -83,8 +102,10 @@ export const writeTool: ToolDefinition = {
|
|
|
83
102
|
throw err
|
|
84
103
|
}
|
|
85
104
|
|
|
86
|
-
// Track as read since we just wrote it (future writes allowed)
|
|
105
|
+
// Track as read since we just wrote it (future writes allowed). The model
|
|
106
|
+
// authored every byte of the new content, so this is a whole-file read too.
|
|
87
107
|
ctx.readFiles?.add(filePath)
|
|
108
|
+
ctx.readFilesComplete?.add(filePath)
|
|
88
109
|
|
|
89
110
|
const lines = content.split('\n').length
|
|
90
111
|
const action = fileExists ? 'Updated' : 'Wrote'
|
|
@@ -202,6 +202,41 @@ function withOffsetNotice(
|
|
|
202
202
|
return header + window + notice
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
+
/**
|
|
206
|
+
* Flatten an error and its `cause` chain into one line.
|
|
207
|
+
*
|
|
208
|
+
* Bun/undici wrap the actual failure in `cause`; the top-level message is often
|
|
209
|
+
* only "Unable to connect", which says nothing about *why*.
|
|
210
|
+
*/
|
|
211
|
+
function errorChain(err: unknown, depth = 0): string {
|
|
212
|
+
if (!(err instanceof Error)) return String(err)
|
|
213
|
+
const head = `${err.name}: ${err.message}`
|
|
214
|
+
const cause = (err as { cause?: unknown }).cause
|
|
215
|
+
if (!cause || depth >= 3) return head
|
|
216
|
+
return `${head} ← ${errorChain(cause, depth + 1)}`
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Turn a thrown fetch error into a diagnosis the reader can act on.
|
|
221
|
+
*
|
|
222
|
+
* A TLS failure (expired, self-signed, wrong host, or a proxy intercepting the
|
|
223
|
+
* connection) otherwise reads exactly like "the site is down" — and the model
|
|
224
|
+
* responds by trying mirrors that are just as unreachable. Naming the class is
|
|
225
|
+
* the difference between fixing the cause and guessing.
|
|
226
|
+
*/
|
|
227
|
+
export function describeFetchFailure(err: unknown): string {
|
|
228
|
+
const text = errorChain(err)
|
|
229
|
+
if (/certificate|CERT_|ERR_TLS|\bSSL\b|\bTLS\b|self[- ]signed|unable to verify/i.test(text)) {
|
|
230
|
+
return (
|
|
231
|
+
`TLS/certificate failure: ${text}. The server's certificate could not be verified ` +
|
|
232
|
+
'(expired, self-signed, wrong host, or replaced by a proxy on the network path). ' +
|
|
233
|
+
'Retrying a mirror will not help and certificate verification must not be disabled — ' +
|
|
234
|
+
'the user needs to trust the proxy CA or use a reachable source.'
|
|
235
|
+
)
|
|
236
|
+
}
|
|
237
|
+
return `Fetch failed: ${text}. If direct network is blocked, retry via the web-access skill (CDP through the user's logged-in Chrome).`
|
|
238
|
+
}
|
|
239
|
+
|
|
205
240
|
// ── Tool Definition ──
|
|
206
241
|
|
|
207
242
|
export const webFetchTool: ToolDefinition = {
|
|
@@ -348,7 +383,7 @@ export const webFetchTool: ToolDefinition = {
|
|
|
348
383
|
const message =
|
|
349
384
|
err instanceof Error && err.name === 'AbortError'
|
|
350
385
|
? 'Request timed out (30s)'
|
|
351
|
-
:
|
|
386
|
+
: describeFetchFailure(err)
|
|
352
387
|
return { success: false, content: '', error: message }
|
|
353
388
|
} finally {
|
|
354
389
|
clearTimeout(timer)
|
package/src/ui/commands.ts
CHANGED
|
@@ -660,9 +660,11 @@ const switchCmd: CommandHandler = (ctx, args) => {
|
|
|
660
660
|
}
|
|
661
661
|
}
|
|
662
662
|
|
|
663
|
-
ctx.engine.switchProvider(newProvider, newModel)
|
|
663
|
+
const warning = ctx.engine.switchProvider(newProvider, newModel)
|
|
664
664
|
return {
|
|
665
|
-
content:
|
|
665
|
+
content:
|
|
666
|
+
t('commands.switch.confirmed', { provider: newProvider, model: newModel }) +
|
|
667
|
+
(warning ? `\n${warning}` : ''),
|
|
666
668
|
nextProvider: newProvider,
|
|
667
669
|
nextModel: newModel,
|
|
668
670
|
}
|