@miphamai/cli 0.85.25 → 0.85.27
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 +34 -24
- package/package.json +1 -1
- package/src/agent/agent-context.ts +23 -3
- package/src/agent/sub-agent.ts +42 -15
- package/src/core/context.ts +32 -0
- package/src/core/engine.ts +182 -20
- package/src/core/instructions.ts +64 -17
- package/src/core/memory/memory-audit.ts +105 -0
- package/src/core/memory/memory-manager.ts +78 -53
- package/src/core/merge-gate.ts +158 -0
- package/src/core/number-provenance.ts +106 -0
- package/src/core/permission-rule-ack.ts +67 -0
- package/src/daemon/engine-capabilities.ts +2 -0
- package/src/daemon/remote-engine.ts +11 -5
- package/src/daemon/schedule-manager.ts +32 -3
- package/src/daemon/server.ts +6 -0
- package/src/i18n-core/locales/en-US.json +11 -3
- package/src/i18n-core/locales/zh-CN.json +11 -3
- package/src/index.tsx +36 -4
- package/src/mcp/client.ts +37 -2
- package/src/mcp/http-transport.ts +20 -1
- package/src/mcp/protocol.ts +13 -5
- package/src/mcp/registry.ts +8 -3
- package/src/mcp/transport.ts +40 -3
- package/src/providers/anthropic.ts +3 -1
- package/src/providers/fetch-utils.ts +40 -6
- package/src/providers/openai-compat.ts +2 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +9 -0
- package/src/tools/exec/bash.ts +1 -1
- package/src/tools/exec/task.ts +144 -21
- package/src/tools/network/web-fetch.ts +7 -7
- package/src/tools/network/web-search.ts +6 -5
- package/src/ui/commands.ts +43 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.27
|
|
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/bin/mipham.ts
CHANGED
|
@@ -346,6 +346,22 @@ async function runUpdate(): Promise<boolean> {
|
|
|
346
346
|
process.exit(0)
|
|
347
347
|
}
|
|
348
348
|
|
|
349
|
+
/**
|
|
350
|
+
* One shape for "the daemon is not answering".
|
|
351
|
+
*
|
|
352
|
+
* Twelve call sites used to print the raw fetch error and exit. The error says
|
|
353
|
+
* what failed and nothing about what to do, and it is the same situation every
|
|
354
|
+
* time — so it gets one message: whether it is still running, and how to bring
|
|
355
|
+
* it back. (The config lives at a fixed `~/.mipham/daemon.pid`, i.e. there is
|
|
356
|
+
* exactly one daemon per user, so there is nothing to disambiguate between.)
|
|
357
|
+
*/
|
|
358
|
+
function reportDaemonUnreachable(port: number, err: unknown): never {
|
|
359
|
+
console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
|
|
360
|
+
console.error('Check whether it is still running: mipham daemon status')
|
|
361
|
+
console.error('Start it again: mipham daemon start')
|
|
362
|
+
process.exit(1)
|
|
363
|
+
}
|
|
364
|
+
|
|
349
365
|
// ── Daemon lifecycle commands ──────────────────────────────────────────────────
|
|
350
366
|
|
|
351
367
|
async function runDaemonCLI(): Promise<boolean> {
|
|
@@ -386,6 +402,12 @@ async function runDaemonCLI(): Promise<boolean> {
|
|
|
386
402
|
// process is confirmed gone; the old code printed it right after send().
|
|
387
403
|
if (await terminateDaemonProcess(status.pid)) {
|
|
388
404
|
console.log(`Daemon stopped (PID: ${status.pid})`)
|
|
405
|
+
// 说清楚这一刀的后果:在这个 daemon 里跑着的后台会话(含 attach 中的那些)
|
|
406
|
+
// 一起结束了。历史仍在库里 —— 重启 daemon 后重新 attach 即可接着用。
|
|
407
|
+
// 不写「会重启」:没有任何东西会替你重启它。
|
|
408
|
+
console.log(
|
|
409
|
+
'Background sessions running in it have ended. Start it again with "mipham daemon start".',
|
|
410
|
+
)
|
|
389
411
|
process.exit(0)
|
|
390
412
|
}
|
|
391
413
|
console.error(
|
|
@@ -507,8 +529,7 @@ async function runAttachCLI(): Promise<boolean> {
|
|
|
507
529
|
sessions = data.data.sessions.filter((s) => s.status === 'active' || s.status === 'idle')
|
|
508
530
|
}
|
|
509
531
|
} catch (err) {
|
|
510
|
-
|
|
511
|
-
process.exit(1)
|
|
532
|
+
reportDaemonUnreachable(port, err)
|
|
512
533
|
}
|
|
513
534
|
|
|
514
535
|
const latestFlag = args.includes('--latest')
|
|
@@ -630,8 +651,7 @@ async function runAgentCLI(): Promise<boolean> {
|
|
|
630
651
|
}
|
|
631
652
|
}
|
|
632
653
|
} catch (err) {
|
|
633
|
-
|
|
634
|
-
process.exit(1)
|
|
654
|
+
reportDaemonUnreachable(port, err)
|
|
635
655
|
}
|
|
636
656
|
process.exit(0)
|
|
637
657
|
}
|
|
@@ -685,8 +705,7 @@ async function runAgentCLI(): Promise<boolean> {
|
|
|
685
705
|
}
|
|
686
706
|
console.log(`Message sent to agent ${agentId}`)
|
|
687
707
|
} catch (err) {
|
|
688
|
-
|
|
689
|
-
process.exit(1)
|
|
708
|
+
reportDaemonUnreachable(port, err)
|
|
690
709
|
}
|
|
691
710
|
process.exit(0)
|
|
692
711
|
}
|
|
@@ -708,8 +727,7 @@ async function runAgentCLI(): Promise<boolean> {
|
|
|
708
727
|
}
|
|
709
728
|
console.log(`Agent ${agentId} stopped.`)
|
|
710
729
|
} catch (err) {
|
|
711
|
-
|
|
712
|
-
process.exit(1)
|
|
730
|
+
reportDaemonUnreachable(port, err)
|
|
713
731
|
}
|
|
714
732
|
process.exit(0)
|
|
715
733
|
}
|
|
@@ -760,8 +778,7 @@ async function runAgentCLI(): Promise<boolean> {
|
|
|
760
778
|
if (a.branch) console.log(` Branch: ${a.branch}`)
|
|
761
779
|
if (a.prUrl) console.log(` PR: ${a.prUrl}`)
|
|
762
780
|
} catch (err) {
|
|
763
|
-
|
|
764
|
-
process.exit(1)
|
|
781
|
+
reportDaemonUnreachable(port, err)
|
|
765
782
|
}
|
|
766
783
|
process.exit(0)
|
|
767
784
|
}
|
|
@@ -827,8 +844,7 @@ async function runGoalCLI(): Promise<boolean> {
|
|
|
827
844
|
}
|
|
828
845
|
}
|
|
829
846
|
} catch (err) {
|
|
830
|
-
|
|
831
|
-
process.exit(1)
|
|
847
|
+
reportDaemonUnreachable(port, err)
|
|
832
848
|
}
|
|
833
849
|
process.exit(0)
|
|
834
850
|
}
|
|
@@ -866,8 +882,7 @@ async function runGoalCLI(): Promise<boolean> {
|
|
|
866
882
|
}
|
|
867
883
|
console.log(`Goal #${data.data!.id} created.`)
|
|
868
884
|
} catch (err) {
|
|
869
|
-
|
|
870
|
-
process.exit(1)
|
|
885
|
+
reportDaemonUnreachable(port, err)
|
|
871
886
|
}
|
|
872
887
|
process.exit(0)
|
|
873
888
|
}
|
|
@@ -893,8 +908,7 @@ async function runGoalCLI(): Promise<boolean> {
|
|
|
893
908
|
}
|
|
894
909
|
console.log(`Goal #${goalId} marked as done.`)
|
|
895
910
|
} catch (err) {
|
|
896
|
-
|
|
897
|
-
process.exit(1)
|
|
911
|
+
reportDaemonUnreachable(port, err)
|
|
898
912
|
}
|
|
899
913
|
process.exit(0)
|
|
900
914
|
}
|
|
@@ -920,8 +934,7 @@ async function runGoalCLI(): Promise<boolean> {
|
|
|
920
934
|
}
|
|
921
935
|
console.log(`Goal #${goalId} paused.`)
|
|
922
936
|
} catch (err) {
|
|
923
|
-
|
|
924
|
-
process.exit(1)
|
|
937
|
+
reportDaemonUnreachable(port, err)
|
|
925
938
|
}
|
|
926
939
|
process.exit(0)
|
|
927
940
|
}
|
|
@@ -995,8 +1008,7 @@ async function runScheduleCLI(): Promise<boolean> {
|
|
|
995
1008
|
}
|
|
996
1009
|
}
|
|
997
1010
|
} catch (err) {
|
|
998
|
-
|
|
999
|
-
process.exit(1)
|
|
1011
|
+
reportDaemonUnreachable(port, err)
|
|
1000
1012
|
}
|
|
1001
1013
|
process.exit(0)
|
|
1002
1014
|
}
|
|
@@ -1028,8 +1040,7 @@ async function runScheduleCLI(): Promise<boolean> {
|
|
|
1028
1040
|
}
|
|
1029
1041
|
console.log(`Schedule #${data.data!.id} created (cron: ${cronExpr}).`)
|
|
1030
1042
|
} catch (err) {
|
|
1031
|
-
|
|
1032
|
-
process.exit(1)
|
|
1043
|
+
reportDaemonUnreachable(port, err)
|
|
1033
1044
|
}
|
|
1034
1045
|
process.exit(0)
|
|
1035
1046
|
}
|
|
@@ -1051,8 +1062,7 @@ async function runScheduleCLI(): Promise<boolean> {
|
|
|
1051
1062
|
}
|
|
1052
1063
|
console.log(`Schedule #${scheduleId} removed.`)
|
|
1053
1064
|
} catch (err) {
|
|
1054
|
-
|
|
1055
|
-
process.exit(1)
|
|
1065
|
+
reportDaemonUnreachable(port, err)
|
|
1056
1066
|
}
|
|
1057
1067
|
process.exit(0)
|
|
1058
1068
|
}
|
package/package.json
CHANGED
|
@@ -130,7 +130,27 @@ export function createAgentContext(
|
|
|
130
130
|
|
|
131
131
|
context.setSystemPrompt(systemPrompt)
|
|
132
132
|
|
|
133
|
-
|
|
133
|
+
return { context, allowedTools: selectAgentTools(agentDef, toolRegistry), systemPrompt }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The tools an agent definition is allowed to use, read from the **current**
|
|
138
|
+
* registry.
|
|
139
|
+
*
|
|
140
|
+
* Exported because the answer is not a one-time fact: MCP servers connect in the
|
|
141
|
+
* background, so a sub-agent that started early would otherwise be pinned to the
|
|
142
|
+
* tool table of the moment it started, and a server that finished connecting a
|
|
143
|
+
* second later could never be used by it — even though calling the tool would
|
|
144
|
+
* have worked (`sub-agent.ts` resolves each call against the live registry).
|
|
145
|
+
*
|
|
146
|
+
* `warnOnEmpty` is for the repeat callers: the warning is worth printing once
|
|
147
|
+
* per run, not once per turn.
|
|
148
|
+
*/
|
|
149
|
+
export function selectAgentTools(
|
|
150
|
+
agentDef: AgentDefinition,
|
|
151
|
+
toolRegistry: Map<string, ToolDefinition>,
|
|
152
|
+
warnOnEmpty = true,
|
|
153
|
+
): ToolDefinition[] {
|
|
134
154
|
let allowedTools = Array.from(toolRegistry.values())
|
|
135
155
|
|
|
136
156
|
if (agentDef.tools) {
|
|
@@ -148,7 +168,7 @@ export function createAgentContext(
|
|
|
148
168
|
allowedTools = allowedTools.filter(
|
|
149
169
|
(t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
|
|
150
170
|
)
|
|
151
|
-
if (allowedTools.length === 0) {
|
|
171
|
+
if (allowedTools.length === 0 && warnOnEmpty) {
|
|
152
172
|
process.stderr.write(
|
|
153
173
|
`⚠️ Agent "${agentDef.name}": tools list (${allowRules.join(', ')}) matched no registered tool — the agent will run without tools.\n`,
|
|
154
174
|
)
|
|
@@ -165,5 +185,5 @@ export function createAgentContext(
|
|
|
165
185
|
allowedTools = allowedTools.filter((t) => !denySet.has(t.name))
|
|
166
186
|
}
|
|
167
187
|
|
|
168
|
-
return
|
|
188
|
+
return allowedTools
|
|
169
189
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -2,12 +2,13 @@ import type { ProviderRegistry } from '../providers/registry'
|
|
|
2
2
|
import type { Llm } from '../providers/llm'
|
|
3
3
|
import type { Message, ToolDefinition, ToolContext } from '../shared/index.ts'
|
|
4
4
|
import type { SubAgentType, SubAgentOptions, AgentDefinition } from './types'
|
|
5
|
-
import { createAgentContext } from './agent-context'
|
|
5
|
+
import { createAgentContext, selectAgentTools } from './agent-context'
|
|
6
6
|
import { shrinkAgentMessages } from './auto-compact'
|
|
7
7
|
import { getBackgroundAgentRegistry } from './background-registry'
|
|
8
8
|
import { formatInboundMessage, getMessageBus } from './message-bus'
|
|
9
9
|
import type { HookEngine } from '../core/hooks'
|
|
10
10
|
import { PermissionSystem } from '../core/permission'
|
|
11
|
+
import { noteToolOutcome, reviewLedger } from '../core/merge-gate'
|
|
11
12
|
import { buildPermissionBlock } from '../core/instructions'
|
|
12
13
|
import { AgentExperience } from './agent-experience'
|
|
13
14
|
import { PatternAnalyzer } from './pattern-analyzer.js'
|
|
@@ -390,11 +391,11 @@ export class SubAgent {
|
|
|
390
391
|
? Math.min(declaredWindow, contextWindow ?? declaredWindow)
|
|
391
392
|
: undefined
|
|
392
393
|
// 这一份**已含 agent memory**,是发出去的那个提示的唯一来源。
|
|
393
|
-
const {
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
394
|
+
const { context, systemPrompt: composedSystemPrompt } = createAgentContext(
|
|
395
|
+
resolvedDef,
|
|
396
|
+
this.toolRegistry,
|
|
397
|
+
compactWindow ?? contextWindow,
|
|
398
|
+
)
|
|
398
399
|
|
|
399
400
|
// 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
|
|
400
401
|
// 那一份设过上下文,这里用裸提示再设一遍只会把记忆从上下文里抹掉,而请求读的又不是
|
|
@@ -417,15 +418,10 @@ export class SubAgent {
|
|
|
417
418
|
context.addMessage({ role: 'user', content: opening })
|
|
418
419
|
|
|
419
420
|
const messages = context.getMessages()
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
description: t.description,
|
|
425
|
-
parameters: t.parameters,
|
|
426
|
-
input_schema: t.parameters,
|
|
427
|
-
}))
|
|
428
|
-
: undefined
|
|
421
|
+
// 广告出去的工具表**每轮**从 registry 现算(见下面 `tools: toolDefs` 前那一段),
|
|
422
|
+
// 不在这里采一次:MCP server 是启动后在后台连的,这一刻的快照会让晚一秒连上的
|
|
423
|
+
// 工具永远进不了这个子代理 —— 而调用本身其实是通的(每轮按 `tu.name` 读的是
|
|
424
|
+
// **当前** registry)。声明与执行必须读同一个事实。
|
|
429
425
|
|
|
430
426
|
const chunks: string[] = []
|
|
431
427
|
const MAX_TOOL_TURNS = options.maxTurns || 5
|
|
@@ -493,6 +489,10 @@ export class SubAgent {
|
|
|
493
489
|
// synchronous (see `resolveRunInBackground`). Set on the shared literal so it
|
|
494
490
|
// covers the synchronous *and* background runs — both go through here.
|
|
495
491
|
isSubAgent: true,
|
|
492
|
+
// Tools that keep per-session state (the Task list) must file it under the
|
|
493
|
+
// session this work belongs to, not under the literal 'sub-agent' — that
|
|
494
|
+
// one bucket is shared by every nested call from every session.
|
|
495
|
+
parentSessionId: options.toolContext?.sessionId,
|
|
496
496
|
// A name a peer can hold onto. `sessionId` is the literal 'sub-agent' for
|
|
497
497
|
// every sub-agent, so `SendMessage` had nothing stable to put on the
|
|
498
498
|
// envelope and minted `sub-agent-<ms>` afresh per message — two messages
|
|
@@ -545,6 +545,21 @@ export class SubAgent {
|
|
|
545
545
|
// nothing downstream could tell that from a finished one.
|
|
546
546
|
let turnTruncated = false
|
|
547
547
|
|
|
548
|
+
// Per turn: an MCP server that finished connecting while this turn was
|
|
549
|
+
// running must be usable in the next one. Reading the registry here (and
|
|
550
|
+
// the same registry below when resolving `tu.name`) keeps the advertised
|
|
551
|
+
// list and the executable set from drifting apart.
|
|
552
|
+
const allowedNow = selectAgentTools(resolvedDef, this.toolRegistry, false)
|
|
553
|
+
const toolDefs =
|
|
554
|
+
allowedNow.length > 0
|
|
555
|
+
? allowedNow.map((t) => ({
|
|
556
|
+
name: t.name,
|
|
557
|
+
description: t.description,
|
|
558
|
+
parameters: t.parameters,
|
|
559
|
+
input_schema: t.parameters,
|
|
560
|
+
}))
|
|
561
|
+
: undefined
|
|
562
|
+
|
|
548
563
|
for await (const chunk of (this.llm ?? this.registry).chat({
|
|
549
564
|
model: finalModel,
|
|
550
565
|
messages: currentMessages,
|
|
@@ -707,6 +722,18 @@ export class SubAgent {
|
|
|
707
722
|
try {
|
|
708
723
|
const result = await tool.execute(effectiveInput, toolContext)
|
|
709
724
|
|
|
725
|
+
// Merge gate: a review delegated here still counts for the session
|
|
726
|
+
// that will merge. This loop bypasses `Engine.executeTool`, so the
|
|
727
|
+
// engine's own recording never sees this call — the same two-path
|
|
728
|
+
// shape as tool telemetry, and both paths have to carry it.
|
|
729
|
+
noteToolOutcome(
|
|
730
|
+
reviewLedger,
|
|
731
|
+
toolContext.parentSessionId ?? 'sub-agent',
|
|
732
|
+
tu.name,
|
|
733
|
+
effectiveInput,
|
|
734
|
+
result.success,
|
|
735
|
+
)
|
|
736
|
+
|
|
710
737
|
// ── P0-5: Run PostToolUse hooks ──
|
|
711
738
|
let displayResult = result
|
|
712
739
|
if (this.hookEngine) {
|
package/src/core/context.ts
CHANGED
|
@@ -130,6 +130,15 @@ export class ContextManager {
|
|
|
130
130
|
* 组装时烘进去的话,本次会话里后连上的 server 永远进不了提示 —— 用户只能重启。
|
|
131
131
|
*/
|
|
132
132
|
private mcpInstructionsSource: (() => string) | null = null
|
|
133
|
+
/**
|
|
134
|
+
* 重建整个系统提示的方式,由 `index.tsx` 在装提示的同时登记。
|
|
135
|
+
*
|
|
136
|
+
* 提示是启动那一刻的快照,而其中最大的那一段 —— 指令文件(`CLAUDE.md` /
|
|
137
|
+
* `AGENTS.md` / `USER.md`)—— 在会话中会被改。压缩之后由引擎调一次
|
|
138
|
+
* `refreshSystemPrompt()`,让规则按磁盘现状生效。**重建方式必须与首次组装
|
|
139
|
+
* 同一条路径**,否则刷新会悄悄丢掉启动时拼进去的那些段(技能提醒、记忆召回…)。
|
|
140
|
+
*/
|
|
141
|
+
private systemPromptRebuilder: (() => string) | null = null
|
|
133
142
|
/**
|
|
134
143
|
* **消息那部分**的估值,增量累加(提示那部分见 `promptTokens()`,读时派生)。
|
|
135
144
|
*
|
|
@@ -258,6 +267,29 @@ export class ContextManager {
|
|
|
258
267
|
this.mcpInstructionsSource = fn
|
|
259
268
|
}
|
|
260
269
|
|
|
270
|
+
/**
|
|
271
|
+
* 接线点(`index.tsx`):重建系统提示的方式。
|
|
272
|
+
*
|
|
273
|
+
* 传 `null` 撤销。**不接**时 `refreshSystemPrompt()` 是空操作 —— daemon 等路径
|
|
274
|
+
* 从不设置系统提示,凭空造一份出来会改变它们每个请求的形状。
|
|
275
|
+
*/
|
|
276
|
+
setSystemPromptRebuilder(fn: (() => string) | null): void {
|
|
277
|
+
this.systemPromptRebuilder = fn
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 用登记好的重建器重刷系统提示。返回是否真的重刷了。
|
|
282
|
+
*
|
|
283
|
+
* 调用点是压缩之后(`Engine.compactWithHooks`):对话刚被换成摘要,而指令文件
|
|
284
|
+
* 那一段还是启动那一刻的拷贝。重建器在里面先回读磁盘(`InstructionsLoader.refresh`),
|
|
285
|
+
* 所以这里拿到的是当前磁盘上的规则。
|
|
286
|
+
*/
|
|
287
|
+
refreshSystemPrompt(): boolean {
|
|
288
|
+
if (!this.systemPromptRebuilder) return false
|
|
289
|
+
this.systemPrompt = this.systemPromptRebuilder()
|
|
290
|
+
return true
|
|
291
|
+
}
|
|
292
|
+
|
|
261
293
|
/**
|
|
262
294
|
* 存储的提示 + 读时派生的段(权限 / MCP instructions)。
|
|
263
295
|
*
|
package/src/core/engine.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type {
|
|
|
5
5
|
InferenceHookConfig,
|
|
6
6
|
CrsiConfig,
|
|
7
7
|
CrossSessionConfig,
|
|
8
|
+
Message,
|
|
9
|
+
ContentBlock,
|
|
8
10
|
} from '../shared/index.ts'
|
|
9
11
|
import { ProviderRegistry } from '../providers/registry'
|
|
10
12
|
import type { ChatRequest } from '../providers/registry'
|
|
@@ -24,6 +26,8 @@ import type { Skills } from '../skills/seam'
|
|
|
24
26
|
import { getBackgroundAgentRegistry } from '../agent/background-registry'
|
|
25
27
|
import { RulesLoader } from './rules-loader'
|
|
26
28
|
import { extractBashFileAccess } from './permission-rules'
|
|
29
|
+
import { noteToolOutcome, reviewLedger } from './merge-gate'
|
|
30
|
+
import { unprovenCountClaims } from './number-provenance'
|
|
27
31
|
import type { InstructionsLoader } from './instructions'
|
|
28
32
|
import { ExperienceRuleEngine } from './rule-engine.js'
|
|
29
33
|
import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
|
|
@@ -386,6 +390,10 @@ export class QueryEngine {
|
|
|
386
390
|
private touchedFiles: Set<string> = new Set()
|
|
387
391
|
/** A tool call failed since the last nudge check. */
|
|
388
392
|
private pendingToolFailure = false
|
|
393
|
+
/** 本轮用户输入 —— 数字出处判定里它是合法的出处之一。 */
|
|
394
|
+
private currentTurnInput = ''
|
|
395
|
+
/** 数字出处质疑每轮至多一次。 */
|
|
396
|
+
private numberNudgeSent = false
|
|
389
397
|
/** The recall nudge is offered at most once per engine (session). */
|
|
390
398
|
private lessonNudgeOffered = false
|
|
391
399
|
private usageTracker = new UsageTracker()
|
|
@@ -603,8 +611,8 @@ export class QueryEngine {
|
|
|
603
611
|
const summaryPrompt = `You are a conversation summarizer. Create a concise summary (1-3 paragraphs) of this conversation excerpt. Focus on: key topics discussed, decisions made, code changes mentioned, and open questions. Heading: ${heading}`
|
|
604
612
|
|
|
605
613
|
// Collect full summary text from streaming response
|
|
606
|
-
|
|
607
|
-
|
|
614
|
+
const requestSummary = async (prompt: string): Promise<string> => {
|
|
615
|
+
let out = ''
|
|
608
616
|
for await (const chunk of this.llmChat({
|
|
609
617
|
model: this.registry.getActiveModel(),
|
|
610
618
|
// The instruction goes in `systemPrompt`, **not** as a `system` message
|
|
@@ -614,7 +622,7 @@ export class QueryEngine {
|
|
|
614
622
|
// so the array form reached the OpenAI-compatible providers and no one
|
|
615
623
|
// else — the summarizer's instruction was missing for anthropic users
|
|
616
624
|
// while it worked here. `systemPrompt` is the one spelling both read.
|
|
617
|
-
systemPrompt:
|
|
625
|
+
systemPrompt: prompt,
|
|
618
626
|
messages: [{ role: 'user', content: text }],
|
|
619
627
|
maxTokens: 2000,
|
|
620
628
|
// An interrupt has to reach *this* call too. Summarising a long
|
|
@@ -624,13 +632,34 @@ export class QueryEngine {
|
|
|
624
632
|
signal,
|
|
625
633
|
})) {
|
|
626
634
|
if (chunk.type === 'text' && chunk.content) {
|
|
627
|
-
|
|
635
|
+
out += chunk.content
|
|
628
636
|
}
|
|
629
637
|
if (chunk.type === 'stop') break
|
|
630
638
|
if (chunk.type === 'error') break
|
|
631
639
|
}
|
|
640
|
+
return out
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
let summary = ''
|
|
644
|
+
try {
|
|
645
|
+
summary = await requestSummary(summaryPrompt)
|
|
632
646
|
} catch {
|
|
633
|
-
//
|
|
647
|
+
// A round trip that failed outright is not retried into: the same
|
|
648
|
+
// provider will fail the same way. Falls through to the placeholder.
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// 回复里没有摘要(这一趟只回了工具调用 / 空文本)时**再问一次**,而不是
|
|
652
|
+
// 立刻把整段历史换成一个「已省略」占位符:那一步是不可逆的,而模型这一次
|
|
653
|
+
// 什么都没写通常只是没把话放在正文里。第二次把要求说得更死(只要摘要正文),
|
|
654
|
+
// 因为同一个提示重发一遍只会得到同一个空回复。
|
|
655
|
+
if (!summary.trim() && !signal?.aborted) {
|
|
656
|
+
try {
|
|
657
|
+
summary = await requestSummary(
|
|
658
|
+
`${summaryPrompt}\n\nReturn only the summary text itself — no tool calls, no preamble.`,
|
|
659
|
+
)
|
|
660
|
+
} catch {
|
|
661
|
+
// Still nothing usable: the placeholder below is honest about it.
|
|
662
|
+
}
|
|
634
663
|
}
|
|
635
664
|
|
|
636
665
|
// Surrogate-safe: this string lands in the JSONL transcript, where a lone
|
|
@@ -678,6 +707,9 @@ export class QueryEngine {
|
|
|
678
707
|
|
|
679
708
|
// Add user message to context
|
|
680
709
|
this.context.addMessage({ role: 'user', content: userInput })
|
|
710
|
+
// 数字出处判定的本轮基准:用户这句话本身是合法出处,一次质疑也只给一回。
|
|
711
|
+
this.currentTurnInput = userInput
|
|
712
|
+
this.numberNudgeSent = false
|
|
681
713
|
|
|
682
714
|
// ── Restore point for `/rewind` ──
|
|
683
715
|
// Taken **here** — the prompt is in history, none of the reply is. That is what
|
|
@@ -1508,6 +1540,10 @@ export class QueryEngine {
|
|
|
1508
1540
|
// Track touched files for rules matching
|
|
1509
1541
|
this.trackTouchedFile(name, effectiveParams)
|
|
1510
1542
|
|
|
1543
|
+
// Merge gate: only a review that actually ran (and succeeded) may later
|
|
1544
|
+
// permit a merge. Recorded on the one funnel every tool call passes.
|
|
1545
|
+
noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
|
|
1546
|
+
|
|
1511
1547
|
// Prepend CRSI warnings to result content
|
|
1512
1548
|
if (hookWarnings.length > 0 && result.success) {
|
|
1513
1549
|
result.content = hookWarnings.join('\n') + '\n' + (result.content || '')
|
|
@@ -1696,6 +1732,11 @@ export class QueryEngine {
|
|
|
1696
1732
|
// fresh attempt after a failed one.
|
|
1697
1733
|
const ownsFlow = !(this.llm && this.llm !== this.registry)
|
|
1698
1734
|
let failure: string | null = null
|
|
1735
|
+
// Re-bound after a mid-turn compaction: the request that follows must be the
|
|
1736
|
+
// *new* conversation, not the oversized one the provider just rejected.
|
|
1737
|
+
let msgs = messages
|
|
1738
|
+
let sysPrompt = systemPrompt
|
|
1739
|
+
let compactedForOverflow = false
|
|
1699
1740
|
// A provider that marks the failure deterministic opts out of both retries. Only
|
|
1700
1741
|
// an explicit `false` counts: an absent flag means "unknown", which keeps the
|
|
1701
1742
|
// old try-again behaviour for every provider that says nothing.
|
|
@@ -1715,8 +1756,8 @@ export class QueryEngine {
|
|
|
1715
1756
|
try {
|
|
1716
1757
|
for await (const chunk of this.llmChat({
|
|
1717
1758
|
model: activeModel,
|
|
1718
|
-
messages,
|
|
1719
|
-
systemPrompt,
|
|
1759
|
+
messages: msgs,
|
|
1760
|
+
systemPrompt: sysPrompt,
|
|
1720
1761
|
tools: toolDefs,
|
|
1721
1762
|
signal,
|
|
1722
1763
|
effort: this.effort,
|
|
@@ -1747,6 +1788,35 @@ export class QueryEngine {
|
|
|
1747
1788
|
if (isAbortError(err)) throw err
|
|
1748
1789
|
failure = String(err)
|
|
1749
1790
|
}
|
|
1791
|
+
// A request the provider rejected as *too large* is the one failure that is
|
|
1792
|
+
// worth a different retry: re-sending it is guaranteed to fail the same way
|
|
1793
|
+
// (the prompt did not get smaller), while compacting changes the thing that
|
|
1794
|
+
// was rejected. It therefore sits **above** the retry budget below — that
|
|
1795
|
+
// budget is for flaky transports, and spending it on an oversized prompt is
|
|
1796
|
+
// how a turn used to end with the raw upstream error.
|
|
1797
|
+
if (
|
|
1798
|
+
!compactedForOverflow &&
|
|
1799
|
+
ownsFlow &&
|
|
1800
|
+
!signal?.aborted &&
|
|
1801
|
+
isContextOverflowError(failure)
|
|
1802
|
+
) {
|
|
1803
|
+
compactedForOverflow = true
|
|
1804
|
+
yield {
|
|
1805
|
+
type: 'warning',
|
|
1806
|
+
content: `${activeId} rejected the request as too large — compacting the conversation and retrying`,
|
|
1807
|
+
restart: true,
|
|
1808
|
+
}
|
|
1809
|
+
try {
|
|
1810
|
+
await this.compactWithHooks('context overflow', signal)
|
|
1811
|
+
msgs = this.context.getMessages()
|
|
1812
|
+
sysPrompt = this.context.getSystemPrompt()
|
|
1813
|
+
} catch (err) {
|
|
1814
|
+
if (isAbortError(err)) throw err
|
|
1815
|
+
// Compaction itself failed: fall through to the ordinary retry/fallback
|
|
1816
|
+
// path so the turn still ends with an explanation rather than nothing.
|
|
1817
|
+
}
|
|
1818
|
+
continue
|
|
1819
|
+
}
|
|
1750
1820
|
if (!retryable || !ownsFlow || attempt >= 1) break
|
|
1751
1821
|
// `restart: true` tells the consumer to drop what the failed attempt already
|
|
1752
1822
|
// yielded. Without it the retry's tool calls are *added* to the failed
|
|
@@ -1820,8 +1890,8 @@ export class QueryEngine {
|
|
|
1820
1890
|
try {
|
|
1821
1891
|
for await (const chunk of this.llmChat({
|
|
1822
1892
|
model: fallbackModel,
|
|
1823
|
-
messages,
|
|
1824
|
-
systemPrompt,
|
|
1893
|
+
messages: msgs,
|
|
1894
|
+
systemPrompt: sysPrompt,
|
|
1825
1895
|
tools: toolDefs,
|
|
1826
1896
|
signal,
|
|
1827
1897
|
effort: this.effort,
|
|
@@ -2099,6 +2169,12 @@ export class QueryEngine {
|
|
|
2099
2169
|
|
|
2100
2170
|
await this.context.compact(heading, signal)
|
|
2101
2171
|
|
|
2172
|
+
// 规则那一段是启动那一刻的拷贝。会话中被改过的 `CLAUDE.md` / `AGENTS.md` /
|
|
2173
|
+
// `USER.md` 若不重读,压缩换掉的只是对话,规则还是旧的 —— 而压缩正是「对话刚
|
|
2174
|
+
// 被替换」的那一刻,用户会以为模型拿到了新规则。重建器里先回读磁盘再重建;
|
|
2175
|
+
// 没登记重建器时(daemon)是空操作。
|
|
2176
|
+
this.context.refreshSystemPrompt()
|
|
2177
|
+
|
|
2102
2178
|
if (this.hookEngine) {
|
|
2103
2179
|
const postResult = await this.hookEngine.executePostCompact(this.sessionId)
|
|
2104
2180
|
if (postResult.additionalContext) {
|
|
@@ -2115,10 +2191,8 @@ export class QueryEngine {
|
|
|
2115
2191
|
signal?: AbortSignal,
|
|
2116
2192
|
roundsLeft: number = MAX_TOOL_TURNS,
|
|
2117
2193
|
): AsyncGenerator<StreamChunk> {
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
const stopResult = await this.hookEngine.executeStop(this.sessionId)
|
|
2121
|
-
if (stopResult.decision !== 'block') return
|
|
2194
|
+
const block = await this.stopBlock()
|
|
2195
|
+
if (!block) return
|
|
2122
2196
|
|
|
2123
2197
|
// A block asks for more work, and more work means another round — which the
|
|
2124
2198
|
// turn may have none of left. Saying so is the point: a hook quietly ignored
|
|
@@ -2128,21 +2202,109 @@ export class QueryEngine {
|
|
|
2128
2202
|
type: 'warning',
|
|
2129
2203
|
content: t('errors.stop_hook_budget_spent', {
|
|
2130
2204
|
max: String(MAX_TOOL_TURNS),
|
|
2131
|
-
reason:
|
|
2205
|
+
reason: block.reason,
|
|
2132
2206
|
}),
|
|
2133
2207
|
}
|
|
2134
2208
|
return
|
|
2135
2209
|
}
|
|
2136
2210
|
|
|
2137
2211
|
// Feed the block reason back to the AI and continue
|
|
2138
|
-
this.context.injectContext(
|
|
2139
|
-
'stop-hook',
|
|
2140
|
-
t('system.context.stop_blocked', {
|
|
2141
|
-
reason: stopResult.reason || 'Continue working.',
|
|
2142
|
-
}),
|
|
2143
|
-
)
|
|
2212
|
+
this.context.injectContext(block.source, block.text)
|
|
2144
2213
|
yield* this.continueWithTools(signal, roundsLeft)
|
|
2145
2214
|
}
|
|
2215
|
+
|
|
2216
|
+
/**
|
|
2217
|
+
* 什么构成了「这一轮还结束不了」。
|
|
2218
|
+
*
|
|
2219
|
+
* 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
|
|
2220
|
+
* 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
|
|
2221
|
+
*/
|
|
2222
|
+
private async stopBlock(): Promise<{ source: string; text: string; reason: string } | null> {
|
|
2223
|
+
if (this.hookEngine) {
|
|
2224
|
+
const stopResult = await this.hookEngine.executeStop(this.sessionId)
|
|
2225
|
+
if (stopResult.decision === 'block') {
|
|
2226
|
+
const reason = stopResult.reason || 'Continue working.'
|
|
2227
|
+
return {
|
|
2228
|
+
source: 'stop-hook',
|
|
2229
|
+
text: t('system.context.stop_blocked', { reason }),
|
|
2230
|
+
reason,
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
const claims = this.unprovenNumbers()
|
|
2236
|
+
if (!claims) return null
|
|
2237
|
+
// 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
|
|
2238
|
+
// 把整段问话塞进 warning 只会让人读一屏。
|
|
2239
|
+
return {
|
|
2240
|
+
source: 'number-provenance',
|
|
2241
|
+
text: t('system.context.numbers_unproven', { claims }),
|
|
2242
|
+
reason: claims,
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
/**
|
|
2247
|
+
* 「这个数是你量出来的,还是你推出来的?」
|
|
2248
|
+
*
|
|
2249
|
+
* 判据只收窄到**带计数单位的数量**(见 `number-provenance.ts`),出处只认本轮
|
|
2250
|
+
* 工具结果与用户这句话 —— 模型自己前一轮写下的话不算,那正是「先猜一个、再当
|
|
2251
|
+
* 事实复述」的形状。每轮至多问一次:问过还不改口就作罢,否则一次质疑会变成
|
|
2252
|
+
* 一台永动机。
|
|
2253
|
+
*/
|
|
2254
|
+
private unprovenNumbers(): string | null {
|
|
2255
|
+
if (this.numberNudgeSent) return null
|
|
2256
|
+
const messages = this.context.getMessages()
|
|
2257
|
+
|
|
2258
|
+
let reply = ''
|
|
2259
|
+
for (let i = messages.length - 1; i >= 0 && !reply; i--) {
|
|
2260
|
+
const message = messages[i]!
|
|
2261
|
+
if (message.role === 'assistant') reply = flatText(message.content)
|
|
2262
|
+
}
|
|
2263
|
+
if (!reply) return null
|
|
2264
|
+
|
|
2265
|
+
const evidence = [
|
|
2266
|
+
this.currentTurnInput,
|
|
2267
|
+
...messages.map((m) => (Array.isArray(m.content) ? toolResultText(m.content) : '')),
|
|
2268
|
+
].join('\n')
|
|
2269
|
+
|
|
2270
|
+
const claims = unprovenCountClaims(reply, evidence)
|
|
2271
|
+
if (claims.length === 0) return null
|
|
2272
|
+
this.numberNudgeSent = true
|
|
2273
|
+
return claims.map((c) => `\`${c.context}\``).join(' / ')
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
/** 一条消息里的可见文本(不含 tool_use 入参与 thinking)。 */
|
|
2278
|
+
function flatText(content: Message['content']): string {
|
|
2279
|
+
if (typeof content === 'string') return content
|
|
2280
|
+
return content
|
|
2281
|
+
.filter((b) => b.type === 'text')
|
|
2282
|
+
.map((b) => (b.type === 'text' ? b.text : ''))
|
|
2283
|
+
.join('\n')
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
/** 一条消息里的工具结果正文 —— 数字的唯一合法出处。 */
|
|
2287
|
+
function toolResultText(content: ContentBlock[]): string {
|
|
2288
|
+
return content
|
|
2289
|
+
.filter((b) => b.type === 'tool_result')
|
|
2290
|
+
.map((b) => (b.type === 'tool_result' ? b.content : ''))
|
|
2291
|
+
.join('\n')
|
|
2292
|
+
}
|
|
2293
|
+
|
|
2294
|
+
/**
|
|
2295
|
+
* Does this failure say "the request itself does not fit"?
|
|
2296
|
+
*
|
|
2297
|
+
* Kept narrow on purpose: a false positive costs one wasted compaction (the turn
|
|
2298
|
+
* retries either way), while a false negative ends the turn with a raw upstream
|
|
2299
|
+
* error the user cannot act on. All of these phrasings are ones the providers
|
|
2300
|
+
* actually send — the last is the one a 1M-context model returns while the
|
|
2301
|
+
* account has not enabled the charge.
|
|
2302
|
+
*/
|
|
2303
|
+
export function isContextOverflowError(message: string | null | undefined): boolean {
|
|
2304
|
+
if (!message) return false
|
|
2305
|
+
return /context[_ ]length|context window|prompt is too long|too many tokens|maximum context length|exceeds? the (?:model'?s )?(?:maximum )?context|usage credits required for 1m context/i.test(
|
|
2306
|
+
message,
|
|
2307
|
+
)
|
|
2146
2308
|
}
|
|
2147
2309
|
|
|
2148
2310
|
function isAbortError(err: unknown): boolean {
|