@miphamai/cli 0.85.23 → 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 +21 -2
- package/package.json +1 -1
- 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/core/context-microcompact.ts +1 -1
- package/src/core/context.ts +167 -10
- package/src/core/engine.ts +14 -5
- package/src/core/hooks.ts +13 -3
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/mcp/client.ts +22 -8
- 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/skills/loader.ts +41 -3
- package/src/tools/agent/workflow.ts +9 -2
- package/src/tools/exec/bash.ts +38 -11
- package/src/tools/network/web-fetch.ts +11 -3
- package/src/tools/network/web-search.ts +5 -1
- package/src/tools/scheduling/schedule-wakeup.ts +3 -2
- package/src/tools/validation.ts +11 -0
- package/src/ui/commands.ts +7 -5
- 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
|
@@ -1274,6 +1274,7 @@ Usage:
|
|
|
1274
1274
|
|
|
1275
1275
|
Flags:
|
|
1276
1276
|
--dump-config Print the assembled profile tree
|
|
1277
|
+
--profile <name> Profile for --dump-config (default: default)
|
|
1277
1278
|
--safe-mode Skip custom agents, skills, hooks, plugins
|
|
1278
1279
|
--resume <name> Open a saved session (see /resume for names)
|
|
1279
1280
|
--permission <mode> Start in this mode: ${ALL_MODES.join('|')}
|
|
@@ -1295,8 +1296,17 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1295
1296
|
const { loadProfile, loadBundle, assemble, dumpConfig } = await import('../src/vajra/compose')
|
|
1296
1297
|
|
|
1297
1298
|
const profileIdx = process.argv.indexOf('--profile')
|
|
1298
|
-
|
|
1299
|
-
|
|
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'
|
|
1300
1310
|
const dir = join(homedir(), '.mipham', 'profiles')
|
|
1301
1311
|
const profilePath = join(dir, `${profileName}.yml`)
|
|
1302
1312
|
|
|
@@ -1311,6 +1321,15 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1311
1321
|
process.exit(0)
|
|
1312
1322
|
}
|
|
1313
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
|
+
|
|
1314
1333
|
// ── Update / upgrade ──────────────────────────────────────────────────────
|
|
1315
1334
|
const handledUpdate = await runUpdate()
|
|
1316
1335
|
if (handledUpdate) return
|
package/package.json
CHANGED
|
@@ -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
|
|
@@ -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
|
package/src/core/engine.ts
CHANGED
|
@@ -585,12 +585,16 @@ export class QueryEngine {
|
|
|
585
585
|
|
|
586
586
|
/** Wire LLM-based conversation summarization into the context manager. */
|
|
587
587
|
setupContextSummarizer(): void {
|
|
588
|
-
this.context.setSummarizer(async (messages, heading) => {
|
|
588
|
+
this.context.setSummarizer(async (messages, heading, signal) => {
|
|
589
589
|
const text = messages
|
|
590
590
|
.map((m) => {
|
|
591
591
|
const role = m.role
|
|
592
592
|
const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content)
|
|
593
|
-
|
|
593
|
+
// 2000 字符是摘要器读得到的上限,但不能是**静默**上限:被切掉的那半里
|
|
594
|
+
// 常是工具结果的结论部分,摘要据此写成「做了什么」而漏掉「结果如何」。
|
|
595
|
+
// 写明省略了多少,摘要器才知道这条不完整。
|
|
596
|
+
if (content.length <= 2000) return `[${role}]: ${content}`
|
|
597
|
+
return `[${role}]: ${content.slice(0, 2000)} … [${content.length - 2000} characters omitted]`
|
|
594
598
|
})
|
|
595
599
|
.join('\n')
|
|
596
600
|
|
|
@@ -612,6 +616,11 @@ export class QueryEngine {
|
|
|
612
616
|
systemPrompt: summaryPrompt,
|
|
613
617
|
messages: [{ role: 'user', content: text }],
|
|
614
618
|
maxTokens: 2000,
|
|
619
|
+
// An interrupt has to reach *this* call too. Summarising a long
|
|
620
|
+
// conversation is a full model round trip; without the signal, Ctrl+C
|
|
621
|
+
// arrives at the compaction step and simply waits for it to finish
|
|
622
|
+
// before the turn can stop.
|
|
623
|
+
signal,
|
|
615
624
|
})) {
|
|
616
625
|
if (chunk.type === 'text' && chunk.content) {
|
|
617
626
|
summary += chunk.content
|
|
@@ -678,7 +687,7 @@ export class QueryEngine {
|
|
|
678
687
|
|
|
679
688
|
// Check compaction before processing
|
|
680
689
|
if (this.context.needsCompaction()) {
|
|
681
|
-
await this.compactWithHooks('conversation summary')
|
|
690
|
+
await this.compactWithHooks('conversation summary', signal)
|
|
682
691
|
}
|
|
683
692
|
|
|
684
693
|
const systemPrompt = this.context.getSystemPrompt()
|
|
@@ -2073,7 +2082,7 @@ export class QueryEngine {
|
|
|
2073
2082
|
}
|
|
2074
2083
|
|
|
2075
2084
|
/** Wrap context compaction with PreCompact/PostCompact hooks. */
|
|
2076
|
-
private async compactWithHooks(heading: string): Promise<void> {
|
|
2085
|
+
private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
|
|
2077
2086
|
if (this.hookEngine) {
|
|
2078
2087
|
const preResult = await this.hookEngine.executePreCompact(this.sessionId)
|
|
2079
2088
|
if (preResult.additionalContext) {
|
|
@@ -2084,7 +2093,7 @@ export class QueryEngine {
|
|
|
2084
2093
|
}
|
|
2085
2094
|
}
|
|
2086
2095
|
|
|
2087
|
-
await this.context.compact(heading)
|
|
2096
|
+
await this.context.compact(heading, signal)
|
|
2088
2097
|
|
|
2089
2098
|
if (this.hookEngine) {
|
|
2090
2099
|
const postResult = await this.hookEngine.executePostCompact(this.sessionId)
|
package/src/core/hooks.ts
CHANGED
|
@@ -361,6 +361,15 @@ export class HookEngine {
|
|
|
361
361
|
|
|
362
362
|
const result: HookResult = { allowed: true }
|
|
363
363
|
|
|
364
|
+
// A guard that could not run denies — but the denial is *remembered* rather
|
|
365
|
+
// than returned on the spot. Returning early would end the loop, and every
|
|
366
|
+
// later hook is a hook the call never got to consult: an explicit deny
|
|
367
|
+
// written after the broken one would never be reached, so the model gets
|
|
368
|
+
// "hook broke" where the real answer is "this was refused, here is why".
|
|
369
|
+
// Keep going, keep the first guard failure, and let an explicit deny
|
|
370
|
+
// (which returns immediately at its own branch) outweigh it.
|
|
371
|
+
let guardDenial: HookResult | undefined
|
|
372
|
+
|
|
364
373
|
for (const hook of matching) {
|
|
365
374
|
const key = this.healthKey(hook)
|
|
366
375
|
|
|
@@ -371,7 +380,7 @@ export class HookEngine {
|
|
|
371
380
|
// it for `PreToolUse` would turn five failures into a permanent allow
|
|
372
381
|
// for the rest of the cooldown — the same fail-open hole, delayed.
|
|
373
382
|
if (guardFailureBlocks(hook)) {
|
|
374
|
-
|
|
383
|
+
guardDenial ??= {
|
|
375
384
|
allowed: false,
|
|
376
385
|
reason:
|
|
377
386
|
`Hook "${key}" is temporarily disabled after repeated failures; ` +
|
|
@@ -379,6 +388,7 @@ export class HookEngine {
|
|
|
379
388
|
`Fix the hook, re-enable it with /hooks enable "${key}", or set ` +
|
|
380
389
|
`"failureMode": "open" to allow instead.`,
|
|
381
390
|
}
|
|
391
|
+
continue
|
|
382
392
|
}
|
|
383
393
|
result.additionalContext = result.additionalContext
|
|
384
394
|
? result.additionalContext +
|
|
@@ -446,7 +456,7 @@ export class HookEngine {
|
|
|
446
456
|
// that is not "allow" — see `guardFailureBlocks`.
|
|
447
457
|
if (guardFailureBlocks(hook)) {
|
|
448
458
|
const message = (err as { message?: string }).message || String(err)
|
|
449
|
-
|
|
459
|
+
guardDenial ??= {
|
|
450
460
|
allowed: false,
|
|
451
461
|
reason:
|
|
452
462
|
`Hook "${key}" failed and the PreToolUse guard is fail-closed: ${message} ` +
|
|
@@ -457,7 +467,7 @@ export class HookEngine {
|
|
|
457
467
|
}
|
|
458
468
|
}
|
|
459
469
|
|
|
460
|
-
return result
|
|
470
|
+
return guardDenial ?? result
|
|
461
471
|
}
|
|
462
472
|
|
|
463
473
|
listHooks(): HookDefinition[] {
|
|
@@ -952,6 +952,7 @@
|
|
|
952
952
|
"tool_collision": "[mcp] Tool collision: \"{name}\" already registered. Skipping.",
|
|
953
953
|
"missing_param": "Missing required parameter: \"{param}\"",
|
|
954
954
|
"invalid_params": "Invalid parameters: {errors}",
|
|
955
|
+
"unparseable_args": "The arguments for this tool call were not valid JSON ({detail}). Nothing was executed. Re-issue the call with complete JSON — do not infer the parameters from the fragment.",
|
|
955
956
|
"type_string": "\"{key}\" must be a string",
|
|
956
957
|
"type_number": "\"{key}\" must be a number",
|
|
957
958
|
"type_boolean": "\"{key}\" must be a boolean",
|
|
@@ -952,6 +952,7 @@
|
|
|
952
952
|
"tool_collision": "[mcp] 工具冲突:\"{name}\" 已注册,跳过。",
|
|
953
953
|
"missing_param": "缺少必需参数:\"{param}\"",
|
|
954
954
|
"invalid_params": "参数无效:{errors}",
|
|
955
|
+
"unparseable_args": "这次工具调用的参数不是合法 JSON({detail}),没有执行任何操作。请带着完整的 JSON 重新发起调用 —— 不要从这段残片里猜参数。",
|
|
955
956
|
"type_string": "\"{key}\" 必须是字符串",
|
|
956
957
|
"type_number": "\"{key}\" 必须是数字",
|
|
957
958
|
"type_boolean": "\"{key}\" 必须是布尔值",
|
package/src/mcp/client.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { HttpTransport, McpHttpError } from './http-transport'
|
|
|
11
11
|
import { McpProtocol } from './protocol'
|
|
12
12
|
import { OAuthClient } from './oauth'
|
|
13
13
|
import { TokenStore } from './token-store'
|
|
14
|
+
import { createAwakeTimer } from '../providers/fetch-utils'
|
|
14
15
|
import { createT } from '../i18n-core/t'
|
|
15
16
|
import enUS from '../i18n-core/locales/en-US.json'
|
|
16
17
|
import zhCN from '../i18n-core/locales/zh-CN.json'
|
|
@@ -454,10 +455,22 @@ export class McpClient {
|
|
|
454
455
|
}
|
|
455
456
|
}
|
|
456
457
|
|
|
457
|
-
/**
|
|
458
|
+
/**
|
|
459
|
+
* Race the connect handshake against a timeout so a hung server fails fast.
|
|
460
|
+
*
|
|
461
|
+
* The budget counts *awake* time (`createAwakeTimer`), not wall time: a laptop
|
|
462
|
+
* that sleeps mid-handshake would otherwise fire the whole budget the instant
|
|
463
|
+
* the lid opens, latch the connection as `error`, and — because a failed
|
|
464
|
+
* server registers no tools — never give `markIfTransportLost` a chance to
|
|
465
|
+
* reconnect. The server is fine; only the clock moved.
|
|
466
|
+
*/
|
|
458
467
|
private async withConnectTimeout<T>(name: string, fn: () => Promise<T>): Promise<T> {
|
|
459
468
|
const timeoutMs = connectTimeoutMs()
|
|
460
|
-
let timer
|
|
469
|
+
// Held in an object, not a `let`: the timer is armed inside the Promise
|
|
470
|
+
// executor, and assignments made there are invisible to control-flow
|
|
471
|
+
// narrowing — TS keeps the variable typed `null` and the cleanup call below
|
|
472
|
+
// is a type error rather than code.
|
|
473
|
+
const timer: { cancel?: () => void } = {}
|
|
461
474
|
// Swallow a late rejection: if the timeout wins, transport.close() in the
|
|
462
475
|
// caller's catch makes fn()'s pending request reject after we've moved on.
|
|
463
476
|
const work = fn()
|
|
@@ -466,14 +479,13 @@ export class McpClient {
|
|
|
466
479
|
return await Promise.race([
|
|
467
480
|
work,
|
|
468
481
|
new Promise<never>((_, reject) => {
|
|
469
|
-
timer =
|
|
470
|
-
|
|
471
|
-
timeoutMs,
|
|
482
|
+
timer.cancel = createAwakeTimer(timeoutMs, () =>
|
|
483
|
+
reject(new Error(`MCP connect timed out for "${name}" after ${timeoutMs}ms`)),
|
|
472
484
|
)
|
|
473
485
|
}),
|
|
474
486
|
])
|
|
475
487
|
} finally {
|
|
476
|
-
|
|
488
|
+
timer.cancel?.()
|
|
477
489
|
}
|
|
478
490
|
}
|
|
479
491
|
|
|
@@ -493,11 +505,13 @@ export class McpClient {
|
|
|
493
505
|
* nothing to wait for, and `callTool` will say so.
|
|
494
506
|
*/
|
|
495
507
|
async waitUntilReady(name: string, timeoutMs: number = connectTimeoutMs()): Promise<boolean> {
|
|
496
|
-
|
|
508
|
+
// Awake time, same as the handshake budget it mirrors: a sleep mid-wait must
|
|
509
|
+
// not spend the deadline the server never got to use.
|
|
510
|
+
const deadline = performance.now() + timeoutMs
|
|
497
511
|
for (;;) {
|
|
498
512
|
const conn = this.connections.get(name)
|
|
499
513
|
if (!conn || conn.status !== 'connecting') return true
|
|
500
|
-
if (
|
|
514
|
+
if (performance.now() >= deadline) return false
|
|
501
515
|
await new Promise((resolve) => setTimeout(resolve, CONNECT_POLL_MS))
|
|
502
516
|
}
|
|
503
517
|
}
|
|
@@ -310,8 +310,14 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
310
310
|
let parsedInput: Record<string, unknown> = {}
|
|
311
311
|
try {
|
|
312
312
|
parsedInput = JSON.parse(accumulatedToolInput)
|
|
313
|
-
} catch {
|
|
314
|
-
|
|
313
|
+
} catch (err) {
|
|
314
|
+
// Same tag as the OpenAI-compatible path: a bare fragment
|
|
315
|
+
// reaches the validator as "missing required parameter",
|
|
316
|
+
// which sends the model looking for the wrong mistake.
|
|
317
|
+
parsedInput = {
|
|
318
|
+
_parseError: `${err instanceof Error ? err.message : String(err)}; received ${accumulatedToolInput.length} characters`,
|
|
319
|
+
_raw: accumulatedToolInput,
|
|
320
|
+
}
|
|
315
321
|
}
|
|
316
322
|
|
|
317
323
|
yield {
|
|
@@ -33,6 +33,11 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
33
33
|
stream: true,
|
|
34
34
|
max_tokens: req.maxTokens || declaredMaxOutput || 8192,
|
|
35
35
|
temperature: req.temperature,
|
|
36
|
+
// Without this the server never sends the final usage chunk, so callers
|
|
37
|
+
// that report token use (sub-agents, the metrics footer) record 0 for
|
|
38
|
+
// every OpenAI-compatible provider — a number that reads as "free" rather
|
|
39
|
+
// than "not measured".
|
|
40
|
+
stream_options: { include_usage: true },
|
|
36
41
|
tools: req.tools?.map((t) => ({ type: 'function', function: t })),
|
|
37
42
|
}
|
|
38
43
|
|
|
@@ -448,8 +453,15 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
448
453
|
if (!raw) return {}
|
|
449
454
|
try {
|
|
450
455
|
return JSON.parse(raw)
|
|
451
|
-
} catch {
|
|
452
|
-
|
|
456
|
+
} catch (err) {
|
|
457
|
+
// Tag the failure instead of handing back a bare fragment: the tool's
|
|
458
|
+
// validator would then report "missing required parameter", and the model
|
|
459
|
+
// would spend its retry supplying a parameter it had already written
|
|
460
|
+
// rather than re-sending the JSON it truncated.
|
|
461
|
+
return {
|
|
462
|
+
_parseError: `${err instanceof Error ? err.message : String(err)}; received ${raw.length} characters`,
|
|
463
|
+
_raw: raw,
|
|
464
|
+
}
|
|
453
465
|
}
|
|
454
466
|
}
|
|
455
467
|
|
|
@@ -44,6 +44,7 @@ const KNOWN_FLAGS = [
|
|
|
44
44
|
'--help',
|
|
45
45
|
'-h',
|
|
46
46
|
'--dump-config',
|
|
47
|
+
'--profile',
|
|
47
48
|
'--safe-mode',
|
|
48
49
|
'--resume',
|
|
49
50
|
'--permission',
|
|
@@ -71,7 +72,7 @@ const KNOWN_FLAGS = [
|
|
|
71
72
|
* actually wrong never mentioned, exit 1, no CLI. Their values are open (a provider may
|
|
72
73
|
* be user-defined), so — unlike `--permission` — this module owns only their spelling.
|
|
73
74
|
*/
|
|
74
|
-
const VALUE_FLAGS = ['--resume', '--permission', '--provider', '--model']
|
|
75
|
+
const VALUE_FLAGS = ['--resume', '--permission', '--provider', '--model', '--profile']
|
|
75
76
|
|
|
76
77
|
/**
|
|
77
78
|
* The first token that would be read as a command, skipping flags and the values
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
export const PACKAGE_NAME = '@miphamai/cli' as const
|
|
10
10
|
|
|
11
11
|
/** 当前发布版本 */
|
|
12
|
-
export const PACKAGE_VERSION = '0.85.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.24' as const
|
|
13
13
|
|
|
14
14
|
/** npm install 全局安装命令 */
|
|
15
15
|
export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
|
|
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
|
|
|
90
90
|
* —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
|
|
91
91
|
* 但**总数相同**(两边都把被 skip 的算进去)。
|
|
92
92
|
*/
|
|
93
|
-
export const TEST_COUNT =
|
|
93
|
+
export const TEST_COUNT = 4388 as const
|
package/src/skills/loader.ts
CHANGED
|
@@ -227,7 +227,7 @@ export class SkillsLoader implements Skills {
|
|
|
227
227
|
type,
|
|
228
228
|
body,
|
|
229
229
|
tools: data.tools as SkillDefinition['tools'],
|
|
230
|
-
hooks: data.hooks
|
|
230
|
+
hooks: parseSkillHooks(data.hooks, skillName),
|
|
231
231
|
prompts: data.prompts as SkillDefinition['prompts'],
|
|
232
232
|
// NEW: frontmatter fields for fork/auto-trigger support
|
|
233
233
|
context: data.context as string | undefined,
|
|
@@ -305,10 +305,48 @@ export class SkillsLoader implements Skills {
|
|
|
305
305
|
}
|
|
306
306
|
}
|
|
307
307
|
|
|
308
|
+
/**
|
|
309
|
+
* 只接受**真带 handler** 的技能钩子。
|
|
310
|
+
*
|
|
311
|
+
* YAML 里没有闭包,所以技能 frontmatter 写的 `hooks:` 到这一步只是数据,`handler`
|
|
312
|
+
* 恒为 `undefined`(`as` 断言把类型骗过去了)。原样注册的后果不是「钩子不生效」,
|
|
313
|
+
* 是**每一个工具调用都被拒**:`runHooks` 调 `undefined(ctx)` 抛 TypeError,而
|
|
314
|
+
* PreToolUse 的守卫是 fail-closed —— 引擎把它读成「守卫答不出来」,于是整场会话
|
|
315
|
+
* 的每一次工具调用都返回拒绝。插件路径交进来的钩子带真 handler,照常放行。
|
|
316
|
+
*/
|
|
317
|
+
function parseSkillHooks(raw: unknown, skillName: string): SkillDefinition['hooks'] {
|
|
318
|
+
if (!Array.isArray(raw)) return undefined
|
|
319
|
+
|
|
320
|
+
const accepted: SkillDefinition['hooks'] = []
|
|
321
|
+
for (const entry of raw) {
|
|
322
|
+
const handler = (entry as { handler?: unknown } | null)?.handler
|
|
323
|
+
if (typeof handler === 'function') {
|
|
324
|
+
accepted.push({
|
|
325
|
+
...(entry as object),
|
|
326
|
+
source: skillName,
|
|
327
|
+
} as NonNullable<SkillDefinition['hooks']>[number])
|
|
328
|
+
continue
|
|
329
|
+
}
|
|
330
|
+
process.stderr.write(
|
|
331
|
+
`⚠️ Skill "${skillName}": a hook entry has no handler (frontmatter cannot carry ` +
|
|
332
|
+
`functions) — ignored. Declare the hook in settings.json instead.\n`,
|
|
333
|
+
)
|
|
334
|
+
}
|
|
335
|
+
return accepted.length > 0 ? accepted : undefined
|
|
336
|
+
}
|
|
337
|
+
|
|
308
338
|
const COMPACT_DESC_MAX_CHARS = 80
|
|
309
339
|
|
|
310
|
-
/**
|
|
311
|
-
|
|
340
|
+
/**
|
|
341
|
+
* Collapse a description to a single short line.
|
|
342
|
+
*
|
|
343
|
+
* Used both by the compact system reminder and by the human-facing `/skills`
|
|
344
|
+
* listing: skill descriptions are written for the *model* and are often
|
|
345
|
+
* several paragraphs of instructions. Pasting that into a terminal listing
|
|
346
|
+
* turns three skills into a screenful; the first line + an ellipsis is the
|
|
347
|
+
* honest short form (there is no separate short-description field to read).
|
|
348
|
+
*/
|
|
349
|
+
export function truncateSkillDescription(desc: string): string {
|
|
312
350
|
const firstLine = desc.split('\n')[0]?.trim() ?? ''
|
|
313
351
|
return firstLine.length > COMPACT_DESC_MAX_CHARS
|
|
314
352
|
? firstLine.slice(0, COMPACT_DESC_MAX_CHARS) + '…'
|
|
@@ -93,11 +93,18 @@ export const workflowTool: ToolDefinition = {
|
|
|
93
93
|
}
|
|
94
94
|
}
|
|
95
95
|
|
|
96
|
-
// Build a minimal engine-like interface for runWorkflow
|
|
96
|
+
// Build a minimal engine-like interface for runWorkflow.
|
|
97
|
+
//
|
|
98
|
+
// `runWorkflow` reads four accessors, not two: without `getPermission` /
|
|
99
|
+
// `getLlm` this stub made every Workflow call throw `engine.getPermission is
|
|
100
|
+
// not a function` before the script even started. The cast hid it — the
|
|
101
|
+
// object was asserted to be a QueryEngine, and nothing exercised the call.
|
|
97
102
|
const engineStub = {
|
|
98
103
|
getRegistry: () => ctx.registry!,
|
|
99
104
|
getTools: () => ctx.toolRegistry!,
|
|
100
|
-
|
|
105
|
+
getPermission: () => ctx.permissionSystem,
|
|
106
|
+
getLlm: () => ctx.llm,
|
|
107
|
+
} as unknown as QueryEngine
|
|
101
108
|
|
|
102
109
|
try {
|
|
103
110
|
const { runId, result, cacheHits, cacheMisses } = await runWorkflow(
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -16,32 +16,53 @@ import { withValidation } from '../validation'
|
|
|
16
16
|
// target being the last thing on the line, so `rm -rf /*` was refused while
|
|
17
17
|
// `rm -rf /* > log`, `rm -rf /* foo` and `rm -rf /*; echo x` — the same
|
|
18
18
|
// deletion — were not.
|
|
19
|
+
// Any spelling of the recursive flag: `-rf`, `-fr`, `-r`, `-R`, `--recursive`.
|
|
20
|
+
// Another flag may sit on either side (`-f -r`, `-i -r -v`), because the shell
|
|
21
|
+
// does not care about flag order or which letters share a cluster.
|
|
22
|
+
//
|
|
23
|
+
// Matching only `-rf`/`-fr` made the refusal a spelling test rather than a
|
|
24
|
+
// behaviour test: `rm -r /Volumes` deletes exactly what `rm -rf /Volumes` does
|
|
25
|
+
// and passed. Every guard below needs the same fragment, so it is written once.
|
|
26
|
+
const RM_OTHER_FLAGS = String.raw`(?:-[A-Za-z]+|--[a-z][a-z-]*)`
|
|
27
|
+
const RM_RECURSIVE = String.raw`(?:-[A-Za-z]*[rR][A-Za-z]*|--recursive)`
|
|
28
|
+
const RM_LEAD = String.raw`\brm\s+(?:${RM_OTHER_FLAGS}\s+)*${RM_RECURSIVE}(?:\s+${RM_OTHER_FLAGS})*\s+`
|
|
29
|
+
|
|
30
|
+
/** `rm` with the recursive flag in any spelling, followed by `target`. */
|
|
31
|
+
function rmRecursiveOn(target: string, flags = ''): RegExp {
|
|
32
|
+
return new RegExp(RM_LEAD + target, flags)
|
|
33
|
+
}
|
|
34
|
+
|
|
19
35
|
const BLOCKED_PATTERNS = [
|
|
20
36
|
// Recursive root deletion without preserve-root safeguard.
|
|
21
37
|
// The operand may be quoted: `rm -rf '/'` reaches the same path as `rm -rf /`, so
|
|
22
38
|
// the quote belongs to the *delimiter* class, not to the path — `['"]?` opens the
|
|
23
39
|
// operand and the lookahead accepts the closing quote.
|
|
24
|
-
|
|
25
|
-
|
|
40
|
+
rmRecursiveOn(String.raw`['"]?\/(?=["'\s]|$)`),
|
|
41
|
+
rmRecursiveOn(String.raw`['"]?\/\*(?=["'\s;&|>]|$)`),
|
|
26
42
|
/\bsudo\s+rm\s+.*\//,
|
|
27
43
|
// rm -rf on home directory or any absolute path (relative dirs like node_modules stay allowed)
|
|
28
|
-
|
|
29
|
-
|
|
44
|
+
rmRecursiveOn(String.raw`['"]?~(?:["'\s\/]|$)`),
|
|
45
|
+
rmRecursiveOn(String.raw`['"]?\/(?![\s*])`),
|
|
30
46
|
// rm -rf on dangerous cwd globs
|
|
31
|
-
|
|
47
|
+
rmRecursiveOn(String.raw`['"]?\*(?=["'\s;&|>]|$)`),
|
|
32
48
|
// `rm -rf .` and its path spellings `./` and `../` delete the working directory;
|
|
33
49
|
// `./build` and `../vendor` name an entry inside it and stay allowed.
|
|
34
|
-
|
|
50
|
+
rmRecursiveOn(String.raw`['"]?\.\.?(?:\/)?(?=["'\s;&|>]|$)`),
|
|
35
51
|
// The home directory under another name is still the home directory. `$HOME`
|
|
36
52
|
// expands to the same tree as `~`; on Windows `C:\Users\<name>` *is* the profile
|
|
37
53
|
// directory, long or in its 8.3 short form (`C:\Users\GUOHUA~1`). Guarding only
|
|
38
54
|
// the literal spellings above leaves each of these a one-word bypass.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
55
|
+
rmRecursiveOn(String.raw`['"]?\$\{?HOME\}?(?:["'\s/]|$)`),
|
|
56
|
+
rmRecursiveOn(String.raw`['"]?[A-Za-z]:[\\/](?=["'\s;&|>]|$)`),
|
|
57
|
+
// `C:\Users` itself is the parent of every profile on the drive — the drive's
|
|
58
|
+
// equivalent of `/home`, so the profile name is optional rather than required.
|
|
59
|
+
rmRecursiveOn(
|
|
60
|
+
String.raw`['"]?[A-Za-z]:[\\/]Users(?:[\\/](?:[^\\/\s"']+(?:[\\/])?)?)?(?=["'\s;&|>]|$)`,
|
|
61
|
+
'i',
|
|
62
|
+
),
|
|
42
63
|
// cmd.exe spells the same directories with percent signs; in scope whenever a
|
|
43
64
|
// command hands off to cmd (`cmd /c …`).
|
|
44
|
-
|
|
65
|
+
rmRecursiveOn(String.raw`['"]?%(?:USERPROFILE|HOMEPATH|HOMEDRIVE)%`, 'i'),
|
|
45
66
|
// Filesystem manipulation
|
|
46
67
|
/\bmkfs\./,
|
|
47
68
|
/\bdd\s+if=/,
|
|
@@ -531,6 +552,10 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
531
552
|
)
|
|
532
553
|
.join('\n')
|
|
533
554
|
}
|
|
555
|
+
// A full disk is the one failure whose raw form (`ENOSPC … /some/path`)
|
|
556
|
+
// reads like a *path* problem, so the model starts checking permissions
|
|
557
|
+
// on a path that is fine. Say what happened instead.
|
|
558
|
+
const diskFull = /ENOSPC|No space left on device/i.test(stderr)
|
|
534
559
|
return {
|
|
535
560
|
success: false,
|
|
536
561
|
content: errorContent,
|
|
@@ -538,7 +563,9 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
538
563
|
? `Command cancelled (SIGKILL to its process group)`
|
|
539
564
|
: timedOut
|
|
540
565
|
? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
|
|
541
|
-
:
|
|
566
|
+
: diskFull
|
|
567
|
+
? `The disk is full (ENOSPC) — the command could not finish, and anything it had written may be partial: ${stderr.slice(0, 1_000)}`
|
|
568
|
+
: `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
|
|
542
569
|
}
|
|
543
570
|
}
|
|
544
571
|
|
|
@@ -307,11 +307,19 @@ export const webFetchTool: ToolDefinition = {
|
|
|
307
307
|
const contentType = response.headers.get('content-type') || ''
|
|
308
308
|
const isHtml = contentType.includes('text/html') || contentType.includes('application/xhtml')
|
|
309
309
|
|
|
310
|
+
// A 4xx/5xx is a statement about the site, not a failure of the tool:
|
|
311
|
+
// hand the status and whatever body it returned to the model as a normal
|
|
312
|
+
// result, so it can re-aim the request instead of treating the fetch as
|
|
313
|
+
// broken. Deliberately not cached — a 404 today may be a 200 tomorrow.
|
|
310
314
|
if (!response.ok) {
|
|
315
|
+
const body = await response.text().catch(() => '')
|
|
316
|
+
const text = isHtml ? htmlToMarkdown(body, response.url || url) : body
|
|
311
317
|
return {
|
|
312
|
-
success:
|
|
313
|
-
content:
|
|
314
|
-
|
|
318
|
+
success: true,
|
|
319
|
+
content:
|
|
320
|
+
`HTTP ${response.status}: ${response.statusText}` +
|
|
321
|
+
(text ? `\n\n${text.slice(0, MAX_RETURN_CHARS)}` : ''),
|
|
322
|
+
metadata: { url, status: response.status },
|
|
315
323
|
}
|
|
316
324
|
}
|
|
317
325
|
|
|
@@ -158,8 +158,12 @@ export const webSearchTool: ToolDefinition = {
|
|
|
158
158
|
return {
|
|
159
159
|
success: false,
|
|
160
160
|
content: '',
|
|
161
|
+
// 说清楚「绕不过去」:不写这一句,模型最常见的下一步是改用 WebFetch
|
|
162
|
+
// 或浏览器去同一个站点再问一遍 —— 那既不会恢复配额,又是另一份预算。
|
|
161
163
|
error:
|
|
162
|
-
'Brave Search API rate limit reached (2,000/month on free tier).
|
|
164
|
+
'Brave Search API rate limit reached (2,000/month on free tier). ' +
|
|
165
|
+
'Do not route around it with WebFetch or a browser — the quota is spent ' +
|
|
166
|
+
'either way. Tell the user and wait for it to reset.',
|
|
163
167
|
}
|
|
164
168
|
}
|
|
165
169
|
if (response.status === 401) {
|
|
@@ -173,7 +173,7 @@ export function resumeWakeups(opts: { sessionId: string; now?: Date }): LostWake
|
|
|
173
173
|
export const scheduleWakeupTool: ToolDefinition = {
|
|
174
174
|
name: 'ScheduleWakeup',
|
|
175
175
|
description:
|
|
176
|
-
'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600].',
|
|
176
|
+
'Schedule when to resume work in /loop dynamic mode — the user invoked /loop without an interval, asking you to self-pace iterations of a specific task. Do NOT schedule a short-interval wakeup to poll for background work you started — when harness-tracked work finishes, you are re-invoked automatically. The runtime clamps to [60, 3600]. Pick the delay by cache window, not by round minutes: sleeping past 300s means the next turn re-reads the conversation uncached. Use 60–270s while actively watching something nothing else will notify you about, 1200–1800s for idle waits. Avoid exactly 300s (pays the cache miss without buying a long wait), and do NOT pick 3600 — that fires just after the 1-hour prompt cache expires, so the full re-read buys nothing; 3300 or less lands inside the window.',
|
|
177
177
|
category: 'scheduling',
|
|
178
178
|
permission: 'self',
|
|
179
179
|
parameters: {
|
|
@@ -181,7 +181,8 @@ export const scheduleWakeupTool: ToolDefinition = {
|
|
|
181
181
|
properties: {
|
|
182
182
|
delaySeconds: {
|
|
183
183
|
type: 'number',
|
|
184
|
-
description:
|
|
184
|
+
description:
|
|
185
|
+
'Seconds from now to wake up. Clamped to [60, 3600] by the runtime; prefer 3300 or less so the next turn stays inside the prompt-cache window.',
|
|
185
186
|
},
|
|
186
187
|
reason: {
|
|
187
188
|
type: 'string',
|
package/src/tools/validation.ts
CHANGED
|
@@ -76,6 +76,17 @@ export function withValidation(tool: ToolDefinition): ToolDefinition {
|
|
|
76
76
|
return {
|
|
77
77
|
...tool,
|
|
78
78
|
async execute(params, ctx): Promise<ToolResult> {
|
|
79
|
+
// 参数不是合法 JSON 时,providers 交回的是 `{ _parseError, _raw }` 而不是
|
|
80
|
+
// `{}`。照常校验的话,模型会读到「缺少必需参数 url」—— 一个它明明写过的
|
|
81
|
+
// 参数,于是它去补参数,而不是去补那半个 JSON。先把这个事实说清楚。
|
|
82
|
+
if (typeof params._parseError === 'string') {
|
|
83
|
+
return {
|
|
84
|
+
success: false,
|
|
85
|
+
content: '',
|
|
86
|
+
error: t('errors.unparseable_args', { detail: params._parseError }),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
79
90
|
const cleanParams = sanitizeParams(params)
|
|
80
91
|
const errors = validateParams(schema, cleanParams)
|
|
81
92
|
if (errors.length > 0) {
|
package/src/ui/commands.ts
CHANGED
|
@@ -8,7 +8,7 @@ import type { QueryEngine } from '../core/engine'
|
|
|
8
8
|
import type { MiphamConfig } from '../shared/index.ts'
|
|
9
9
|
import { formatContextWindow } from '../shared/format'
|
|
10
10
|
import { sanitizeInlineField } from '../shared/sanitize'
|
|
11
|
-
import type
|
|
11
|
+
import { truncateSkillDescription, type SkillsLoader } from '../skills/loader'
|
|
12
12
|
import { loadSkillUsage } from '../skills/usage'
|
|
13
13
|
import type { PluginManager } from '../plugin/plugin-manager'
|
|
14
14
|
import type { Message } from '../shared/types.js'
|
|
@@ -677,10 +677,11 @@ const skillsCmd: CommandHandler = (ctx) => {
|
|
|
677
677
|
|
|
678
678
|
const lines: string[] = [
|
|
679
679
|
`── Standard Skills (${counts.standard}) ──`,
|
|
680
|
-
|
|
680
|
+
// 描述是写给模型的(常是好几段指令),不是终端里的一行摘要。
|
|
681
|
+
...standard.map((s) => ` ${s.name.padEnd(28)} ${truncateSkillDescription(s.description)}`),
|
|
681
682
|
'',
|
|
682
683
|
`── Mipham Exclusive (${counts.mipham}) ──`,
|
|
683
|
-
...mipham.map((s) => ` ${s.name.padEnd(20)} ${s.description}`),
|
|
684
|
+
...mipham.map((s) => ` ${s.name.padEnd(20)} ${truncateSkillDescription(s.description)}`),
|
|
684
685
|
'',
|
|
685
686
|
t('commands.skills.loaded', { count: String(counts.total) }),
|
|
686
687
|
]
|
|
@@ -2534,7 +2535,7 @@ const reloadSkillsCmd: CommandHandler = (ctx) => {
|
|
|
2534
2535
|
}
|
|
2535
2536
|
const skills = ctx.skillsLoader.list()
|
|
2536
2537
|
return {
|
|
2537
|
-
content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${s.description}`).join('\n')}`,
|
|
2538
|
+
content: `${t('commands.reload_skills.confirmed', { count: String(skills.length) })}\n\n${skills.map((s) => ` ${s.name.padEnd(28)} ${s.type.padEnd(10)} ${truncateSkillDescription(s.description)}`).join('\n')}`,
|
|
2538
2539
|
}
|
|
2539
2540
|
} catch (err) {
|
|
2540
2541
|
return { content: t('commands.reload_skills.failed', { error: String(err) }) }
|
|
@@ -3230,7 +3231,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3230
3231
|
`You are in an autonomous loop. Each iteration:\n` +
|
|
3231
3232
|
`1. Make progress on the task above\n` +
|
|
3232
3233
|
`2. When you need to wait (e.g., for a deploy, CI, external event), call ScheduleWakeup with:\n` +
|
|
3233
|
-
` - delaySeconds: your best estimate of how long to wait (60-3600
|
|
3234
|
+
` - delaySeconds: your best estimate of how long to wait (60-3600; prefer ≤3300\n` +
|
|
3235
|
+
` so the wake-up stays inside the prompt-cache window)\n` +
|
|
3234
3236
|
` - reason: one sentence explaining why\n` +
|
|
3235
3237
|
` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
|
|
3236
3238
|
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
@@ -222,22 +222,51 @@ export async function workflowAgent(
|
|
|
222
222
|
/* best-effort */
|
|
223
223
|
}
|
|
224
224
|
|
|
225
|
-
// Remove worktree and branch
|
|
225
|
+
// Remove worktree and branch.
|
|
226
|
+
//
|
|
227
|
+
// Every step here used to be fire-and-forget: a `worktree remove` that
|
|
228
|
+
// failed left the registration behind, the `branch -D` then failed too
|
|
229
|
+
// ("used by worktree at …"), and the run reported clean either way. So
|
|
230
|
+
// check both exits and say what is left — an unchanged agent worktree
|
|
231
|
+
// that nobody removes is state the next run has to trip over.
|
|
232
|
+
const leftovers: string[] = []
|
|
226
233
|
try {
|
|
227
234
|
const rmProc = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
|
|
228
235
|
stdout: 'pipe',
|
|
229
236
|
stderr: 'pipe',
|
|
230
237
|
})
|
|
231
|
-
await rmProc.exited
|
|
238
|
+
let removed = (await rmProc.exited) === 0
|
|
239
|
+
if (!removed) {
|
|
240
|
+
// A worktree whose directory is already gone leaves only a stale
|
|
241
|
+
// registration; prune clears it so the branch delete can proceed.
|
|
242
|
+
const pruneProc = Bun.spawn(['git', 'worktree', 'prune'], {
|
|
243
|
+
stdout: 'pipe',
|
|
244
|
+
stderr: 'pipe',
|
|
245
|
+
})
|
|
246
|
+
await pruneProc.exited
|
|
247
|
+
const retry = Bun.spawn(['git', 'worktree', 'remove', '--force', worktreePath], {
|
|
248
|
+
stdout: 'pipe',
|
|
249
|
+
stderr: 'pipe',
|
|
250
|
+
})
|
|
251
|
+
removed = (await retry.exited) === 0
|
|
252
|
+
}
|
|
253
|
+
if (!removed) leftovers.push(`worktree ${worktreePath}`)
|
|
254
|
+
|
|
232
255
|
if (worktreeBranch) {
|
|
233
256
|
const brProc = Bun.spawn(['git', 'branch', '-D', worktreeBranch], {
|
|
234
257
|
stdout: 'pipe',
|
|
235
258
|
stderr: 'pipe',
|
|
236
259
|
})
|
|
237
|
-
await brProc.exited
|
|
260
|
+
if ((await brProc.exited) !== 0) leftovers.push(`branch ${worktreeBranch}`)
|
|
238
261
|
}
|
|
239
|
-
} catch {
|
|
240
|
-
|
|
262
|
+
} catch (err) {
|
|
263
|
+
leftovers.push(`${worktreePath} (${err instanceof Error ? err.message : String(err)})`)
|
|
264
|
+
}
|
|
265
|
+
if (leftovers.length > 0) {
|
|
266
|
+
process.stderr.write(
|
|
267
|
+
`⚠️ workflow: could not clean up ${leftovers.join(' and ')} — ` +
|
|
268
|
+
`the run finished, but this state needs manual removal.\n`,
|
|
269
|
+
)
|
|
241
270
|
}
|
|
242
271
|
}
|
|
243
272
|
}
|
|
@@ -11,15 +11,33 @@
|
|
|
11
11
|
* picks the winner, and optionally synthesizes a final result.
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
-
import { workflowAgent } from './agent'
|
|
15
14
|
import { parallel } from './parallel'
|
|
16
|
-
import type { WorkflowAgentOpts } from './agent'
|
|
17
15
|
|
|
18
|
-
// Agent function signature matching the sandbox-injected
|
|
19
|
-
// (prompt, opts?) → result.
|
|
20
|
-
//
|
|
21
|
-
|
|
22
|
-
|
|
16
|
+
// Agent function signature matching the sandbox-injected `agent`:
|
|
17
|
+
// (prompt, opts?) → result. The workflow runtime passes its own wrapped agent
|
|
18
|
+
// in, so every verify()/judge() fan-out is journaled and replayable on resume.
|
|
19
|
+
export type AgentFn = (prompt: string, opts?: Record<string, unknown>) => Promise<unknown>
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* These primitives must run **inside** a workflow run.
|
|
23
|
+
*
|
|
24
|
+
* The run's `agent` is what makes an agent call journaled (so resume replays it
|
|
25
|
+
* instead of re-running) and what binds the provider registry, tools and
|
|
26
|
+
* permission system. Without it there is no sensible fallback: calling the raw
|
|
27
|
+
* `workflowAgent` here would need a registry positionally, so it would either
|
|
28
|
+
* crash or — worse — run unbudgeted and unjournaled, and every resumed run
|
|
29
|
+
* would re-run all of its skeptics.
|
|
30
|
+
*/
|
|
31
|
+
function resolveAgent(opts: { agent?: AgentFn; _mockAgent?: AgentFn }): AgentFn {
|
|
32
|
+
const fn = opts.agent ?? opts._mockAgent
|
|
33
|
+
if (!fn) {
|
|
34
|
+
throw new Error(
|
|
35
|
+
"verify()/judge() need the run's agent(): they are only callable inside a workflow run, " +
|
|
36
|
+
'where the runtime injects it.',
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
return fn
|
|
40
|
+
}
|
|
23
41
|
|
|
24
42
|
// ── Types ──
|
|
25
43
|
|
|
@@ -39,8 +57,10 @@ export interface VerifyOpts {
|
|
|
39
57
|
voters?: number // consensus: default 3
|
|
40
58
|
threshold?: number
|
|
41
59
|
schema: Record<string, unknown>
|
|
42
|
-
/**
|
|
43
|
-
|
|
60
|
+
/** Injected by the workflow runtime: the run's wrapped `agent` (journal + resume cache). */
|
|
61
|
+
agent?: AgentFn
|
|
62
|
+
/** Test-only: inject a mock agent function. */
|
|
63
|
+
_mockAgent?: AgentFn
|
|
44
64
|
}
|
|
45
65
|
|
|
46
66
|
interface VerdictVote {
|
|
@@ -67,8 +87,10 @@ export interface JudgeOpts {
|
|
|
67
87
|
judges?: number // default: 3
|
|
68
88
|
synthesize?: boolean // default: true
|
|
69
89
|
schema: Record<string, unknown>
|
|
90
|
+
/** Injected by the workflow runtime: the run's wrapped `agent` (journal + resume cache). */
|
|
91
|
+
agent?: AgentFn
|
|
70
92
|
/** Test-only: inject a mock agent function. */
|
|
71
|
-
_mockAgent?:
|
|
93
|
+
_mockAgent?: AgentFn
|
|
72
94
|
}
|
|
73
95
|
|
|
74
96
|
// ── Helpers ──
|
|
@@ -82,10 +104,7 @@ function defaultThreshold(mode: VerifyMode, total: number): number {
|
|
|
82
104
|
// ── verify() ──
|
|
83
105
|
|
|
84
106
|
export async function verify(finding: unknown, opts: VerifyOpts): Promise<VerifyResult> {
|
|
85
|
-
|
|
86
|
-
// In production sandbox usage, _mockAgent is set to the pre-bound agent
|
|
87
|
-
// function injected by the workflow runtime.
|
|
88
|
-
const agentFn: AgentFn = opts._mockAgent ?? (workflowAgent as unknown as AgentFn)
|
|
107
|
+
const agentFn = resolveAgent(opts)
|
|
89
108
|
const mode = opts.mode
|
|
90
109
|
|
|
91
110
|
const findingStr = JSON.stringify(finding, null, 2)
|
|
@@ -126,9 +145,7 @@ export async function verify(finding: unknown, opts: VerifyOpts): Promise<Verify
|
|
|
126
145
|
|
|
127
146
|
// Fan out all agent calls concurrently
|
|
128
147
|
const rawVotes = await parallel(
|
|
129
|
-
prompts.map(
|
|
130
|
-
(p) => () => agentFn(p.prompt, { schema: opts.schema as WorkflowAgentOpts['schema'] }),
|
|
131
|
-
),
|
|
148
|
+
prompts.map((p) => () => agentFn(p.prompt, { schema: opts.schema })),
|
|
132
149
|
)
|
|
133
150
|
|
|
134
151
|
// Filter out failed agents (null) and build vote objects
|
|
@@ -160,8 +177,7 @@ export async function verify(finding: unknown, opts: VerifyOpts): Promise<Verify
|
|
|
160
177
|
// ── judge() ──
|
|
161
178
|
|
|
162
179
|
export async function judge(attempts: unknown[], opts: JudgeOpts): Promise<JudgeResult> {
|
|
163
|
-
|
|
164
|
-
const agentFn: AgentFn = opts._mockAgent ?? (workflowAgent as unknown as AgentFn)
|
|
180
|
+
const agentFn = resolveAgent(opts)
|
|
165
181
|
const judgeCount = opts.judges ?? 3
|
|
166
182
|
const schemaDesc = JSON.stringify(opts.schema)
|
|
167
183
|
|
|
@@ -198,7 +214,7 @@ export async function judge(attempts: unknown[], opts: JudgeOpts): Promise<Judge
|
|
|
198
214
|
`You are judge #${sp.judgeIndex + 1}. Score this attempt against the criteria: ${opts.criteria.join(', ')}.\n\n` +
|
|
199
215
|
`Attempt:\n${JSON.stringify(sp.attempt, null, 2)}\n\n` +
|
|
200
216
|
`Return JSON matching this schema:\n${schemaDesc}`,
|
|
201
|
-
{ schema: opts.schema
|
|
217
|
+
{ schema: opts.schema },
|
|
202
218
|
),
|
|
203
219
|
),
|
|
204
220
|
)
|
package/src/workflow/runtime.ts
CHANGED
|
@@ -223,8 +223,16 @@ export async function runWorkflow(
|
|
|
223
223
|
sandboxCtx.agent = sealValue(agent)
|
|
224
224
|
sandboxCtx.parallel = sealValue(parallel)
|
|
225
225
|
sandboxCtx.pipeline = sealValue(pipeline)
|
|
226
|
-
|
|
227
|
-
|
|
226
|
+
// verify()/judge() fan out their own agent calls, so they need the run's agent
|
|
227
|
+
// too. Handing them the bare primitive would put those calls outside the
|
|
228
|
+
// journal and the resume cache: a resumed run would replay every agent() it
|
|
229
|
+
// can see and then silently re-run all of verify's skeptics and judge's scores.
|
|
230
|
+
sandboxCtx.verify = sealValue((finding: unknown, opts: Record<string, unknown> = {}) =>
|
|
231
|
+
verify(finding, { ...opts, agent } as Parameters<typeof verify>[1]),
|
|
232
|
+
)
|
|
233
|
+
sandboxCtx.judge = sealValue((attempts: unknown[], opts: Record<string, unknown> = {}) =>
|
|
234
|
+
judge(attempts, { ...opts, agent } as Parameters<typeof judge>[1]),
|
|
235
|
+
)
|
|
228
236
|
sandboxCtx.loopUntilConvergence = sealValue(loopUntilConvergence)
|
|
229
237
|
sandboxCtx.phase = sealValue(wrappedPhase)
|
|
230
238
|
sandboxCtx.log = sealValue(log)
|