@miphamai/cli 0.85.27 → 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/bin/mipham.ts +0 -32
- package/package.json +8 -8
- package/src/agent/sub-agent.ts +1 -0
- package/src/config/defaults.ts +1 -1
- package/src/core/engine.ts +171 -34
- package/src/core/hooks-executor.ts +20 -2
- package/src/core/instructions.ts +24 -4
- 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 +19 -3
- package/src/providers/fetch-utils.ts +31 -0
- package/src/providers/openai-compat.ts +16 -3
- 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/bin/mipham.ts
CHANGED
|
@@ -1193,38 +1193,6 @@ async function main() {
|
|
|
1193
1193
|
throw err
|
|
1194
1194
|
}
|
|
1195
1195
|
|
|
1196
|
-
// ── Disable terminal special characters ──────────────────────────────────
|
|
1197
|
-
// Terminal intercepts Ctrl+S (XOFF), Ctrl+T (SIGINFO/status), Ctrl+R (rprnt)
|
|
1198
|
-
// before the app sees them. Disable these so Agent Dashboard shortcuts work.
|
|
1199
|
-
// IMPORTANT: stty needs the real terminal on stdin — 'ignore' won't work.
|
|
1200
|
-
const { execSync } = await import('node:child_process')
|
|
1201
|
-
let savedStty = ''
|
|
1202
|
-
try {
|
|
1203
|
-
savedStty = execSync('stty -g', {
|
|
1204
|
-
encoding: 'utf-8',
|
|
1205
|
-
stdio: ['inherit', 'pipe', 'ignore'],
|
|
1206
|
-
}).trim()
|
|
1207
|
-
execSync('stty -ixon stop undef start undef status undef rprnt undef', {
|
|
1208
|
-
stdio: ['inherit', 'ignore', 'ignore'],
|
|
1209
|
-
})
|
|
1210
|
-
} catch {
|
|
1211
|
-
// Non-POSIX platform (Windows) — no special chars to disable
|
|
1212
|
-
}
|
|
1213
|
-
// Restore original terminal settings on exit
|
|
1214
|
-
const restoreTerminal = () => {
|
|
1215
|
-
if (!savedStty) return
|
|
1216
|
-
try {
|
|
1217
|
-
execSync(`stty ${savedStty}`, {
|
|
1218
|
-
stdio: ['inherit', 'ignore', 'ignore'],
|
|
1219
|
-
})
|
|
1220
|
-
} catch {
|
|
1221
|
-
/* ignore */
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
process.on('exit', restoreTerminal)
|
|
1225
|
-
process.on('SIGINT', restoreTerminal)
|
|
1226
|
-
process.on('SIGTERM', restoreTerminal)
|
|
1227
|
-
|
|
1228
1196
|
// ── Version: build-time constant (bundled into the compiled binary) ──
|
|
1229
1197
|
const { PACKAGE_NAME, PACKAGE_VERSION } = await import('../src/shared/package-info')
|
|
1230
1198
|
const APP_VERSION = PACKAGE_VERSION
|
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/config/defaults.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { PACKAGE_VERSION } from '../shared/index.ts'
|
|
|
11
11
|
export const DEFAULT_CONFIG: MiphamConfig = {
|
|
12
12
|
version: PACKAGE_VERSION,
|
|
13
13
|
defaultProvider: 'deepseek',
|
|
14
|
-
defaultModel: 'deepseek-v4-
|
|
14
|
+
defaultModel: 'deepseek-v4-flash',
|
|
15
15
|
permission: 'default',
|
|
16
16
|
showThinking: 'off',
|
|
17
17
|
showSchedulingNotices: false,
|
package/src/core/engine.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
ContentBlock,
|
|
10
10
|
} from '../shared/index.ts'
|
|
11
11
|
import { ProviderRegistry } from '../providers/registry'
|
|
12
|
+
import { createAwakeTimer } from '../providers/fetch-utils'
|
|
12
13
|
import type { ChatRequest } from '../providers/registry'
|
|
13
14
|
import type { Llm } from '../providers/llm'
|
|
14
15
|
import { ContextManager } from './context'
|
|
@@ -80,6 +81,34 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
|
|
|
80
81
|
*/
|
|
81
82
|
const MAX_TOOL_TURNS = 100
|
|
82
83
|
|
|
84
|
+
/**
|
|
85
|
+
* How long a turn may go without producing anything it can act on (a text
|
|
86
|
+
* delta, a tool call, a tool result) before it is declared stalled.
|
|
87
|
+
*
|
|
88
|
+
* Measured against `performance.now()`, which is monotonic and does *not*
|
|
89
|
+
* advance while the machine is suspended: a laptop that sleeps mid-turn would
|
|
90
|
+
* otherwise wake up to "no activity for 8 hours" and kill a turn that was never
|
|
91
|
+
* stalled.
|
|
92
|
+
*/
|
|
93
|
+
const TURN_TIMEOUT_MS = 15 * 60 * 1000
|
|
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
|
+
|
|
106
|
+
/** The turn's stall clock: when it last moved, and whether it ran out. */
|
|
107
|
+
interface TurnBudget {
|
|
108
|
+
last: number
|
|
109
|
+
hit: boolean
|
|
110
|
+
}
|
|
111
|
+
|
|
83
112
|
/**
|
|
84
113
|
* Drop inbound messages whose timestamp is older than the dialog-expiry TTL.
|
|
85
114
|
* A stale message's approval dialog is no longer relevant, so it's discarded
|
|
@@ -114,6 +143,8 @@ export class QueryEngine {
|
|
|
114
143
|
private _selfCritique?: SelfCritique
|
|
115
144
|
/** Files read this session — tracks what the Read tool has loaded */
|
|
116
145
|
private readFiles = new Set<string>()
|
|
146
|
+
/** Subset of `readFiles` whose reads covered the whole file (no window) */
|
|
147
|
+
private readFilesComplete = new Set<string>()
|
|
117
148
|
private goal?: string
|
|
118
149
|
private maxGoalLoops = 20
|
|
119
150
|
private lastAssistantContent?: string
|
|
@@ -238,6 +269,7 @@ export class QueryEngine {
|
|
|
238
269
|
*/
|
|
239
270
|
resetFileTracking(): void {
|
|
240
271
|
this.readFiles.clear()
|
|
272
|
+
this.readFilesComplete.clear()
|
|
241
273
|
}
|
|
242
274
|
|
|
243
275
|
/** Set the session identifier (called from index.tsx at startup with the actual session name). */
|
|
@@ -760,13 +792,17 @@ export class QueryEngine {
|
|
|
760
792
|
const turnStart = Date.now()
|
|
761
793
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
762
794
|
|
|
763
|
-
// Stream model response
|
|
795
|
+
// Stream model response — under the same turn budget the continuation rounds
|
|
796
|
+
// use, so the *first* request of a turn cannot outlive it either.
|
|
797
|
+
const budget: TurnBudget = { last: performance.now(), hit: false }
|
|
764
798
|
try {
|
|
765
|
-
for await (const chunk of this.
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
799
|
+
for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
|
|
800
|
+
this.chatWithFallback(
|
|
801
|
+
messages,
|
|
802
|
+
systemPrompt,
|
|
803
|
+
toolDefs.length > 0 ? toolDefs : undefined,
|
|
804
|
+
innerSignal,
|
|
805
|
+
),
|
|
770
806
|
)) {
|
|
771
807
|
yield chunk
|
|
772
808
|
|
|
@@ -871,6 +907,11 @@ export class QueryEngine {
|
|
|
871
907
|
return
|
|
872
908
|
}
|
|
873
909
|
|
|
910
|
+
// The round was cut short by the turn budget. The partial answer is already
|
|
911
|
+
// committed above; the warning and `stop` are already on the wire, so nothing
|
|
912
|
+
// may follow them — least of all a tool call from an interrupted round.
|
|
913
|
+
if (budget.hit) return
|
|
914
|
+
|
|
874
915
|
// Record the provider's cached prefix (all messages except the newest)
|
|
875
916
|
// for cache-aware microcompaction.
|
|
876
917
|
if (messages.length >= 2) {
|
|
@@ -1079,6 +1120,77 @@ export class QueryEngine {
|
|
|
1079
1120
|
}
|
|
1080
1121
|
}
|
|
1081
1122
|
|
|
1123
|
+
/**
|
|
1124
|
+
* Stream one model round under the turn's stall budget — and *interrupt* it
|
|
1125
|
+
* when the budget runs out.
|
|
1126
|
+
*
|
|
1127
|
+
* The budget used to be a plain `if` at the top of the round loop, so it could
|
|
1128
|
+
* only ever fire *between* rounds. A request that never returns — no error, no
|
|
1129
|
+
* read timeout, nothing — therefore had nothing above it, and the turn waited
|
|
1130
|
+
* forever with the user looking at a spinner. Nothing below this layer bounds
|
|
1131
|
+
* it either: the provider's read timeout measures socket silence, and a
|
|
1132
|
+
* gateway that keeps the socket warm defeats it.
|
|
1133
|
+
*
|
|
1134
|
+
* A stalled round is not a failure: it is the same `stop` the user's own
|
|
1135
|
+
* Ctrl+C produces, preceded by a warning that says which wait ran out. So the
|
|
1136
|
+
* caller keeps its existing abort handling untouched.
|
|
1137
|
+
*/
|
|
1138
|
+
private async *streamUnderTurnBudget(
|
|
1139
|
+
budget: TurnBudget,
|
|
1140
|
+
signal: AbortSignal | undefined,
|
|
1141
|
+
run: (signal?: AbortSignal) => AsyncGenerator<StreamChunk>,
|
|
1142
|
+
): AsyncGenerator<StreamChunk> {
|
|
1143
|
+
const expired = new AbortController()
|
|
1144
|
+
let cancelTimer: (() => void) | undefined
|
|
1145
|
+
const arm = (): void => {
|
|
1146
|
+
cancelTimer?.()
|
|
1147
|
+
const remainingMs = Math.max(0, budget.last + TURN_TIMEOUT_MS - performance.now())
|
|
1148
|
+
cancelTimer = createAwakeTimer(remainingMs, () => {
|
|
1149
|
+
budget.hit = true
|
|
1150
|
+
// Abort rather than merely stop reading: the request is what has to be
|
|
1151
|
+
// let go of, or every stalled round leaves a socket behind.
|
|
1152
|
+
expired.abort()
|
|
1153
|
+
})
|
|
1154
|
+
}
|
|
1155
|
+
const effectiveSignal = signal ? AbortSignal.any([signal, expired.signal]) : expired.signal
|
|
1156
|
+
|
|
1157
|
+
const stalled: StreamChunk[] = [
|
|
1158
|
+
{
|
|
1159
|
+
type: 'warning',
|
|
1160
|
+
content: t('errors.turn_timeout', {
|
|
1161
|
+
minutes: String(Math.round(TURN_TIMEOUT_MS / 60000)),
|
|
1162
|
+
}),
|
|
1163
|
+
},
|
|
1164
|
+
{ type: 'stop' },
|
|
1165
|
+
]
|
|
1166
|
+
|
|
1167
|
+
arm()
|
|
1168
|
+
try {
|
|
1169
|
+
for await (const chunk of run(effectiveSignal)) {
|
|
1170
|
+
// The same set the round loops call "activity": something the turn can
|
|
1171
|
+
// act on. A stream that is merely alive never produces one of these.
|
|
1172
|
+
if (chunk.type === 'text' || chunk.type === 'thinking' || chunk.type === 'tool_use') {
|
|
1173
|
+
budget.last = performance.now()
|
|
1174
|
+
arm()
|
|
1175
|
+
}
|
|
1176
|
+
yield chunk
|
|
1177
|
+
}
|
|
1178
|
+
} catch (err) {
|
|
1179
|
+
// A real failure still wins: only the abort *this* timer caused is turned
|
|
1180
|
+
// into a stall, or a provider error that happens to land at the deadline
|
|
1181
|
+
// would be reported as "took too long".
|
|
1182
|
+
if (!budget.hit || !isAbortError(err)) throw err
|
|
1183
|
+
for (const chunk of stalled) yield chunk
|
|
1184
|
+
return
|
|
1185
|
+
} finally {
|
|
1186
|
+
cancelTimer?.()
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
// The request ended at the same moment the budget did. The warning still
|
|
1190
|
+
// belongs on screen — otherwise the turn looks like it finished normally.
|
|
1191
|
+
if (budget.hit) for (const chunk of stalled) yield chunk
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1082
1194
|
private async *continueWithTools(
|
|
1083
1195
|
signal?: AbortSignal,
|
|
1084
1196
|
roundsLeft: number = MAX_TOOL_TURNS,
|
|
@@ -1086,19 +1198,15 @@ export class QueryEngine {
|
|
|
1086
1198
|
// Task-level stall guard: a turn that produces no text or tool result for
|
|
1087
1199
|
// this long is considered stalled and stopped (prevents ~40-min idle spins).
|
|
1088
1200
|
//
|
|
1089
|
-
//
|
|
1090
|
-
// the
|
|
1091
|
-
// that
|
|
1092
|
-
//
|
|
1093
|
-
|
|
1094
|
-
// returns to their desk.
|
|
1095
|
-
const TURN_TIMEOUT_MS = 15 * 60 * 1000
|
|
1096
|
-
const monotonicNow = (): number => performance.now()
|
|
1097
|
-
let lastActivity = monotonicNow()
|
|
1201
|
+
// Two places enforce it, because they see different moments: this check
|
|
1202
|
+
// covers the gap *between* rounds, and `streamUnderTurnBudget` covers a round
|
|
1203
|
+
// that is still in flight. Keeping only this one is what let a hung request
|
|
1204
|
+
// wait without any bound at all.
|
|
1205
|
+
const budget: TurnBudget = { last: performance.now(), hit: false }
|
|
1098
1206
|
const toolDefs = this.getToolDefinitions()
|
|
1099
1207
|
|
|
1100
1208
|
for (let turn = 0; turn < roundsLeft; turn++) {
|
|
1101
|
-
if (
|
|
1209
|
+
if (performance.now() - budget.last > TURN_TIMEOUT_MS) {
|
|
1102
1210
|
yield {
|
|
1103
1211
|
type: 'warning',
|
|
1104
1212
|
content: t('errors.turn_timeout', {
|
|
@@ -1139,11 +1247,13 @@ export class QueryEngine {
|
|
|
1139
1247
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
1140
1248
|
|
|
1141
1249
|
try {
|
|
1142
|
-
for await (const chunk of this.
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1250
|
+
for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
|
|
1251
|
+
this.chatWithFallback(
|
|
1252
|
+
messages,
|
|
1253
|
+
systemPrompt,
|
|
1254
|
+
toolDefs.length > 0 ? toolDefs : undefined,
|
|
1255
|
+
innerSignal,
|
|
1256
|
+
),
|
|
1147
1257
|
)) {
|
|
1148
1258
|
yield chunk
|
|
1149
1259
|
|
|
@@ -1160,7 +1270,7 @@ export class QueryEngine {
|
|
|
1160
1270
|
if (chunk.type === 'text' && chunk.content) {
|
|
1161
1271
|
assistantContent += chunk.content
|
|
1162
1272
|
this.context.recordChunk(chunk.content)
|
|
1163
|
-
|
|
1273
|
+
budget.last = performance.now()
|
|
1164
1274
|
}
|
|
1165
1275
|
|
|
1166
1276
|
if (chunk.reasoning_content) {
|
|
@@ -1219,6 +1329,10 @@ export class QueryEngine {
|
|
|
1219
1329
|
this.context.addMessage(msg)
|
|
1220
1330
|
}
|
|
1221
1331
|
|
|
1332
|
+
// The round was cut short by the turn budget: the partial answer is
|
|
1333
|
+
// committed above, and the warning + `stop` already ended the turn.
|
|
1334
|
+
if (budget.hit) return
|
|
1335
|
+
|
|
1222
1336
|
// Safety: when max turns reached with pending tools, ask model to summarize
|
|
1223
1337
|
if (turn === roundsLeft - 1 && toolUses.length > 0) {
|
|
1224
1338
|
this.context.addMessage({
|
|
@@ -1260,7 +1374,7 @@ export class QueryEngine {
|
|
|
1260
1374
|
for (const toolUse of toolUses) {
|
|
1261
1375
|
const result = await this.executeTool(toolUse.name, toolUse.input, signal)
|
|
1262
1376
|
if (!result.success) this.pendingToolFailure = true
|
|
1263
|
-
|
|
1377
|
+
budget.last = performance.now()
|
|
1264
1378
|
yield {
|
|
1265
1379
|
type: 'tool_result',
|
|
1266
1380
|
tool_use_id: toolUse.id,
|
|
@@ -1535,6 +1649,7 @@ export class QueryEngine {
|
|
|
1535
1649
|
ruleEngine: this.ruleEngine,
|
|
1536
1650
|
llm: this.llm,
|
|
1537
1651
|
readFiles: this.readFiles,
|
|
1652
|
+
readFilesComplete: this.readFilesComplete,
|
|
1538
1653
|
})
|
|
1539
1654
|
|
|
1540
1655
|
// Track touched files for rules matching
|
|
@@ -2122,18 +2237,30 @@ export class QueryEngine {
|
|
|
2122
2237
|
}
|
|
2123
2238
|
}
|
|
2124
2239
|
|
|
2125
|
-
|
|
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 {
|
|
2126
2250
|
this.registry.switchProvider(providerId, modelId)
|
|
2127
2251
|
// Update context manager's max tokens to match the new model's context window
|
|
2128
|
-
if (modelId)
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
}
|
|
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
|
+
})
|
|
2136
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
|
|
2137
2264
|
}
|
|
2138
2265
|
|
|
2139
2266
|
/**
|
|
@@ -2155,6 +2282,16 @@ export class QueryEngine {
|
|
|
2155
2282
|
return n >= 1_000_000 ? `${Math.round(n / 100_000) / 10}M` : `${Math.round(n / 1000)}K`
|
|
2156
2283
|
}
|
|
2157
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
|
+
|
|
2158
2295
|
/** Wrap context compaction with PreCompact/PostCompact hooks. */
|
|
2159
2296
|
private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
|
|
2160
2297
|
if (this.hookEngine) {
|
|
@@ -2162,7 +2299,7 @@ export class QueryEngine {
|
|
|
2162
2299
|
if (preResult.additionalContext) {
|
|
2163
2300
|
this.context.injectContext(
|
|
2164
2301
|
'pre-compact',
|
|
2165
|
-
`[Pre-compact context]: ${preResult.additionalContext}`,
|
|
2302
|
+
`[Pre-compact context]: ${this.capHookContext(preResult.additionalContext)}`,
|
|
2166
2303
|
)
|
|
2167
2304
|
}
|
|
2168
2305
|
}
|
|
@@ -2180,7 +2317,7 @@ export class QueryEngine {
|
|
|
2180
2317
|
if (postResult.additionalContext) {
|
|
2181
2318
|
this.context.injectContext(
|
|
2182
2319
|
'post-compact',
|
|
2183
|
-
`[Post-compact context]: ${postResult.additionalContext}`,
|
|
2320
|
+
`[Post-compact context]: ${this.capHookContext(postResult.additionalContext)}`,
|
|
2184
2321
|
)
|
|
2185
2322
|
}
|
|
2186
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,
|
package/src/core/instructions.ts
CHANGED
|
@@ -57,6 +57,26 @@ export function stripSections(content: string, excluded: string[]): string {
|
|
|
57
57
|
return out.join('\n')
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Strip the leading metadata blockquote — the `> **项目** / > **版本** / > **最后更新** …`
|
|
62
|
+
* header that precedes the first `##` section. These lines are document metadata for
|
|
63
|
+
* human readers (the model's identity and version come from MIPHAM.md and the
|
|
64
|
+
* provenance comment). Gated by the `prompt-exclude-header` frontmatter key — not by
|
|
65
|
+
* `prompt-exclude`, whose entries are title-exact and whose integrity guard rejects any
|
|
66
|
+
* entry that matches no heading.
|
|
67
|
+
*/
|
|
68
|
+
export function stripLeadingBlockquote(content: string): string {
|
|
69
|
+
const lines = content.split('\n')
|
|
70
|
+
const out: string[] = []
|
|
71
|
+
let seenSection = false
|
|
72
|
+
for (const line of lines) {
|
|
73
|
+
if (!seenSection && /^##\s/.test(line)) seenSection = true
|
|
74
|
+
if (!seenSection && /^>\s/.test(line)) continue
|
|
75
|
+
out.push(line)
|
|
76
|
+
}
|
|
77
|
+
return out.join('\n')
|
|
78
|
+
}
|
|
79
|
+
|
|
60
80
|
/** Normalize a `prompt-exclude` frontmatter value (YAML list or single string). */
|
|
61
81
|
export function parsePromptExclude(value: unknown): string[] {
|
|
62
82
|
if (Array.isArray(value)) return value.map((v) => String(v))
|
|
@@ -223,10 +243,10 @@ const LEVEL_LABELS: Record<string, string> = {
|
|
|
223
243
|
*/
|
|
224
244
|
function instructionPartText(inst: InstructionFile): string | null {
|
|
225
245
|
if (inst.privacy === 'private') return null
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
246
|
+
let content = stripSections(inst.content, parsePromptExclude(inst.frontmatter['prompt-exclude']))
|
|
247
|
+
if (inst.frontmatter['prompt-exclude-header']) {
|
|
248
|
+
content = stripLeadingBlockquote(content)
|
|
249
|
+
}
|
|
230
250
|
return `<!-- ${LEVEL_LABELS[inst.level] || inst.level} (${inst.path}) -->\n${content}`
|
|
231
251
|
}
|
|
232
252
|
|
|
@@ -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}`,
|
|
@@ -219,6 +220,14 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
219
220
|
// passes aren't mistaken for a stalled connection.
|
|
220
221
|
const STREAM_READ_TIMEOUT_MS = streamIdleTimeoutMs(req.effort)
|
|
221
222
|
|
|
223
|
+
// The budget restarts on *progress*, not on any byte. It used to be armed
|
|
224
|
+
// fresh for every `reader.read()`, and this API sends a `ping` event every
|
|
225
|
+
// ~30s on a long request — so the guard could never fire at all while the
|
|
226
|
+
// answer was still silent. Anything the answer can use advances the clock;
|
|
227
|
+
// `ping` is the API saying "still here", which is exactly the thing that
|
|
228
|
+
// must not count as progress.
|
|
229
|
+
let lastProgress = performance.now()
|
|
230
|
+
|
|
222
231
|
// The read loop and the trailing stop share one reader, and that reader owns
|
|
223
232
|
// the connection. `engine.ts` breaks out of this generator on the ordinary
|
|
224
233
|
// `stop` chunk, and a sub-agent throws mid-stream on abort — both call
|
|
@@ -230,14 +239,16 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
230
239
|
while (true) {
|
|
231
240
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
232
241
|
let cancelIdle: (() => void) | undefined
|
|
242
|
+
// What is left of the budget since the last frame the answer could use.
|
|
243
|
+
const remaining = Math.max(0, lastProgress + STREAM_READ_TIMEOUT_MS - performance.now())
|
|
233
244
|
try {
|
|
234
245
|
readResult = await Promise.race([
|
|
235
246
|
reader.read(),
|
|
236
247
|
new Promise<never>((_, reject) => {
|
|
237
|
-
cancelIdle = createAwakeTimer(
|
|
248
|
+
cancelIdle = createAwakeTimer(remaining, () =>
|
|
238
249
|
reject(
|
|
239
250
|
new Error(
|
|
240
|
-
`Stream read timeout — no
|
|
251
|
+
`Stream read timeout — no progress for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
241
252
|
),
|
|
242
253
|
),
|
|
243
254
|
)
|
|
@@ -264,6 +275,11 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
264
275
|
try {
|
|
265
276
|
const event = JSON.parse(data) as AnthropicSSEEvent
|
|
266
277
|
|
|
278
|
+
// Progress = an event whose payload the answer can use. `ping` carries
|
|
279
|
+
// nothing and arrives on a fixed schedule, so counting it would make
|
|
280
|
+
// the budget unreachable by construction.
|
|
281
|
+
if (event.type !== 'ping') lastProgress = performance.now()
|
|
282
|
+
|
|
267
283
|
switch (event.type) {
|
|
268
284
|
case 'content_block_start': {
|
|
269
285
|
const cb = event.content_block
|
|
@@ -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}`,
|
|
@@ -82,6 +83,12 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
82
83
|
// (DeepSeek V4 / reasoning models) aren't mistaken for a stalled connection.
|
|
83
84
|
const STREAM_READ_TIMEOUT_MS = streamIdleTimeoutMs(req.effort)
|
|
84
85
|
|
|
86
|
+
// The budget restarts on *progress*, not on any byte. It used to be armed
|
|
87
|
+
// fresh for every `reader.read()`, so a gateway that keeps the socket warm
|
|
88
|
+
// with SSE comment frames (`: keep-alive`) while the answer never starts fed
|
|
89
|
+
// the guard forever — no timeout, no error, the turn waits with no bound.
|
|
90
|
+
let lastProgress = performance.now()
|
|
91
|
+
|
|
85
92
|
// The read loop and the fallback stop share one reader, and that reader owns
|
|
86
93
|
// the connection. `engine.ts` breaks out of this generator on the ordinary
|
|
87
94
|
// `stop` chunk, and a sub-agent throws mid-stream on abort — both call
|
|
@@ -93,14 +100,16 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
93
100
|
while (true) {
|
|
94
101
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
95
102
|
let cancelIdle: (() => void) | undefined
|
|
103
|
+
// What is left of the budget since the last frame the answer could use.
|
|
104
|
+
const remaining = Math.max(0, lastProgress + STREAM_READ_TIMEOUT_MS - performance.now())
|
|
96
105
|
try {
|
|
97
106
|
readResult = await Promise.race([
|
|
98
107
|
reader.read(),
|
|
99
108
|
new Promise<never>((_, reject) => {
|
|
100
|
-
cancelIdle = createAwakeTimer(
|
|
109
|
+
cancelIdle = createAwakeTimer(remaining, () =>
|
|
101
110
|
reject(
|
|
102
111
|
new Error(
|
|
103
|
-
`Stream read timeout — no
|
|
112
|
+
`Stream read timeout — no progress for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
104
113
|
),
|
|
105
114
|
),
|
|
106
115
|
)
|
|
@@ -172,6 +181,10 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
172
181
|
return
|
|
173
182
|
}
|
|
174
183
|
|
|
184
|
+
// Progress = a frame the answer can use: `choices` carries text /
|
|
185
|
+
// tool-call deltas / finish_reason, and `usage` only arrives from a
|
|
186
|
+
// server that is answering. Everything else is liveness, not progress.
|
|
187
|
+
if (choice || parsed.usage) lastProgress = performance.now()
|
|
175
188
|
if (!choice) continue
|
|
176
189
|
|
|
177
190
|
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.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
|
}
|