@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/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.14
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@miphamai/cli",
|
|
3
|
-
"version": "0.85.
|
|
3
|
+
"version": "0.85.14",
|
|
4
4
|
"description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -44,23 +44,23 @@
|
|
|
44
44
|
"mutate": "stryker run"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@larksuiteoapi/node-sdk": "^1.
|
|
47
|
+
"@larksuiteoapi/node-sdk": "^1.74.0",
|
|
48
48
|
"commander": "^13.1.0",
|
|
49
49
|
"ink": "^7.1.1",
|
|
50
50
|
"ink-text-input": "^6.0.0",
|
|
51
51
|
"react": "^19.3.0",
|
|
52
52
|
"react-devtools-core": "^8.0.0",
|
|
53
|
-
"yaml": "^2.9.
|
|
53
|
+
"yaml": "^2.9.1"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@mipham/shared": "workspace:*",
|
|
57
57
|
"@stryker-mutator/core": "10.0.0",
|
|
58
58
|
"@stryker-mutator/vitest-runner": "10.0.0",
|
|
59
59
|
"@types/bun": "^1.4.2",
|
|
60
|
-
"@types/node": "^22.
|
|
60
|
+
"@types/node": "^22.20.4",
|
|
61
61
|
"@types/react": "^19.3.0",
|
|
62
|
-
"@vitest/coverage-v8": "^5.0.
|
|
62
|
+
"@vitest/coverage-v8": "^5.0.2",
|
|
63
63
|
"ink-testing-library": "^4.0.0",
|
|
64
|
-
"vitest": "^5.0.
|
|
64
|
+
"vitest": "^5.0.2"
|
|
65
65
|
}
|
|
66
66
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -484,6 +484,13 @@ export class SubAgent {
|
|
|
484
484
|
// synchronous (see `resolveRunInBackground`). Set on the shared literal so it
|
|
485
485
|
// covers the synchronous *and* background runs — both go through here.
|
|
486
486
|
isSubAgent: true,
|
|
487
|
+
// A name a peer can hold onto. `sessionId` is the literal 'sub-agent' for
|
|
488
|
+
// every sub-agent, so `SendMessage` had nothing stable to put on the
|
|
489
|
+
// envelope and minted `sub-agent-<ms>` afresh per message — two messages
|
|
490
|
+
// from one agent arrived under two senders. Same derivation as the footer
|
|
491
|
+
// (`ui/app.tsx`) and the experience logs below: the definition's name, else
|
|
492
|
+
// the type.
|
|
493
|
+
agentName: agentDef?.name || agentType,
|
|
487
494
|
}
|
|
488
495
|
|
|
489
496
|
try {
|
|
@@ -714,9 +721,16 @@ export class SubAgent {
|
|
|
714
721
|
|
|
715
722
|
const result = chunks.join('')
|
|
716
723
|
if (hitMaxTurns) {
|
|
724
|
+
// Only advertise the SendMessage route where a route exists. A background
|
|
725
|
+
// agent has an address (`bg-…`, minted by the registry and handed to the
|
|
726
|
+
// executor) and drains it every turn, so a peer can genuinely continue it.
|
|
727
|
+
// The synchronous path is called without one, and by the time this notice
|
|
728
|
+
// is built the run is over — there is no loop left to drain anything, so
|
|
729
|
+
// "Use SendMessage to continue this sub-agent" there points at nothing.
|
|
730
|
+
const canContinue = agentId ? ' Use SendMessage to continue this sub-agent.' : ''
|
|
717
731
|
return (
|
|
718
732
|
`[partial result — sub-agent reached its ${MAX_TOOL_TURNS}-turn limit; ` +
|
|
719
|
-
|
|
733
|
+
`task may be incomplete.${canContinue}]\n\n` +
|
|
720
734
|
result
|
|
721
735
|
)
|
|
722
736
|
}
|
package/src/config/loader.ts
CHANGED
|
@@ -414,7 +414,23 @@ export interface SettingsJson {
|
|
|
414
414
|
* validator here would be a second value domain, and the two would drift the
|
|
415
415
|
* day a mode is added.
|
|
416
416
|
*/
|
|
417
|
-
permissions: {
|
|
417
|
+
permissions: {
|
|
418
|
+
allow: string[]
|
|
419
|
+
deny: string[]
|
|
420
|
+
defaultMode?: string
|
|
421
|
+
/**
|
|
422
|
+
* Which model rules in `auto` mode. Absent ⇒ the model the operator has
|
|
423
|
+
* active; `'active'` says the same thing out loud; `'fast'` picks the
|
|
424
|
+
* Flash-class model; any other string is a model id, passed through
|
|
425
|
+
* unvalidated (the provider is the only thing that can say what exists).
|
|
426
|
+
*/
|
|
427
|
+
classifierModel?: string
|
|
428
|
+
/**
|
|
429
|
+
* Milliseconds a single ruling may take before it is abandoned. Absent ⇒
|
|
430
|
+
* `DEFAULT_CLASSIFIER_TIMEOUT_MS`.
|
|
431
|
+
*/
|
|
432
|
+
classifierTimeoutMs?: number
|
|
433
|
+
}
|
|
418
434
|
/**
|
|
419
435
|
* Present (and `true`) only when the project-level file really did declare
|
|
420
436
|
* hooks and they were withheld because the caller did not vouch for the
|
|
@@ -439,6 +455,14 @@ export interface SettingsJson {
|
|
|
439
455
|
* that declares `allow` but no mode sets this one and not the other.
|
|
440
456
|
*/
|
|
441
457
|
projectAllowSkipped?: true
|
|
458
|
+
/**
|
|
459
|
+
* Same shape, for `permissions.classifierModel` / `classifierTimeoutMs`: the
|
|
460
|
+
* two knobs on **how** the `auto` gate rules rather than on what it permits.
|
|
461
|
+
* Both can widen it — a weaker judge, or more time for a ruling that would
|
|
462
|
+
* otherwise time out into a denial — so both are withheld from a project file
|
|
463
|
+
* for the same reason `defaultMode` is, and the one marker covers both.
|
|
464
|
+
*/
|
|
465
|
+
projectClassifierSkipped?: true
|
|
442
466
|
/**
|
|
443
467
|
* The subset of `hooks` that came from the project-level file — the entries
|
|
444
468
|
* the workspace-trust gate governs. Absent unless the caller vouched for the
|
|
@@ -489,13 +513,20 @@ export function loadSettingsJson(
|
|
|
489
513
|
options: { includeProjectHooks?: boolean } = {},
|
|
490
514
|
): SettingsJson {
|
|
491
515
|
const hooks: SettingsHooks = {}
|
|
492
|
-
const permissions: {
|
|
516
|
+
const permissions: {
|
|
517
|
+
allow: string[]
|
|
518
|
+
deny: string[]
|
|
519
|
+
defaultMode?: string
|
|
520
|
+
classifierModel?: string
|
|
521
|
+
classifierTimeoutMs?: number
|
|
522
|
+
} = {
|
|
493
523
|
allow: [],
|
|
494
524
|
deny: [],
|
|
495
525
|
}
|
|
496
526
|
let projectHooksSkipped = false
|
|
497
527
|
let projectModeSkipped = false
|
|
498
528
|
let projectAllowSkipped = false
|
|
529
|
+
let projectClassifierSkipped = false
|
|
499
530
|
// The project file's entries, kept out of the merge so provenance survives it.
|
|
500
531
|
const projectHooks: SettingsHooks = {}
|
|
501
532
|
|
|
@@ -537,7 +568,13 @@ export function loadSettingsJson(
|
|
|
537
568
|
}
|
|
538
569
|
const parsed = JSON.parse(raw) as {
|
|
539
570
|
hooks?: Record<string, unknown>
|
|
540
|
-
permissions?: {
|
|
571
|
+
permissions?: {
|
|
572
|
+
allow?: unknown
|
|
573
|
+
deny?: unknown
|
|
574
|
+
defaultMode?: unknown
|
|
575
|
+
classifierModel?: unknown
|
|
576
|
+
classifierTimeoutMs?: unknown
|
|
577
|
+
}
|
|
541
578
|
}
|
|
542
579
|
|
|
543
580
|
if (!readHooks) {
|
|
@@ -597,6 +634,43 @@ export function loadSettingsJson(
|
|
|
597
634
|
if (!permissions[key].includes(p)) permissions[key].push(p)
|
|
598
635
|
}
|
|
599
636
|
}
|
|
637
|
+
|
|
638
|
+
// The two knobs on **how** the gate rules, rather than on what it lets
|
|
639
|
+
// through. Both can widen it — a weaker judge (measured 2026-09-30: the
|
|
640
|
+
// fast model allows 8/20 borderline calls the reasoning one blocks), or
|
|
641
|
+
// more time, since a ruling that does not finish in budget is a denial —
|
|
642
|
+
// so both are withheld from a project file like `defaultMode`.
|
|
643
|
+
//
|
|
644
|
+
// Unlike `defaultMode`, a value that cannot be used is dropped **here**
|
|
645
|
+
// and said so: there is no applier downstream that knows these spellings,
|
|
646
|
+
// and silently ignoring a knob the user wrote is indistinguishable from
|
|
647
|
+
// never reading their file.
|
|
648
|
+
const rawClassifierModel = parsed.permissions.classifierModel
|
|
649
|
+
if (rawClassifierModel !== undefined) {
|
|
650
|
+
if (typeof rawClassifierModel === 'string' && rawClassifierModel.trim() !== '') {
|
|
651
|
+
if (isProject) projectClassifierSkipped = true
|
|
652
|
+
else permissions.classifierModel = rawClassifierModel.trim()
|
|
653
|
+
} else {
|
|
654
|
+
process.stderr.write(
|
|
655
|
+
`⚠ Mipham Code: ignoring permissions.classifierModel from ${path} — expected a non-empty model id.\n`,
|
|
656
|
+
)
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const rawClassifierTimeout = parsed.permissions.classifierTimeoutMs
|
|
660
|
+
if (rawClassifierTimeout !== undefined) {
|
|
661
|
+
if (
|
|
662
|
+
typeof rawClassifierTimeout === 'number' &&
|
|
663
|
+
Number.isFinite(rawClassifierTimeout) &&
|
|
664
|
+
rawClassifierTimeout > 0
|
|
665
|
+
) {
|
|
666
|
+
if (isProject) projectClassifierSkipped = true
|
|
667
|
+
else permissions.classifierTimeoutMs = rawClassifierTimeout
|
|
668
|
+
} else {
|
|
669
|
+
process.stderr.write(
|
|
670
|
+
`⚠ Mipham Code: ignoring permissions.classifierTimeoutMs from ${path} — expected a positive number of milliseconds.\n`,
|
|
671
|
+
)
|
|
672
|
+
}
|
|
673
|
+
}
|
|
600
674
|
}
|
|
601
675
|
} catch (err: unknown) {
|
|
602
676
|
// Malformed JSON is the other half of the same problem: the file exists and
|
|
@@ -617,6 +691,7 @@ export function loadSettingsJson(
|
|
|
617
691
|
if (projectHooksSkipped) result.projectHooksSkipped = true
|
|
618
692
|
if (projectModeSkipped) result.projectModeSkipped = true
|
|
619
693
|
if (projectAllowSkipped) result.projectAllowSkipped = true
|
|
694
|
+
if (projectClassifierSkipped) result.projectClassifierSkipped = true
|
|
620
695
|
if (Object.values(projectHooks).some((entries) => Array.isArray(entries) && entries.length > 0)) {
|
|
621
696
|
result.projectHooks = projectHooks
|
|
622
697
|
}
|
|
@@ -27,6 +27,47 @@ const TOKEN_REDACTION_PATTERN =
|
|
|
27
27
|
// goes and the host survives.
|
|
28
28
|
const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Zero-width and formatting characters stripped before anything is matched.
|
|
32
|
+
*
|
|
33
|
+
* They carry no meaning in command output, and their only effect here is to
|
|
34
|
+
* split a key name so a name-based pattern cannot see it: `"apiKey": "…"`
|
|
35
|
+
* reads as `apiKey` to a human and as nothing at all to the regex. Stripping
|
|
36
|
+
* first means every pattern below sees the name the reader sees.
|
|
37
|
+
*
|
|
38
|
+
* ZWJ (U+200D) and ZWNJ (U+200C) are **deliberately kept** — they are
|
|
39
|
+
* load-bearing in emoji sequences and in several writing systems, so stripping
|
|
40
|
+
* them would mangle output this has no business touching. A key split with
|
|
41
|
+
* those two therefore still evades; that is a narrower gap than the one closed
|
|
42
|
+
* here, and the only residue that keeps the fix from corrupting real text.
|
|
43
|
+
*/
|
|
44
|
+
const FORMAT_CHARS = /[\u00ad\u061c\u200b\u200e\u200f\u2060\ufeff]/g
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* `Authorization: Bearer <token>` — the header name is the one credential
|
|
48
|
+
* carrier the configured patterns do not cover, because neither `authorization`
|
|
49
|
+
* nor the scheme words are key-shaped (`apiKey`, `secret`, `token`, `…_pat`).
|
|
50
|
+
* The secret sits behind `Bearer ` and leaks untouched.
|
|
51
|
+
*
|
|
52
|
+
* Keeps the header name and the scheme so the line stays readable; redacts only
|
|
53
|
+
* the credential, quoted or not.
|
|
54
|
+
*/
|
|
55
|
+
const AUTH_HEADER_PATTERN =
|
|
56
|
+
/(\b(?:authorization|proxy-authorization)\b\s*["']?\s*[:=]\s*["']?(?:bearer|basic|digest|token)\s+)("[^"]*"|'[^']*'|[^\s"']+)/gi
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A bare `Bearer <token>` / `Basic <b64>` with no header name in front of it —
|
|
60
|
+
* how the value looks once it is in a shell argument, a log line, or a `.env`.
|
|
61
|
+
*
|
|
62
|
+
* The lookahead is the guard against prose: `Bearer authentication` must not be
|
|
63
|
+
* redacted, so the credential has to contain a digit or a base64/JWT punctuation
|
|
64
|
+
* character. An all-lowercase-letter run of that length is a word, not a token.
|
|
65
|
+
*/
|
|
66
|
+
const BARE_AUTH_SCHEME_PATTERNS: RegExp[] = [
|
|
67
|
+
/\b(bearer)(\s+)(?=[A-Za-z0-9\-._~+/]*[0-9._~+/=\-])[A-Za-z0-9\-._~+/]{12,}=*/gi,
|
|
68
|
+
/\b(basic)(\s+)(?=[A-Za-z0-9+/]*[0-9+/=A-Z])[A-Za-z0-9+/]{12,}={0,2}/g,
|
|
69
|
+
]
|
|
70
|
+
|
|
30
71
|
/**
|
|
31
72
|
* Scrub credential patterns from stdout/stderr output.
|
|
32
73
|
* Uses the configured output_scrubbing patterns to detect and replace
|
|
@@ -35,7 +76,8 @@ const URL_USERINFO_PATTERN = /([a-z][a-z0-9+.-]*:\/\/)([^/\s:@]+):([^/\s]+)@/gi
|
|
|
35
76
|
export function maskOutput(output: string, config: CredentialMaskingConfig): string {
|
|
36
77
|
if (!config.enabled || !config.output_scrubbing.enabled) return output
|
|
37
78
|
|
|
38
|
-
|
|
79
|
+
// Normalize away zero-width padding before any name is matched (see FORMAT_CHARS).
|
|
80
|
+
let masked = output.replace(FORMAT_CHARS, '')
|
|
39
81
|
|
|
40
82
|
// Redact bare secret tokens by prefix (always on, independent of config patterns).
|
|
41
83
|
masked = masked.replace(TOKEN_REDACTION_PATTERN, CREDENTIAL_SENTINEL)
|
|
@@ -43,6 +85,12 @@ export function maskOutput(output: string, config: CredentialMaskingConfig): str
|
|
|
43
85
|
// Redact URL-embedded passwords — also shape-based, also always on.
|
|
44
86
|
masked = masked.replace(URL_USERINFO_PATTERN, `$1$2:${CREDENTIAL_SENTINEL}@`)
|
|
45
87
|
|
|
88
|
+
// Redact Authorization-header credentials — also shape-based, also always on.
|
|
89
|
+
masked = masked.replace(AUTH_HEADER_PATTERN, `$1${CREDENTIAL_SENTINEL}`)
|
|
90
|
+
for (const regex of BARE_AUTH_SCHEME_PATTERNS) {
|
|
91
|
+
masked = masked.replace(regex, `$1$2${CREDENTIAL_SENTINEL}`)
|
|
92
|
+
}
|
|
93
|
+
|
|
46
94
|
// Redact bare sk-/sk-ant-/JWT tokens — wire the SecurityGate credential-leak
|
|
47
95
|
// detection into the output path (defense-in-depth beyond the config patterns).
|
|
48
96
|
masked = SecurityGate.redactCredentialLeak(masked)
|
|
@@ -51,15 +99,80 @@ export function maskOutput(output: string, config: CredentialMaskingConfig): str
|
|
|
51
99
|
try {
|
|
52
100
|
// Strip (?i) inline flags — JS uses the 'i' flag instead
|
|
53
101
|
const clean = pattern.replace(/^\(\?i\)/, '')
|
|
54
|
-
|
|
55
|
-
masked = masked.replace(regex, (match) => {
|
|
56
|
-
// Replace everything after the separator (= or :), swallowing the quote
|
|
57
|
-
// a JSON-shaped hit puts in front of it (`"apiKey": "…"`).
|
|
58
|
-
return match.replace(/\s*["']?\s*[:=]\s*["']?\S+/, `=${CREDENTIAL_SENTINEL}`)
|
|
59
|
-
})
|
|
102
|
+
masked = redactValues(masked, new RegExp(clean, 'gim'))
|
|
60
103
|
} catch {
|
|
61
104
|
// Invalid regex — skip
|
|
62
105
|
}
|
|
63
106
|
}
|
|
64
107
|
return masked
|
|
65
108
|
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The separator and the value it introduces, in whichever quoting they arrive.
|
|
112
|
+
*
|
|
113
|
+
* The prefix stops **before** the value's opening quote, deliberately: let it
|
|
114
|
+
* swallow that quote and the quoted branch can no longer match, so the bare
|
|
115
|
+
* branch takes `value"}` whole and the closing quote and brace go with it.
|
|
116
|
+
*
|
|
117
|
+
* `bareQuote` carries a value's opening quote when it has no partner inside the
|
|
118
|
+
* match — what a value containing whitespace looks like, since the configured
|
|
119
|
+
* pattern's own `\S+` cut its match short mid-value. Keeping that quote is what
|
|
120
|
+
* leaves `{"pwd": "<SENTINEL> rest"}` parseable instead of quote-less.
|
|
121
|
+
*/
|
|
122
|
+
const SEPARATOR_AND_VALUE = /(\s*["']?\s*[:=]\s*)(?:"([^"]*)"|'([^']*)'|(["']?)([^\s"']+))/
|
|
123
|
+
|
|
124
|
+
/** Redact the value inside one pattern match, keeping separator and quoting. */
|
|
125
|
+
function redactValue(match: string): string {
|
|
126
|
+
return match.replace(
|
|
127
|
+
SEPARATOR_AND_VALUE,
|
|
128
|
+
(_m, prefix: string, dbl: string | undefined, sgl: string | undefined, bareQuote: string) => {
|
|
129
|
+
if (dbl !== undefined) return `${prefix}"${CREDENTIAL_SENTINEL}"`
|
|
130
|
+
if (sgl !== undefined) return `${prefix}'${CREDENTIAL_SENTINEL}'`
|
|
131
|
+
return `${prefix}${bareQuote}${CREDENTIAL_SENTINEL}`
|
|
132
|
+
},
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Run one configured pattern over `input`, redacting every value it names.
|
|
138
|
+
*
|
|
139
|
+
* An explicit scan rather than `String.replace`, because the resume point has to
|
|
140
|
+
* land **inside** the match. A compact JSON line has no whitespace, so the
|
|
141
|
+
* pattern's own `\S+` runs to the end of it: the first pair's match *contains*
|
|
142
|
+
* every pair after it, and `String.replace` resumes past all of them — redacting
|
|
143
|
+
* only the first. That is not a hypothetical shape; `/config` prints
|
|
144
|
+
* `JSON.stringify(config)`, which is exactly this, several `apiKey`s and all.
|
|
145
|
+
* Resuming just past the value we redacted lets the same pattern see the next
|
|
146
|
+
* pair. (The redaction that destroys the tail instead — replacing `\S+` wholesale
|
|
147
|
+
* — hides the leak rather than fixing it, and mangles the line doing so.)
|
|
148
|
+
*/
|
|
149
|
+
function redactValues(input: string, scan: RegExp): string {
|
|
150
|
+
const out: string[] = []
|
|
151
|
+
let emitted = 0
|
|
152
|
+
let match: RegExpExecArray | null
|
|
153
|
+
scan.lastIndex = 0
|
|
154
|
+
while ((match = scan.exec(input)) !== null) {
|
|
155
|
+
const hit = match[0]
|
|
156
|
+
if (hit.length === 0) {
|
|
157
|
+
// Zero-length match: step over it or `exec` will not advance.
|
|
158
|
+
scan.lastIndex++
|
|
159
|
+
continue
|
|
160
|
+
}
|
|
161
|
+
const inner = SEPARATOR_AND_VALUE.exec(hit)
|
|
162
|
+
if (!inner) {
|
|
163
|
+
// No separator in the match, so nothing here to redact — emit it untouched
|
|
164
|
+
// and let the scan carry on past it.
|
|
165
|
+
out.push(input.slice(emitted, match.index + hit.length))
|
|
166
|
+
emitted = match.index + hit.length
|
|
167
|
+
continue
|
|
168
|
+
}
|
|
169
|
+
const consumed = inner.index + inner[0].length
|
|
170
|
+
out.push(input.slice(emitted, match.index), redactValue(hit.slice(0, consumed)))
|
|
171
|
+
emitted = match.index + consumed
|
|
172
|
+
// Not `scan.lastIndex = emitted + hit.length`: the rest of the match has to stay
|
|
173
|
+
// in view. It is emitted unchanged by a later iteration (or by the tail below).
|
|
174
|
+
scan.lastIndex = emitted
|
|
175
|
+
}
|
|
176
|
+
out.push(input.slice(emitted))
|
|
177
|
+
return out.join('')
|
|
178
|
+
}
|
package/src/core/engine.ts
CHANGED
|
@@ -657,6 +657,16 @@ export class QueryEngine {
|
|
|
657
657
|
)) {
|
|
658
658
|
yield chunk
|
|
659
659
|
|
|
660
|
+
if (chunk.restart) {
|
|
661
|
+
// A retried turn: everything the failed attempt accumulated is
|
|
662
|
+
// superseded. Drop it here or `toolUses` would carry both attempts'
|
|
663
|
+
// calls and each would execute (see `restart` in StreamChunk).
|
|
664
|
+
assistantContent = ''
|
|
665
|
+
reasoningContent = ''
|
|
666
|
+
thinkingContent = ''
|
|
667
|
+
toolUses.length = 0
|
|
668
|
+
}
|
|
669
|
+
|
|
660
670
|
if (chunk.type === 'error') {
|
|
661
671
|
// #23: client-generated errors are system lines, not model output —
|
|
662
672
|
// store as `system` so resume renders an error line (⚠) rather than
|
|
@@ -998,15 +1008,23 @@ export class QueryEngine {
|
|
|
998
1008
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
999
1009
|
|
|
1000
1010
|
try {
|
|
1001
|
-
for await (const chunk of this.
|
|
1002
|
-
model: this.registry.getActiveModel(),
|
|
1011
|
+
for await (const chunk of this.chatWithFallback(
|
|
1003
1012
|
messages,
|
|
1004
1013
|
systemPrompt,
|
|
1005
|
-
|
|
1014
|
+
toolDefs.length > 0 ? toolDefs : undefined,
|
|
1006
1015
|
signal,
|
|
1007
|
-
|
|
1016
|
+
)) {
|
|
1008
1017
|
yield chunk
|
|
1009
1018
|
|
|
1019
|
+
if (chunk.restart) {
|
|
1020
|
+
// Tool continuation rounds get the same retry + fallback as the first
|
|
1021
|
+
// call via `chatWithFallback`; a retry re-streams the round, so drop
|
|
1022
|
+
// the failed attempt's accumulation or its tools execute twice.
|
|
1023
|
+
assistantContent = ''
|
|
1024
|
+
reasoningContent = ''
|
|
1025
|
+
thinkingContent = ''
|
|
1026
|
+
toolUses.length = 0
|
|
1027
|
+
}
|
|
1010
1028
|
if (chunk.type === 'error') return
|
|
1011
1029
|
if (chunk.type === 'text' && chunk.content) {
|
|
1012
1030
|
assistantContent += chunk.content
|
|
@@ -1083,13 +1101,12 @@ export class QueryEngine {
|
|
|
1083
1101
|
try {
|
|
1084
1102
|
const finalSystemPrompt = this.context.getSystemPrompt()
|
|
1085
1103
|
const finalMessages = this.context.getMessages()
|
|
1086
|
-
for await (const chunk of this.
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
tools: undefined, // no tools — force text-only summary
|
|
1104
|
+
for await (const chunk of this.chatWithFallback(
|
|
1105
|
+
finalMessages,
|
|
1106
|
+
finalSystemPrompt,
|
|
1107
|
+
undefined, // no tools — force text-only summary
|
|
1091
1108
|
signal,
|
|
1092
|
-
|
|
1109
|
+
)) {
|
|
1093
1110
|
yield chunk
|
|
1094
1111
|
if (chunk.type === 'error') return
|
|
1095
1112
|
}
|
|
@@ -1497,12 +1514,23 @@ export class QueryEngine {
|
|
|
1497
1514
|
* 被干净地关掉、正常写完,在字节流上是同一个形状),而这里是**每一处消费
|
|
1498
1515
|
* chat 流的地方都必经的唯一出口** —— 转发的循环有两个(`process` 与
|
|
1499
1516
|
* `continueWithTools`),各自补一次正是「两条渲染路径只接一条」的老毛病。
|
|
1517
|
+
*
|
|
1518
|
+
* 被拒绝的一轮同理:`refusal` 也只有 provider 能判(200 拒答与正常 `end_turn`
|
|
1519
|
+
* 在下游是同一个终止 `stop`),而拒答可能**一个字都没有** —— 没有这里点名,
|
|
1520
|
+
* 那一轮就是一块空白屏,用户连「被拒了」都看不出。
|
|
1500
1521
|
*/
|
|
1501
1522
|
private async *llmChat(req: ChatRequest): AsyncGenerator<StreamChunk> {
|
|
1502
1523
|
for await (const chunk of (this.llm ?? this.registry).chat(req)) {
|
|
1503
1524
|
if (chunk.type === 'stop' && chunk.truncated) {
|
|
1504
1525
|
yield { type: 'warning', content: t('errors.turn_truncated') }
|
|
1505
1526
|
}
|
|
1527
|
+
if (chunk.type === 'stop' && chunk.refusal) {
|
|
1528
|
+
const reason = chunk.refusal.explanation
|
|
1529
|
+
yield {
|
|
1530
|
+
type: 'warning',
|
|
1531
|
+
content: reason ? t('errors.turn_refused_reason', { reason }) : t('errors.turn_refused'),
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1506
1534
|
yield chunk
|
|
1507
1535
|
}
|
|
1508
1536
|
}
|
|
@@ -1570,7 +1598,15 @@ export class QueryEngine {
|
|
|
1570
1598
|
failure = String(err)
|
|
1571
1599
|
}
|
|
1572
1600
|
if (!retryable || !ownsFlow || attempt >= 1) break
|
|
1573
|
-
|
|
1601
|
+
// `restart: true` tells the consumer to drop what the failed attempt already
|
|
1602
|
+
// yielded. Without it the retry's tool calls are *added* to the failed
|
|
1603
|
+
// attempt's, and their ids are regenerated per attempt, so nothing
|
|
1604
|
+
// downstream dedupes them and a side-effecting tool runs twice.
|
|
1605
|
+
yield {
|
|
1606
|
+
type: 'warning',
|
|
1607
|
+
content: `${activeId} failed (${failure}) — retrying once`,
|
|
1608
|
+
restart: true,
|
|
1609
|
+
}
|
|
1574
1610
|
}
|
|
1575
1611
|
const detail = failure ?? 'Unknown error'
|
|
1576
1612
|
|
|
@@ -1607,10 +1643,20 @@ export class QueryEngine {
|
|
|
1607
1643
|
// window than the one we fell back from (1M → 128K). Switching the registry
|
|
1608
1644
|
// alone left compaction armed to the *old* model's window, so the summary would
|
|
1609
1645
|
// not trigger until ~950K — long past the point the fallback model overflows.
|
|
1646
|
+
const beforeWindow = this.effectiveWindow(activeModel)
|
|
1610
1647
|
this.switchProvider(defaultId, fallbackModel)
|
|
1648
|
+
// Say so when the switch shrank the window. The user picked a model for what
|
|
1649
|
+
// it could hold; a fallback to a 200K model silently cuts how much of the
|
|
1650
|
+
// conversation still fits (1M → 200K), and that is not obvious from the model
|
|
1651
|
+
// name alone — the same fact the switch itself already acted on.
|
|
1652
|
+
const afterWindow = this.effectiveWindow(fallbackModel)
|
|
1653
|
+
const windowNote =
|
|
1654
|
+
beforeWindow !== undefined && afterWindow !== undefined && afterWindow < beforeWindow
|
|
1655
|
+
? ` (context window ${this.fmtWindow(beforeWindow)} → ${this.fmtWindow(afterWindow)})`
|
|
1656
|
+
: ''
|
|
1611
1657
|
yield {
|
|
1612
1658
|
type: 'warning',
|
|
1613
|
-
content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})`,
|
|
1659
|
+
content: `${activeId} unreachable — degraded to ${defaultId} (${fallbackModel})${windowNote}`,
|
|
1614
1660
|
}
|
|
1615
1661
|
|
|
1616
1662
|
try {
|
|
@@ -1681,6 +1727,8 @@ export class QueryEngine {
|
|
|
1681
1727
|
return t('errors.tool_denied_ask_rule', { name, pattern: rulePattern ?? '?' })
|
|
1682
1728
|
case 'dangerous-rm':
|
|
1683
1729
|
return t('errors.tool_denied_dangerous_rm', { name, target: target ?? '?' })
|
|
1730
|
+
case 'world-writable-chmod':
|
|
1731
|
+
return t('errors.tool_denied_world_writable_chmod', { name, target: target ?? '?' })
|
|
1684
1732
|
default:
|
|
1685
1733
|
// mode-baseline / tool-default / legacy-rule / system-default — a mode
|
|
1686
1734
|
// switch (or /permissions) resolves it.
|
|
@@ -1860,6 +1908,25 @@ export class QueryEngine {
|
|
|
1860
1908
|
}
|
|
1861
1909
|
}
|
|
1862
1910
|
|
|
1911
|
+
/**
|
|
1912
|
+
* The context window a model actually gets in this process: its nominal size,
|
|
1913
|
+
* unless the 1M cap is disabled and it exceeds 200K — the same rule
|
|
1914
|
+
* `switchProvider` applies, so the fallback notice reports the *effective*
|
|
1915
|
+
* window, not the model sheet's.
|
|
1916
|
+
*/
|
|
1917
|
+
private effectiveWindow(modelId: string): number | undefined {
|
|
1918
|
+
const model = this.registry.findModel(modelId)
|
|
1919
|
+
if (!model) return undefined
|
|
1920
|
+
return process.env.MIPHAM_DISABLE_1M_CONTEXT === '1' && model.contextWindow > 200_000
|
|
1921
|
+
? 200_000
|
|
1922
|
+
: model.contextWindow
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
/** `1000000` → `1M`, `128000` → `128K` — for the fallback context-window notice. */
|
|
1926
|
+
private fmtWindow(n: number): string {
|
|
1927
|
+
return n >= 1_000_000 ? `${Math.round(n / 100_000) / 10}M` : `${Math.round(n / 1000)}K`
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1863
1930
|
/** Wrap context compaction with PreCompact/PostCompact hooks. */
|
|
1864
1931
|
private async compactWithHooks(heading: string): Promise<void> {
|
|
1865
1932
|
if (this.hookEngine) {
|
|
@@ -68,18 +68,30 @@ export const PROMPT_VERSION = 'mipham-auto-classifier/1'
|
|
|
68
68
|
* refused for". A budget derived from the fail-open side would be a budget
|
|
69
69
|
* derived from the wrong question.
|
|
70
70
|
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
71
|
+
* 30s is measured, not picked: 24 realistic `ask`-worthy calls per pass, same
|
|
72
|
+
* machine and minute, each request's model read back off the wire rather than
|
|
73
|
+
* trusted from a label.
|
|
74
|
+
*
|
|
75
|
+
* active (reasoning) median 7.6s p90 35.6s max 120.0s over the old 2s: 23/24
|
|
76
|
+
* fast (flash) median 1.3s p90 3.7s max 16.5s over the old 2s: 9/24
|
|
77
|
+
*
|
|
78
|
+
* So the old bound was wrong for **both** models — and since a timeout here is
|
|
79
|
+
* indistinguishable from a denial, "too tight" does not mean slow: every ruled
|
|
80
|
+
* call pays the full wait and the gate then says no to work it should have
|
|
81
|
+
* allowed.
|
|
82
|
+
*
|
|
83
|
+
* The fast model is not the free win its 6× median suggests: over the 20
|
|
84
|
+
* borderline calls sampled against both, it allowed 8 the reasoning model
|
|
85
|
+
* blocked (2 the other way). Speed there is bought with leak, so the default
|
|
86
|
+
* stays the operator's own model (`resolveClassifierModel`), and the number
|
|
87
|
+
* above is the active model's p90 with room for the tail it measured —
|
|
88
|
+
* `permissions.classifierTimeoutMs` exists for a user who has decided otherwise.
|
|
89
|
+
*
|
|
90
|
+
* A longer budget is not the lever it looks like either: both models answer
|
|
91
|
+
* clear-cut calls stably and coin-flip on borderline ones, so what is left here
|
|
92
|
+
* is judgement quality, not patience. Re-measure before re-basing this.
|
|
81
93
|
*/
|
|
82
|
-
export const DEFAULT_CLASSIFIER_TIMEOUT_MS =
|
|
94
|
+
export const DEFAULT_CLASSIFIER_TIMEOUT_MS = 30_000
|
|
83
95
|
|
|
84
96
|
/**
|
|
85
97
|
* Per-value cap on serialized tool input. Truncation is a real boundary here,
|
|
@@ -452,7 +464,19 @@ export class LlmPermissionClassifier implements PermissionClassifier {
|
|
|
452
464
|
}
|
|
453
465
|
|
|
454
466
|
if (streamError) {
|
|
455
|
-
|
|
467
|
+
// The provider surfaces its abort as a *yielded* error chunk, not a throw
|
|
468
|
+
// (`providers/openai-compat.ts`), so a timeout we caused arrives here — and
|
|
469
|
+
// a naive read of `streamError` reports it as "Stream stalled", sending the
|
|
470
|
+
// reader hunting for a network problem. Our own budget expiring is the one
|
|
471
|
+
// cause we already know; name it. (`timedOut` is false for an external
|
|
472
|
+
// abort, so a user interrupt still reads as "unavailable", not "timed out".)
|
|
473
|
+
return {
|
|
474
|
+
allow: false,
|
|
475
|
+
reason: timedOut
|
|
476
|
+
? `classifier timed out after ${this.timeoutMs}ms`
|
|
477
|
+
: `classifier unavailable: ${streamError}`,
|
|
478
|
+
retryable: true,
|
|
479
|
+
}
|
|
456
480
|
}
|
|
457
481
|
|
|
458
482
|
const parsed = parseClassifierResponse(text)
|