@miphamai/cli 0.85.11 → 0.85.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +22 -0
- package/src/config/loader.ts +101 -6
- package/src/core/context-microcompact.ts +3 -5
- package/src/core/context.ts +17 -11
- package/src/core/credential-masker/output-scrub.ts +7 -1
- package/src/core/crsi-sandbox.ts +101 -49
- package/src/core/engine.ts +22 -2
- package/src/core/hooks-executor.ts +165 -16
- package/src/core/permission-classifier.ts +36 -12
- package/src/core/permission.ts +45 -0
- package/src/core/self-critique.ts +3 -15
- package/src/core/task-performance.ts +32 -4
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +15 -1
- package/src/plugin/plugin-loader.ts +10 -9
- package/src/providers/anthropic.ts +11 -3
- package/src/providers/fetch-utils.ts +29 -0
- package/src/providers/openai-compat.ts +24 -2
- package/src/providers/registry.ts +38 -0
- package/src/security/world-writable-chmod.ts +157 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +33 -0
- package/src/shared/types.ts +30 -0
- package/src/tools/agent/agent.ts +18 -3
- package/src/tools/agent/exit-plan.ts +49 -9
- package/src/tools/artifact/artifact.ts +0 -1
- package/src/tools/exec/bash.ts +28 -3
- package/src/tools/index.ts +7 -1
- package/src/tools/network/web-fetch.ts +2 -1
- package/src/ui/chat.tsx +2 -1
- package/src/ui/commands.ts +7 -6
- package/src/ui/input.tsx +5 -0
- package/src/workflow/event-bus.ts +13 -0
- package/src/workflow/journal.ts +8 -0
- package/src/workflow/runtime.ts +59 -11
|
@@ -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
|
|
@@ -2,6 +2,44 @@ import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/
|
|
|
2
2
|
import type { Llm } from './llm'
|
|
3
3
|
import { getMetrics } from '../core/metrics'
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* The model a secondary call should use when it wants speed rather than depth:
|
|
7
|
+
* the first active model whose id looks like a small one, else whatever is
|
|
8
|
+
* active. Exported so the permission classifier and `self-critique` pick the
|
|
9
|
+
* same model — two private copies of this heuristic would drift apart silently.
|
|
10
|
+
*/
|
|
11
|
+
export function pickFastestModel(registry: ProviderRegistry): string {
|
|
12
|
+
const models = registry.listModels?.() ?? []
|
|
13
|
+
const flash = models.find(
|
|
14
|
+
(m) => m.id.toLowerCase().includes('flash') || m.id.toLowerCase().includes('1.5b'),
|
|
15
|
+
)
|
|
16
|
+
return flash ? flash.id : registry.getActiveModel()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Resolve `permissions.classifierModel` to a model id.
|
|
21
|
+
*
|
|
22
|
+
* Three inputs, three meanings — and the default is the point:
|
|
23
|
+
*
|
|
24
|
+
* - absent / `'active'` ⇒ the operator's own model. A gate that quietly
|
|
25
|
+
* downgraded to a cheaper judge would make `auto` mean "judged by something
|
|
26
|
+
* you did not pick", and the two models do not agree on borderline calls
|
|
27
|
+
* (measured 2026-09-30: the fast one allowed 8/20 that the reasoning one
|
|
28
|
+
* blocked, 2/20 the other way).
|
|
29
|
+
* - `'fast'` ⇒ `pickFastestModel`, falling back to the active model rather
|
|
30
|
+
* than inventing an id that may not exist.
|
|
31
|
+
* - anything else ⇒ used verbatim. Whether it exists is the provider's to say;
|
|
32
|
+
* a second registry here would be a second value domain that drifts.
|
|
33
|
+
*/
|
|
34
|
+
export function resolveClassifierModel(
|
|
35
|
+
choice: string | undefined,
|
|
36
|
+
registry: ProviderRegistry,
|
|
37
|
+
): string {
|
|
38
|
+
if (choice === undefined || choice === '' || choice === 'active') return registry.getActiveModel()
|
|
39
|
+
if (choice === 'fast') return pickFastestModel(registry)
|
|
40
|
+
return choice
|
|
41
|
+
}
|
|
42
|
+
|
|
5
43
|
export interface ProviderInstance {
|
|
6
44
|
config: ProviderConfig
|
|
7
45
|
chat(req: ChatRequest): AsyncGenerator<StreamChunk>
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recursive `chmod` that grants world-write to a target the command does not
|
|
3
|
+
* bound.
|
|
4
|
+
*
|
|
5
|
+
* `chmod -R 777 ./dist` names where the write lands. `chmod -R 777 $DIR` does
|
|
6
|
+
* not — the target is produced at run time, so nothing that reasons *about* the
|
|
7
|
+
* command can say how far the grant reaches. Same argument as `dangerous-rm`:
|
|
8
|
+
* the text is exactly what is missing, so a second opinion reading the same text
|
|
9
|
+
* is reading the same gap.
|
|
10
|
+
*
|
|
11
|
+
* ## Why this is decided structurally rather than by the classifier
|
|
12
|
+
*
|
|
13
|
+
* This is the call shape the `auto` gate was measured getting wrong most often.
|
|
14
|
+
* Over 5 samples each, same machine and minute, the reasoning model allowed
|
|
15
|
+
* `chmod -R 777 /tmp/shared` 1/5 and the fast model 4/5 — the widest swing in the
|
|
16
|
+
* set (2026-09-30). Neither model is being asked a hard question; they are being
|
|
17
|
+
* asked a question with no rule behind it ("Irreversible Local Destruction" is
|
|
18
|
+
* about deleting, "Shared Infrastructure" is about deploys), so the answer is a
|
|
19
|
+
* coin flip. Both halves of the real question are decidable:
|
|
20
|
+
*
|
|
21
|
+
* - the **grant** is in the mode token (`777`, `o+w`, `a=rwx`), and
|
|
22
|
+
* - the **bound** is in the target.
|
|
23
|
+
*
|
|
24
|
+
* ## Scope — what this deliberately does not cover
|
|
25
|
+
*
|
|
26
|
+
* Recursion is required. Plain `chmod 777 <path>` is ordinary permission work,
|
|
27
|
+
* and where its target is absolute the Bash tool's own `BLOCKED_PATTERNS`
|
|
28
|
+
* already refuses it. Widening to the non-recursive forms would refuse routine
|
|
29
|
+
* work for no measured gain.
|
|
30
|
+
*
|
|
31
|
+
* A *bounded* relative target is left to the classifier on purpose: `chmod -R
|
|
32
|
+
* 777 ./dist` is untidy, not unbounded, and refusing it would be the false
|
|
33
|
+
* denial that makes an operator turn this mode off.
|
|
34
|
+
*
|
|
35
|
+
* Judged on every command line inside the input, via the same `flattenCommand`
|
|
36
|
+
* the deny rules use: reading one normalisation while those read another is how
|
|
37
|
+
* a guard fires on one spelling and not on its twin.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import { flattenCommand } from '../core/permission-rules'
|
|
41
|
+
|
|
42
|
+
export type WorldWritableChmodKind =
|
|
43
|
+
/** The target is an absolute path: `chmod -R 777 /tmp/shared`. */
|
|
44
|
+
| 'absolute'
|
|
45
|
+
/** The target is anchored to the home directory: `chmod -R 777 ~/shared`. */
|
|
46
|
+
| 'home'
|
|
47
|
+
/** The target is a shell variable: `chmod -R 777 $DIR`. */
|
|
48
|
+
| 'variable'
|
|
49
|
+
/** The target is led by command-substitution output: `chmod -R 777 "$(pwd)"`. */
|
|
50
|
+
| 'substitution'
|
|
51
|
+
/** The target climbs out of the directory the command runs in: `chmod -R 777 ../shared`. */
|
|
52
|
+
| 'parent'
|
|
53
|
+
|
|
54
|
+
export interface WorldWritableChmod {
|
|
55
|
+
kind: WorldWritableChmodKind
|
|
56
|
+
/** The offending target, with its surrounding quotes stripped. */
|
|
57
|
+
target: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Strip one layer of matching quotes — `"$(pwd)"` and `$(pwd)` are one target. */
|
|
61
|
+
function stripQuotes(s: string): string {
|
|
62
|
+
if (s.length < 2) return s
|
|
63
|
+
const first = s[0]
|
|
64
|
+
const last = s[s.length - 1]
|
|
65
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) return s.slice(1, -1)
|
|
66
|
+
return s
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Split a command segment into operands, keeping a quoted run or a `$(…)`
|
|
71
|
+
* substitution whole.
|
|
72
|
+
*
|
|
73
|
+
* Plain whitespace splitting fails in the direction that matters:
|
|
74
|
+
* `chmod -R 777 "$(git rev-parse --show-toplevel)"` tokenises to `['"$(git', …]`,
|
|
75
|
+
* so the target never reads as a substitution at all, and the cases this guard
|
|
76
|
+
* exists to catch are exactly the ones containing spaces.
|
|
77
|
+
*/
|
|
78
|
+
function splitOperands(segment: string): string[] {
|
|
79
|
+
const out: string[] = []
|
|
80
|
+
const re = /"(?:[^"\\]|\\.)*"|'[^']*'|\$\([^)]*\)|`[^`]*`|\S+/g
|
|
81
|
+
let match: RegExpExecArray | null
|
|
82
|
+
while ((match = re.exec(segment)) !== null) out.push(match[0])
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* True for a `chmod` invocation carrying a recursive flag.
|
|
88
|
+
*
|
|
89
|
+
* `-R` is the recursive one; lowercase `-r` is not (for `chmod` it removes read
|
|
90
|
+
* permission). A combined cluster (`-Rv`) counts, and so does `--recursive`; a
|
|
91
|
+
* bare `--` is an end-of-options separator, not a flag in this sense.
|
|
92
|
+
*/
|
|
93
|
+
function isRecursiveChmod(tokens: string[]): boolean {
|
|
94
|
+
if (tokens[0] !== 'chmod') return false
|
|
95
|
+
return tokens.slice(1).some((t) => {
|
|
96
|
+
if (t === '--recursive') return true
|
|
97
|
+
return /^-[A-Za-z]+$/.test(t) && t.includes('R')
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* True when the mode token grants write permission to "other" (or to all).
|
|
103
|
+
*
|
|
104
|
+
* Octal is judged by its last digit — the "other" triad — so `777`, `776` and
|
|
105
|
+
* `707` all count and `755` and `775` do not. Symbolic clauses are judged by
|
|
106
|
+
* their *operator*: `o+w` and `o=rwx` grant, while `o-w` and `go-w` take away,
|
|
107
|
+
* and `u+w` is nobody's business. A clause with no who-part (`+w`) means all.
|
|
108
|
+
*/
|
|
109
|
+
function grantsWorldWrite(mode: string): boolean {
|
|
110
|
+
if (/^[0-7]{3,4}$/.test(mode)) {
|
|
111
|
+
return '2367'.includes(mode[mode.length - 1]!)
|
|
112
|
+
}
|
|
113
|
+
for (const clause of mode.split(',')) {
|
|
114
|
+
const parsed = /^([ugoa]*)((?:[+-=][rwxXst]*)+)$/.exec(clause)
|
|
115
|
+
if (!parsed) continue
|
|
116
|
+
const who = parsed[1]!
|
|
117
|
+
if (who !== '' && !/[oa]/.test(who)) continue
|
|
118
|
+
for (const op of parsed[2]!.match(/[+-=][rwxXst]*/g) ?? []) {
|
|
119
|
+
if ((op[0] === '+' || op[0] === '=') && op.includes('w')) return true
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return false
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Which unbounded shape (if any) this target has.
|
|
127
|
+
*
|
|
128
|
+
* Anything else is a relative path that names its own landing place, which is
|
|
129
|
+
* the ordinary case this must not refuse.
|
|
130
|
+
*/
|
|
131
|
+
function classifyTarget(raw: string): WorldWritableChmodKind | null {
|
|
132
|
+
const target = stripQuotes(raw)
|
|
133
|
+
if (target.startsWith('$(') || target.startsWith('`')) return 'substitution'
|
|
134
|
+
if (target.startsWith('$')) return 'variable'
|
|
135
|
+
if (target.startsWith('~')) return 'home'
|
|
136
|
+
if (target.startsWith('/')) return 'absolute'
|
|
137
|
+
if (target === '..' || target.startsWith('../')) return 'parent'
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Return the first unbounded recursive-world-writable `chmod` target, or `null`. */
|
|
142
|
+
export function detectWorldWritableChmod(command: string): WorldWritableChmod | null {
|
|
143
|
+
for (const segment of flattenCommand(command)) {
|
|
144
|
+
const tokens = splitOperands(segment)
|
|
145
|
+
if (!isRecursiveChmod(tokens)) continue
|
|
146
|
+
// Flags may sit on either side of the mode, so both are read off the
|
|
147
|
+
// non-flag operands: the first is the mode, the rest are targets.
|
|
148
|
+
const operands = tokens.slice(1).filter((t) => !t.startsWith('-'))
|
|
149
|
+
const mode = operands[0]
|
|
150
|
+
if (!mode || !grantsWorldWrite(mode)) continue
|
|
151
|
+
for (const raw of operands.slice(1)) {
|
|
152
|
+
const kind = classifyTarget(raw)
|
|
153
|
+
if (kind) return { kind, target: stripQuotes(raw) }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
@@ -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.13' 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 = 3879 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 {
|
|
@@ -1,5 +1,35 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
2
3
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
4
|
+
import { MIPHAM_DIR } from '../../shared/constants.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Newest `plan-*.md` under `<cwd>/.mipham/plans/`, or null when there is none.
|
|
8
|
+
*
|
|
9
|
+
* This backs the `planFile` parameter's documented default. Without it the
|
|
10
|
+
* docstring promised a fallback the body never performed (`planFile || ''`), so an
|
|
11
|
+
* omission read as "use the most recent plan" and quietly produced no plan at all.
|
|
12
|
+
*/
|
|
13
|
+
function mostRecentPlanFile(cwd: string): string | null {
|
|
14
|
+
const dir = join(cwd, MIPHAM_DIR, 'plans')
|
|
15
|
+
let names: string[]
|
|
16
|
+
try {
|
|
17
|
+
names = readdirSync(dir).filter((n) => n.startsWith('plan-') && n.endsWith('.md'))
|
|
18
|
+
} catch {
|
|
19
|
+
return null // no plans directory — nothing to fall back to
|
|
20
|
+
}
|
|
21
|
+
let newest: { path: string; mtime: number } | null = null
|
|
22
|
+
for (const name of names) {
|
|
23
|
+
const path = join(dir, name)
|
|
24
|
+
try {
|
|
25
|
+
const mtime = statSync(path).mtimeMs
|
|
26
|
+
if (!newest || mtime > newest.mtime) newest = { path, mtime }
|
|
27
|
+
} catch {
|
|
28
|
+
// Unreadable entry — not a fallback candidate.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return newest?.path ?? null
|
|
32
|
+
}
|
|
3
33
|
|
|
4
34
|
export const exitPlanModeTool: ToolDefinition = {
|
|
5
35
|
name: 'ExitPlanMode',
|
|
@@ -21,27 +51,37 @@ export const exitPlanModeTool: ToolDefinition = {
|
|
|
21
51
|
},
|
|
22
52
|
required: [],
|
|
23
53
|
},
|
|
24
|
-
async execute(params,
|
|
25
|
-
const planFile = (params.planFile as string) || ''
|
|
54
|
+
async execute(params, ctx) {
|
|
55
|
+
const planFile = (params.planFile as string) || mostRecentPlanFile(ctx.cwd) || ''
|
|
26
56
|
|
|
27
57
|
// Try to read the plan to confirm it exists
|
|
28
58
|
let planContent = ''
|
|
59
|
+
let readError = ''
|
|
29
60
|
try {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
planContent = readFileSync(planPath, 'utf-8')
|
|
61
|
+
if (planFile) {
|
|
62
|
+
planContent = readFileSync(planFile, 'utf-8')
|
|
33
63
|
}
|
|
34
|
-
} catch {
|
|
35
|
-
|
|
64
|
+
} catch (err) {
|
|
65
|
+
readError = err instanceof Error ? err.message : String(err)
|
|
36
66
|
}
|
|
37
67
|
|
|
68
|
+
// Say which of the three states we are actually in. The old text asserted
|
|
69
|
+
// "Plan file saved" unconditionally, so a missing or unreadable plan still read
|
|
70
|
+
// as success and the model would present a plan it never retrieved.
|
|
71
|
+
const planStatus = planContent
|
|
72
|
+
? '✓ Plan file read. Present your plan to the user now.'
|
|
73
|
+
: planFile
|
|
74
|
+
? `⚠️ Plan file not readable (${planFile}): ${readError}`
|
|
75
|
+
: '⚠️ No plan file found — present the plan from your own context.'
|
|
76
|
+
|
|
38
77
|
return {
|
|
39
78
|
success: true,
|
|
40
79
|
content: [
|
|
41
80
|
'── Plan Ready for Review ──',
|
|
42
81
|
'',
|
|
43
82
|
'✓ Exiting plan mode.',
|
|
44
|
-
|
|
83
|
+
planStatus,
|
|
84
|
+
planFile ? `Plan file: ${planFile}` : '',
|
|
45
85
|
'',
|
|
46
86
|
'⚠️ IMPORTANT: You are still in limited permission mode.',
|
|
47
87
|
' The user must explicitly approve before you can make changes.',
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -439,8 +439,24 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
439
439
|
timedOut = true
|
|
440
440
|
killProcessGroup(proc.pid)
|
|
441
441
|
}, timeout)
|
|
442
|
+
|
|
443
|
+
// Cancellation. The turn's signal used to stop at the approval prompt and the
|
|
444
|
+
// model stream, so a long-running command had no way to be stopped: nothing
|
|
445
|
+
// it received ever changed. Abort has to reach the process group, or Escape
|
|
446
|
+
// kills the turn while the command keeps writing to the user's disk.
|
|
447
|
+
let aborted = false
|
|
448
|
+
const onAbort = () => {
|
|
449
|
+
aborted = true
|
|
450
|
+
killProcessGroup(proc.pid)
|
|
451
|
+
}
|
|
452
|
+
if (ctx.signal) {
|
|
453
|
+
if (ctx.signal.aborted) onAbort()
|
|
454
|
+
else ctx.signal.addEventListener('abort', onAbort, { once: true })
|
|
455
|
+
}
|
|
456
|
+
|
|
442
457
|
const exitCode = await proc.exited
|
|
443
458
|
clearTimeout(timer)
|
|
459
|
+
ctx.signal?.removeEventListener('abort', onAbort)
|
|
444
460
|
|
|
445
461
|
// The shell is gone, so only a pipe-holding descendant can still be
|
|
446
462
|
// holding these up. Released by the group kill, at most once.
|
|
@@ -493,12 +509,21 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
493
509
|
return {
|
|
494
510
|
success: false,
|
|
495
511
|
content: errorContent,
|
|
496
|
-
error:
|
|
497
|
-
? `Command
|
|
498
|
-
:
|
|
512
|
+
error: aborted
|
|
513
|
+
? `Command cancelled (SIGKILL to its process group)`
|
|
514
|
+
: timedOut
|
|
515
|
+
? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
|
|
516
|
+
: `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
|
|
499
517
|
}
|
|
500
518
|
}
|
|
501
519
|
|
|
520
|
+
// An aborted command may also exit 0 (SIGKILL raced the natural exit). Report
|
|
521
|
+
// the cancellation either way, so a half-finished command is never handed back
|
|
522
|
+
// as a clean success.
|
|
523
|
+
if (aborted) {
|
|
524
|
+
return { success: false, content: output.slice(0, 5_000), error: 'Command cancelled' }
|
|
525
|
+
}
|
|
526
|
+
|
|
502
527
|
let successContent = output.slice(0, 100_000) || '(no output)'
|
|
503
528
|
if (violations.length > 0) {
|
|
504
529
|
successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
package/src/tools/index.ts
CHANGED
|
@@ -74,7 +74,13 @@ export function createToolRegistry(
|
|
|
74
74
|
sendMessageTool,
|
|
75
75
|
listAgentsTool,
|
|
76
76
|
// Network tools
|
|
77
|
-
|
|
77
|
+
// `MIPHAM_DISABLE_WEB_FETCH=1` removes WebFetch from the registry entirely, so
|
|
78
|
+
// it is never advertised to the model. A `permissionRules.deny: ["WebFetch"]`
|
|
79
|
+
// reaches the same endpoint by a different mechanism — the tool is still listed
|
|
80
|
+
// in the schema and only rejected when called, which costs a wasted turn (and a
|
|
81
|
+
// perplexed model) before the refusal lands. An env kill-switch has to act at
|
|
82
|
+
// registration, not at call time.
|
|
83
|
+
...(process.env.MIPHAM_DISABLE_WEB_FETCH === '1' ? [] : [webFetchTool]),
|
|
78
84
|
webSearchTool,
|
|
79
85
|
// System tools
|
|
80
86
|
mcpTool,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
2
|
+
import { PACKAGE_VERSION } from '../../shared/package-info'
|
|
2
3
|
import { validateUrl } from '../../security/url'
|
|
3
4
|
|
|
4
5
|
// ── In-memory cache (15-min TTL per URL) ──
|
|
@@ -195,7 +196,7 @@ export const webFetchTool: ToolDefinition = {
|
|
|
195
196
|
for (let hop = 0; hop <= 5; hop++) {
|
|
196
197
|
response = await fetch(currentUrl, {
|
|
197
198
|
headers: {
|
|
198
|
-
'User-Agent':
|
|
199
|
+
'User-Agent': `Mipham-Code/${PACKAGE_VERSION}`,
|
|
199
200
|
Accept: 'text/html,application/xhtml+xml,*/*',
|
|
200
201
|
},
|
|
201
202
|
redirect: 'manual',
|
package/src/ui/chat.tsx
CHANGED
|
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react'
|
|
|
2
2
|
import { Box, Text } from 'ink'
|
|
3
3
|
import { useI18n } from '../i18n-context'
|
|
4
4
|
import type { ChatMessage } from './app'
|
|
5
|
+
import { decodeDisplayEntities } from '../shared/sanitize'
|
|
5
6
|
import { homedir } from 'node:os'
|
|
6
7
|
|
|
7
8
|
interface ChatPanelProps {
|
|
@@ -93,7 +94,7 @@ const MessageRow = React.memo(
|
|
|
93
94
|
⚠ {t('ui.system.role_label')}:
|
|
94
95
|
</Text>
|
|
95
96
|
) : null}
|
|
96
|
-
<Text>{msg.content}</Text>
|
|
97
|
+
<Text>{msg.toolMeta ? msg.content : decodeDisplayEntities(msg.content)}</Text>
|
|
97
98
|
</>
|
|
98
99
|
)}
|
|
99
100
|
</Box>
|
package/src/ui/commands.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { QueryEngine } from '../core/engine'
|
|
8
8
|
import type { MiphamConfig } from '../shared/index.ts'
|
|
9
9
|
import { formatContextWindow } from '../shared/format'
|
|
10
|
+
import { sanitizeInlineField } from '../shared/sanitize'
|
|
10
11
|
import type { SkillsLoader } from '../skills/loader'
|
|
11
12
|
import { loadSkillUsage } from '../skills/usage'
|
|
12
13
|
import type { PluginManager } from '../plugin/plugin-manager'
|
|
@@ -4948,7 +4949,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
4948
4949
|
const config = mcpServers.find((s) => s.name === name)
|
|
4949
4950
|
if (!config) {
|
|
4950
4951
|
return {
|
|
4951
|
-
content: `Server "${name}" not found in config.\n\nConfigured: ${mcpServers.map((s) => s.name).join(', ') || '(none)'}`,
|
|
4952
|
+
content: `Server "${sanitizeInlineField(name)}" not found in config.\n\nConfigured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ') || '(none)'}`,
|
|
4952
4953
|
}
|
|
4953
4954
|
}
|
|
4954
4955
|
if (config.auth?.type === 'oauth') {
|
|
@@ -4968,7 +4969,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
4968
4969
|
const headerKeys = config.headers ? Object.keys(config.headers) : []
|
|
4969
4970
|
const headerLine = headerKeys.length > 0 ? `\nHeaders to send: ${headerKeys.join(', ')}` : ''
|
|
4970
4971
|
return {
|
|
4971
|
-
content: `── MCP Connect: ${name} ──\n\nConnecting via HTTP\nURL: ${config.url}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
|
|
4972
|
+
content: `── MCP Connect: ${sanitizeInlineField(name)} ──\n\nConnecting via HTTP\nURL: ${sanitizeInlineField(config.url)}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
|
|
4972
4973
|
forwardToAI: `Connect to MCP server "${name}" using McpClient.getInstance().connect(config), then register its tools. Report the result.`,
|
|
4973
4974
|
}
|
|
4974
4975
|
}
|
|
@@ -5058,15 +5059,15 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
5058
5059
|
: '⚪'
|
|
5059
5060
|
const statusLabel = live ? live.status : 'not started'
|
|
5060
5061
|
const oauthTag = s.auth?.type === 'oauth' ? ' [OAuth]' : ''
|
|
5061
|
-
lines.push(` ${statusIcon} ${s.name}${oauthTag} [${statusLabel}]`)
|
|
5062
|
+
lines.push(` ${statusIcon} ${sanitizeInlineField(s.name)}${oauthTag} [${statusLabel}]`)
|
|
5062
5063
|
const transportInfo = s.url
|
|
5063
|
-
? `URL: ${s.url}`
|
|
5064
|
-
: `Command: ${s.command ?? ''} ${(s.args ?? []).join(' ')}`
|
|
5064
|
+
? `URL: ${sanitizeInlineField(s.url)}`
|
|
5065
|
+
: `Command: ${sanitizeInlineField(s.command ?? '')} ${(s.args ?? []).map(sanitizeInlineField).join(' ')}`
|
|
5065
5066
|
lines.push(` ${transportInfo}`)
|
|
5066
5067
|
if (live?.tools && live.tools.length > 0) {
|
|
5067
5068
|
lines.push(` Tools: ${live.tools.length} registered`)
|
|
5068
5069
|
}
|
|
5069
|
-
if (live?.error) lines.push(` Error: ${live.error}`)
|
|
5070
|
+
if (live?.error) lines.push(` Error: ${sanitizeInlineField(live.error)}`)
|
|
5070
5071
|
lines.push('')
|
|
5071
5072
|
}
|
|
5072
5073
|
} else {
|