@miphamai/cli 0.85.22 → 0.85.24
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/bin/mipham.ts +40 -13
- package/package.json +1 -1
- package/src/agent/agent-context.ts +19 -6
- package/src/agent/agent-registry.ts +42 -2
- package/src/agent/message-router.ts +30 -0
- package/src/agent/sub-agent.ts +17 -0
- package/src/config/loader.ts +41 -0
- package/src/core/context-microcompact.ts +1 -1
- package/src/core/context.ts +167 -10
- package/src/core/cron-poller.ts +74 -6
- package/src/core/engine.ts +34 -7
- package/src/core/hooks-config.ts +4 -0
- package/src/core/hooks-executor.ts +96 -28
- package/src/core/hooks.ts +49 -3
- package/src/core/permission-rules.ts +32 -2
- package/src/core/safe-mode.ts +11 -0
- package/src/core/session-exit.ts +73 -0
- package/src/core/session-log.ts +36 -1
- package/src/daemon/engine-capabilities.ts +13 -4
- package/src/daemon/launch.ts +37 -0
- package/src/daemon/server.ts +9 -1
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/index.tsx +68 -27
- package/src/mcp/client.ts +22 -8
- package/src/mcp/http-transport.ts +19 -4
- package/src/mcp/registry.ts +40 -5
- package/src/plugin/plugin-loader.ts +4 -0
- package/src/providers/anthropic.ts +8 -2
- package/src/providers/openai-compat.ts +14 -2
- package/src/shared/arg-validation.ts +2 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +18 -0
- package/src/skills/loader.ts +86 -4
- package/src/tools/agent/workflow.ts +9 -2
- package/src/tools/exec/bash.ts +38 -11
- package/src/tools/exec/exit-worktree.ts +45 -4
- package/src/tools/file/read.ts +16 -2
- package/src/tools/network/web-fetch.ts +11 -3
- package/src/tools/network/web-search.ts +5 -1
- package/src/tools/scheduling/cron.ts +2 -1
- package/src/tools/scheduling/schedule-wakeup.ts +23 -8
- package/src/tools/validation.ts +11 -0
- package/src/ui/app.tsx +6 -5
- package/src/ui/commands.ts +17 -8
- package/src/workflow/primitives/agent.ts +34 -5
- package/src/workflow/primitives/verify.ts +36 -20
- package/src/workflow/runtime.ts +10 -2
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.24
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/bin/mipham.ts
CHANGED
|
@@ -375,18 +375,23 @@ async function runDaemonCLI(): Promise<boolean> {
|
|
|
375
375
|
|
|
376
376
|
if (subcmd === 'stop') {
|
|
377
377
|
const { getDaemonStatus } = await import('../src/daemon/index')
|
|
378
|
+
const { terminateDaemonProcess } = await import('../src/daemon/launch')
|
|
378
379
|
const status = getDaemonStatus()
|
|
379
380
|
if (!status) {
|
|
380
381
|
console.log('Daemon is not running.')
|
|
381
382
|
process.exit(0)
|
|
382
383
|
}
|
|
383
|
-
|
|
384
|
-
|
|
384
|
+
const started = Date.now()
|
|
385
|
+
// SIGTERM → wait → SIGKILL → wait. "Stopped" is printed only when the
|
|
386
|
+
// process is confirmed gone; the old code printed it right after send().
|
|
387
|
+
if (await terminateDaemonProcess(status.pid)) {
|
|
385
388
|
console.log(`Daemon stopped (PID: ${status.pid})`)
|
|
386
|
-
|
|
387
|
-
console.log('Daemon is not running.')
|
|
389
|
+
process.exit(0)
|
|
388
390
|
}
|
|
389
|
-
|
|
391
|
+
console.error(
|
|
392
|
+
`Failed to stop daemon (PID: ${status.pid}) after ${Date.now() - started}ms — it is still running.`,
|
|
393
|
+
)
|
|
394
|
+
process.exit(1)
|
|
390
395
|
}
|
|
391
396
|
|
|
392
397
|
if (subcmd === 'status') {
|
|
@@ -1214,6 +1219,15 @@ async function main() {
|
|
|
1214
1219
|
const { PACKAGE_NAME, PACKAGE_VERSION } = await import('../src/shared/package-info')
|
|
1215
1220
|
const APP_VERSION = PACKAGE_VERSION
|
|
1216
1221
|
|
|
1222
|
+
// ── Safe mode ─────────────────────────────────────────────────────────────
|
|
1223
|
+
// Set the env var before subcommand dispatch: `daemon start` re-execs this
|
|
1224
|
+
// binary with an inherited environment, so parsing the flag after
|
|
1225
|
+
// `runDaemonCLI()` would leave the daemon running with every customization
|
|
1226
|
+
// loaded while the foreground CLI believed it had skipped them.
|
|
1227
|
+
if (process.argv.includes('--safe-mode')) {
|
|
1228
|
+
process.env.MIPHAM_SAFE_MODE = '1'
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1217
1231
|
// ── Version flag ──────────────────────────────────────────────────────────
|
|
1218
1232
|
if (
|
|
1219
1233
|
process.argv.includes('--version') ||
|
|
@@ -1260,6 +1274,7 @@ Usage:
|
|
|
1260
1274
|
|
|
1261
1275
|
Flags:
|
|
1262
1276
|
--dump-config Print the assembled profile tree
|
|
1277
|
+
--profile <name> Profile for --dump-config (default: default)
|
|
1263
1278
|
--safe-mode Skip custom agents, skills, hooks, plugins
|
|
1264
1279
|
--resume <name> Open a saved session (see /resume for names)
|
|
1265
1280
|
--permission <mode> Start in this mode: ${ALL_MODES.join('|')}
|
|
@@ -1281,8 +1296,17 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1281
1296
|
const { loadProfile, loadBundle, assemble, dumpConfig } = await import('../src/vajra/compose')
|
|
1282
1297
|
|
|
1283
1298
|
const profileIdx = process.argv.indexOf('--profile')
|
|
1284
|
-
|
|
1285
|
-
|
|
1299
|
+
if (profileIdx !== -1) {
|
|
1300
|
+
const value = process.argv[profileIdx + 1]
|
|
1301
|
+
// A bare `--profile` (or `--profile --safe-mode`) used to fall through to
|
|
1302
|
+
// the `default` profile — the same silent substitution as a misspelled
|
|
1303
|
+
// session name, on the one path where nothing else would catch it.
|
|
1304
|
+
if (!value || value.startsWith('-')) {
|
|
1305
|
+
console.error('Usage: mipham --dump-config --profile <name>')
|
|
1306
|
+
process.exit(1)
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
const profileName = profileIdx !== -1 ? process.argv[profileIdx + 1]! : 'default'
|
|
1286
1310
|
const dir = join(homedir(), '.mipham', 'profiles')
|
|
1287
1311
|
const profilePath = join(dir, `${profileName}.yml`)
|
|
1288
1312
|
|
|
@@ -1297,6 +1321,15 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1297
1321
|
process.exit(0)
|
|
1298
1322
|
}
|
|
1299
1323
|
|
|
1324
|
+
// `--profile` only means something with `--dump-config`. Saying so beats
|
|
1325
|
+
// launching the interactive CLI with a flag that silently does nothing.
|
|
1326
|
+
if (process.argv.includes('--profile')) {
|
|
1327
|
+
console.error(
|
|
1328
|
+
'--profile <name> only applies to --dump-config:\n mipham --dump-config --profile <name>',
|
|
1329
|
+
)
|
|
1330
|
+
process.exit(1)
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1300
1333
|
// ── Update / upgrade ──────────────────────────────────────────────────────
|
|
1301
1334
|
const handledUpdate = await runUpdate()
|
|
1302
1335
|
if (handledUpdate) return
|
|
@@ -1356,12 +1389,6 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1356
1389
|
process.exit(1)
|
|
1357
1390
|
}
|
|
1358
1391
|
|
|
1359
|
-
// Parse --safe-mode flag: skip custom agents, skills, hooks, plugins
|
|
1360
|
-
const safeModeFlag = process.argv.includes('--safe-mode')
|
|
1361
|
-
if (safeModeFlag) {
|
|
1362
|
-
process.env.MIPHAM_SAFE_MODE = '1'
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
1392
|
// Parse --resume <name>: open a saved session instead of starting a new one.
|
|
1366
1393
|
// `runApp` has accepted `options.resume` all along — it restores the session log
|
|
1367
1394
|
// and chdirs to the cwd recorded in the session's `session/start` event — but
|
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { readdirSync, readFileSync, existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { ContextManager } from '../core/context'
|
|
5
|
+
import { mcpServerPrefix } from '../core/permission-rules'
|
|
5
6
|
import type { ToolDefinition } from '../shared/index.ts'
|
|
6
7
|
import type { AgentDefinition } from './types'
|
|
7
8
|
import type { CrsiConfig } from '../shared/index.ts'
|
|
@@ -133,13 +134,25 @@ export function createAgentContext(
|
|
|
133
134
|
let allowedTools = Array.from(toolRegistry.values())
|
|
134
135
|
|
|
135
136
|
if (agentDef.tools) {
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
137
|
+
const allowRules = agentDef.tools
|
|
138
|
+
.split(',')
|
|
139
|
+
.map((s) => s.trim())
|
|
140
|
+
.filter(Boolean)
|
|
141
|
+
// `mcp__server` / `mcp__server__*` mean "every tool on that server".
|
|
142
|
+
// Without expansion these exact-match nothing, so an agent that asks for a
|
|
143
|
+
// whole server silently receives no tools at all.
|
|
144
|
+
const serverPrefixes = allowRules
|
|
145
|
+
.map((r) => mcpServerPrefix(r))
|
|
146
|
+
.filter((p): p is string => p !== null)
|
|
147
|
+
const allowSet = new Set(allowRules.filter((r) => mcpServerPrefix(r) === null))
|
|
148
|
+
allowedTools = allowedTools.filter(
|
|
149
|
+
(t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
|
|
141
150
|
)
|
|
142
|
-
|
|
151
|
+
if (allowedTools.length === 0) {
|
|
152
|
+
process.stderr.write(
|
|
153
|
+
`⚠️ Agent "${agentDef.name}": tools list (${allowRules.join(', ')}) matched no registered tool — the agent will run without tools.\n`,
|
|
154
|
+
)
|
|
155
|
+
}
|
|
143
156
|
}
|
|
144
157
|
|
|
145
158
|
if (agentDef.disallowedTools) {
|
|
@@ -24,6 +24,47 @@ function parseFrontmatter(raw: string): FrontmatterResult {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** `autoCompactWindow` 的合法区间:小到 0 是「一直压」,大到超过任何窗口都是笔误。 */
|
|
28
|
+
const MIN_COMPACT_WINDOW = 1_000
|
|
29
|
+
const MAX_COMPACT_WINDOW = 2_000_000
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 解析 agent 定义里的 `autoCompactWindow`,接受 `200000`、`200k`、`1M` 三种写法。
|
|
33
|
+
*
|
|
34
|
+
* 先前只吃 `number`,字符串被**静默**丢成 `undefined` —— 于是 `autoCompactWindow: 200k`
|
|
35
|
+
* 的代理从不收缩,而且没有任何一处说它被忽略了。一个声明被吞掉时,至少要说一声。
|
|
36
|
+
*/
|
|
37
|
+
export function parseTokenWindow(value: unknown, agentName: string): number | undefined {
|
|
38
|
+
if (value === undefined || value === null) return undefined
|
|
39
|
+
|
|
40
|
+
let parsed: number | undefined
|
|
41
|
+
if (typeof value === 'number') {
|
|
42
|
+
parsed = value
|
|
43
|
+
} else if (typeof value === 'string') {
|
|
44
|
+
const m = value.trim().match(/^(\d+(?:\.\d+)?)\s*([kKmM])?$/)
|
|
45
|
+
if (m) {
|
|
46
|
+
const scale = m[2] ? (/m/i.test(m[2]) ? 1_000_000 : 1_000) : 1
|
|
47
|
+
parsed = Math.round(parseFloat(m[1]!) * scale)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (parsed === undefined) {
|
|
52
|
+
console.warn(
|
|
53
|
+
`⚠ Agent "${agentName}": autoCompactWindow "${String(value)}" is not a number ` +
|
|
54
|
+
`(${MIN_COMPACT_WINDOW}–${MAX_COMPACT_WINDOW}, or 200k / 1M). Ignored.`,
|
|
55
|
+
)
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
58
|
+
if (parsed < MIN_COMPACT_WINDOW || parsed > MAX_COMPACT_WINDOW) {
|
|
59
|
+
console.warn(
|
|
60
|
+
`⚠ Agent "${agentName}": autoCompactWindow ${parsed} is outside ` +
|
|
61
|
+
`${MIN_COMPACT_WINDOW}–${MAX_COMPACT_WINDOW}. Ignored.`,
|
|
62
|
+
)
|
|
63
|
+
return undefined
|
|
64
|
+
}
|
|
65
|
+
return parsed
|
|
66
|
+
}
|
|
67
|
+
|
|
27
68
|
const BUILTIN_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
|
|
28
69
|
general: 'You are a focused sub-agent. Complete the assigned task thoroughly and return results.',
|
|
29
70
|
explore:
|
|
@@ -79,8 +120,7 @@ export class AgentRegistry {
|
|
|
79
120
|
: undefined,
|
|
80
121
|
background: typeof data.background === 'boolean' ? data.background : undefined,
|
|
81
122
|
memory: data.memory as 'user' | 'project' | 'local' | undefined,
|
|
82
|
-
autoCompactWindow:
|
|
83
|
-
typeof data.autoCompactWindow === 'number' ? data.autoCompactWindow : undefined,
|
|
123
|
+
autoCompactWindow: parseTokenWindow(data.autoCompactWindow, name),
|
|
84
124
|
source,
|
|
85
125
|
filePath: fullPath,
|
|
86
126
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getMessageBus } from './message-bus'
|
|
2
|
+
import { getBackgroundAgentRegistry } from './background-registry'
|
|
2
3
|
import { getFileInboxTransport } from './cross-session/file-inbox'
|
|
3
4
|
import { discoverSessions, createSessionInfo } from './cross-session/discovery'
|
|
4
5
|
import type { AgentMessage } from './message-bus'
|
|
@@ -82,6 +83,35 @@ export class MessageRouter {
|
|
|
82
83
|
async route(from: string, to: string, summary: string, message: string): Promise<RouteResult> {
|
|
83
84
|
// Same-process routing: "main" or background task IDs
|
|
84
85
|
if (to === 'main' || to.startsWith('bg-') || to.startsWith('sub-agent-')) {
|
|
86
|
+
// A message is only delivered if something is still reading the address.
|
|
87
|
+
// Background and sub-agent ids are drained from inside their own turn
|
|
88
|
+
// loop (`sub-agent.ts` `drainInboundMessages`), so once that loop has
|
|
89
|
+
// exited the queue entry is never looked at again — posting anyway and
|
|
90
|
+
// reporting success tells the caller to expect a reply from an agent that
|
|
91
|
+
// will never run. The registry is the liveness record; "main" has no id
|
|
92
|
+
// in it and is always drainable by the parent engine.
|
|
93
|
+
if (to !== 'main') {
|
|
94
|
+
const task = getBackgroundAgentRegistry().get(to)
|
|
95
|
+
if (!task) {
|
|
96
|
+
return {
|
|
97
|
+
success: false,
|
|
98
|
+
routedTo: 'bus',
|
|
99
|
+
error:
|
|
100
|
+
`No live agent "${to}" in this process. A background agent is only ` +
|
|
101
|
+
`addressable by its task ID while it is still running.`,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (task.status !== 'running') {
|
|
105
|
+
return {
|
|
106
|
+
success: false,
|
|
107
|
+
routedTo: 'bus',
|
|
108
|
+
error:
|
|
109
|
+
`Agent "${to}" is ${task.status} and is no longer reading messages, ` +
|
|
110
|
+
`so this message would never be seen. Its final result is available ` +
|
|
111
|
+
`through the Task tool; start a new agent to continue the work.`,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
85
115
|
try {
|
|
86
116
|
const bus = getMessageBus()
|
|
87
117
|
const msgId = bus.post(from, to, summary, message)
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -509,6 +509,11 @@ export class SubAgent {
|
|
|
509
509
|
artifactSessionId: `${options.toolContext?.sessionId ?? 'main'}:sub:${agentDef?.name || agentType}`,
|
|
510
510
|
}
|
|
511
511
|
|
|
512
|
+
// Whether the *last* turn ended because the model hit its output ceiling.
|
|
513
|
+
// Kept outside the loop because the answer the caller receives is the last
|
|
514
|
+
// turn's text, so that is the turn whose completeness matters.
|
|
515
|
+
let lastTurnTruncated = false
|
|
516
|
+
|
|
512
517
|
try {
|
|
513
518
|
for (let turn = 0; turn < MAX_TOOL_TURNS; turn++) {
|
|
514
519
|
// Check abort signal
|
|
@@ -535,6 +540,10 @@ export class SubAgent {
|
|
|
535
540
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
536
541
|
let turnText = ''
|
|
537
542
|
let streamError: string | null = null
|
|
543
|
+
// The provider says so on the stop chunk when the model ran out of output
|
|
544
|
+
// budget (`max_tokens`). The answer is real but cut off mid-thought, and
|
|
545
|
+
// nothing downstream could tell that from a finished one.
|
|
546
|
+
let turnTruncated = false
|
|
538
547
|
|
|
539
548
|
for await (const chunk of (this.llm ?? this.registry).chat({
|
|
540
549
|
model: finalModel,
|
|
@@ -577,6 +586,7 @@ export class SubAgent {
|
|
|
577
586
|
break
|
|
578
587
|
}
|
|
579
588
|
if (chunk.type === 'stop') {
|
|
589
|
+
if (chunk.truncated) turnTruncated = true
|
|
580
590
|
break
|
|
581
591
|
}
|
|
582
592
|
if (chunk.type === 'usage') {
|
|
@@ -586,6 +596,7 @@ export class SubAgent {
|
|
|
586
596
|
}
|
|
587
597
|
|
|
588
598
|
chunks.push(turnText)
|
|
599
|
+
lastTurnTruncated = turnTruncated
|
|
589
600
|
|
|
590
601
|
// Nothing came back at all, so there is no partial response to continue
|
|
591
602
|
// from — that is a genuine failure and is reported as one.
|
|
@@ -771,6 +782,12 @@ export class SubAgent {
|
|
|
771
782
|
}
|
|
772
783
|
|
|
773
784
|
const result = chunks.join('')
|
|
785
|
+
// Ran out of output budget rather than finished. Saying so is the whole
|
|
786
|
+
// point: the text looks like a complete answer, so a caller with no marker
|
|
787
|
+
// treats a half-sentence conclusion as the agent's verdict.
|
|
788
|
+
if (!hitMaxTurns && lastTurnTruncated) {
|
|
789
|
+
return `[partial result — sub-agent hit the model's output limit; answer may be cut off]\n\n${result}`
|
|
790
|
+
}
|
|
774
791
|
if (hitMaxTurns) {
|
|
775
792
|
// Only advertise the SendMessage route where a route exists. A background
|
|
776
793
|
// agent has an address (`bg-…`, minted by the registry and handed to the
|
package/src/config/loader.ts
CHANGED
|
@@ -107,6 +107,44 @@ function mergeProviders(
|
|
|
107
107
|
return merged
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
+
/** Context window assumed for a hand-written model that does not declare one. */
|
|
111
|
+
const DEFAULT_CONTEXT_WINDOW = 128_000
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Ensure every configured model carries a usable `contextWindow`.
|
|
115
|
+
*
|
|
116
|
+
* `ModelInfo.contextWindow` is required in TypeScript but nothing checks the
|
|
117
|
+
* YAML at runtime, and a user-defined provider's `models` reach the registry
|
|
118
|
+
* exactly as written. A model that is found but lacks the field produces
|
|
119
|
+
* `undefined` at `index.tsx`'s `activeModel.contextWindow` — and that becomes
|
|
120
|
+
* `ContextManager.maxTokens`. `needsCompaction()` then compares tokens against
|
|
121
|
+
* `NaN` and is **permanently false**: auto-compaction never runs, and the first
|
|
122
|
+
* sign of trouble is the provider rejecting an oversized request.
|
|
123
|
+
*
|
|
124
|
+
* The fallback is the same 128K `index.tsx` uses for an unknown model. Warn
|
|
125
|
+
* once per model: the whole defect is that this was silent. A value that is
|
|
126
|
+
* present but not a positive finite number (0, negative, a quoted string) is
|
|
127
|
+
* equally unusable and gets the same treatment.
|
|
128
|
+
*
|
|
129
|
+
* Runs on the final provider list — not on an override as it is merged — so a
|
|
130
|
+
* custom provider added wholesale is covered by the same check.
|
|
131
|
+
*/
|
|
132
|
+
function normalizeModelContextWindows(providers: ProviderConfig[]): void {
|
|
133
|
+
for (const provider of providers) {
|
|
134
|
+
if (!provider || !Array.isArray(provider.models)) continue
|
|
135
|
+
for (const model of provider.models) {
|
|
136
|
+
if (!model || typeof model !== 'object') continue
|
|
137
|
+
const window = model.contextWindow
|
|
138
|
+
if (typeof window === 'number' && Number.isFinite(window) && window > 0) continue
|
|
139
|
+
model.contextWindow = DEFAULT_CONTEXT_WINDOW
|
|
140
|
+
process.stderr.write(
|
|
141
|
+
`⚠ Mipham Code: model "${model.id ?? '<unnamed>'}" (provider "${provider.id}") ` +
|
|
142
|
+
`has no usable contextWindow — assuming 128K.\n`,
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
110
148
|
/**
|
|
111
149
|
* Merge `override` into `base`, recursing into plain objects so that a source
|
|
112
150
|
* setting one branch of an object does not drop the other source's siblings
|
|
@@ -914,6 +952,9 @@ export function loadConfig(cwd: string = process.cwd()): MiphamConfig {
|
|
|
914
952
|
// ── Decrypt API keys at rest (enc:v1:) back to plaintext ──
|
|
915
953
|
decryptProviderApiKeys(config.providers)
|
|
916
954
|
|
|
955
|
+
// Last step, so it sees the final merged list from every source.
|
|
956
|
+
normalizeModelContextWindows(config.providers)
|
|
957
|
+
|
|
917
958
|
return config
|
|
918
959
|
}
|
|
919
960
|
|
|
@@ -72,7 +72,7 @@ function countToolPairs(messages: Message[]): number {
|
|
|
72
72
|
return count
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
function isToolResultUserMessage(msg: Message): boolean {
|
|
75
|
+
export function isToolResultUserMessage(msg: Message): boolean {
|
|
76
76
|
if (msg.role !== 'user') return false
|
|
77
77
|
if (!Array.isArray(msg.content)) return false
|
|
78
78
|
return msg.content.some(
|
package/src/core/context.ts
CHANGED
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
ContentBlock,
|
|
3
|
+
Message,
|
|
4
|
+
TextContent,
|
|
5
|
+
ToolResult,
|
|
6
|
+
ToolResultContent,
|
|
7
|
+
} from '../shared/index.ts'
|
|
2
8
|
import { snipMessages } from './context-snip'
|
|
3
|
-
import { microcompact, shouldMicrocompact } from './context-microcompact'
|
|
4
|
-
import {
|
|
9
|
+
import { microcompact, shouldMicrocompact, isToolResultUserMessage } from './context-microcompact'
|
|
10
|
+
import {
|
|
11
|
+
estimateMessageTokens,
|
|
12
|
+
NoopCacheTracker,
|
|
13
|
+
type CacheTracker,
|
|
14
|
+
type CacheStatus,
|
|
15
|
+
} from './context-token'
|
|
5
16
|
import {
|
|
6
17
|
SessionLog,
|
|
7
18
|
messageToEvents,
|
|
@@ -11,7 +22,49 @@ import {
|
|
|
11
22
|
closeInterruptedToolCalls,
|
|
12
23
|
} from './session-log'
|
|
13
24
|
|
|
14
|
-
export type Summarizer = (
|
|
25
|
+
export type Summarizer = (
|
|
26
|
+
messages: Message[],
|
|
27
|
+
heading: string,
|
|
28
|
+
signal?: AbortSignal,
|
|
29
|
+
) => Promise<string>
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 削一段文本直到估计值落进预算:对半切、逐次复估 —— 与脚本文种无关的收敛法
|
|
33
|
+
* (`estimateMessageTokens` 对 CJK / emoji 的换算和拉丁文不同,按字符数硬算会切多或切少)。
|
|
34
|
+
* 够小就原样返回;削过则**说出削了多少**,悄悄截断会让模型把自己的半条证据当成全文。
|
|
35
|
+
*/
|
|
36
|
+
function shrinkText(text: string, maxTokens: number): string {
|
|
37
|
+
const estimate = (t: string): number => estimateMessageTokens({ role: 'user', content: t })
|
|
38
|
+
if (estimate(text) <= maxTokens) return text
|
|
39
|
+
|
|
40
|
+
let out = text
|
|
41
|
+
for (let guard = 0; guard < 32 && out.length > 0 && estimate(out) > maxTokens; guard++) {
|
|
42
|
+
out = out.slice(0, Math.floor(out.length / 2))
|
|
43
|
+
}
|
|
44
|
+
return `${out}\n… [truncated to fit the context budget; ${text.length - out.length} characters omitted]`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 把单条消息里可削的文本削进 `maxTokens`;结构(角色、块类型、`tool_use_id`)一律不动。 */
|
|
48
|
+
function truncateToBudget(msg: Message, maxTokens: number): Message {
|
|
49
|
+
if (typeof msg.content === 'string') {
|
|
50
|
+
const text = shrinkText(msg.content, maxTokens)
|
|
51
|
+
return text === msg.content ? msg : { ...msg, content: text }
|
|
52
|
+
}
|
|
53
|
+
if (!Array.isArray(msg.content)) return msg
|
|
54
|
+
|
|
55
|
+
const blocks = msg.content.map((b): ContentBlock => {
|
|
56
|
+
if (!b || typeof b !== 'object') return b
|
|
57
|
+
const block = b as unknown as Record<string, unknown>
|
|
58
|
+
if (block.type === 'text' && typeof block.text === 'string') {
|
|
59
|
+
return { ...(b as TextContent), text: shrinkText(block.text, maxTokens) }
|
|
60
|
+
}
|
|
61
|
+
if (block.type === 'tool_result' && typeof block.content === 'string') {
|
|
62
|
+
return { ...(b as ToolResultContent), content: shrinkText(block.content, maxTokens) }
|
|
63
|
+
}
|
|
64
|
+
return b
|
|
65
|
+
})
|
|
66
|
+
return { ...msg, content: blocks }
|
|
67
|
+
}
|
|
15
68
|
|
|
16
69
|
interface ContextConfig {
|
|
17
70
|
maxTokens: number
|
|
@@ -317,7 +370,7 @@ export class ContextManager {
|
|
|
317
370
|
return this.getEstimatedTokens() > this.config.maxTokens * this.config.compactionThreshold
|
|
318
371
|
}
|
|
319
372
|
|
|
320
|
-
async compact(heading: string): Promise<{ before: number; after: number }> {
|
|
373
|
+
async compact(heading: string, signal?: AbortSignal): Promise<{ before: number; after: number }> {
|
|
321
374
|
const beforeTokens = this.getEstimatedTokens()
|
|
322
375
|
|
|
323
376
|
for (let i = 0; i < COMPACTION_PASSES.length; i++) {
|
|
@@ -326,34 +379,138 @@ export class ContextManager {
|
|
|
326
379
|
// 仍超预算时继续 —— 这一句就是「压完再判一次」。
|
|
327
380
|
if (i > 0 && !this.needsCompaction()) break
|
|
328
381
|
if (this.messages.length <= pass.minLength) continue
|
|
329
|
-
await this.compactOnce(heading, pass.keep)
|
|
382
|
+
await this.compactOnce(heading, pass.keep, signal)
|
|
330
383
|
}
|
|
331
384
|
|
|
385
|
+
// 终端一趟:尺是**预算**,不是条数。
|
|
386
|
+
//
|
|
387
|
+
// 上面两趟都按条数削,而触发尺按 token —— 一段十来条消息、里头几个几十万字符的
|
|
388
|
+
// 工具结果 / 长文档的会话,两趟的 `minLength` 闸都会 `continue`,一次也不压。
|
|
389
|
+
// 于是 `needsCompaction()` 恒真、每轮都重试同一个空操作,直到上游拒收。
|
|
390
|
+
// 这里按预算从尾部往前留,留不下的**数清楚**再丢掉,并把这件事写进上下文。
|
|
391
|
+
if (this.needsCompaction()) this.enforceBudget()
|
|
392
|
+
|
|
332
393
|
return { before: beforeTokens, after: this.getEstimatedTokens() }
|
|
333
394
|
}
|
|
334
395
|
|
|
396
|
+
/**
|
|
397
|
+
* 把消息列表削到预算之内,且**只**在按条数的两趟都够不着时才会走到这里。
|
|
398
|
+
*
|
|
399
|
+
* 两点都是判据本身:
|
|
400
|
+
* - **从尾部往前留**,因为最新的一轮才是模型接下来要接着做的;
|
|
401
|
+
* - 丢弃要留痕。`compactOnce` 的两条路都靠一句话交代「前面被压过」,而这里丢掉的
|
|
402
|
+
* 东西没经摘要器,模型若不被告知,会把自己没见过的早期决定当成从未发生过。
|
|
403
|
+
*/
|
|
404
|
+
private enforceBudget(): void {
|
|
405
|
+
// 消息那半能用的额度 = 总预算 − 提示那半。提示段(系统提示、权限段、MCP
|
|
406
|
+
// instructions)不归这里管:它们本来就每轮重派生,而按整份总额度削消息的话,
|
|
407
|
+
// 一段很长的系统提示会让这里把好好的对话截碎,且**削完照样超**。
|
|
408
|
+
const target = Math.max(
|
|
409
|
+
1,
|
|
410
|
+
this.config.maxTokens * this.config.compactionThreshold - this.promptTokens(),
|
|
411
|
+
)
|
|
412
|
+
const est = (m: Message): number => this.estimateTokensForMessages([m])
|
|
413
|
+
|
|
414
|
+
let cut = this.messages.length
|
|
415
|
+
let used = 0
|
|
416
|
+
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
417
|
+
const t = est(this.messages[i]!)
|
|
418
|
+
// 最后一条无条件留下:全丢光就没有可回复的上下文了。
|
|
419
|
+
if (cut < this.messages.length && used + t > target) break
|
|
420
|
+
cut = i
|
|
421
|
+
used += t
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// 幸存窗口不能以一条 `tool_result` 开头 —— 它的 `tool_use` 落在被丢的那半里,
|
|
425
|
+
// 上游会拒收「没有对应调用的结果」。往前多带一条,代价是多一点预算。
|
|
426
|
+
while (cut > 0 && isToolResultUserMessage(this.messages[cut]!)) {
|
|
427
|
+
cut--
|
|
428
|
+
used += est(this.messages[cut]!)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const dropped = this.messages.slice(0, cut)
|
|
432
|
+
let kept = this.messages.slice(cut)
|
|
433
|
+
|
|
434
|
+
// 一条消息自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可丢的,只能截内容。
|
|
435
|
+
// 每条分到的是它自己那份预算,不是整份额度 —— 否则几条各占三分之一的消息谁也
|
|
436
|
+
// 没超,削完还是超。
|
|
437
|
+
if (dropped.length === 0 && kept.length > 0) {
|
|
438
|
+
const perMessage = Math.max(1, Math.floor(target / kept.length))
|
|
439
|
+
kept = kept.map((m) => truncateToBudget(m, perMessage))
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const omittedNotice = (n: number): Message => ({
|
|
443
|
+
role: 'user',
|
|
444
|
+
content:
|
|
445
|
+
`[${n} earlier message${n === 1 ? '' : 's'} omitted — the context budget ` +
|
|
446
|
+
`could not hold them. They were not summarized; ask before assuming what ` +
|
|
447
|
+
`they said.]`,
|
|
448
|
+
})
|
|
449
|
+
|
|
450
|
+
// 通知自己也占预算,所以头部再补削,直到**含通知**的整份落进预算。少了这一步,
|
|
451
|
+
// 「刚好削到线内」的会话会因多出这一条而重新超线 —— 下一轮再削一次,逐轮掉消息。
|
|
452
|
+
// 顺带保住配对:若补削后的第一条是 `tool_result`,它的调用已在被丢的那半里,
|
|
453
|
+
// 一起丢,别留一个没有调用的结果给上游。
|
|
454
|
+
while (kept.length > 1) {
|
|
455
|
+
const withNotice = [omittedNotice(dropped.length), ...kept]
|
|
456
|
+
if (this.estimateTokensForMessages(withNotice) <= target) break
|
|
457
|
+
dropped.push(kept[0]!)
|
|
458
|
+
kept = kept.slice(1)
|
|
459
|
+
while (kept.length > 1 && isToolResultUserMessage(kept[0]!)) {
|
|
460
|
+
dropped.push(kept[0]!)
|
|
461
|
+
kept = kept.slice(1)
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const notice: Message | null = dropped.length > 0 ? omittedNotice(dropped.length) : null
|
|
466
|
+
const next = notice ? [notice, ...kept] : kept
|
|
467
|
+
|
|
468
|
+
if (this.log) {
|
|
469
|
+
this.log.append({ type: 'compaction/rewrite', at: Date.now(), messages: next })
|
|
470
|
+
this.messages = deriveMessages(this.log.events())
|
|
471
|
+
} else {
|
|
472
|
+
this.messages = next
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
this.recountMessageTokens()
|
|
476
|
+
}
|
|
477
|
+
|
|
335
478
|
/**
|
|
336
479
|
* 压缩一趟:把消息削到最近 `keep` 条。
|
|
337
480
|
*
|
|
338
481
|
* body(除 `keep` 外)逐行取自旧 `compact()`,两种分支原样保留:LLM 摘要(失败回落截断)
|
|
339
482
|
* 与纯截断。`recountMessageTokens()` 留在**这里**而不是调用方 —— 下一趟的闸要读它。
|
|
340
483
|
*/
|
|
341
|
-
private async compactOnce(heading: string, keep: number): Promise<void> {
|
|
484
|
+
private async compactOnce(heading: string, keep: number, signal?: AbortSignal): Promise<void> {
|
|
342
485
|
const toDrop = this.messages.slice(0, -keep)
|
|
343
486
|
|
|
344
487
|
if (this.summarizer && toDrop.length >= 4) {
|
|
345
488
|
// LLM-based summarization of truncated messages
|
|
346
489
|
try {
|
|
347
|
-
const summary = await this.summarizer(toDrop, heading)
|
|
490
|
+
const summary = await this.summarizer(toDrop, heading, signal)
|
|
491
|
+
// 摘要**替换**了这些东西,而不是它们被逐字保留:摘要器只读到每条前 2000 字符
|
|
492
|
+
// (见 `Engine.setupContextSummarizer`),写得再详细也回不到原文。把量说在
|
|
493
|
+
// 摘要后面,读的人才知道自己手里是一份缩写,不是完整历史 —— 前缀
|
|
494
|
+
// `[Earlier conversation summary]:` 是 `session-log` 的投影标记,不能改。
|
|
495
|
+
const annotated =
|
|
496
|
+
`${summary}\n\n(${toDrop.length} earlier message` +
|
|
497
|
+
`${toDrop.length === 1 ? '' : 's'} condensed into this summary.)`
|
|
348
498
|
const summaryMsg: Message = {
|
|
349
499
|
role: 'user',
|
|
350
|
-
content: `[Earlier conversation summary]: ${
|
|
500
|
+
content: `[Earlier conversation summary]: ${annotated}`,
|
|
351
501
|
}
|
|
352
502
|
this.messages = [summaryMsg, ...this.messages.slice(-keep)]
|
|
353
503
|
if (this.log) {
|
|
354
504
|
const derivedCount = deriveMessages(this.log.events()).length
|
|
355
505
|
const replacedCount = Math.max(0, derivedCount - keep)
|
|
356
|
-
|
|
506
|
+
// 记 `annotated` 而不是裸 `summary`:日志是消息投影的唯一真源,
|
|
507
|
+
// 两条路径拼出的字节必须一致(见 session-log 的 SUMMARY_PREFIX)。
|
|
508
|
+
this.log.append({
|
|
509
|
+
type: 'compaction/summary',
|
|
510
|
+
at: Date.now(),
|
|
511
|
+
summary: annotated,
|
|
512
|
+
replacedCount,
|
|
513
|
+
})
|
|
357
514
|
}
|
|
358
515
|
} catch {
|
|
359
516
|
// Fall back to truncation on summarizer failure
|