@miphamai/cli 0.85.12 → 0.85.14
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 +6 -6
- package/src/agent/sub-agent.ts +15 -1
- package/src/config/loader.ts +78 -3
- package/src/core/credential-masker/output-scrub.ts +120 -7
- package/src/core/engine.ts +79 -12
- 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/i18n-core/locales/en-US.json +3 -0
- package/src/i18n-core/locales/zh-CN.json +3 -0
- package/src/index.tsx +15 -1
- package/src/mcp/oauth.ts +14 -0
- package/src/plugin/plugin-manager.ts +19 -1
- package/src/providers/anthropic.ts +38 -3
- package/src/providers/openai-compat.ts +3 -1
- 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/types.ts +35 -0
- package/src/tools/agent/send-message.ts +9 -2
- package/src/ui/command-picker.tsx +0 -1
- package/src/ui/commands.ts +17 -5
- package/src/ui/input.tsx +10 -1
package/src/core/permission.ts
CHANGED
|
@@ -9,6 +9,8 @@ import type { PermissionRuleEntry } from '../shared/index.ts'
|
|
|
9
9
|
import { matchBashRule, compileRule } from './permission-rules'
|
|
10
10
|
import { detectDangerousRm } from '../security/dangerous-rm'
|
|
11
11
|
import type { DangerousRm } from '../security/dangerous-rm'
|
|
12
|
+
import { detectWorldWritableChmod } from '../security/world-writable-chmod'
|
|
13
|
+
import type { WorldWritableChmod } from '../security/world-writable-chmod'
|
|
12
14
|
import {
|
|
13
15
|
loadPermissionConfig,
|
|
14
16
|
nextMode,
|
|
@@ -127,6 +129,7 @@ export type PermissionDenialReason =
|
|
|
127
129
|
| 'system-default' // no rule, no tool permission → fallback ask
|
|
128
130
|
| 'classifier-deny' // `auto` mode's classifier ruled against the call
|
|
129
131
|
| 'dangerous-rm' // recursive rm whose target is not a path in the command text
|
|
132
|
+
| 'world-writable-chmod' // recursive chmod granting world-write to an unbounded target
|
|
130
133
|
|
|
131
134
|
/**
|
|
132
135
|
* Which denial reasons `auto` mode's classifier is allowed to rule on — an
|
|
@@ -147,6 +150,11 @@ export type PermissionDenialReason =
|
|
|
147
150
|
* reason answers. Every other reason here is "the mode was not sure, let a second
|
|
148
151
|
* opinion decide"; this one is "the command does not say what it will delete", and
|
|
149
152
|
* a second opinion reading the same command is reading the same missing text.
|
|
153
|
+
*
|
|
154
|
+
* `world-writable-chmod` is absent for that same reason, and the measurement says
|
|
155
|
+
* so out loud: the gate was asked it anyway, and answered by coin flip (1/5 vs
|
|
156
|
+
* 4/5 across the two models, 2026-09-30). Both halves — is the grant world-write,
|
|
157
|
+
* is the target bounded — are in the text, so the ruling belongs to the text.
|
|
150
158
|
*/
|
|
151
159
|
const CLASSIFIABLE: ReadonlySet<PermissionDenialReason> = new Set<PermissionDenialReason>([
|
|
152
160
|
'mode-baseline',
|
|
@@ -532,6 +540,16 @@ export class PermissionSystem {
|
|
|
532
540
|
return 'ask'
|
|
533
541
|
}
|
|
534
542
|
|
|
543
|
+
// ── A recursive `chmod` granting world-write to an unbounded target ──
|
|
544
|
+
// Same placement and the same two reasons, so it is spelled once and read
|
|
545
|
+
// once: it sits ahead of the allow rules and every mode baseline (including
|
|
546
|
+
// `auto`, whose classifier was measured answering this one 1/5 versus 4/5),
|
|
547
|
+
// and it is also uncached because the escape hatch is read from the
|
|
548
|
+
// environment on each call.
|
|
549
|
+
if (this.worldWritableChmod(tool, input)) {
|
|
550
|
+
return 'ask'
|
|
551
|
+
}
|
|
552
|
+
|
|
535
553
|
// ── Cache lookup (P2): reuse decision for same tool+mode+input ──
|
|
536
554
|
const cacheKey = this.cacheKey(tool, input)
|
|
537
555
|
if (this.cacheMode === this.mode) {
|
|
@@ -635,6 +653,10 @@ export class PermissionSystem {
|
|
|
635
653
|
if (dangerous) {
|
|
636
654
|
return { reason: 'dangerous-rm', target: dangerous.target }
|
|
637
655
|
}
|
|
656
|
+
const worldWritable = this.worldWritableChmod(tool, input)
|
|
657
|
+
if (worldWritable) {
|
|
658
|
+
return { reason: 'world-writable-chmod', target: worldWritable.target }
|
|
659
|
+
}
|
|
638
660
|
if (this.legacyRules.has(tool.name)) {
|
|
639
661
|
return { reason: 'legacy-rule' }
|
|
640
662
|
}
|
|
@@ -678,6 +700,29 @@ export class PermissionSystem {
|
|
|
678
700
|
return detectDangerousRm(command)
|
|
679
701
|
}
|
|
680
702
|
|
|
703
|
+
/**
|
|
704
|
+
* A recursive `chmod` handing world-write to a target the command does not bound.
|
|
705
|
+
*
|
|
706
|
+
* Only the Bash tool, and the escape hatch is read from the **environment**
|
|
707
|
+
* rather than from tool parameters — both for the same reasons as `dangerousRm`
|
|
708
|
+
* above. A parameter the call can set is a guard the call can turn off, so the
|
|
709
|
+
* opt-out has to come from whoever started the process.
|
|
710
|
+
*
|
|
711
|
+
* The measured case for making this structural is in the module's own header:
|
|
712
|
+
* the gate was asked this question and answered it 1/5 versus 4/5 depending on
|
|
713
|
+
* which model happened to be active.
|
|
714
|
+
*/
|
|
715
|
+
private worldWritableChmod(
|
|
716
|
+
tool: ToolDefinition,
|
|
717
|
+
input: Record<string, unknown>,
|
|
718
|
+
): WorldWritableChmod | null {
|
|
719
|
+
if (tool.name !== 'Bash') return null
|
|
720
|
+
if (process.env.MIPHAM_DISABLE_CHMOD_PROMPT === '1') return null
|
|
721
|
+
const command = input.command
|
|
722
|
+
if (typeof command !== 'string') return null
|
|
723
|
+
return detectWorldWritableChmod(command)
|
|
724
|
+
}
|
|
725
|
+
|
|
681
726
|
/**
|
|
682
727
|
* Resolve a call to a decision, consulting `auto` mode's classifier when — and
|
|
683
728
|
* only when — the static chain answered `'ask'` for a reason a classifier is
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* on every tool call — making it auditable on a per-action basis.
|
|
22
22
|
*/
|
|
23
23
|
|
|
24
|
-
import type
|
|
24
|
+
import { pickFastestModel, type ProviderRegistry } from '../providers/registry'
|
|
25
25
|
import type { Llm } from '../providers/llm'
|
|
26
26
|
import { DEFAULT_CONSTITUTION } from './constitution-loader'
|
|
27
27
|
|
|
@@ -62,7 +62,7 @@ export const DEFAULT_SELF_CRITIQUE_CONFIG: SelfCritiqueConfig = {
|
|
|
62
62
|
threshold: 0.6,
|
|
63
63
|
targetTools: ['Bash', 'Write', 'Edit', 'Agent'],
|
|
64
64
|
// Measured, not chosen: 30 real critiques against the configured provider
|
|
65
|
-
// (`
|
|
65
|
+
// (`pickFastestModel` → `deepseek-v4-flash`; default model is the slower
|
|
66
66
|
// `-pro`) took min 1.85s / median 3.95s / max 17.9s, and **28 of 30 exceeded
|
|
67
67
|
// 2s** — the value this replaced. At 2s the budget would have skipped 93% of
|
|
68
68
|
// critiques, and since `critique()` fails *open* (null ⇒ the tool runs
|
|
@@ -175,7 +175,7 @@ export class SelfCritique {
|
|
|
175
175
|
)
|
|
176
176
|
|
|
177
177
|
try {
|
|
178
|
-
const critiqueModel = this.config.model ||
|
|
178
|
+
const critiqueModel = this.config.model || pickFastestModel(registry)
|
|
179
179
|
|
|
180
180
|
const controller = new AbortController()
|
|
181
181
|
const timeout = setTimeout(() => controller.abort(), this.config.timeoutMs)
|
|
@@ -219,18 +219,6 @@ export class SelfCritique {
|
|
|
219
219
|
|
|
220
220
|
// ── Private ──
|
|
221
221
|
|
|
222
|
-
/** Find the fastest available model for low-latency critique. */
|
|
223
|
-
private findFastestModel(registry: ProviderRegistry): string {
|
|
224
|
-
// Prefer Flash models (Qwen2.5-1.5B or similar small models)
|
|
225
|
-
const models = registry.listModels?.() || []
|
|
226
|
-
const flashModel = models.find(
|
|
227
|
-
(m) => m.id.toLowerCase().includes('flash') || m.id.toLowerCase().includes('1.5b'),
|
|
228
|
-
)
|
|
229
|
-
if (flashModel) return flashModel.id
|
|
230
|
-
// Fall back to whatever's active
|
|
231
|
-
return registry.getActiveModel()
|
|
232
|
-
}
|
|
233
|
-
|
|
234
222
|
/** Extract JSON object from model response (may have markdown fences). */
|
|
235
223
|
private extractJson(text: string): Record<string, unknown> | null {
|
|
236
224
|
// Try direct parse
|
|
@@ -938,6 +938,7 @@
|
|
|
938
938
|
"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.",
|
|
939
939
|
"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, or allow it outright with: /permissions allow \"{name}\" Treat this denial as covering the outcome, not only this exact command.",
|
|
940
940
|
"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",
|
|
941
|
+
"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",
|
|
941
942
|
"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.",
|
|
942
943
|
"tool_blocked": "Tool \"{name}\" blocked by hook",
|
|
943
944
|
"tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
|
|
@@ -963,6 +964,8 @@
|
|
|
963
964
|
"max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
|
|
964
965
|
"turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
|
|
965
966
|
"turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed.",
|
|
967
|
+
"turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
|
|
968
|
+
"turn_refused_reason": "The model declined this request: {reason}",
|
|
966
969
|
"stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
|
|
967
970
|
"mcp_not_connected": "Error: MCP server \"{server}\" not connected",
|
|
968
971
|
"mcp_tool_error": "MCP tool error: {error}",
|
|
@@ -938,6 +938,7 @@
|
|
|
938
938
|
"tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可) 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
939
939
|
"tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则,或直接放行:/permissions allow \"{name}\" 请把这次拒绝理解为对结果本身的禁止,而不只是这一条命令。",
|
|
940
940
|
"tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
941
|
+
"tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
941
942
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
942
943
|
"tool_blocked": "工具 \"{name}\" 被钩子拦截",
|
|
943
944
|
"tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
|
|
@@ -963,6 +964,8 @@
|
|
|
963
964
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
|
964
965
|
"turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
|
|
965
966
|
"turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。",
|
|
967
|
+
"turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
|
|
968
|
+
"turn_refused_reason": "模型拒绝了这次请求:{reason}",
|
|
966
969
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
|
967
970
|
"mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
|
|
968
971
|
"mcp_tool_error": "MCP 工具错误:{error}",
|
package/src/index.tsx
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
discoverSessions,
|
|
22
22
|
} from './agent/cross-session/discovery'
|
|
23
23
|
import { bootstrapProviders } from './providers/bootstrap'
|
|
24
|
+
import { resolveClassifierModel } from './providers/registry'
|
|
24
25
|
import { InstructionsLoader, formatInstructionSizeNotice } from './core/instructions'
|
|
25
26
|
import { loadSessionMemories, getMemoryManager } from './core/memory/memory-loader'
|
|
26
27
|
import { ContextManager } from './core/context'
|
|
@@ -460,6 +461,15 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
460
461
|
` (an allow rule widens the gate — move the rules to ${settingsPathFor('user', process.cwd())})\n`,
|
|
461
462
|
)
|
|
462
463
|
}
|
|
464
|
+
// Same reason, one key group over: these two choose **how** the `auto` gate
|
|
465
|
+
// rules, and both directions of that choice widen it (a weaker judge, or enough
|
|
466
|
+
// time that a ruling no longer times out into a denial).
|
|
467
|
+
if (settingsJson.projectClassifierSkipped) {
|
|
468
|
+
process.stderr.write(
|
|
469
|
+
`⚠ Mipham Code: ignored permissions.classifierModel / classifierTimeoutMs from ${settingsPathFor('project', process.cwd())}\n` +
|
|
470
|
+
` (a repository must not choose how the approval gate rules — set them in ${settingsPathFor('user', process.cwd())})\n`,
|
|
471
|
+
)
|
|
472
|
+
}
|
|
463
473
|
// Apply org-level permission restrictions (P0: bypassPermissions policy gap)
|
|
464
474
|
if (config.permissionRestrictions) {
|
|
465
475
|
permission.setRestrictions(config.permissionRestrictions)
|
|
@@ -486,7 +496,11 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
486
496
|
// here would freeze it at whatever was active at startup, so a user who switches to
|
|
487
497
|
// a cheaper model would keep paying for the old one with nothing on screen to say so.
|
|
488
498
|
permission.setClassifier(
|
|
489
|
-
new LlmPermissionClassifier(registry, {
|
|
499
|
+
new LlmPermissionClassifier(registry, {
|
|
500
|
+
resolveModel: () =>
|
|
501
|
+
resolveClassifierModel(settingsJson.permissions.classifierModel, registry),
|
|
502
|
+
timeoutMs: settingsJson.permissions.classifierTimeoutMs,
|
|
503
|
+
}),
|
|
490
504
|
)
|
|
491
505
|
|
|
492
506
|
// Load instructions
|
package/src/mcp/oauth.ts
CHANGED
|
@@ -88,10 +88,24 @@ export class OAuthClient {
|
|
|
88
88
|
res.end(
|
|
89
89
|
`<html><body><h1>${t('system.oauth.authenticated')}</h1><p>${t('system.oauth.close_window')}</p></body></html>`,
|
|
90
90
|
)
|
|
91
|
+
clearTimeout(timer)
|
|
91
92
|
server.close()
|
|
92
93
|
resolve(receivedCode)
|
|
93
94
|
}
|
|
94
95
|
})
|
|
96
|
+
// A listen failure (`EADDRINUSE` — the port is taken, or a second flow
|
|
97
|
+
// raced this one) arrives as an `'error'` event. With no listener Node
|
|
98
|
+
// re-throws it as an uncaught exception and takes the whole process down:
|
|
99
|
+
// the flow cannot *fail cleanly* if the failure signal itself is fatal.
|
|
100
|
+
// Reject instead so the caller sees an error and the attempt ends here.
|
|
101
|
+
const timer = setTimeout(() => {
|
|
102
|
+
server.close()
|
|
103
|
+
reject(new Error(t('errors.oauth_timeout')))
|
|
104
|
+
}, 300_000)
|
|
105
|
+
server.on('error', (err) => {
|
|
106
|
+
clearTimeout(timer)
|
|
107
|
+
reject(err)
|
|
108
|
+
})
|
|
95
109
|
server.listen(port, '127.0.0.1', () => {
|
|
96
110
|
const authUrl = new URL(auth.authorizationUrl)
|
|
97
111
|
authUrl.searchParams.set('response_type', 'code')
|
|
@@ -131,9 +131,27 @@ export class PluginManager {
|
|
|
131
131
|
// of its own to be loaded from here. `execFileSync` (argv array, no
|
|
132
132
|
// shell) keeps the command line independent of packageName, so package
|
|
133
133
|
// name validation is not the only thing standing between us and a shell.
|
|
134
|
+
//
|
|
135
|
+
// `--registry`: name validation constrains the *top-level* name only —
|
|
136
|
+
// every transitive dependency is resolved by npm from whatever registry
|
|
137
|
+
// the user's config/env points at, so a hijacked `npm_config_registry` (or
|
|
138
|
+
// an `.npmrc` in scope) gets to serve code that lands on this machine.
|
|
139
|
+
// Pinning to an explicit HTTPS registry takes the environment out of the
|
|
140
|
+
// resolver. The value is the npm default already declared in this repo's
|
|
141
|
+
// registry chain (`src/shared/update.ts`), not a new literal. The flag is
|
|
142
|
+
// honoured over npm config because command-line flags outrank it.
|
|
134
143
|
execFileSync(
|
|
135
144
|
'npm',
|
|
136
|
-
[
|
|
145
|
+
[
|
|
146
|
+
'install',
|
|
147
|
+
packageName,
|
|
148
|
+
'--prefix',
|
|
149
|
+
stagingDir,
|
|
150
|
+
'--no-save',
|
|
151
|
+
'--ignore-scripts',
|
|
152
|
+
'--registry',
|
|
153
|
+
'https://registry.npmjs.org',
|
|
154
|
+
],
|
|
137
155
|
{
|
|
138
156
|
encoding: 'utf-8',
|
|
139
157
|
stdio: 'pipe',
|
|
@@ -34,6 +34,11 @@ interface AnthropicSSEEvent {
|
|
|
34
34
|
thinking?: string
|
|
35
35
|
partial_json?: string
|
|
36
36
|
stop_reason?: string | null
|
|
37
|
+
/**
|
|
38
|
+
* Sits beside `stop_reason` on the `message_delta` event, and is the only
|
|
39
|
+
* explanation that exists when a refusal comes back with no content at all.
|
|
40
|
+
*/
|
|
41
|
+
stop_details?: { category?: string; explanation?: string }
|
|
37
42
|
}
|
|
38
43
|
error?: { type: string; message: string }
|
|
39
44
|
usage?: { input_tokens: number; output_tokens: number }
|
|
@@ -78,6 +83,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
78
83
|
// off at the output ceiling rather than ended by the model.
|
|
79
84
|
let truncated = false
|
|
80
85
|
|
|
86
|
+
// Set when the provider reports `stop_reason: 'refusal'`. A refusal is a
|
|
87
|
+
// **successful** response (HTTP 200) that declines to answer, and it may carry
|
|
88
|
+
// an empty content array — so without this the turn ends as a blank screen,
|
|
89
|
+
// because `end_turn` and `refusal` both arrive at the same terminal stop below.
|
|
90
|
+
let refusal: { category?: string; explanation?: string } | undefined
|
|
91
|
+
|
|
81
92
|
// Whether this stream reached `message_stop`. A stream that runs out without
|
|
82
93
|
// one was cut — a proxy or gateway closing the connection cleanly looks
|
|
83
94
|
// exactly like a finished response otherwise.
|
|
@@ -87,6 +98,15 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
87
98
|
// second one; emitting it twice makes the engine run the tool twice.
|
|
88
99
|
const emittedToolIds = new Set<string>()
|
|
89
100
|
|
|
101
|
+
// Both terminal emissions go through here so the two flags can never drift
|
|
102
|
+
// apart on one path. Reads `truncated`/`refusal` at call time, so it is
|
|
103
|
+
// declared before either is set.
|
|
104
|
+
const terminalStop = (): StreamChunk => ({
|
|
105
|
+
type: 'stop',
|
|
106
|
+
...(truncated ? { truncated: true } : {}),
|
|
107
|
+
...(refusal ? { refusal } : {}),
|
|
108
|
+
})
|
|
109
|
+
|
|
90
110
|
const messages = this.convertMessages(req.messages)
|
|
91
111
|
this.markPrefixCacheBreakpoint(messages)
|
|
92
112
|
|
|
@@ -298,12 +318,22 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
298
318
|
if (stopReason === 'max_tokens') {
|
|
299
319
|
truncated = true
|
|
300
320
|
}
|
|
321
|
+
// A refusal is a successful response that declines to answer, and
|
|
322
|
+
// it can arrive with no content at all. Capture the provider's own
|
|
323
|
+
// reason here — it is the only one that will ever exist, and the
|
|
324
|
+
// stream is the only place it appears.
|
|
325
|
+
if (stopReason === 'refusal') {
|
|
326
|
+
refusal = {}
|
|
327
|
+
const details = event.delta?.stop_details
|
|
328
|
+
if (details?.category !== undefined) refusal.category = details.category
|
|
329
|
+
if (details?.explanation !== undefined) refusal.explanation = details.explanation
|
|
330
|
+
}
|
|
301
331
|
break
|
|
302
332
|
}
|
|
303
333
|
|
|
304
334
|
case 'message_stop': {
|
|
305
335
|
sawTerminalEvent = true
|
|
306
|
-
yield
|
|
336
|
+
yield terminalStop()
|
|
307
337
|
return
|
|
308
338
|
}
|
|
309
339
|
|
|
@@ -327,7 +357,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
327
357
|
// closed connection and a finished response are otherwise the same stream.
|
|
328
358
|
if (!sawTerminalEvent) truncated = true
|
|
329
359
|
|
|
330
|
-
yield
|
|
360
|
+
yield terminalStop()
|
|
331
361
|
} finally {
|
|
332
362
|
await reader.cancel().catch(() => {})
|
|
333
363
|
}
|
|
@@ -434,7 +464,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
434
464
|
tool_use_id: block.tool_use_id,
|
|
435
465
|
// 空 content 同样整条请求被拒(见 NO_TOOL_OUTPUT)。`||` 而非 `=== ''`:
|
|
436
466
|
// 投影层缺失该字段时这里是 `undefined`,空数组同理。
|
|
437
|
-
|
|
467
|
+
// 非字符串(工具/MCP/插件违约返回对象或数字)同样要先成文本 ——
|
|
468
|
+
// 直接透传会作为 JSON 值进请求体,而 API 只收字符串。
|
|
469
|
+
content:
|
|
470
|
+
(typeof block.content === 'string'
|
|
471
|
+
? block.content
|
|
472
|
+
: JSON.stringify(block.content)) || NO_TOOL_OUTPUT,
|
|
438
473
|
// 只在失败时下发 —— 成功请求体与改动前逐字节相同,不引入 prompt-cache 前缀抖动
|
|
439
474
|
...(block.is_error === true ? { is_error: true } : {}),
|
|
440
475
|
}
|
|
@@ -417,7 +417,9 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
417
417
|
result.push({
|
|
418
418
|
role: 'tool',
|
|
419
419
|
tool_call_id: tr.tool_use_id,
|
|
420
|
-
content
|
|
420
|
+
// 非字符串 content 需成文本:tool 消息的 content 只收字符串,透传对象
|
|
421
|
+
// 会让它作为 JSON 值进请求体。空串保持空串(此处无占位回退)。
|
|
422
|
+
content: typeof tr.content === 'string' ? tr.content : JSON.stringify(tr.content),
|
|
421
423
|
})
|
|
422
424
|
}
|
|
423
425
|
continue
|
|
@@ -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.14' 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 = 3922 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -162,6 +162,29 @@ export interface StreamChunk {
|
|
|
162
162
|
* either way, and tool calls cut off mid-arguments are dropped silently.
|
|
163
163
|
*/
|
|
164
164
|
truncated?: boolean
|
|
165
|
+
/**
|
|
166
|
+
* Set on the `warning` chunk a retried turn emits just before it re-streams
|
|
167
|
+
* (`chatWithFallback`). Everything the failed attempt already yielded is on
|
|
168
|
+
* screen and cannot be recalled, so a consumer that accumulates a turn's
|
|
169
|
+
* output — assistant text, tool calls — must **discard the previous attempt**
|
|
170
|
+
* when it sees this. Without it a retry re-executes the tool calls that
|
|
171
|
+
* attempt already emitted: their ids are regenerated per attempt, so nothing
|
|
172
|
+
* downstream de-duplicates them and a side-effecting tool runs twice.
|
|
173
|
+
*/
|
|
174
|
+
restart?: boolean
|
|
175
|
+
/**
|
|
176
|
+
* The provider declined to answer — a terminal outcome, not a failure.
|
|
177
|
+
*
|
|
178
|
+
* Anthropic reports this as `stop_reason: 'refusal'` on a **successful**
|
|
179
|
+
* response (HTTP 200, not an error), sending `stop_details` alongside it on
|
|
180
|
+
* the same `message_delta`. A refusal may carry an **empty content array**,
|
|
181
|
+
* so without this the turn is a blank screen with nothing to explain it;
|
|
182
|
+
* `explanation` is the provider's own stated reason for the decline.
|
|
183
|
+
*
|
|
184
|
+
* Set **only on refusal** — absent on every normal stop, so the success path
|
|
185
|
+
* stays byte-identical (same shape as `truncated` above).
|
|
186
|
+
*/
|
|
187
|
+
refusal?: { category?: string; explanation?: string }
|
|
165
188
|
}
|
|
166
189
|
|
|
167
190
|
// ── Config Types ──
|
|
@@ -595,6 +618,18 @@ export interface ToolContext {
|
|
|
595
618
|
* consume a background handle, so its default flips to synchronous.
|
|
596
619
|
*/
|
|
597
620
|
isSubAgent?: boolean
|
|
621
|
+
/**
|
|
622
|
+
* The agent's own name, when this call is being executed by a sub-agent.
|
|
623
|
+
*
|
|
624
|
+
* `isSubAgent` says *that* we are one level down; this says *which* agent, so a
|
|
625
|
+
* peer reading `Message from @…` can tell two agents apart, and can recognise the
|
|
626
|
+
* same agent across two messages. Without it `SendMessage` has only the anonymous
|
|
627
|
+
* `'sub-agent'` session string to go on and mints a fresh `sub-agent-<ms>` sender
|
|
628
|
+
* per message — the parent neither sees who sent it nor can address a reply. Set
|
|
629
|
+
* by `SubAgent.runExecution` from the same `agentDef.name || type` the footer and
|
|
630
|
+
* the experience logs use. Absent for the main session.
|
|
631
|
+
*/
|
|
632
|
+
agentName?: string
|
|
598
633
|
}
|
|
599
634
|
|
|
600
635
|
export interface ToolDefinition {
|
|
@@ -36,10 +36,17 @@ export const sendMessageTool: ToolDefinition = {
|
|
|
36
36
|
// P1-1: Truncate long summaries instead of rejecting (max 200 chars)
|
|
37
37
|
const truncatedSummary = summary.length > 200 ? summary.slice(0, 197) + '...' : summary
|
|
38
38
|
|
|
39
|
+
// Prefer the agent's own name when it has one (a sub-agent gets it from
|
|
40
|
+
// `SubAgent.runExecution`): `sessionId` is the literal 'sub-agent' for every
|
|
41
|
+
// sub-agent, so keying off it alone gave the parent an opaque sender — and one
|
|
42
|
+
// minted per message, so two messages from the same agent could not be grouped
|
|
43
|
+
// or replied to. Callers with no identity (the main session) keep the previous
|
|
44
|
+
// shape byte-for-byte.
|
|
39
45
|
const from =
|
|
40
|
-
ctx.
|
|
46
|
+
ctx.agentName ||
|
|
47
|
+
(ctx.sessionId === 'sub-agent'
|
|
41
48
|
? `sub-agent-${Date.now().toString(36)}`
|
|
42
|
-
: ctx.sessionId || 'main'
|
|
49
|
+
: ctx.sessionId || 'main')
|
|
43
50
|
|
|
44
51
|
const router = getMessageRouter()
|
|
45
52
|
const result = await router.route(from, to, truncatedSummary, message)
|