@miphamai/cli 0.85.16 → 0.85.18
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 +7 -0
- package/src/config/defaults.ts +6 -1
- package/src/core/credential-masker/output-scrub.ts +8 -1
- package/src/core/engine.ts +43 -4
- package/src/core/instructions.ts +20 -1
- package/src/core/permission-rules.ts +52 -4
- package/src/core/permission.ts +6 -2
- package/src/core/session-log.ts +10 -0
- package/src/i18n-core/locales/en-US.json +1 -1
- package/src/i18n-core/locales/zh-CN.json +1 -1
- package/src/index.tsx +22 -1
- package/src/mcp/client.ts +20 -1
- package/src/mcp/http-transport.ts +48 -3
- package/src/providers/anthropic.ts +47 -12
- package/src/providers/fetch-utils.ts +48 -3
- package/src/providers/openai-compat.ts +13 -10
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +14 -3
- package/src/shared/types.ts +12 -0
- package/src/skills/loader.ts +13 -2
- package/src/skills/sanitizer.ts +16 -8
- package/src/tools/artifact/artifact.ts +9 -9
- package/src/tools/file/read.ts +21 -0
- package/src/tools/network/web-fetch.ts +87 -22
- package/src/tools/scheduling/schedule-wakeup.ts +156 -32
- package/src/ui/app.tsx +46 -5
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.18
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 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
package/src/agent/sub-agent.ts
CHANGED
|
@@ -491,6 +491,13 @@ export class SubAgent {
|
|
|
491
491
|
// (`ui/app.tsx`) and the experience logs below: the definition's name, else
|
|
492
492
|
// the type.
|
|
493
493
|
agentName: agentDef?.name || agentType,
|
|
494
|
+
// Artifacts need a bucket of their own. `sessionId` is the shared literal
|
|
495
|
+
// 'sub-agent' (kept — `SendMessage` addresses the parent off it), so every
|
|
496
|
+
// sub-agent in every session would file artifacts in one directory and
|
|
497
|
+
// `archiveVersion` would treat another agent's same-named artifact as the
|
|
498
|
+
// "previous version" of this one. Parent session plus this agent's name
|
|
499
|
+
// keeps two agents apart without touching the messaging contract.
|
|
500
|
+
artifactSessionId: `${options.toolContext?.sessionId ?? 'main'}:sub:${agentDef?.name || agentType}`,
|
|
494
501
|
}
|
|
495
502
|
|
|
496
503
|
try {
|
package/src/config/defaults.ts
CHANGED
|
@@ -72,8 +72,13 @@ export const DEFAULT_CREDENTIAL_MASKING_CONFIG: CredentialMaskingConfig = {
|
|
|
72
72
|
// 名字那一段:`_key` 出现在标识符**中间**也算(`AWS_ACCESS_KEY_ID=…`),但**不许吞掉
|
|
73
73
|
// 词后面的字符** —— 否则 `"keys": […]`、`total tokens: 1234` 这类**不是秘密**的输出
|
|
74
74
|
// 会被整段擦掉。中间那对引号可选,为的是 JSON 形状的 `"apiKey": "…"`。
|
|
75
|
+
//
|
|
76
|
+
// 环绕 `[_-]key` 的两段量词**有界**(`{0,64}`),且这个界是承重的,不是装饰。无界的
|
|
77
|
+
// `[A-Za-z0-9_.-]*` 后面跟着必须匹配的 `[_-]key` 时,在一段没有 `_` 的长串(`keykey…`、
|
|
78
|
+
// 一段长 token)上会在每个起点回溯扫过整条尾巴,退化成 O(n²)(实测 16k 字符 ~2.2s,
|
|
79
|
+
// 每翻倍 ×4)。真实标识符名字远到不了 64 字符,加界零代价,却让每个起点的扫描变成线性。
|
|
75
80
|
patterns: [
|
|
76
|
-
'(?i)(api[_-]?key|[A-Za-z0-9_.-]
|
|
81
|
+
'(?i)(api[_-]?key|[A-Za-z0-9_.-]{0,64}[_-]key[A-Za-z0-9_.-]{0,64}|secret|token|password|credential|[_-]pat)["\']?\\s*[:=]\\s*["\']?\\S+',
|
|
77
82
|
],
|
|
78
83
|
},
|
|
79
84
|
env_filter: {
|
|
@@ -25,7 +25,14 @@ const TOKEN_REDACTION_PATTERN =
|
|
|
25
25
|
// *first* `@`, redacting only `p` and leaving `ss@host` in the clear. Greedy
|
|
26
26
|
// `[^/\s]+` runs to the last `@` on the line and backtracks, so the whole password
|
|
27
27
|
// goes and the host survives.
|
|
28
|
-
|
|
28
|
+
//
|
|
29
|
+
// The scheme's `*` is **bounded** (`{0,63}`), and that bound is load-bearing, not
|
|
30
|
+
// cosmetic. An unbounded `[a-z0-9+.-]*` followed by a required `://` re-scans the
|
|
31
|
+
// whole tail from every start position on a long run with no `://` (minified JS,
|
|
32
|
+
// base64, a long token — none of which contain `://`), giving O(n²) behaviour:
|
|
33
|
+
// measured ~2.5 s at 40 k chars, ×4 per doubling. No real scheme name approaches
|
|
34
|
+
// 63 chars, so the bound costs nothing and makes the scan linear per position.
|
|
35
|
+
const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]{0,63}:\/\/)([^/\s:@]+):([^/\s]+)@/gi
|
|
29
36
|
|
|
30
37
|
/**
|
|
31
38
|
* Zero-width and formatting characters stripped before anything is matched.
|
package/src/core/engine.ts
CHANGED
|
@@ -608,6 +608,16 @@ export class QueryEngine {
|
|
|
608
608
|
// Add user message to context
|
|
609
609
|
this.context.addMessage({ role: 'user', content: userInput })
|
|
610
610
|
|
|
611
|
+
// ── Restore point for `/rewind` ──
|
|
612
|
+
// Taken **here** — the prompt is in history, none of the reply is. That is what
|
|
613
|
+
// makes `/rewind` ("Undo last AI turn") mean what it says: the prompt survives,
|
|
614
|
+
// the answer and its tool results go. A checkpoint taken at the *end* of a turn
|
|
615
|
+
// already contains that turn's reply, so restoring it is a no-op and nothing
|
|
616
|
+
// but an older turn is reachable. One site covers every entry point — the TUI,
|
|
617
|
+
// `/loop` turns, goal mode (`processWithGoal` delegates here) and daemon
|
|
618
|
+
// sessions — so no caller can be the one that forgot.
|
|
619
|
+
this.context.saveCheckpoint('pre-turn')
|
|
620
|
+
|
|
611
621
|
// Check compaction before processing
|
|
612
622
|
if (this.context.needsCompaction()) {
|
|
613
623
|
await this.compactWithHooks('conversation summary')
|
|
@@ -971,12 +981,20 @@ export class QueryEngine {
|
|
|
971
981
|
): AsyncGenerator<StreamChunk> {
|
|
972
982
|
// Task-level stall guard: a turn that produces no text or tool result for
|
|
973
983
|
// this long is considered stalled and stopped (prevents ~40-min idle spins).
|
|
984
|
+
//
|
|
985
|
+
// The clock is `performance.now()` (monotonic, and it does not advance while
|
|
986
|
+
// the machine is suspended) rather than `Date.now()` (wall clock). A laptop
|
|
987
|
+
// that sleeps mid-turn jumps the wall clock forward by the whole nap, which
|
|
988
|
+
// reads as "no activity for 8 hours" and kills a turn that was never stalled
|
|
989
|
+
// — the failure shows up as a spurious timeout, exactly when the user
|
|
990
|
+
// returns to their desk.
|
|
974
991
|
const TURN_TIMEOUT_MS = 15 * 60 * 1000
|
|
975
|
-
|
|
992
|
+
const monotonicNow = (): number => performance.now()
|
|
993
|
+
let lastActivity = monotonicNow()
|
|
976
994
|
const toolDefs = this.getToolDefinitions()
|
|
977
995
|
|
|
978
996
|
for (let turn = 0; turn < roundsLeft; turn++) {
|
|
979
|
-
if (
|
|
997
|
+
if (monotonicNow() - lastActivity > TURN_TIMEOUT_MS) {
|
|
980
998
|
yield {
|
|
981
999
|
type: 'warning',
|
|
982
1000
|
content: t('errors.turn_timeout', {
|
|
@@ -1038,7 +1056,7 @@ export class QueryEngine {
|
|
|
1038
1056
|
if (chunk.type === 'text' && chunk.content) {
|
|
1039
1057
|
assistantContent += chunk.content
|
|
1040
1058
|
this.context.recordChunk(chunk.content)
|
|
1041
|
-
lastActivity =
|
|
1059
|
+
lastActivity = monotonicNow()
|
|
1042
1060
|
}
|
|
1043
1061
|
|
|
1044
1062
|
if (chunk.reasoning_content) {
|
|
@@ -1138,7 +1156,7 @@ export class QueryEngine {
|
|
|
1138
1156
|
for (const toolUse of toolUses) {
|
|
1139
1157
|
const result = await this.executeTool(toolUse.name, toolUse.input, signal)
|
|
1140
1158
|
if (!result.success) this.pendingToolFailure = true
|
|
1141
|
-
lastActivity =
|
|
1159
|
+
lastActivity = monotonicNow()
|
|
1142
1160
|
yield {
|
|
1143
1161
|
type: 'tool_result',
|
|
1144
1162
|
tool_use_id: toolUse.id,
|
|
@@ -1353,6 +1371,27 @@ export class QueryEngine {
|
|
|
1353
1371
|
}
|
|
1354
1372
|
}
|
|
1355
1373
|
|
|
1374
|
+
// The gate at the top of this method ruled on `params`. Everything since —
|
|
1375
|
+
// the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
|
|
1376
|
+
// SIS preflight `fix` — can rewrite the params the tool actually receives
|
|
1377
|
+
// (`effectiveParams`), and the tool runs on those. A gate that ruled on input
|
|
1378
|
+
// X must not stand as the gate for input Y: a repository-supplied hook could
|
|
1379
|
+
// pass a benign call and swap in a destructive one *after* the check, and the
|
|
1380
|
+
// substitution would never be re-judged. Whenever any stage changed the
|
|
1381
|
+
// params, run the same approval resolution again on what will actually run.
|
|
1382
|
+
// (This mirrors the correct order in `agent/sub-agent.ts`: hook → apply
|
|
1383
|
+
// `modifiedInput` → resolve approval on the effective input.)
|
|
1384
|
+
if (effectiveParams !== params) {
|
|
1385
|
+
const recheck = await this.permission.resolveApproval(tool, effectiveParams, { signal })
|
|
1386
|
+
if (recheck.level === 'ask') {
|
|
1387
|
+
return {
|
|
1388
|
+
success: false,
|
|
1389
|
+
content: '',
|
|
1390
|
+
error: this.buildDenialError(name, tool, effectiveParams, recheck),
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1356
1395
|
try {
|
|
1357
1396
|
// Every tool is handed the session's working directory, and that directory
|
|
1358
1397
|
// can be deleted while the session runs. Nothing upstream notices: Node
|
package/src/core/instructions.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync, existsSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, existsSync, lstatSync } from 'node:fs'
|
|
2
2
|
import { join, resolve, relative, sep, isAbsolute } from 'node:path'
|
|
3
3
|
import { execSync } from 'node:child_process'
|
|
4
4
|
import { parse as parseYaml } from 'yaml'
|
|
@@ -547,6 +547,25 @@ Never omit it or present the work as purely human-authored.`)
|
|
|
547
547
|
private tryLoad(path: string, level: InstructionFile['level']): void {
|
|
548
548
|
if (!existsSync(path)) return
|
|
549
549
|
|
|
550
|
+
// A repo-controlled instruction file must be a regular file, not a symlink.
|
|
551
|
+
// A cloned repository can ship `CLAUDE.md -> ~/.ssh/id_rsa`: this loader runs
|
|
552
|
+
// with no permission gate at all, so following the link would put any local
|
|
553
|
+
// file into the system prompt without the model ever asking for it. `lstat`
|
|
554
|
+
// reports the link as itself, which is what makes the shape visible.
|
|
555
|
+
//
|
|
556
|
+
// Only the levels that live *inside* the checkout (`project`, `directory`)
|
|
557
|
+
// are gated. A symlinked `~/.mipham/USER.md` pointing at a dotfiles repo is
|
|
558
|
+
// the user's own arrangement, and the group/company tiers point at the
|
|
559
|
+
// surrounding monorepo the user cloned deliberately — refusing those would
|
|
560
|
+
// break real setups without closing anything a repo did not already control.
|
|
561
|
+
if (level === 'project' || level === 'directory') {
|
|
562
|
+
try {
|
|
563
|
+
if (lstatSync(path).isSymbolicLink()) return
|
|
564
|
+
} catch {
|
|
565
|
+
return
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
550
569
|
try {
|
|
551
570
|
const raw = readFileSync(path, 'utf-8')
|
|
552
571
|
const { data, content } = parseFrontmatter(raw)
|
|
@@ -202,7 +202,19 @@ function stripQuotes(s: string): string {
|
|
|
202
202
|
/** Shell 结构符号:分组与取反 —— 它们自身不是命令,紧跟其后的是。 */
|
|
203
203
|
const LEADING_SHELL_PUNCT = new Set(['(', '{', '!'])
|
|
204
204
|
|
|
205
|
-
/**
|
|
205
|
+
/**
|
|
206
|
+
* Shell 关键字:其后才是真正的命令(`do rm -rf x` 执行的命令是 `rm`)。
|
|
207
|
+
*
|
|
208
|
+
* **`export` / `declare` / `readonly` / `typeset` 刻意不在表里**,尽管它们同样出现在
|
|
209
|
+
* 命令前。区别在语义:一条裸赋值把这段环境交给**后面的命令**,而这四个是 bash 内建
|
|
210
|
+
* **命令本身**,其后的词全是它的参数 —— `export FOO=1 rm -rf x` 执行的是 `export`,
|
|
211
|
+
* `rm` 一次都不跑(本机实测,用 victim 文件作判据:`X=1 rm -f victim` 删掉了 victim;
|
|
212
|
+
* `export`/`declare`/`readonly`/`typeset` 四种写法 victim 全在,只有 "not a valid
|
|
213
|
+
* identifier" 的报错)。剥掉它们不会补上漏洞,只会让匹配器声称一条**没跑过**的命令
|
|
214
|
+
* 在跑。命令替换形态(`export FOO=$(rm -rf x)`)由 `extractSubstitutions` 覆盖,
|
|
215
|
+
* 与这四个词在不在表里无关。边界用例见 `test/core/permission-rules.test.ts`
|
|
216
|
+
* 「前导赋值的边界」。
|
|
217
|
+
*/
|
|
206
218
|
const LEADING_SHELL_KEYWORDS = new Set([
|
|
207
219
|
'do',
|
|
208
220
|
'then',
|
|
@@ -514,14 +526,34 @@ function scanReaderWriterCommands(
|
|
|
514
526
|
// `sed -i` / `perl -i` read AND write their file args.
|
|
515
527
|
const inPlace = args.some((a) => a === '-i' || a.startsWith('--in-place'))
|
|
516
528
|
for (const arg of args) {
|
|
517
|
-
if (arg.startsWith('-'))
|
|
529
|
+
if (arg.startsWith('-')) {
|
|
530
|
+
// `--include=*secret*` / `--file=.env`: the option VALUE is a path the
|
|
531
|
+
// reader opens, but the `-` guard used to drop the whole token, so a
|
|
532
|
+
// Read() deny rule never saw it. Pull the value after the first `=`
|
|
533
|
+
// and treat it as a path candidate. (`--opt value` needs nothing here
|
|
534
|
+
// — the value is already a separate, non-`-` token handled below.)
|
|
535
|
+
const eq = arg.indexOf('=')
|
|
536
|
+
if (eq === -1) continue
|
|
537
|
+
const v = stripQuotes(arg.slice(eq + 1))
|
|
538
|
+
if (v === '' || v.startsWith('-')) continue
|
|
539
|
+
read.push(v)
|
|
540
|
+
if (inPlace) write.push(v)
|
|
541
|
+
continue
|
|
542
|
+
}
|
|
518
543
|
const p = stripQuotes(arg)
|
|
519
544
|
read.push(p)
|
|
520
545
|
if (inPlace) write.push(p)
|
|
521
546
|
}
|
|
522
547
|
} else if (WRITER_COMMANDS.has(base)) {
|
|
523
548
|
for (const arg of args) {
|
|
524
|
-
if (arg.startsWith('-'))
|
|
549
|
+
if (arg.startsWith('-')) {
|
|
550
|
+
const eq = arg.indexOf('=')
|
|
551
|
+
if (eq === -1) continue
|
|
552
|
+
const v = stripQuotes(arg.slice(eq + 1))
|
|
553
|
+
if (v === '' || v.startsWith('-')) continue
|
|
554
|
+
write.push(v)
|
|
555
|
+
continue
|
|
556
|
+
}
|
|
525
557
|
write.push(stripQuotes(arg))
|
|
526
558
|
}
|
|
527
559
|
}
|
|
@@ -637,7 +669,14 @@ function matchPathRule(path: string, pattern: string, segmentMode: 'any' | 'all'
|
|
|
637
669
|
}
|
|
638
670
|
}
|
|
639
671
|
|
|
640
|
-
|
|
672
|
+
/**
|
|
673
|
+
* A reader/writer argument that still carries shell wildcards is **unresolved**:
|
|
674
|
+
* the shell expands it to a file set the extracted token does not name. Used to
|
|
675
|
+
* fail a deny/ask rule closed rather than let the anchored path match miss it.
|
|
676
|
+
*/
|
|
677
|
+
function hasGlobMeta(path: string): boolean {
|
|
678
|
+
return /[*?[\]]/.test(path)
|
|
679
|
+
}
|
|
641
680
|
//
|
|
642
681
|
// Pattern formats:
|
|
643
682
|
// "Bash" → matches any Bash call
|
|
@@ -684,6 +723,15 @@ export function matchBashRule(
|
|
|
684
723
|
const cmd = String(toolInput.command || '')
|
|
685
724
|
const access = extractBashFileAccess(cmd)
|
|
686
725
|
const paths = baseTool === 'Read' ? access.read : access.write
|
|
726
|
+
// A shell glob in a reader/writer argument expands to an unknown file set —
|
|
727
|
+
// `cat *secret*` reads files the literal argument `*secret*` does not name —
|
|
728
|
+
// so the anchored path match below would miss a `Read(**/secret*)` deny
|
|
729
|
+
// entirely. Fail closed: under deny/ask (`'any'`) an unresolved glob counts
|
|
730
|
+
// as a match (refuse). Under allow (`'all'`) a glob path cannot satisfy a
|
|
731
|
+
// concrete grant anyway, so the grant direction already fails closed. This
|
|
732
|
+
// is deliberately blunt — one extra ask beats reading a file a deny rule was
|
|
733
|
+
// written to protect.
|
|
734
|
+
if (segmentMode !== 'all' && paths.some(hasGlobMeta)) return true
|
|
687
735
|
return qualifies(paths, (p) => matchPathRule(p, subPattern!, segmentMode))
|
|
688
736
|
}
|
|
689
737
|
|
package/src/core/permission.ts
CHANGED
|
@@ -47,8 +47,12 @@ function isVerificationCommand(input: Record<string, unknown>): boolean {
|
|
|
47
47
|
const cmd = (input.command as string) || ''
|
|
48
48
|
// A verification command must be a single simple command — any shell
|
|
49
49
|
// metacharacter (&&, ;, |, >, <, backtick, $) means it can chain a destructive
|
|
50
|
-
// action (e.g. `cat x && rm -rf ~`), so never auto-approve it.
|
|
51
|
-
|
|
50
|
+
// action (e.g. `cat x && rm -rf ~`), so never auto-approve it. A shell
|
|
51
|
+
// wildcard (`*`, `?`, `[`, `]`) is refused for the same reason: the shell
|
|
52
|
+
// expands it to a file set the rule-matcher never saw, so `cat *secret*` is
|
|
53
|
+
// not `cat secret` — auto-approving it would read files a `Read(...)` rule
|
|
54
|
+
// means to protect.
|
|
55
|
+
if (/[;&|><`$*?\[\]]/.test(cmd)) return false
|
|
52
56
|
// Patterns for verification-only commands (no side effects on codebase)
|
|
53
57
|
const verifyPatterns = [
|
|
54
58
|
/\bpnpm\s+test\b/, // test runner
|
package/src/core/session-log.ts
CHANGED
|
@@ -14,6 +14,16 @@ export type SessionEvent =
|
|
|
14
14
|
provider?: string
|
|
15
15
|
model?: string
|
|
16
16
|
cwd?: string
|
|
17
|
+
/**
|
|
18
|
+
* The permission mode this session started in.
|
|
19
|
+
*
|
|
20
|
+
* Not reconstructible from the transcript: the same tool call appears in
|
|
21
|
+
* the log whether it was auto-approved or approved by hand, so a resumed
|
|
22
|
+
* session could not tell which gate it was running under. Recorded here so
|
|
23
|
+
* `--resume` can put the mode back instead of silently dropping to the
|
|
24
|
+
* config default (plan mode in particular was lost on every resume).
|
|
25
|
+
*/
|
|
26
|
+
permissionMode?: string
|
|
17
27
|
}
|
|
18
28
|
| { type: 'user/message'; at: number; message: Message }
|
|
19
29
|
| { type: 'assistant/message'; at: number; message: Message }
|
|
@@ -930,7 +930,7 @@
|
|
|
930
930
|
"tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
|
|
931
931
|
"tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
|
|
932
932
|
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\") Treat this denial as covering the outcome, not only this exact command.",
|
|
933
|
-
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule
|
|
933
|
+
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool. Treat this denial as covering the outcome, not only this exact command.",
|
|
934
934
|
"tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
935
935
|
"tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
936
936
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
@@ -930,7 +930,7 @@
|
|
|
930
930
|
"tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
|
|
931
931
|
"tool_denied_ask_rule": "工具 \"{name}\" 需要批准(ask 规则:\"{pattern}\")。请在提示时批准,或不再询问:/permissions allow \"{pattern}\"",
|
|
932
932
|
"tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可) 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
933
|
-
"tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 ——
|
|
933
|
+
"tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
934
934
|
"tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
935
935
|
"tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
936
936
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
package/src/index.tsx
CHANGED
|
@@ -570,6 +570,7 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
570
570
|
provider: defaultProvider,
|
|
571
571
|
model: defaultModel,
|
|
572
572
|
cwd: process.cwd(),
|
|
573
|
+
permissionMode: permission.getMode(),
|
|
573
574
|
})
|
|
574
575
|
context.setLog(sessionLog)
|
|
575
576
|
// Cache-aware microcompaction: track the provider's prompt-cache prefix.
|
|
@@ -596,7 +597,7 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
596
597
|
const events = log.events()
|
|
597
598
|
if (events.length > 0) {
|
|
598
599
|
const start = events.find((e) => e.type === 'session/start') as
|
|
599
|
-
{ type: 'session/start'; cwd?: string } | undefined
|
|
600
|
+
{ type: 'session/start'; cwd?: string; permissionMode?: string } | undefined
|
|
600
601
|
if (start?.cwd && existsSync(start.cwd)) {
|
|
601
602
|
try {
|
|
602
603
|
process.chdir(start.cwd)
|
|
@@ -604,6 +605,26 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
604
605
|
// cwd 可能已不存在
|
|
605
606
|
}
|
|
606
607
|
}
|
|
608
|
+
// Put the permission mode back. It is part of what this session *was* —
|
|
609
|
+
// plan mode especially, which is lost on every resume otherwise. An
|
|
610
|
+
// explicit `--permission` on this invocation still wins: that is the
|
|
611
|
+
// operator's word, typed seconds ago, against a value written days ago.
|
|
612
|
+
// The restore is announced whenever it widens away from the configured
|
|
613
|
+
// default, because "the gate you were running under changed" is exactly
|
|
614
|
+
// the kind of difference that must not be silent (same reason a withheld
|
|
615
|
+
// project-level mode is announced above).
|
|
616
|
+
const resumedMode = start?.permissionMode
|
|
617
|
+
if (resumedMode && !options.permission) {
|
|
618
|
+
const before = permission.getMode()
|
|
619
|
+
permission.setDefaultLevel(resumedMode as PermissionLevel)
|
|
620
|
+
const after = permission.getMode()
|
|
621
|
+
if (after !== before) {
|
|
622
|
+
process.stderr.write(
|
|
623
|
+
`⚠ Mipham Code: resumed permission mode "${after}" from this session ` +
|
|
624
|
+
`(was "${before}"). Shift+Tab to change it.\n`,
|
|
625
|
+
)
|
|
626
|
+
}
|
|
627
|
+
}
|
|
607
628
|
context.restoreLog(log)
|
|
608
629
|
context.setSystemPrompt(instructions.buildSystemPrompt())
|
|
609
630
|
}
|
package/src/mcp/client.ts
CHANGED
|
@@ -36,6 +36,24 @@ function connectTimeoutMs(): number {
|
|
|
36
36
|
return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
+
/**
|
|
40
|
+
* Will retrying this connect failure change the answer?
|
|
41
|
+
*
|
|
42
|
+
* A 4xx is the server stating a verdict about *this request* — a rejected token,
|
|
43
|
+
* a path that does not exist, a malformed handshake. It says the same thing on
|
|
44
|
+
* attempt 10 as on attempt 1, so the ten-attempt backoff (~8 minutes) only
|
|
45
|
+
* delays telling the user what is wrong. 408 (request timeout) and 429 (rate
|
|
46
|
+
* limited) are the two 4xx that explicitly mean "try again", so they stay
|
|
47
|
+
* retryable along with everything that is not an HTTP verdict at all (connection
|
|
48
|
+
* refused, DNS, a 5xx).
|
|
49
|
+
*/
|
|
50
|
+
function isTransientConnectError(err: unknown): boolean {
|
|
51
|
+
if (err instanceof McpHttpError) {
|
|
52
|
+
return !(err.status >= 400 && err.status < 500) || err.status === 408 || err.status === 429
|
|
53
|
+
}
|
|
54
|
+
return true
|
|
55
|
+
}
|
|
56
|
+
|
|
39
57
|
/**
|
|
40
58
|
* Render a connect failure for the user, adding the one hint a bare error
|
|
41
59
|
* cannot carry: that the fix is to authenticate.
|
|
@@ -279,7 +297,8 @@ export class McpClient {
|
|
|
279
297
|
this.emit('reconnected', name)
|
|
280
298
|
return
|
|
281
299
|
} catch (err) {
|
|
282
|
-
|
|
300
|
+
// Stop early on a definitive refusal — see `isTransientConnectError`.
|
|
301
|
+
if (!isTransientConnectError(err) || attempt === maxAttempts) {
|
|
283
302
|
connection.status = 'error'
|
|
284
303
|
connection.error = String(err)
|
|
285
304
|
this.emit('disconnected', name, err)
|
|
@@ -106,6 +106,51 @@ function parseSseResponse(
|
|
|
106
106
|
return { content: [{ type: 'text', text: texts.join('') }], isError: false }
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/**
|
|
110
|
+
* Upper bound on a single response body, in bytes.
|
|
111
|
+
*
|
|
112
|
+
* `response.text()` / `.json()` buffer whatever the server sends, so a buggy
|
|
113
|
+
* server (a runaway log line) or a hostile one (an 8 GB "result") would be
|
|
114
|
+
* pulled into memory in full before any comparison could run. The cap has to
|
|
115
|
+
* be part of the read, not a check after it.
|
|
116
|
+
*/
|
|
117
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024
|
|
118
|
+
|
|
119
|
+
/** Read a response body, refusing anything past `maxBytes`. */
|
|
120
|
+
async function readBodyCapped(
|
|
121
|
+
response: Response,
|
|
122
|
+
maxBytes: number = MAX_RESPONSE_BYTES,
|
|
123
|
+
): Promise<string> {
|
|
124
|
+
// A declared Content-Length lets us refuse before reading a single byte.
|
|
125
|
+
const declared = Number(response.headers.get('content-length'))
|
|
126
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
127
|
+
throw new Error(`MCP response body declared ${declared} bytes (limit ${maxBytes})`)
|
|
128
|
+
}
|
|
129
|
+
// Header absent or lying — fall back to a streaming read with a running total.
|
|
130
|
+
if (!response.body) return await response.text()
|
|
131
|
+
|
|
132
|
+
const reader = response.body.getReader()
|
|
133
|
+
const decoder = new TextDecoder()
|
|
134
|
+
let text = ''
|
|
135
|
+
let total = 0
|
|
136
|
+
try {
|
|
137
|
+
for (;;) {
|
|
138
|
+
const { done, value } = await reader.read()
|
|
139
|
+
if (done) break
|
|
140
|
+
if (!value) continue
|
|
141
|
+
total += value.byteLength
|
|
142
|
+
if (total > maxBytes) {
|
|
143
|
+
await reader.cancel().catch(() => {})
|
|
144
|
+
throw new Error(`MCP response body exceeded the ${maxBytes}-byte limit`)
|
|
145
|
+
}
|
|
146
|
+
text += decoder.decode(value, { stream: true })
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
reader.releaseLock()
|
|
150
|
+
}
|
|
151
|
+
return text + decoder.decode()
|
|
152
|
+
}
|
|
153
|
+
|
|
109
154
|
/**
|
|
110
155
|
* MCP Streamable HTTP transport — speaks JSON-RPC 2.0 to an HTTP endpoint
|
|
111
156
|
* (e.g. Forge's `POST /mcp`), returning plain JSON or reassembled SSE streams.
|
|
@@ -183,7 +228,7 @@ export class HttpTransport implements Transport {
|
|
|
183
228
|
if (!response.ok) {
|
|
184
229
|
let detail = `HTTP ${response.status}`
|
|
185
230
|
try {
|
|
186
|
-
detail = JSON.stringify(await response
|
|
231
|
+
detail = JSON.stringify(JSON.parse(await readBodyCapped(response)))
|
|
187
232
|
} catch {
|
|
188
233
|
/* keep status-only detail */
|
|
189
234
|
}
|
|
@@ -197,10 +242,10 @@ export class HttpTransport implements Transport {
|
|
|
197
242
|
|
|
198
243
|
const contentType = response.headers.get('content-type') || ''
|
|
199
244
|
if (contentType.includes('text/event-stream')) {
|
|
200
|
-
return parseSseResponse(await response
|
|
245
|
+
return parseSseResponse(await readBodyCapped(response), (n) => this.dispatchNotification(n))
|
|
201
246
|
}
|
|
202
247
|
|
|
203
|
-
const json = (await response
|
|
248
|
+
const json = JSON.parse(await readBodyCapped(response)) as JsonRpcResponse
|
|
204
249
|
if (json.error) {
|
|
205
250
|
throw new Error(`MCP error ${json.error.code}: ${json.error.message}`)
|
|
206
251
|
}
|
|
@@ -6,7 +6,12 @@ import type {
|
|
|
6
6
|
ContentBlock,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { ProviderInstance, ChatRequest } from './registry'
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
fetchWithRetry,
|
|
11
|
+
streamIdleTimeoutMs,
|
|
12
|
+
isRetryableFailure,
|
|
13
|
+
createAwakeTimer,
|
|
14
|
+
} from './fetch-utils'
|
|
10
15
|
|
|
11
16
|
interface AnthropicContentBlock {
|
|
12
17
|
type: string
|
|
@@ -66,11 +71,43 @@ function isEmptyTextBlock(block: Record<string, unknown>): boolean {
|
|
|
66
71
|
}
|
|
67
72
|
|
|
68
73
|
export class AnthropicProvider implements ProviderInstance {
|
|
69
|
-
private baseUrl = 'https://api.anthropic.com/v1'
|
|
70
74
|
private anthropicVersion = '2023-06-01'
|
|
71
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Honour a user-level `baseUrl` override the way `openai-compat` does.
|
|
78
|
+
*
|
|
79
|
+
* The config loader treats `baseUrl` as a **routing** field — it decides where
|
|
80
|
+
* the user's API key is sent, so only trusted (user-level) config may set it
|
|
81
|
+
* (see `config/loader.ts`). Hard-coding the endpoint here silently dropped that
|
|
82
|
+
* override: a user who pointed the provider at a proxy or gateway still had
|
|
83
|
+
* every request sent to `api.anthropic.com`. Read it, with the official
|
|
84
|
+
* endpoint as the fallback the default config (which sets no `baseUrl`) relies
|
|
85
|
+
* on. `baseURL` is accepted too — the same common typo `openai-compat` allows.
|
|
86
|
+
*/
|
|
87
|
+
private get baseUrl(): string {
|
|
88
|
+
const raw = this.config.baseUrl ?? (this.config as { baseURL?: string }).baseURL
|
|
89
|
+
return raw?.replace(/\/+$/, '') || 'https://api.anthropic.com/v1'
|
|
90
|
+
}
|
|
91
|
+
|
|
72
92
|
constructor(public config: ProviderConfig) {}
|
|
73
93
|
|
|
94
|
+
/**
|
|
95
|
+
* Are we talking to api.anthropic.com itself, or to a custom `baseUrl`?
|
|
96
|
+
*
|
|
97
|
+
* `anthropic-beta` is a header for Anthropic's own gateway. A custom base URL
|
|
98
|
+
* is by definition some other gateway — a proxy, a corporate relay, an
|
|
99
|
+
* Anthropic-compatible shim — and sending a beta flag that gateway does not
|
|
100
|
+
* implement is a way to turn a working setup into `400 Bad Request` the moment
|
|
101
|
+
* the endpoint changes, with nothing in the message pointing at the header.
|
|
102
|
+
*/
|
|
103
|
+
private get isDefaultApiHost(): boolean {
|
|
104
|
+
try {
|
|
105
|
+
return new URL(this.baseUrl).host === 'api.anthropic.com'
|
|
106
|
+
} catch {
|
|
107
|
+
return false
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
74
111
|
async *chat(req: ChatRequest): AsyncGenerator<StreamChunk> {
|
|
75
112
|
const apiKey = this.resolveApiKey(this.config.apiKey)
|
|
76
113
|
|
|
@@ -149,7 +186,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
149
186
|
'Content-Type': 'application/json',
|
|
150
187
|
'x-api-key': apiKey,
|
|
151
188
|
'anthropic-version': this.anthropicVersion,
|
|
152
|
-
'anthropic-beta': 'prompt-caching-2024-07-31',
|
|
189
|
+
...(this.isDefaultApiHost ? { 'anthropic-beta': 'prompt-caching-2024-07-31' } : {}),
|
|
153
190
|
},
|
|
154
191
|
body: JSON.stringify(body),
|
|
155
192
|
// Same as `openai-compat`: without this the caller's signal never reaches
|
|
@@ -190,19 +227,17 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
190
227
|
try {
|
|
191
228
|
while (true) {
|
|
192
229
|
let readResult: Awaited<ReturnType<typeof reader.read>>
|
|
193
|
-
let
|
|
230
|
+
let cancelIdle: (() => void) | undefined
|
|
194
231
|
try {
|
|
195
232
|
readResult = await Promise.race([
|
|
196
233
|
reader.read(),
|
|
197
234
|
new Promise<never>((_, reject) => {
|
|
198
|
-
|
|
199
|
-
(
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
203
|
-
),
|
|
235
|
+
cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
|
|
236
|
+
reject(
|
|
237
|
+
new Error(
|
|
238
|
+
`Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
|
|
204
239
|
),
|
|
205
|
-
|
|
240
|
+
),
|
|
206
241
|
)
|
|
207
242
|
}),
|
|
208
243
|
])
|
|
@@ -210,7 +245,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
210
245
|
yield { type: 'error', error: `Stream stalled: ${String(err)}` }
|
|
211
246
|
return
|
|
212
247
|
} finally {
|
|
213
|
-
|
|
248
|
+
cancelIdle?.()
|
|
214
249
|
}
|
|
215
250
|
const { done, value } = readResult
|
|
216
251
|
if (done) break
|