@miphamai/cli 0.85.35 → 0.85.37
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 +4 -4
- package/package.json +1 -1
- package/src/commands/environment.ts +53 -69
- package/src/commands/git.ts +53 -16
- package/src/commands/keys.ts +28 -17
- package/src/commands/project.ts +10 -17
- package/src/commands/workflow-view.ts +24 -6
- package/src/config/loader.ts +81 -4
- package/src/core/engine.ts +29 -2
- package/src/core/hooks-executor.ts +15 -0
- package/src/core/improvement-track.ts +37 -1
- package/src/core/meta-rule-engine.ts +3 -1
- package/src/core/permission-rules.ts +60 -0
- package/src/core/permission.ts +17 -5
- package/src/core/rule-engine.ts +11 -5
- package/src/core/task-performance.ts +41 -0
- package/src/daemon/attach-protocol.ts +25 -0
- package/src/daemon/remote-engine.ts +161 -4
- package/src/daemon/session-worker.ts +50 -0
- package/src/i18n-core/detect.ts +16 -4
- package/src/i18n-core/locales/en-US.json +6 -5
- package/src/i18n-core/locales/zh-CN.json +6 -5
- package/src/i18n-core/preference.ts +55 -0
- package/src/index.tsx +3 -2
- package/src/mcp/registry.ts +66 -14
- package/src/shared/package-info.ts +3 -3
- package/src/skills/loader.ts +30 -0
- package/src/skills/seam.ts +7 -0
- package/src/tools/agent/report-findings.ts +20 -2
- package/src/tools/agent/skill.ts +9 -1
- package/src/tools/exec/bash.ts +59 -0
- package/src/tools/exec/git.ts +82 -0
- package/src/tools/network/web-fetch.ts +20 -0
- package/src/ui/app.tsx +40 -20
- package/src/ui/commands.ts +539 -98
- package/src/ui/strip-indent.ts +9 -4
package/src/core/engine.ts
CHANGED
|
@@ -125,6 +125,17 @@ export function filterExpiredMessages(
|
|
|
125
125
|
return messages.filter((m) => now - new Date(m.timestamp).getTime() <= maxAgeMs)
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
const ULTRACODE_INSTRUCTION = `## Ultracode mode is ON
|
|
129
|
+
|
|
130
|
+
For every substantive task, prefer the Workflow tool: fan out independent work to
|
|
131
|
+
parallel agents where it helps, then synthesize. Keep one-shot trivia direct.
|
|
132
|
+
This instruction persists for the session until /ultracode off.`
|
|
133
|
+
|
|
134
|
+
/** Append the mode instruction to a system prompt (pure, so it is testable). */
|
|
135
|
+
export function applyUltracodeMode(prompt: string, on: boolean): string {
|
|
136
|
+
return on ? `${prompt}\n\n${ULTRACODE_INSTRUCTION}` : prompt
|
|
137
|
+
}
|
|
138
|
+
|
|
128
139
|
export class QueryEngine {
|
|
129
140
|
/**
|
|
130
141
|
* `false` for the local engine; `true` for the attach-mode `RemoteEngine`.
|
|
@@ -163,6 +174,13 @@ export class QueryEngine {
|
|
|
163
174
|
private lastAssistantContent?: string
|
|
164
175
|
/** Reasoning effort (low|medium|high|xhigh|max) — scales the provider idle timeout. */
|
|
165
176
|
private effort: string = 'high'
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Ultracode mode is a **persistent instruction**, not a one-turn prompt.
|
|
180
|
+
* `/ultracode on` used to set a React state nobody read, and its effect ended
|
|
181
|
+
* with the current turn's injected prompt.
|
|
182
|
+
*/
|
|
183
|
+
private ultracode = false
|
|
166
184
|
/** Custom verification shell script path for goal checking. */
|
|
167
185
|
private goalVerifyScript?: string
|
|
168
186
|
/** Custom verification skill name for goal checking. */
|
|
@@ -271,6 +289,15 @@ export class QueryEngine {
|
|
|
271
289
|
this.effort = level
|
|
272
290
|
}
|
|
273
291
|
|
|
292
|
+
/** Toggle ultracode mode; the instruction is re-applied to every request. */
|
|
293
|
+
setUltracodeMode(on: boolean): void {
|
|
294
|
+
this.ultracode = on
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
getUltracodeMode(): boolean {
|
|
298
|
+
return this.ultracode
|
|
299
|
+
}
|
|
300
|
+
|
|
274
301
|
/**
|
|
275
302
|
* Forget which files the Read tool has loaded.
|
|
276
303
|
*
|
|
@@ -771,7 +798,7 @@ export class QueryEngine {
|
|
|
771
798
|
await this.compactWithHooks('conversation summary', signal)
|
|
772
799
|
}
|
|
773
800
|
|
|
774
|
-
const systemPrompt = this.context.getSystemPrompt()
|
|
801
|
+
const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
|
|
775
802
|
const messages = this.context.getMessages()
|
|
776
803
|
const toolDefs = this.getToolDefinitions()
|
|
777
804
|
|
|
@@ -1229,7 +1256,7 @@ export class QueryEngine {
|
|
|
1229
1256
|
yield { type: 'stop' }
|
|
1230
1257
|
return
|
|
1231
1258
|
}
|
|
1232
|
-
const systemPrompt = this.context.getSystemPrompt()
|
|
1259
|
+
const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
|
|
1233
1260
|
const messages = this.context.getMessages()
|
|
1234
1261
|
|
|
1235
1262
|
// ── PreInference DLP checkpoint (every tool-calling turn) ──
|
|
@@ -457,6 +457,21 @@ async function executeCommand(
|
|
|
457
457
|
}
|
|
458
458
|
}
|
|
459
459
|
|
|
460
|
+
// Exit 127 is the shell's "command not found": the hook never started, so it
|
|
461
|
+
// never decided anything. Told apart from a normal non-zero exit (which *is*
|
|
462
|
+
// an answer) and routed through the same fail-closed path as a spawn
|
|
463
|
+
// failure — otherwise a missing interpreter is printed as a warning and a
|
|
464
|
+
// guard that never ran reads exactly like a guard that said yes.
|
|
465
|
+
if (result.status === 127) {
|
|
466
|
+
return failureResult(
|
|
467
|
+
cfg,
|
|
468
|
+
ctx,
|
|
469
|
+
`Hook error ${failingLabel(cfg.command, source)}: exit 127 — the hook's command or ` +
|
|
470
|
+
`interpreter was not found, so its check may not have run`,
|
|
471
|
+
'exit 127: command or interpreter not found',
|
|
472
|
+
)
|
|
473
|
+
}
|
|
474
|
+
|
|
460
475
|
const failure = spawnFailureCause(result, hookTimeoutSeconds(cfg))
|
|
461
476
|
if (failure) {
|
|
462
477
|
return failureResult(
|
|
@@ -32,6 +32,14 @@ export interface ImprovementReport {
|
|
|
32
32
|
*/
|
|
33
33
|
baselineDurations?: number[]
|
|
34
34
|
postDurations?: number[]
|
|
35
|
+
/**
|
|
36
|
+
* 空模型闸(null-model ablation):空程序也能通过的题数 / 总题数。
|
|
37
|
+
* 两个字段同生同灭;缺席 = 旧记录或未测。
|
|
38
|
+
*/
|
|
39
|
+
nullModelPassed?: number
|
|
40
|
+
nullModelTotal?: number
|
|
41
|
+
/** 闸的结论:failed = 有题空程序也能过 ⇒ `improved` 不可归因。 */
|
|
42
|
+
nullModelGate?: 'passed' | 'failed'
|
|
35
43
|
}
|
|
36
44
|
|
|
37
45
|
export interface ImprovementRecord extends ImprovementReport {
|
|
@@ -70,7 +78,20 @@ export function buildImprovementReport(
|
|
|
70
78
|
const deltaMean = mean(sample.postScores) - mean(sample.baselineScores)
|
|
71
79
|
const noise = stdDev(sample.baselineScores)
|
|
72
80
|
const minEffect = computeMinEffect(noise)
|
|
73
|
-
const
|
|
81
|
+
const rawVerdict = classifyDelta(deltaMean, minEffect)
|
|
82
|
+
|
|
83
|
+
// 空模型闸:只拦「假赢」。空程序能通过的题不测模型,故 improved 不可归因;
|
|
84
|
+
// regressed 照旧 —— 它说的是「变差了」,与题是不是真空题无关。
|
|
85
|
+
const nullModelMeasured =
|
|
86
|
+
sample.nullModelPassed !== undefined && sample.nullModelTotal !== undefined
|
|
87
|
+
const nullModelGate = nullModelMeasured
|
|
88
|
+
? sample.nullModelPassed! > 0
|
|
89
|
+
? ('failed' as const)
|
|
90
|
+
: ('passed' as const)
|
|
91
|
+
: undefined
|
|
92
|
+
const verdict =
|
|
93
|
+
nullModelGate === 'failed' && rawVerdict === 'improved' ? 'inconclusive' : rawVerdict
|
|
94
|
+
|
|
74
95
|
return {
|
|
75
96
|
skillName: sample.skillName,
|
|
76
97
|
changeSet,
|
|
@@ -94,9 +115,24 @@ export function buildImprovementReport(
|
|
|
94
115
|
...(sample.baselineDurations !== undefined && sample.postDurations !== undefined
|
|
95
116
|
? { baselineDurations: sample.baselineDurations, postDurations: sample.postDurations }
|
|
96
117
|
: {}),
|
|
118
|
+
// 三个键同生同灭:只写一半会让「测过且通过」与「没测」在记录里同形。
|
|
119
|
+
...(nullModelMeasured
|
|
120
|
+
? {
|
|
121
|
+
nullModelPassed: sample.nullModelPassed!,
|
|
122
|
+
nullModelTotal: sample.nullModelTotal!,
|
|
123
|
+
nullModelGate,
|
|
124
|
+
}
|
|
125
|
+
: {}),
|
|
97
126
|
}
|
|
98
127
|
}
|
|
99
128
|
|
|
129
|
+
/** 空模型闸失败时给出一行可见读数;闸通过则不出声(不占显示行)。 */
|
|
130
|
+
export function formatNullModelLine(report: ImprovementReport): string | null {
|
|
131
|
+
if (report.nullModelGate !== 'failed' || report.nullModelPassed === undefined) return null
|
|
132
|
+
const total = report.nullModelTotal ?? 0
|
|
133
|
+
return `🕳️ 空模型闸: 空程序已通过 ${report.nullModelPassed}/${total} 题 —— 这些题测的不是模型,改进判定已降级`
|
|
134
|
+
}
|
|
135
|
+
|
|
100
136
|
/** Wilson score 区间(z 默认 1.96 = 95%)。n=0 → {0,0}。 */
|
|
101
137
|
export function wilsonInterval(
|
|
102
138
|
improved: number,
|
|
@@ -572,7 +572,9 @@ export class MetaRuleEngine {
|
|
|
572
572
|
|
|
573
573
|
const autoApplicable = metaRules.filter((m) => m.autoApplicable)
|
|
574
574
|
if (autoApplicable.length > 0) {
|
|
575
|
-
recommendations.push(
|
|
575
|
+
recommendations.push(
|
|
576
|
+
`${autoApplicable.length} 个元规则可自动应用;当前版本不自动落盘,请人工复核后固化`,
|
|
577
|
+
)
|
|
576
578
|
}
|
|
577
579
|
|
|
578
580
|
if (recommendations.length === 0) {
|
|
@@ -1253,6 +1253,66 @@ export function variableWildcardWarning(pattern: string): string | undefined {
|
|
|
1253
1253
|
)
|
|
1254
1254
|
}
|
|
1255
1255
|
|
|
1256
|
+
/** Runners for which *every* invocation fetches and runs a package (`uvx`, `npx`…). */
|
|
1257
|
+
const ALWAYS_PACKAGE_RUNNERS = new Set(['npx', 'bunx', 'uvx'])
|
|
1258
|
+
|
|
1259
|
+
/** Runners that only do so through a named subcommand (`pnpm dlx`, `pipx run`…). */
|
|
1260
|
+
const PACKAGE_RUNNERS = new Set(['pnpm', 'yarn', 'npm', 'bun', 'pipx', ...ALWAYS_PACKAGE_RUNNERS])
|
|
1261
|
+
|
|
1262
|
+
/** Their subcommands that run a package the rule did not name. */
|
|
1263
|
+
const RUNNER_EXEC_SUBS = new Set(['dlx', 'exec', 'x'])
|
|
1264
|
+
|
|
1265
|
+
/** `pipx run <package>` — `run` is pipx's own spelling, not `npm run`'s script. */
|
|
1266
|
+
const PIPX_EXEC_SUBS = new Set(['run'])
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* Does this **Bash allow** rule grant more than "the program it names"?
|
|
1270
|
+
*
|
|
1271
|
+
* `auto` mode hands everything it is unsure about to the safety classifier — but
|
|
1272
|
+
* an allow rule short-circuits *ahead* of that classifier, so a rule that names
|
|
1273
|
+
* no program at all (`Bash(*)`), names a **path or variable** instead of a
|
|
1274
|
+
* program (`Bash($HOME/bin/…)`, `Bash(/usr/bin/npm:*)`), or names a **package
|
|
1275
|
+
* runner** whose subcommand fetches and runs arbitrary code (`Bash(pnpm dlx *)`)
|
|
1276
|
+
* would silently disable the mode's one safety check for every command it
|
|
1277
|
+
* matches. The rule is still honored in every other mode; only `auto` declines
|
|
1278
|
+
* to read it as a grant, so its commands go to the classifier.
|
|
1279
|
+
*
|
|
1280
|
+
* Deliberately narrow: a rule that names a concrete program (`Bash(npm test:*)`)
|
|
1281
|
+
* keeps granting. The named shapes are ones where the *program* is not decided
|
|
1282
|
+
* by the rule.
|
|
1283
|
+
*/
|
|
1284
|
+
export function isUnboundedBashAllowRule(pattern: string): boolean {
|
|
1285
|
+
const shape = /^Bash\((.+)\)$/.exec(pattern)
|
|
1286
|
+
if (!shape) return false
|
|
1287
|
+
const sub = shape[1]!.trim()
|
|
1288
|
+
if (sub === '' || sub === '*') return true
|
|
1289
|
+
|
|
1290
|
+
// A drive-letter path carries a colon of its own; judging the drive before the
|
|
1291
|
+
// `:`-as-separator split keeps `Bash(C:\tools\x.exe:*)` a path, not a program
|
|
1292
|
+
// called `C`.
|
|
1293
|
+
if (/^[A-Za-z]:[\\/]/.test(sub)) return true
|
|
1294
|
+
|
|
1295
|
+
const words = sub.split(/[:\s]+/).filter(Boolean)
|
|
1296
|
+
const first = words[0] ?? ''
|
|
1297
|
+
if (first === '' || first === '*') return true
|
|
1298
|
+
|
|
1299
|
+
// A variable or a path decides *where* a program lives (or which value is
|
|
1300
|
+
// used), not which program runs — and a shell wildcard inside it can make the
|
|
1301
|
+
// outer match accept a command the author never looked at.
|
|
1302
|
+
if (/^[$~]/.test(first)) return true
|
|
1303
|
+
if (/^\.{0,2}[\\/]/.test(first)) return true
|
|
1304
|
+
if (/^[A-Za-z]:[\\/]/.test(first)) return true
|
|
1305
|
+
|
|
1306
|
+
const program = first.toLowerCase()
|
|
1307
|
+
if (ALWAYS_PACKAGE_RUNNERS.has(program)) return true
|
|
1308
|
+
if (!PACKAGE_RUNNERS.has(program)) return false
|
|
1309
|
+
const second = words[1]?.toLowerCase()
|
|
1310
|
+
// `Bash(npx:*)` names the runner and nothing else; `Bash(pnpm dlx *)` names the
|
|
1311
|
+
// one subcommand whose entire job is "fetch this package and run it".
|
|
1312
|
+
if (second === undefined) return true
|
|
1313
|
+
return program === 'pipx' ? PIPX_EXEC_SUBS.has(second) : RUNNER_EXEC_SUBS.has(second)
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1256
1316
|
/**
|
|
1257
1317
|
* Compile a rule pattern string into a PermissionRuleEntry.
|
|
1258
1318
|
*/
|
package/src/core/permission.ts
CHANGED
|
@@ -6,7 +6,12 @@ import type {
|
|
|
6
6
|
PermissionRestrictions,
|
|
7
7
|
} from '../shared/index.ts'
|
|
8
8
|
import type { PermissionRuleEntry } from '../shared/index.ts'
|
|
9
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
matchBashRule,
|
|
11
|
+
compileRule,
|
|
12
|
+
variableWildcardWarning,
|
|
13
|
+
isUnboundedBashAllowRule,
|
|
14
|
+
} from './permission-rules'
|
|
10
15
|
import { detectDangerousRm } from '../security/dangerous-rm'
|
|
11
16
|
import type { DangerousRm } from '../security/dangerous-rm'
|
|
12
17
|
import { detectWorldWritableChmod } from '../security/world-writable-chmod'
|
|
@@ -637,11 +642,18 @@ export class PermissionSystem {
|
|
|
637
642
|
|
|
638
643
|
// 3. Check allow rules — but an org ceiling still applies (see allowRuleDecision)
|
|
639
644
|
for (const rule of this.allowRules) {
|
|
640
|
-
if (this.ruleMatches(rule, tool, input))
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
645
|
+
if (!this.ruleMatches(rule, tool, input)) continue
|
|
646
|
+
// In `auto`, a rule that names no program does not stand in for the safety
|
|
647
|
+
// classifier. An allow rule sits *ahead* of the mode baseline, so
|
|
648
|
+
// `allow: ["Bash(*)"]` would otherwise make the one mode that examines
|
|
649
|
+
// commands examine none of them — the rule would be a universal bypass of
|
|
650
|
+
// the mode's entire check. The rule still grants in every other mode.
|
|
651
|
+
if (this.mode === 'auto' && tool.name === 'Bash' && isUnboundedBashAllowRule(rule.pattern)) {
|
|
652
|
+
continue
|
|
644
653
|
}
|
|
654
|
+
const result = this.allowRuleDecision(tool, input)
|
|
655
|
+
this.checkCache.set(cacheKey, result)
|
|
656
|
+
return result
|
|
645
657
|
}
|
|
646
658
|
|
|
647
659
|
// 4. Legacy exact-name rules (backward compat)
|
package/src/core/rule-engine.ts
CHANGED
|
@@ -165,12 +165,18 @@ export class ExperienceRuleEngine {
|
|
|
165
165
|
return this.rules.filter((r) => r.enabled)
|
|
166
166
|
}
|
|
167
167
|
|
|
168
|
-
|
|
168
|
+
/** Returns false when no rule has that id — callers must not report success. */
|
|
169
|
+
setRuleEnabled(id: string, enabled: boolean): boolean {
|
|
169
170
|
const rule = this.rules.find((r) => r.id === id)
|
|
170
|
-
if (rule)
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
171
|
+
if (!rule) return false
|
|
172
|
+
rule.enabled = enabled
|
|
173
|
+
this.persist()
|
|
174
|
+
return true
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Find a rule by id (used to tell the user whether a toggle will persist). */
|
|
178
|
+
getRule(id: string): ToolRule | undefined {
|
|
179
|
+
return this.rules.find((r) => r.id === id)
|
|
174
180
|
}
|
|
175
181
|
|
|
176
182
|
/** Persist runtime rules to disk. Builtin 与 managed 规则永不落盘(源码即真相)。 */
|
|
@@ -68,6 +68,35 @@ export interface TaskPerformanceResult {
|
|
|
68
68
|
truncated?: boolean
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/** 空模型闸的读数:`passed` = 空程序也能通过的题数。 */
|
|
72
|
+
export interface NullModelCheck {
|
|
73
|
+
total: number
|
|
74
|
+
passed: number
|
|
75
|
+
/** 空程序也通过的题 id —— 它们正是这道闸抓到的「不是模型题」的题。 */
|
|
76
|
+
failures: string[]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 空模型消融:对每道题只用**空程序**跑冻结测试。
|
|
81
|
+
*
|
|
82
|
+
* 来源是自改进研究的 null-model control:把模型换成空 stub 重跑,分数仍涨就说明
|
|
83
|
+
* 「改进」不是模型带来的。在我们的架构里模型不产出 ⇒ 空程序;能通过,就说明这道
|
|
84
|
+
* 题测的是测试自身的空转(例如恒真断言),不是模型能力。
|
|
85
|
+
*/
|
|
86
|
+
export function countEmptySolutionPasses(tasks: PerformanceTask[]): NullModelCheck {
|
|
87
|
+
const failures: string[] = []
|
|
88
|
+
for (const task of tasks) {
|
|
89
|
+
if (judgeGeneratedCode(task.testCode, '').passed) failures.push(task.id)
|
|
90
|
+
}
|
|
91
|
+
return { total: tasks.length, passed: failures.length, failures }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 按 skill 名取任务集再跑空模型闸;未绑定任何任务的 skill → total 0(空转,不是通过)。 */
|
|
95
|
+
export function runNullModelCheck(skill?: string): NullModelCheck {
|
|
96
|
+
const tasks = loadPerformanceTasks().filter((t) => (t.skill ?? undefined) === skill)
|
|
97
|
+
return countEmptySolutionPasses(tasks)
|
|
98
|
+
}
|
|
99
|
+
|
|
71
100
|
export interface TaskPerformanceReport {
|
|
72
101
|
total: number
|
|
73
102
|
passed: number
|
|
@@ -242,6 +271,13 @@ export interface SkillDeltaSample {
|
|
|
242
271
|
skillName: string
|
|
243
272
|
baselineScores: number[]
|
|
244
273
|
postScores: number[]
|
|
274
|
+
/**
|
|
275
|
+
* 空模型闸:把**空程序**喂给同一组冻结测试,通过的题数。
|
|
276
|
+
* 通过 > 0 ⇒ 这些题空程序也能过,测的不是模型能力 ⇒ 改进判定不可归因。
|
|
277
|
+
* 缺席 = 旧记录 / 未测(与 nullModelTotal 同生同灭)。
|
|
278
|
+
*/
|
|
279
|
+
nullModelPassed?: number
|
|
280
|
+
nullModelTotal?: number
|
|
245
281
|
/**
|
|
246
282
|
* B2 代价维:与分数数组**逐项对齐**的耗时(第 i 项就是产出第 i 个分数的那次采样)。
|
|
247
283
|
* 缺席 = 该样本未记代价(旧记录 / 旧调用点),读侧须按「缺席」处理、不得当成 0。
|
|
@@ -283,11 +319,16 @@ export async function measureSkillDeltaRepeated(
|
|
|
283
319
|
postDurations.push(r.durationMs)
|
|
284
320
|
}
|
|
285
321
|
|
|
322
|
+
// 空模型闸在最后一次采样后算一次:与模型无关,重复跑只是重复同一组测试。
|
|
323
|
+
const nullCheck = runNullModelCheck(resolved.skillName)
|
|
324
|
+
|
|
286
325
|
return {
|
|
287
326
|
skillName: resolved.skillName,
|
|
288
327
|
baselineScores,
|
|
289
328
|
postScores,
|
|
290
329
|
baselineDurations,
|
|
291
330
|
postDurations,
|
|
331
|
+
nullModelPassed: nullCheck.passed,
|
|
332
|
+
nullModelTotal: nullCheck.total,
|
|
292
333
|
}
|
|
293
334
|
}
|
|
@@ -88,6 +88,30 @@ export interface ServerModeMessage {
|
|
|
88
88
|
sessionId: string
|
|
89
89
|
mode: PermissionMode
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* 会话读数(daemon → 客户端)。`attach` 的本地 `getContext()` 是个薄桩,
|
|
93
|
+
* `/status`、`/cost`、`/doctor` 这类只读命令要用到的 token / 窗口 / checkpoint
|
|
94
|
+
* 数都在 daemon 手里 —— 由这一帧送过来,客户端据此作答,而不是显示一排 0。
|
|
95
|
+
*
|
|
96
|
+
* 每个字段都按「daemon 可能没送」处理:两端版本独立,缺字段或类型不对时客户端
|
|
97
|
+
* 保持原值(不拿 NaN 去渲染)。
|
|
98
|
+
*/
|
|
99
|
+
export interface ServerStatsMessage {
|
|
100
|
+
type: 'stats'
|
|
101
|
+
sessionId: string
|
|
102
|
+
/** 引擎上下文当前的估算 token 数。 */
|
|
103
|
+
estimatedTokens: number
|
|
104
|
+
/** 模型上下文窗口。 */
|
|
105
|
+
maxTokens: number
|
|
106
|
+
/** 触发压缩的阈值(token)。 */
|
|
107
|
+
compactionThreshold: number
|
|
108
|
+
/** 引擎上下文里的消息数。 */
|
|
109
|
+
messageCount: number
|
|
110
|
+
/** 本会话已保存的 checkpoint 数。 */
|
|
111
|
+
checkpointCount: number
|
|
112
|
+
/** 当前由 provider prompt cache 提供的 token 数。 */
|
|
113
|
+
cachedTokens: number
|
|
114
|
+
}
|
|
91
115
|
|
|
92
116
|
export type ServerMessage =
|
|
93
117
|
| ServerTextMessage
|
|
@@ -99,3 +123,4 @@ export type ServerMessage =
|
|
|
99
123
|
| ServerErrorMessage
|
|
100
124
|
| ServerSessionStateMessage
|
|
101
125
|
| ServerModeMessage
|
|
126
|
+
| ServerStatsMessage
|
|
@@ -22,10 +22,29 @@ import type {
|
|
|
22
22
|
ClientInterruptMessage,
|
|
23
23
|
ClientSetModeMessage,
|
|
24
24
|
ServerMessage,
|
|
25
|
+
ServerStatsMessage,
|
|
25
26
|
} from './attach-protocol'
|
|
26
27
|
import { ALL_MODES } from '../core/permission-config'
|
|
27
28
|
import type { PermissionMode, StreamChunk } from '../shared/types'
|
|
28
29
|
|
|
30
|
+
/**
|
|
31
|
+
* Flatten a message's content (string, or the provider block array) into the
|
|
32
|
+
* plain text local commands display. Unknown shapes become '' rather than
|
|
33
|
+
* `[object Object]`.
|
|
34
|
+
*/
|
|
35
|
+
function contentToText(value: unknown): string {
|
|
36
|
+
if (typeof value === 'string') return value
|
|
37
|
+
if (!Array.isArray(value)) return ''
|
|
38
|
+
return value
|
|
39
|
+
.map((block) =>
|
|
40
|
+
typeof block === 'object' && block !== null && typeof (block as any).text === 'string'
|
|
41
|
+
? ((block as any).text as string)
|
|
42
|
+
: '',
|
|
43
|
+
)
|
|
44
|
+
.filter((text) => text !== '')
|
|
45
|
+
.join(' ')
|
|
46
|
+
}
|
|
47
|
+
|
|
29
48
|
// ── Public API ───────────────────────────────────────────────────────────────
|
|
30
49
|
|
|
31
50
|
export interface RemoteEngineOptions {
|
|
@@ -89,6 +108,25 @@ export class RemoteEngine {
|
|
|
89
108
|
/** Viewers of the confirmed mode (the TUI footer). See `onPermissionModeChange`. */
|
|
90
109
|
private readonly modeListeners = new Set<(mode: PermissionMode) => void>()
|
|
91
110
|
|
|
111
|
+
// ── Session readings (the numbers live on the daemon) ────────────────────
|
|
112
|
+
//
|
|
113
|
+
// `getContext()` below is the local stand-in slash commands read. Its numbers
|
|
114
|
+
// come from the daemon's `stats` frames — attach sends one immediately, and
|
|
115
|
+
// one follows every completed turn. Fields are merged individually: the two
|
|
116
|
+
// sides version independently, so a missing or malformed field must leave the
|
|
117
|
+
// previous value (or zero) in place rather than poison the display with NaN.
|
|
118
|
+
private stats: {
|
|
119
|
+
estimatedTokens: number
|
|
120
|
+
maxTokens: number
|
|
121
|
+
compactionThreshold: number
|
|
122
|
+
messageCount: number
|
|
123
|
+
checkpointCount: number
|
|
124
|
+
cachedTokens: number
|
|
125
|
+
} | null = null
|
|
126
|
+
|
|
127
|
+
/** Messages from the last `session_state` snapshot, parsed for local commands. */
|
|
128
|
+
private snapshotMessages: Array<{ role: string; content: string }> = []
|
|
129
|
+
|
|
92
130
|
/**
|
|
93
131
|
* One stable object — **not** a fresh closure per `getPermission()` call.
|
|
94
132
|
*
|
|
@@ -322,12 +360,27 @@ export class RemoteEngine {
|
|
|
322
360
|
/** No-op: agents run on the daemon. */
|
|
323
361
|
setAgentRegistry(_reg: unknown): void {}
|
|
324
362
|
|
|
325
|
-
/**
|
|
363
|
+
/**
|
|
364
|
+
* Returns the context stand-in slash commands read. Reads are backed by the
|
|
365
|
+
* daemon's `stats` frames and the last `session_state` snapshot; writes stay
|
|
366
|
+
* no-ops because the conversation lives on the daemon (commands that would
|
|
367
|
+
* mutate it are refused in `commands.ts`, not faked here).
|
|
368
|
+
*/
|
|
326
369
|
getContext(): {
|
|
327
370
|
saveCheckpoint(_label: string): void
|
|
328
371
|
clear(): void
|
|
329
372
|
getMessages(): Array<{ role: string; content: string }>
|
|
330
373
|
getEstimatedTokens(): number
|
|
374
|
+
getMessageCount(): number
|
|
375
|
+
getMaxTokens(): number
|
|
376
|
+
getCompactionThreshold(): number
|
|
377
|
+
getCheckpoints(): unknown[]
|
|
378
|
+
getCacheStatus(): {
|
|
379
|
+
totalMessages: number
|
|
380
|
+
cachedMessages: number
|
|
381
|
+
cachedTokens: number
|
|
382
|
+
uncachedTokens: number
|
|
383
|
+
}
|
|
331
384
|
} {
|
|
332
385
|
return {
|
|
333
386
|
saveCheckpoint: (_label: string) => {
|
|
@@ -336,8 +389,25 @@ export class RemoteEngine {
|
|
|
336
389
|
clear: () => {
|
|
337
390
|
// Remote mode: session history lives on the daemon
|
|
338
391
|
},
|
|
339
|
-
getMessages: () => [],
|
|
340
|
-
getEstimatedTokens: () => 0,
|
|
392
|
+
getMessages: () => [...this.snapshotMessages],
|
|
393
|
+
getEstimatedTokens: () => this.stats?.estimatedTokens ?? 0,
|
|
394
|
+
// Exact when the daemon has reported; the snapshot is only the last 100.
|
|
395
|
+
getMessageCount: () => this.stats?.messageCount ?? this.snapshotMessages.length,
|
|
396
|
+
getMaxTokens: () => this.stats?.maxTokens ?? 0,
|
|
397
|
+
getCompactionThreshold: () => this.stats?.compactionThreshold ?? 0,
|
|
398
|
+
// Callers only read `.length`; the entries themselves have no reader here.
|
|
399
|
+
getCheckpoints: () =>
|
|
400
|
+
Array.from({ length: Math.max(0, this.stats?.checkpointCount ?? 0) }, () => undefined),
|
|
401
|
+
getCacheStatus: () => {
|
|
402
|
+
const estimated = this.stats?.estimatedTokens ?? 0
|
|
403
|
+
const cached = this.stats?.cachedTokens ?? 0
|
|
404
|
+
return {
|
|
405
|
+
totalMessages: this.stats?.messageCount ?? this.snapshotMessages.length,
|
|
406
|
+
cachedMessages: 0,
|
|
407
|
+
cachedTokens: cached,
|
|
408
|
+
uncachedTokens: Math.max(0, estimated - cached),
|
|
409
|
+
}
|
|
410
|
+
},
|
|
341
411
|
}
|
|
342
412
|
}
|
|
343
413
|
|
|
@@ -408,10 +478,17 @@ export class RemoteEngine {
|
|
|
408
478
|
}
|
|
409
479
|
|
|
410
480
|
/** Returns a stub registry so slash commands don't crash. */
|
|
411
|
-
getRegistry(): {
|
|
481
|
+
getRegistry(): {
|
|
482
|
+
getProvider(_id: string): unknown
|
|
483
|
+
getProviders(): unknown[]
|
|
484
|
+
healthMap(): Promise<Map<string, boolean>>
|
|
485
|
+
} {
|
|
412
486
|
return {
|
|
413
487
|
getProvider: (_id: string) => undefined,
|
|
414
488
|
getProviders: () => [],
|
|
489
|
+
// `/status` awaits this. A registry stub without it crashes the command — the
|
|
490
|
+
// same shape as the missing context readers this file now backs with stats.
|
|
491
|
+
healthMap: async () => new Map<string, boolean>(),
|
|
415
492
|
}
|
|
416
493
|
}
|
|
417
494
|
|
|
@@ -451,9 +528,17 @@ export class RemoteEngine {
|
|
|
451
528
|
return
|
|
452
529
|
}
|
|
453
530
|
|
|
531
|
+
// Session readings, not prompt stream: local commands read them, and they must be
|
|
532
|
+
// absorbed even when nothing is consuming chunks.
|
|
533
|
+
if (msg.type === 'stats') {
|
|
534
|
+
this.absorbStats(msg)
|
|
535
|
+
return
|
|
536
|
+
}
|
|
537
|
+
|
|
454
538
|
// Session facts, not prompt stream: they carry the gate's current mode and must be
|
|
455
539
|
// absorbed even when nothing is consuming chunks (a keypress, not a turn).
|
|
456
540
|
if (msg.type === 'mode' || msg.type === 'session_state') {
|
|
541
|
+
if (msg.type === 'session_state') this.absorbSnapshotMessages(msg.messages)
|
|
457
542
|
// A snapshot describes the gate as of connect — see `absorbMode`.
|
|
458
543
|
this.absorbMode(msg.mode, msg.type === 'session_state')
|
|
459
544
|
return
|
|
@@ -516,6 +601,78 @@ export class RemoteEngine {
|
|
|
516
601
|
* it is already superseded by a request that is in flight; the answer is what the footer
|
|
517
602
|
* needs, and the daemon always sends one for a `set_mode` it understood.
|
|
518
603
|
*/
|
|
604
|
+
/**
|
|
605
|
+
* Merge one `stats` frame into the local readings.
|
|
606
|
+
*
|
|
607
|
+
* Per-field merge, not replace: a field the daemon did not send (older daemon,
|
|
608
|
+
* or one that omits a reader) keeps its previous value, and a malformed one is
|
|
609
|
+
* ignored. The alternative is a single `null` turning the footer into `NaN`.
|
|
610
|
+
*/
|
|
611
|
+
private absorbStats(msg: ServerStatsMessage): void {
|
|
612
|
+
const num = (value: unknown): number | undefined =>
|
|
613
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined
|
|
614
|
+
const patch = {
|
|
615
|
+
estimatedTokens: num(msg.estimatedTokens),
|
|
616
|
+
maxTokens: num(msg.maxTokens),
|
|
617
|
+
compactionThreshold: num(msg.compactionThreshold),
|
|
618
|
+
messageCount: num(msg.messageCount),
|
|
619
|
+
checkpointCount: num(msg.checkpointCount),
|
|
620
|
+
cachedTokens: num(msg.cachedTokens),
|
|
621
|
+
}
|
|
622
|
+
const current = this.stats ?? {
|
|
623
|
+
estimatedTokens: 0,
|
|
624
|
+
maxTokens: 0,
|
|
625
|
+
compactionThreshold: 0,
|
|
626
|
+
messageCount: 0,
|
|
627
|
+
checkpointCount: 0,
|
|
628
|
+
cachedTokens: 0,
|
|
629
|
+
}
|
|
630
|
+
this.stats = {
|
|
631
|
+
estimatedTokens: patch.estimatedTokens ?? current.estimatedTokens,
|
|
632
|
+
maxTokens: patch.maxTokens ?? current.maxTokens,
|
|
633
|
+
compactionThreshold: patch.compactionThreshold ?? current.compactionThreshold,
|
|
634
|
+
messageCount: patch.messageCount ?? current.messageCount,
|
|
635
|
+
checkpointCount: patch.checkpointCount ?? current.checkpointCount,
|
|
636
|
+
cachedTokens: patch.cachedTokens ?? current.cachedTokens,
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Parse the snapshot's `MessageRecord[]` into the `{role, content}` shape local
|
|
642
|
+
* commands read. `content` is JSON-serialized on the daemon side; a record whose
|
|
643
|
+
* payload is not JSON is kept as plain text (a malformed record must not drop the
|
|
644
|
+
* whole snapshot).
|
|
645
|
+
*/
|
|
646
|
+
private absorbSnapshotMessages(records: unknown): void {
|
|
647
|
+
if (!Array.isArray(records)) return
|
|
648
|
+
const parsed: Array<{ role: string; content: string }> = []
|
|
649
|
+
for (const record of records) {
|
|
650
|
+
if (typeof record !== 'object' || record === null) continue
|
|
651
|
+
const rec = record as Record<string, unknown>
|
|
652
|
+
let payload: unknown = rec.content
|
|
653
|
+
if (typeof payload === 'string') {
|
|
654
|
+
try {
|
|
655
|
+
payload = JSON.parse(payload)
|
|
656
|
+
} catch {
|
|
657
|
+
// Not JSON — treat the string itself as the content below.
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const payloadRecord =
|
|
661
|
+
typeof payload === 'object' && payload !== null
|
|
662
|
+
? (payload as Record<string, unknown>)
|
|
663
|
+
: null
|
|
664
|
+
const role =
|
|
665
|
+
typeof payloadRecord?.role === 'string'
|
|
666
|
+
? payloadRecord.role
|
|
667
|
+
: typeof rec.role === 'string'
|
|
668
|
+
? rec.role
|
|
669
|
+
: ''
|
|
670
|
+
if (role === '') continue
|
|
671
|
+
parsed.push({ role, content: contentToText(payloadRecord?.content ?? rec.content) })
|
|
672
|
+
}
|
|
673
|
+
this.snapshotMessages = parsed
|
|
674
|
+
}
|
|
675
|
+
|
|
519
676
|
private absorbMode(mode: unknown, fromSnapshot = false): void {
|
|
520
677
|
if (typeof mode !== 'string' || !ALL_MODES.includes(mode as PermissionMode)) return
|
|
521
678
|
const effective = mode as PermissionMode
|