@thincoder/core 0.11.5 → 0.12.1
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/CHANGELOG.md +27 -0
- package/abort-provenance.mjs +23 -0
- package/advisor/citations.mjs +5 -1
- package/advisor/compaction.mjs +13 -10
- package/advisor/history.mjs +6 -1
- package/advisor/loop.mjs +35 -10
- package/advisor/messages.mjs +31 -43
- package/advisor/project-context.mjs +49 -45
- package/advisor/run.mjs +82 -26
- package/advisor.mjs +40 -11
- package/agent/assemble.mjs +5 -5
- package/agent/chat-call.mjs +21 -1
- package/agent/completion.mjs +1 -20
- package/agent/dispatch-gates.mjs +8 -3
- package/agent/dispatch-run.mjs +131 -20
- package/agent/dispatch.mjs +23 -22
- package/agent/family-tools.mjs +4 -7
- package/agent/goal-judge.mjs +99 -0
- package/agent/goal-state.mjs +96 -0
- package/agent/helpers.mjs +13 -4
- package/agent/offload.mjs +1 -1
- package/agent/planning-graph-guardrail.mjs +224 -0
- package/agent/planning-prompt.mjs +179 -0
- package/agent/planning-step.mjs +460 -173
- package/agent/post-turn.mjs +23 -33
- package/agent/record-results.mjs +8 -5
- package/agent/run-stages.mjs +18 -38
- package/agent/run-start.mjs +26 -19
- package/agent/setup-reminders.mjs +16 -14
- package/agent/setup.mjs +3 -2
- package/agent/spawn-child.mjs +17 -4
- package/agent/suspension.mjs +42 -21
- package/agent/task-lifecycle.mjs +165 -52
- package/agent/timers.mjs +9 -1
- package/agent/turn-loop.mjs +160 -69
- package/agent/turn-projection.mjs +26 -15
- package/agent/turn-task-state.mjs +4 -4
- package/agent/write-gate-ledger.mjs +1 -1
- package/agent/write-gate.mjs +14 -11
- package/agent-tools/advisor-async.mjs +2 -0
- package/agent-tools/advisor-launch.mjs +27 -13
- package/agent-tools/advisor-settle.mjs +19 -18
- package/agent-tools/advisor.mjs +90 -13
- package/agent-tools/bash-async.mjs +3 -3
- package/agent-tools/batch-ledger-bind.mjs +8 -5
- package/agent-tools/batch-read.mjs +42 -0
- package/agent-tools/batch-record-write.mjs +20 -12
- package/agent-tools/batch-segment-vocab.mjs +6 -4
- package/agent-tools/batch-skeleton.mjs +43 -12
- package/agent-tools/consult.mjs +5 -1
- package/agent-tools/context.mjs +5 -4
- package/agent-tools/design-slots.mjs +7 -4
- package/agent-tools/design-token.mjs +3 -2
- package/agent-tools/doc-graph.mjs +257 -95
- package/agent-tools/escalate-async.mjs +4 -1
- package/agent-tools/goal.mjs +28 -95
- package/agent-tools/plan.mjs +1 -1
- package/agent-tools/review-facts.mjs +56 -7
- package/agent-tools/settings.mjs +35 -1
- package/agent-tools/ssh-transport.mjs +23 -22
- package/agent-tools/step.mjs +24 -4
- package/agent-tools/subagent-actions.mjs +6 -2
- package/agent-tools/subagent-async.mjs +4 -2
- package/agent-tools/subagent.mjs +1 -1
- package/agent-tools/task.mjs +73 -65
- package/agent-tools.mjs +3 -3
- package/agent.mjs +12 -3
- package/auto-think.mjs +16 -3
- package/browser/actions.mjs +5 -1
- package/browser/cdp.mjs +1 -1
- package/browser/pool.mjs +110 -17
- package/compaction-work-state.mjs +103 -13
- package/compress-form.mjs +29 -3
- package/config-defaults.mjs +27 -3
- package/config-io.mjs +3 -14
- package/config-normalize.mjs +24 -4
- package/config-presets.mjs +40 -26
- package/config-warn.mjs +30 -0
- package/config.mjs +139 -63
- package/context-degrade.mjs +4 -4
- package/context-push.mjs +20 -9
- package/context.mjs +65 -20
- package/doc-graph/anchors.mjs +39 -40
- package/doc-graph/clusters.mjs +49 -0
- package/doc-graph/code-parsers.mjs +494 -0
- package/doc-graph/context-pack.mjs +392 -0
- package/doc-graph/dir-signals.mjs +228 -0
- package/doc-graph/edges.mjs +231 -0
- package/doc-graph/format.mjs +70 -0
- package/doc-graph/gc-cmd.mjs +104 -0
- package/doc-graph/gc.mjs +112 -0
- package/doc-graph/glob-work-graph.mjs +307 -0
- package/doc-graph/golden-set.mjs +131 -0
- package/doc-graph/ls-work-graph.mjs +534 -0
- package/doc-graph/outline.mjs +377 -0
- package/doc-graph/output-annotations.mjs +85 -0
- package/doc-graph/process-docs.mjs +68 -0
- package/doc-graph/read-work-graph.mjs +91 -0
- package/doc-graph/rebuild-cmd.mjs +75 -0
- package/doc-graph/resolvers.mjs +322 -0
- package/doc-graph/roots.mjs +86 -0
- package/doc-graph/schema.mjs +110 -0
- package/doc-graph/search-augment.mjs +418 -0
- package/doc-graph/store.mjs +231 -0
- package/doc-graph/target-resolve.mjs +352 -0
- package/doc-graph/walk.mjs +87 -0
- package/doc-graph.mjs +583 -707
- package/explore-distill.mjs +52 -17
- package/generate-title.mjs +7 -4
- package/ledger-close.mjs +6 -6
- package/ledger-cmd.mjs +3 -3
- package/ledger-consistency.mjs +8 -6
- package/ledger-db.mjs +45 -10
- package/ledger-migrate.mjs +25 -10
- package/ledger-read.mjs +1 -1
- package/ledger-write-ops.mjs +6 -6
- package/ledger.mjs +2 -2
- package/model-context.mjs +54 -18
- package/model-specs.mjs +86 -67
- package/package.json +1 -1
- package/prompt-overlays.mjs +3 -3
- package/prompts/advisor-round1.md +6 -5
- package/prompts/common.md +16 -6
- package/prompts/consult-base.md +2 -1
- package/prompts/discipline-engineering.md +1 -1
- package/prompts/discipline-normal.md +12 -8
- package/prompts/knowledge/doc-lookup.md +2 -2
- package/prompts/knowledge/normal-batch-discipline.md +2 -2
- package/prompts/knowledge/normal-delivery-collaboration.md +3 -3
- package/prompts/knowledge/tool-advisor.md +2 -2
- package/prompts/knowledge/tool-apply-patch.md +1 -1
- package/prompts/knowledge/tool-bash.md +2 -2
- package/prompts/knowledge/tool-batch.md +4 -4
- package/prompts/knowledge/tool-glob.md +9 -2
- package/prompts/knowledge/tool-goal.md +9 -6
- package/prompts/knowledge/tool-grep.md +7 -2
- package/prompts/knowledge/tool-ls.md +11 -5
- package/prompts/knowledge/tool-lsp.md +1 -1
- package/prompts/knowledge/tool-operations.md +3 -2
- package/prompts/knowledge/tool-plan.md +1 -1
- package/prompts/knowledge/tool-read.md +7 -6
- package/prompts/knowledge/tool-repo-graph-read.md +12 -0
- package/prompts/knowledge/tool-repo-graph.md +12 -0
- package/prompts/knowledge/tool-step.md +1 -1
- package/prompts/knowledge/tool-subagent.md +2 -2
- package/prompts/knowledge/tool-task.md +10 -9
- package/prompts/knowledge/tool-tree.md +7 -1
- package/prompts/persona-eng-coder.md +1 -1
- package/prompts/persona-eng-designer.md +1 -1
- package/prompts/persona-engineering.md +2 -1
- package/prompts/persona-explore.md +1 -1
- package/prompts/persona-normal.md +7 -6
- package/prompts/persona-plan.md +2 -2
- package/prompts/planning-next-moves.md +7 -8
- package/provider/anthropic.mjs +53 -51
- package/provider/core.mjs +85 -34
- package/provider/errors.mjs +33 -10
- package/provider/google.mjs +244 -37
- package/provider/list-models.mjs +28 -14
- package/provider/responses-request.mjs +15 -9
- package/provider/responses.mjs +10 -8
- package/provider/sse.mjs +3 -6
- package/proxy-transport.mjs +228 -119
- package/rules-file.mjs +79 -0
- package/rules.mjs +13 -51
- package/session-lifecycle.mjs +32 -20
- package/team-ledger.mjs +7 -7
- package/think-off.mjs +37 -18
- package/token-window.mjs +48 -31
- package/tool-args.mjs +8 -8
- package/tool-docs/bash.md +1 -1
- package/tool-docs/glob.md +3 -1
- package/tool-docs/goal.md +2 -2
- package/tool-docs/grep.md +3 -1
- package/tool-docs/ls.md +7 -1
- package/tool-docs/read.md +1 -1
- package/tool-docs/repo_graph-read.md +3 -0
- package/tool-docs/repo_graph.md +3 -0
- package/tool-docs/tree.md +1 -1
- package/tools/bash.mjs +53 -8
- package/tools/browser.mjs +4 -4
- package/tools/file.mjs +34 -7
- package/tools/glob-dialect.mjs +57 -7
- package/tools/index.mjs +3 -7
- package/tools/patch.mjs +8 -7
- package/tools/process-doc-mark.mjs +13 -0
- package/tools/search.mjs +152 -37
- package/tools/shared.mjs +6 -0
- package/tools/tree.mjs +211 -8
- package/window-policy.mjs +205 -126
- package/prompts/knowledge/tool-doc-graph-read.md +0 -20
- package/prompts/knowledge/tool-doc-graph.md +0 -49
- package/prompts/knowledge/tool-peek.md +0 -10
- package/prompts/knowledge/tool-repo-outline.md +0 -4
- package/tool-docs/doc_graph-read.md +0 -3
- package/tool-docs/doc_graph.md +0 -3
- package/tool-docs/peek.md +0 -3
- package/tool-docs/repo_outline.md +0 -3
- package/tools/peek.mjs +0 -447
package/agent/dispatch-run.mjs
CHANGED
|
@@ -7,11 +7,98 @@
|
|
|
7
7
|
* ——零环。
|
|
8
8
|
*/
|
|
9
9
|
import { logEvent, errText, headText } from "../log.mjs"
|
|
10
|
-
import { offloadToolResult, FILE_MUTATORS } from "./helpers.mjs"
|
|
10
|
+
import { offloadToolResult, FILE_MUTATORS, toolTouchPaths } from "./helpers.mjs"
|
|
11
11
|
import { runHooks } from "../hooks.mjs"
|
|
12
12
|
import { snapshotForUndo } from "../undo-stack.mjs"
|
|
13
13
|
import { PEER_WRITE_TOOLS, peerCollabNote, recordPeerWrites, markClaimNoted } from "../peer-domains.mjs"
|
|
14
14
|
import { logToolError, noteExecutedMutation } from "./dispatch-gates.mjs"
|
|
15
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
16
|
+
import { isAbsolute, relative, resolve } from "node:path"
|
|
17
|
+
|
|
18
|
+
// 并发安全 console 捕获(AsyncLocalStorage + 引用计数 hook):并发工具各自持有独立 sink,
|
|
19
|
+
// 乱序完成绝不互踩或永久劫持全局 console.log/console.error;非工具上下文调用原样转发。
|
|
20
|
+
const consoleCaptureStore = new AsyncLocalStorage()
|
|
21
|
+
let consoleHookDepth = 0
|
|
22
|
+
let realConsoleLog = null
|
|
23
|
+
let realConsoleError = null
|
|
24
|
+
|
|
25
|
+
function acquireConsoleHook() {
|
|
26
|
+
if (consoleHookDepth === 0) {
|
|
27
|
+
realConsoleLog = console.log
|
|
28
|
+
realConsoleError = console.error
|
|
29
|
+
console.log = (...a) => {
|
|
30
|
+
const sink = consoleCaptureStore.getStore()
|
|
31
|
+
if (sink) sink.log(...a)
|
|
32
|
+
else realConsoleLog(...a)
|
|
33
|
+
}
|
|
34
|
+
console.error = (...a) => {
|
|
35
|
+
const sink = consoleCaptureStore.getStore()
|
|
36
|
+
if (sink) sink.error(...a)
|
|
37
|
+
else realConsoleError(...a)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
consoleHookDepth += 1
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function releaseConsoleHook() {
|
|
44
|
+
consoleHookDepth -= 1
|
|
45
|
+
if (consoleHookDepth <= 0) {
|
|
46
|
+
consoleHookDepth = 0
|
|
47
|
+
if (realConsoleLog) console.log = realConsoleLog
|
|
48
|
+
if (realConsoleError) console.error = realConsoleError
|
|
49
|
+
realConsoleLog = null
|
|
50
|
+
realConsoleError = null
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const GRAPH_CODE_FILE_RE = /\.(?:m?js|cjs|jsx?|tsx?|py|go|rs|cs|java|kt|cpp|c|h|hpp|rb|php|swift|sh|ps1)$/i
|
|
55
|
+
const GRAPH_DOC_FILE_RE = /\.(?:md|markdown|txt)$/i
|
|
56
|
+
function normGraphRel(rawPath, cwd) {
|
|
57
|
+
const s = String(rawPath ?? "").trim()
|
|
58
|
+
if (!s) return ""
|
|
59
|
+
const rel = cwd && isAbsolute(s) ? relative(cwd, s) : s
|
|
60
|
+
return rel.replace(/\\/g, "/").replace(/^\.\//, "")
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function recordSessionGraphRead(agent, args) {
|
|
64
|
+
const rawPath = String(args?.path ?? args?.filePath ?? "").trim()
|
|
65
|
+
if (!rawPath || !agent) return
|
|
66
|
+
const norm = normGraphRel(rawPath, agent.cwd)
|
|
67
|
+
if (!norm) return
|
|
68
|
+
const set = agent._graphFullReadFiles instanceof Set
|
|
69
|
+
? agent._graphFullReadFiles
|
|
70
|
+
: (agent._graphFullReadFiles = new Set())
|
|
71
|
+
const isFullRead = args?.offset === undefined && args?.limit === undefined
|
|
72
|
+
if (GRAPH_DOC_FILE_RE.test(rawPath)) {
|
|
73
|
+
if (isFullRead) set.add(norm)
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
if (GRAPH_CODE_FILE_RE.test(rawPath) && isFullRead) set.add(norm)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function computeEditGraphNote(agent, tool, args) {
|
|
80
|
+
if (!agent?.cwd) return null
|
|
81
|
+
const rawPaths = toolTouchPaths(tool, args)
|
|
82
|
+
const codePaths = rawPaths
|
|
83
|
+
.filter((p) => typeof p === "string" && GRAPH_CODE_FILE_RE.test(p))
|
|
84
|
+
.map((p) => normGraphRel(p, agent.cwd))
|
|
85
|
+
.filter(Boolean)
|
|
86
|
+
if (codePaths.length === 0) return null
|
|
87
|
+
try {
|
|
88
|
+
const readSet = agent._graphFullReadFiles instanceof Set ? agent._graphFullReadFiles : new Set()
|
|
89
|
+
const noted = agent._graphNotedPaths instanceof Set
|
|
90
|
+
? agent._graphNotedPaths
|
|
91
|
+
: (agent._graphNotedPaths = new Set())
|
|
92
|
+
const { getEditGraphNote } = await import("../doc-graph.mjs")
|
|
93
|
+
const note = await getEditGraphNote(agent.cwd, codePaths, readSet, noted)
|
|
94
|
+
if (note && Array.isArray(note.notedKeys)) {
|
|
95
|
+
for (const k of note.notedKeys) noted.add(k)
|
|
96
|
+
}
|
|
97
|
+
return note?.text ?? null
|
|
98
|
+
} catch {
|
|
99
|
+
return null
|
|
100
|
+
}
|
|
101
|
+
}
|
|
15
102
|
|
|
16
103
|
/** console 回显预算(AGENT-LOOP.md §5.3 结果 · #863):采集端 cap = 与 helpers.mjs `TOOL_RESULT_OFFLOAD_LIMIT`
|
|
17
104
|
* 同值(65536 字符)——累计到限停收(超出丢弃);发生丢弃 ⇒ 回显段尾恰一行截断标记(逐字——两路径同款)。 */
|
|
@@ -75,20 +162,25 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
|
|
|
75
162
|
const routed = await callbacks.toolRouter(item.toolCall.name, item.args)
|
|
76
163
|
if (routed?.handled) {
|
|
77
164
|
const routedOk = !String(routed.result).startsWith("Error:")
|
|
78
|
-
|
|
165
|
+
if (routedOk && toolName === "read") recordSessionGraphRead(agent, item.args)
|
|
166
|
+
const routedGraphNote = routedOk && FILE_MUTATORS.has(toolName)
|
|
167
|
+
? await computeEditGraphNote(agent, item.tool, item.args)
|
|
168
|
+
: null
|
|
169
|
+
const routedNotes = [peerNote && routedOk ? peerNote.text : null, routedGraphNote].filter(Boolean)
|
|
170
|
+
const routedResult = routedNotes.length > 0 ? `${routed.result}\n${routedNotes.join("\n")}` : routed.result
|
|
79
171
|
if (peerNote && routedOk) markClaimNoted(agent, peerNote.keys) // 提示已附加 ⇒ 落去重标记
|
|
80
172
|
if (isPeerWriteTool && routedOk) recordPeerWrites(agent, item.tool, item.args)
|
|
81
173
|
// fix A:routed 写成功(客户端执行)同样执行期即刻记账(唯一记账点)
|
|
82
174
|
if (routedOk && FILE_MUTATORS.has(toolName)) noteExecutedMutation(agent, item.tool, item.args)
|
|
83
175
|
callbacks.onToolResult?.(item.toolCall.name, routedResult, item.toolCall.id)
|
|
84
176
|
logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(routedResult, 200), child: agent?._logId })
|
|
85
|
-
return { ...item, result: routedResult, ok:
|
|
177
|
+
return { ...item, result: routedResult, ok: routedOk }
|
|
86
178
|
}
|
|
87
179
|
}
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
180
|
+
const consoleSink = {
|
|
181
|
+
log: (...a) => capturedPush(a.map(String).join(" ")),
|
|
182
|
+
error: (...a) => capturedPush("[err] " + a.map(String).join(" ")),
|
|
183
|
+
}
|
|
92
184
|
let rawResult
|
|
93
185
|
// ctx 对象提升为变量(docs/cli/design/TUI.md §6.8):subagent 阻塞 execute 返回前在 ctx 上留
|
|
94
186
|
// _subagentKey(relayPrefix 去尾)——runOne 在 execute 返回后读它作 onToolResult
|
|
@@ -108,33 +200,51 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
|
|
|
108
200
|
onSecretInput: callbacks.onSecretInput,
|
|
109
201
|
onPermissionRequest: callbacks.onPermissionRequest,
|
|
110
202
|
}
|
|
203
|
+
acquireConsoleHook()
|
|
111
204
|
try {
|
|
112
205
|
// SUBAGENT-OBSERVE-SEND D1(评审 #1):in-flight 当前工具记账——工具执行期间在
|
|
113
206
|
// agent 上留 _inflightTools Set(子代理 observe 从 dispatch 状态读——卡在长工具
|
|
114
|
-
// 调用时 history
|
|
115
|
-
//
|
|
207
|
+
// 调用时 history 无新回合、恰需此信号);搭配 `_inflightToolCounts` 引用计数,
|
|
208
|
+
// 并发同名工具先完成者不误删仍在运行的同名项。
|
|
116
209
|
const inflight = agent._inflightTools ?? (agent._inflightTools = new Set())
|
|
210
|
+
const inflightCounts = agent._inflightToolCounts ?? (agent._inflightToolCounts = new Map())
|
|
211
|
+
inflightCounts.set(toolName, (inflightCounts.get(toolName) ?? 0) + 1)
|
|
117
212
|
inflight.add(toolName)
|
|
118
213
|
try {
|
|
119
|
-
rawResult = await item.tool.execute(item.args, toolCtx)
|
|
214
|
+
rawResult = await consoleCaptureStore.run(consoleSink, () => item.tool.execute(item.args, toolCtx))
|
|
120
215
|
} finally {
|
|
121
|
-
|
|
216
|
+
const nextCount = (inflightCounts.get(toolName) ?? 1) - 1
|
|
217
|
+
if (nextCount <= 0) {
|
|
218
|
+
inflightCounts.delete(toolName)
|
|
219
|
+
inflight.delete(toolName)
|
|
220
|
+
} else {
|
|
221
|
+
inflightCounts.set(toolName, nextCount)
|
|
222
|
+
}
|
|
122
223
|
}
|
|
123
224
|
} finally {
|
|
124
|
-
|
|
125
|
-
console.error = origConsoleErr
|
|
225
|
+
releaseConsoleHook()
|
|
126
226
|
}
|
|
127
227
|
if (rawResult === undefined) throw new Error(`Tool "${item.toolCall.name}" returned undefined — all tools must return a string value`)
|
|
128
228
|
const raw = String(rawResult)
|
|
229
|
+
// bash / execute 带合法 filter 时返回纯匹配行(日志首行可能恰好以 "Error:" 开头),不误判为工具执行失败。
|
|
230
|
+
const isFilteredLineOutput = (toolName === "bash" || toolName === "execute")
|
|
231
|
+
&& Boolean(item.args?.filter)
|
|
232
|
+
&& !raw.startsWith("Error: filter regex invalid:")
|
|
233
|
+
const execOk = !raw.startsWith("Error:") || isFilteredLineOutput
|
|
129
234
|
// 写成功(非 "Error:" 字符串结果)→ 足迹计入本回合集合(flush 在 finalizeAgentTurn)
|
|
130
|
-
if (isPeerWriteTool &&
|
|
235
|
+
if (isPeerWriteTool && execOk) {
|
|
131
236
|
recordPeerWrites(agent, item.tool, item.args)
|
|
132
237
|
}
|
|
238
|
+
if (toolName === "read" && execOk) {
|
|
239
|
+
recordSessionGraphRead(agent, item.args)
|
|
240
|
+
}
|
|
133
241
|
// fix A:FILE_MUTATORS 执行成功即刻记账(唯一记账点——取代 record-results 批后
|
|
134
242
|
// 段 + agent.mjs 中断分支——不双计)——同批 launch 前的写在 launchSeq 之前落地 →
|
|
135
243
|
// async advisor settle 不误判 stale(同批 launch 后写仍保守 stale——T-A2/T-24b9)。
|
|
136
|
-
|
|
244
|
+
let editGraphNote = null
|
|
245
|
+
if (FILE_MUTATORS.has(toolName) && execOk) {
|
|
137
246
|
noteExecutedMutation(agent, item.tool, item.args)
|
|
247
|
+
editGraphNote = await computeEditGraphNote(agent, item.tool, item.args)
|
|
138
248
|
}
|
|
139
249
|
// 2026-08-31 工具输出回显 ∥ #863:console 段 ∥ 结果本体拼接先于 offload——并入 64K 判定
|
|
140
250
|
// (超限 ⇒ 落盘 + 预览);采集端发生过丢弃 ⇒ 段尾恰一行截断标记(逐字——错误路径同款)。
|
|
@@ -146,17 +256,18 @@ export async function runPreparedItem(item, agent, depth, signal, callbacks) {
|
|
|
146
256
|
// channel); everything else offloads oversized text to disk. Flag-driven, not
|
|
147
257
|
// name-driven (consult P3, 2026-08-30).
|
|
148
258
|
const result = item.tool?.multimodal ? spliced : await offloadToolResult(spliced, item.toolCall.id)
|
|
149
|
-
// R10 L3:冲突 /
|
|
150
|
-
const notedOk = Boolean(peerNote) &&
|
|
259
|
+
// R10 L3 + Context Graph v2:冲突 / 认领与图谱未读关键上下文软提示附在工具结果末尾(模型可见、不阻断、每路径会话内去重)
|
|
260
|
+
const notedOk = Boolean(peerNote) && execOk
|
|
151
261
|
if (notedOk) markClaimNoted(agent, peerNote.keys)
|
|
152
|
-
const
|
|
153
|
-
|
|
262
|
+
const softNotes = [notedOk ? peerNote.text : null, editGraphNote].filter(Boolean)
|
|
263
|
+
const resultForModel = softNotes.length > 0
|
|
264
|
+
? `${result}\n${softNotes.join("\n")}`
|
|
154
265
|
: result
|
|
155
266
|
callbacks.onToolResult?.(item.toolCall.name, resultForModel, item.toolCall.id, toolCtx._subagentKey)
|
|
156
267
|
// PostToolUse hooks: fire-and-forget (result not awaited on hook failure)
|
|
157
268
|
runHooks("PostToolUse", { agent, toolName: item.toolCall.name, toolArgs: item.args, result: raw }).catch(() => {})
|
|
158
269
|
logEvent("tool:done", { tool: toolName, ms: Date.now() - toolT0, head: headText(resultForModel, 200), child: agent?._logId })
|
|
159
|
-
return { ...item, result: resultForModel, ok:
|
|
270
|
+
return { ...item, result: resultForModel, ok: execOk }
|
|
160
271
|
} catch (error) {
|
|
161
272
|
// Persist to ~/.thincoder/tool-errors/ for post-mortem; only pass message to the model (stack traces confuse LLMs and may leak paths)
|
|
162
273
|
logToolError(item.toolCall.name, item.args, error)
|
package/agent/dispatch.mjs
CHANGED
|
@@ -41,27 +41,28 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
41
41
|
// that REACH the permission stage are collected into one batch — a single merged
|
|
42
42
|
// ask covers the whole toolCalls array (D-B1, "approve all / one by one /
|
|
43
43
|
// deny"). Tools stopped by a pre-gate never join the batch (review #7).
|
|
44
|
-
const prepared =
|
|
45
|
-
const permPending = [] // { toolCall, tool, args } — reached the permission stage
|
|
46
|
-
for (
|
|
44
|
+
const prepared = new Array(toolCalls.length)
|
|
45
|
+
const permPending = [] // { index, toolCall, tool, args } — reached the permission stage
|
|
46
|
+
for (let i = 0; i < toolCalls.length; i++) {
|
|
47
|
+
const toolCall = toolCalls[i]
|
|
47
48
|
const tool = toolByName.get(toolCall.name)
|
|
48
49
|
let args
|
|
49
50
|
try {
|
|
50
51
|
args = JSON.parse(toolCall.arguments || "{}")
|
|
51
52
|
} catch {
|
|
52
53
|
logToolError(toolCall.name, { arguments: toolCall.arguments }, new Error("Invalid JSON arguments"))
|
|
53
|
-
prepared
|
|
54
|
+
prepared[i] = { toolCall, tool: null, error: `Invalid tool arguments JSON: ${toolCall.arguments}` }
|
|
54
55
|
continue
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
if (!tool) {
|
|
58
59
|
logToolError(toolCall.name, {}, new Error(`Unknown tool: ${toolCall.name}`))
|
|
59
|
-
prepared
|
|
60
|
+
prepared[i] = { toolCall, tool: null, error: `Unknown tool: ${toolCall.name}` }
|
|
60
61
|
continue
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
if (agent.planMode && !tool.readonly && !readonlyActionOf(tool, toolCall.name, args) && !controlActionOf(tool, toolCall.name, args)) {
|
|
64
|
-
prepared
|
|
65
|
+
prepared[i] = { toolCall, tool, denied: true, reason: "plan mode" }
|
|
65
66
|
continue
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -70,11 +71,11 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
70
71
|
// must run (and be accepted) before the first write/edit/apply_patch/hashline_edit/insert_after/delete.
|
|
71
72
|
if (agent._role === "eng-coder" && agent.config?.agent?.engineering
|
|
72
73
|
&& !agent._engDesignReviewed && FILE_MUTATORS.has(toolCall.name)) {
|
|
73
|
-
prepared
|
|
74
|
+
prepared[i] = {
|
|
74
75
|
toolCall, tool, denied: true,
|
|
75
76
|
reason: "engineering design gate",
|
|
76
77
|
hint: "Call advisor with type='design' to review the design document before any file modification. If the review found issues, report them to the parent agent.",
|
|
77
|
-
}
|
|
78
|
+
}
|
|
78
79
|
continue
|
|
79
80
|
}
|
|
80
81
|
|
|
@@ -120,11 +121,11 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
120
121
|
const convNote = noteConv
|
|
121
122
|
? ` — this path fell through to product code (no code segment is declared: code paths are empty); declare project conventions in ${manifestFilePath(noteConv.root)} to adjust.`
|
|
122
123
|
: ""
|
|
123
|
-
prepared
|
|
124
|
+
prepared[i] = {
|
|
124
125
|
toolCall, tool, denied: true,
|
|
125
126
|
reason: "engineering design gate",
|
|
126
127
|
hint: `Engineering mode: write the design document first(location per your project's document conventions), then call advisor with type='design' to review it, and wait for user approval. Implementation is done by eng-coder subagents.${convNote}`,
|
|
127
|
-
}
|
|
128
|
+
}
|
|
128
129
|
continue
|
|
129
130
|
}
|
|
130
131
|
}
|
|
@@ -147,17 +148,17 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
147
148
|
if (FILE_MUTATORS.has(toolCall.name)) {
|
|
148
149
|
const crossBatch = batchRecordWriteConflict(agent, depth, absPaths)
|
|
149
150
|
if (crossBatch) {
|
|
150
|
-
prepared
|
|
151
|
+
prepared[i] = { toolCall, tool, denied: true, reason: "cross-batch record write", hint: crossBatch.message }
|
|
151
152
|
continue
|
|
152
153
|
}
|
|
153
154
|
}
|
|
154
155
|
const conflict = freezeWindowConflict(agent, absPaths)
|
|
155
156
|
if (conflict) {
|
|
156
|
-
prepared
|
|
157
|
+
prepared[i] = {
|
|
157
158
|
toolCall, tool, denied: true,
|
|
158
159
|
reason: "d5 freeze window",
|
|
159
160
|
hint: `write refused — design review #${conflict.id} is in flight over ${relative(agent.cwd, conflict.path)} (D5 freeze window). A write now would settle it stale — no token for a pass (the round is lost). Wait for the report, or cancel the review first (subagent action:'cancel' id:'${conflict.id}') and re-launch after the change.`,
|
|
160
|
-
}
|
|
161
|
+
}
|
|
161
162
|
continue
|
|
162
163
|
}
|
|
163
164
|
}
|
|
@@ -173,7 +174,7 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
173
174
|
// 路径集与 `args.ledger` 由判据函数自己取(调形只传 tool + toolName + args)。
|
|
174
175
|
const ledgerConflict = await ledgerBindWriteConflict(agent, depth, tool, toolCall.name, args)
|
|
175
176
|
if (ledgerConflict) {
|
|
176
|
-
prepared
|
|
177
|
+
prepared[i] = { toolCall, tool, denied: true, reason: "ledger binding", hint: ledgerConflict.message }
|
|
177
178
|
continue
|
|
178
179
|
}
|
|
179
180
|
|
|
@@ -189,15 +190,15 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
189
190
|
// parent ask (human in the loop).
|
|
190
191
|
if (tool.readonly || readonlyActionOf(tool, toolCall.name, args) || controlActionOf(tool, toolCall.name, args) || isSubagentConsumeDesignAction(toolCall.name, args) || agent.autoApprove || agent._engTaskAuthorized) {
|
|
191
192
|
if (!(await runHooks("PreToolUse", { agent, toolName: toolCall.name, toolArgs: args }))) {
|
|
192
|
-
prepared
|
|
193
|
+
prepared[i] = { toolCall, tool, denied: true, reason: "blocked by PreToolUse hook" }
|
|
193
194
|
continue
|
|
194
195
|
}
|
|
195
196
|
// Panel area abolished — all tools now stream inline via onToolOutput.
|
|
196
197
|
callbacks.onToolCall?.(toolCall.name, args, toolCall.id)
|
|
197
|
-
prepared
|
|
198
|
+
prepared[i] = { toolCall, tool, args }
|
|
198
199
|
continue
|
|
199
200
|
}
|
|
200
|
-
permPending.push({ toolCall, tool, args })
|
|
201
|
+
permPending.push({ index: i, toolCall, tool, args })
|
|
201
202
|
}
|
|
202
203
|
|
|
203
204
|
// ---- Permission stage: one merged ask for the whole batch (D-B1) ----
|
|
@@ -236,22 +237,22 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
236
237
|
})()
|
|
237
238
|
} else allowed = false
|
|
238
239
|
if (!allowed) {
|
|
239
|
-
prepared.
|
|
240
|
+
prepared[p.index] = {
|
|
240
241
|
toolCall: p.toolCall, tool: p.tool, denied: true,
|
|
241
242
|
reason: (callbacks.onPermissionRequest || batchAllowed === false) ? "denied by user" : "no permission handler",
|
|
242
|
-
}
|
|
243
|
+
}
|
|
243
244
|
continue
|
|
244
245
|
}
|
|
245
246
|
|
|
246
247
|
// PreToolUse hooks: allow user scripts to gate tool execution
|
|
247
248
|
if (!(await runHooks("PreToolUse", { agent, toolName: p.toolCall.name, toolArgs: p.args }))) {
|
|
248
|
-
prepared.
|
|
249
|
+
prepared[p.index] = { toolCall: p.toolCall, tool: p.tool, denied: true, reason: "blocked by PreToolUse hook" }
|
|
249
250
|
continue
|
|
250
251
|
}
|
|
251
252
|
|
|
252
253
|
// Panel area abolished — all tools now stream inline via onToolOutput.
|
|
253
254
|
callbacks.onToolCall?.(p.toolCall.name, p.args, p.toolCall.id)
|
|
254
|
-
prepared.
|
|
255
|
+
prepared[p.index] = { toolCall: p.toolCall, tool: p.tool, args: p.args }
|
|
255
256
|
}
|
|
256
257
|
}
|
|
257
258
|
|
|
@@ -276,7 +277,7 @@ export async function executeToolCalls(agent, toolByName, toolCalls, callbacks,
|
|
|
276
277
|
// escalate action keeps the retired escalate tool's serial placement (no
|
|
277
278
|
// parallel flag): it flushes the batch and runs alone in call order (AGENT-LOOP-SUBAGENT.md §6.7 —
|
|
278
279
|
// spawn stays parallel; status classifies as readonly and batch freely).
|
|
279
|
-
if (item.tool && !item.tool.readonly
|
|
280
|
+
if (!item.error && !item.denied && item.tool && !item.tool.readonly
|
|
280
281
|
&& (!(item.tool.parallel || item.tool.isParallelAction?.(item.args)) || isSubagentEscalateAction(item.tool.name, item.args))) {
|
|
281
282
|
await flush()
|
|
282
283
|
results.push(await runPreparedItem(item, agent, depth, signal, callbacks))
|
package/agent/family-tools.mjs
CHANGED
|
@@ -151,10 +151,9 @@ export async function assembleFamilyTools({
|
|
|
151
151
|
? [decorate?.consultStart ?? withPool(consultStartTool), decorate?.consultStop ?? consultStopTool]
|
|
152
152
|
: []
|
|
153
153
|
|
|
154
|
-
//
|
|
155
|
-
// **一处写、五处展开**——`doc_check`
|
|
156
|
-
//
|
|
157
|
-
// 单子(D-DT4);并成一段又会抹掉各段真实差异。depth-0 段不展开本组:那边挂的是全量 `docGraphTool` + `docCheckTool`。
|
|
154
|
+
// 文档与项目图谱工具面(`AGENT-LOOP-SUBAGENT.md` · 需求 `docs/core/requirements/REPO-GRAPH.md`):
|
|
155
|
+
// **一处写、五处展开**——`doc_check` 与 `repo_graph`(六动作全只读)同挂全部 depth>0 角色段;
|
|
156
|
+
// depth-0 段由下方直挂。
|
|
158
157
|
const docTools = [docCheckTool, docGraphReadTool]
|
|
159
158
|
// 同步阻塞子代理(sync=true)期间父代理被 await 阻塞无法响应 send,不挂载 notify_parent
|
|
160
159
|
// (避免子代理白耗一轮发 ask 并污染 _childUpstream 触发幽灵唤醒);待裁项随最终报告同步返回。
|
|
@@ -173,9 +172,7 @@ export async function assembleFamilyTools({
|
|
|
173
172
|
// 文档纪律机检(`DOC-DISCIPLINE.md` §3.20 条目 S):只读报告态——depth-0 主 agent 段挂本体;
|
|
174
173
|
// 全部 depth>0 角色段由下方 `docTools` 展开供给(`AGENT-LOOP-SUBAGENT.md` §6.60)。
|
|
175
174
|
docCheckTool,
|
|
176
|
-
//
|
|
177
|
-
// 全部 depth>0 角色段挂只读变体(三动作、无 `scan`,契约 = `DOC-GRAPH.md` §2.5.5,装配矩阵单源 =
|
|
178
|
-
// `AGENT-LOOP-SUBAGENT.md` §6.60.2)。位置与 `docCheckTool` 同段(同一族:文档纪律面)。
|
|
175
|
+
// 项目知识图谱 `repo_graph`(`docs/core/design/REPO-GRAPH.md`):全只读五动作,depth-0 与全部子代理同享。
|
|
179
176
|
docGraphTool,
|
|
180
177
|
// 端差(decorate.settings——VSC depth-0 主 agent 面;缺省不追加):核默认形态里
|
|
181
178
|
// settings 住**基础集**(`tools/index.mjs` `assembleBuiltinTools`),端侧自持清单
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent/goal-judge.mjs — goal mode 独立裁判
|
|
3
|
+
* 设计 = `docs/core/design/GOAL.md` §2;需求 = `docs/core/requirements/GOAL.md` §4。
|
|
4
|
+
* 裁判独立于被评模型:单独配置的模型,只看对话记录,不调工具。
|
|
5
|
+
*/
|
|
6
|
+
import { flattenHistory } from "../context.mjs"
|
|
7
|
+
|
|
8
|
+
export const GOAL_JUDGE_TIMEOUT_MS = 30_000
|
|
9
|
+
export const GOAL_JUDGE_VERDICTS = Object.freeze(["not_yet", "met", "impossible"])
|
|
10
|
+
|
|
11
|
+
/** 裁判模型名:goalJudgeModel → subagentModel → null(= 会话模型)。 */
|
|
12
|
+
export function resolveJudgeModelName(agent) {
|
|
13
|
+
const cfg = agent.config?.agent ?? {}
|
|
14
|
+
return cfg.goalJudgeModel ?? cfg.subagentModel ?? null
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** 裁判 provider:与子代理同一套模型解析(`"provider:model"` / 裸模型名 / `default` 别名)。
|
|
18
|
+
* 单源 = `agent-tools/subagent-async.mjs` 的 `resolveChildProvider`——动态 import 避开 `agent → agent-tools` 静态环。 */
|
|
19
|
+
export async function resolveJudgeProvider(agent) {
|
|
20
|
+
const { resolveChildProvider } = await import("../agent-tools/subagent-async.mjs")
|
|
21
|
+
return resolveChildProvider(agent, resolveJudgeModelName(agent))
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 最近对话记录(用户真实指示 + assistant 文本 + 工具调用名与结果摘要,截断到窗口内)。 */
|
|
25
|
+
function transcriptOf(agent, { maxChars = 12_000 } = {}) {
|
|
26
|
+
const flat = flattenHistory(agent.history)
|
|
27
|
+
const lines = []
|
|
28
|
+
for (const m of flat) {
|
|
29
|
+
if (m.role === "user") {
|
|
30
|
+
const raw = typeof m.content === "string"
|
|
31
|
+
? m.content
|
|
32
|
+
: Array.isArray(m.content)
|
|
33
|
+
? m.content.map((p) => (typeof p?.text === "string" ? p.text : "")).filter(Boolean).join("\n")
|
|
34
|
+
: ""
|
|
35
|
+
const text = raw.trim()
|
|
36
|
+
if (text && !/^\[System reminder:/i.test(text)) lines.push(`user: ${text.slice(0, 1000)}`)
|
|
37
|
+
} else if (m.role === "assistant") {
|
|
38
|
+
const text = typeof m.content === "string" ? m.content : ""
|
|
39
|
+
if (text) lines.push(`assistant: ${text.slice(0, 1500)}`)
|
|
40
|
+
for (const tc of m.tool_calls ?? []) {
|
|
41
|
+
const name = tc.function?.name ?? tc.name ?? "?"
|
|
42
|
+
const args = String(tc.function?.arguments ?? tc.arguments ?? "").slice(0, 200)
|
|
43
|
+
lines.push(`tool-call: ${name} ${args}`)
|
|
44
|
+
}
|
|
45
|
+
} else if (m.role === "tool") {
|
|
46
|
+
const text = typeof m.content === "string" ? m.content : ""
|
|
47
|
+
lines.push(`tool-result: ${text.slice(0, 400)}`)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const joined = lines.join("\n")
|
|
51
|
+
return joined.length > maxChars ? joined.slice(-maxChars) : joined
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 判一次:`{ verdict, reason }`;失败抛错(调用方计数,不放行)。 */
|
|
55
|
+
export async function judgeGoal(agent, { signal } = {}) {
|
|
56
|
+
const goal = agent.goal
|
|
57
|
+
if (!goal) throw new Error("goal-judge: no goal")
|
|
58
|
+
const { chat } = await import("../provider/index.mjs")
|
|
59
|
+
const provider = await resolveJudgeProvider(agent)
|
|
60
|
+
const timeout = AbortSignal.timeout(GOAL_JUDGE_TIMEOUT_MS)
|
|
61
|
+
const sig = signal ? AbortSignal.any([signal, timeout]) : timeout
|
|
62
|
+
const res = await chat(provider, {
|
|
63
|
+
// 模型语义参数(2026-12-03 批,台账 #133):判官调用的会话设置(不再是 provider 条目属性)。
|
|
64
|
+
modelParams: agent.modelParams,
|
|
65
|
+
// 会话设置(模型窗口声明 ∥ 档位上限)——判官调用的窗口封顶与会话同源(2026-12-03 批)。
|
|
66
|
+
settings: agent.config,
|
|
67
|
+
messages: [{
|
|
68
|
+
role: "user",
|
|
69
|
+
content: `You are an independent goal judge. Decide whether this goal's condition holds, based only on the transcript below.
|
|
70
|
+
|
|
71
|
+
Goal condition (what counts as done):
|
|
72
|
+
${goal.condition}
|
|
73
|
+
|
|
74
|
+
Transcript (most recent last):
|
|
75
|
+
${transcriptOf(agent) || "(no activity recorded)"}
|
|
76
|
+
|
|
77
|
+
Answer with exactly one verdict line, then one sentence of reason:
|
|
78
|
+
VERDICT: not_yet | met | impossible
|
|
79
|
+
|
|
80
|
+
- met: the condition's check has actually run and passed, and the transcript shows it.
|
|
81
|
+
- impossible: the goal cannot be reached (missing permission, contradictory requirement, external blocker).
|
|
82
|
+
- not_yet: anything else, including "looks close" or "planned but not run".`,
|
|
83
|
+
}],
|
|
84
|
+
tools: [],
|
|
85
|
+
signal: sig,
|
|
86
|
+
logCtx: {
|
|
87
|
+
stage: "goal", kind: "goal-judge",
|
|
88
|
+
role: agent._role ?? null, depth: 0,
|
|
89
|
+
session: agent._sessionStart ?? null, cwd: agent.cwd,
|
|
90
|
+
traces: agent.config?.traces?.enabled !== false,
|
|
91
|
+
},
|
|
92
|
+
})
|
|
93
|
+
const text = String(res.content ?? "").trim()
|
|
94
|
+
const m = /VERDICT:\s*(not_yet|met|impossible)/i.exec(text)
|
|
95
|
+
if (!m) throw new Error(`goal-judge: unparseable verdict "${text.slice(0, 200)}"`)
|
|
96
|
+
const verdict = m[1].toLowerCase()
|
|
97
|
+
const reason = text.slice(m.index + m[0].length).replace(/^[\s:—-]+/, "").trim() || null
|
|
98
|
+
return { verdict, reason }
|
|
99
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent/goal-state.mjs — goal mode 状态机单源
|
|
3
|
+
* 设计 = `docs/core/design/GOAL.md` §1;需求 = `docs/core/requirements/GOAL.md` §3。
|
|
4
|
+
* `/goal` 命令与 `goal` 工具都调本档,不各写一份规则。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export const GOAL_CONDITION_MAX = 4000
|
|
8
|
+
export const GOAL_STATUSES = Object.freeze(["active", "paused", "complete", "blocked"])
|
|
9
|
+
|
|
10
|
+
/** 设目标(覆盖已有目标:先清再建,不保留旧字段)。条件即判据。 */
|
|
11
|
+
export function setGoal(agent, { condition, source = "user" } = {}) {
|
|
12
|
+
const text = String(condition ?? "").trim()
|
|
13
|
+
if (!text) throw new Error("goal: condition is required — write what counts as done")
|
|
14
|
+
if (text.length > GOAL_CONDITION_MAX) {
|
|
15
|
+
throw new Error(`goal: condition is ${text.length} chars, over the ${GOAL_CONDITION_MAX} limit`)
|
|
16
|
+
}
|
|
17
|
+
agent.goal = {
|
|
18
|
+
condition: text,
|
|
19
|
+
status: "active",
|
|
20
|
+
source,
|
|
21
|
+
startedAt: Date.now(),
|
|
22
|
+
turnsEvaluated: 0,
|
|
23
|
+
tokensSpent: 0,
|
|
24
|
+
lastVerdict: null,
|
|
25
|
+
lastReason: null,
|
|
26
|
+
judgeFailures: 0,
|
|
27
|
+
noProgressTurns: 0,
|
|
28
|
+
}
|
|
29
|
+
return agent.goal
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 暂停:只从 active。 */
|
|
33
|
+
export function pauseGoal(agent, reason = null) {
|
|
34
|
+
if (agent.goal?.status !== "active") {
|
|
35
|
+
throw new Error(`goal: cannot pause (current: ${agent.goal?.status ?? "none"})`)
|
|
36
|
+
}
|
|
37
|
+
agent.goal.status = "paused"
|
|
38
|
+
if (reason) agent.goal.lastReason = reason
|
|
39
|
+
return agent.goal
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 恢复:只从 paused;重置计时 / 轮数 / token 基线。 */
|
|
43
|
+
export function resumeGoal(agent) {
|
|
44
|
+
if (agent.goal?.status !== "paused") {
|
|
45
|
+
throw new Error(`goal: cannot resume (current: ${agent.goal?.status ?? "none"})`)
|
|
46
|
+
}
|
|
47
|
+
agent.goal.status = "active"
|
|
48
|
+
agent.goal.startedAt = Date.now()
|
|
49
|
+
agent.goal.turnsEvaluated = 0
|
|
50
|
+
agent.goal.tokensSpent = 0
|
|
51
|
+
agent.goal.judgeFailures = 0
|
|
52
|
+
agent.goal.noProgressTurns = 0
|
|
53
|
+
return agent.goal
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 清除:任意状态。 */
|
|
57
|
+
export function clearGoal(agent) {
|
|
58
|
+
agent.goal = null
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 状态词(无目标 ⇒ null)。 */
|
|
62
|
+
export function goalStatusOf(agent) {
|
|
63
|
+
return agent.goal?.status ?? null
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 裁判判决落账(单源——退出点钩子与工具面共用)。成功落账即清零连续失败计数。 */
|
|
67
|
+
export function recordVerdict(agent, { verdict, reason }) {
|
|
68
|
+
if (!agent.goal) return null
|
|
69
|
+
agent.goal.lastVerdict = verdict
|
|
70
|
+
agent.goal.lastReason = reason ?? null
|
|
71
|
+
agent.goal.turnsEvaluated = (agent.goal.turnsEvaluated ?? 0) + 1
|
|
72
|
+
agent.goal.judgeFailures = 0
|
|
73
|
+
if (verdict === "not_yet") agent.goal.noProgressTurns = (agent.goal.noProgressTurns ?? 0) + 1
|
|
74
|
+
else agent.goal.noProgressTurns = 0
|
|
75
|
+
if (verdict === "met") agent.goal.status = "complete"
|
|
76
|
+
else if (verdict === "impossible") agent.goal.status = "blocked"
|
|
77
|
+
return agent.goal
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 裁判失败计数(不放行:达上限 ⇒ paused)。 */
|
|
81
|
+
export function recordJudgeFailure(agent, { limit = 3, reason = null } = {}) {
|
|
82
|
+
if (!agent.goal) return null
|
|
83
|
+
agent.goal.judgeFailures = (agent.goal.judgeFailures ?? 0) + 1
|
|
84
|
+
if (agent.goal.judgeFailures >= limit) {
|
|
85
|
+
agent.goal.status = "paused"
|
|
86
|
+
agent.goal.lastReason = reason ?? `judge unavailable ${agent.goal.judgeFailures} times`
|
|
87
|
+
}
|
|
88
|
+
return agent.goal
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 目标期间累计 token(退出点钩子每轮调一次)。 */
|
|
92
|
+
export function addGoalTokens(agent, usage) {
|
|
93
|
+
if (!agent.goal || !usage) return
|
|
94
|
+
const n = Number(usage.prompt_tokens ?? 0) + Number(usage.completion_tokens ?? 0)
|
|
95
|
+
if (Number.isFinite(n) && n > 0) agent.goal.tokensSpent = (agent.goal.tokensSpent ?? 0) + n
|
|
96
|
+
}
|
package/agent/helpers.mjs
CHANGED
|
@@ -37,7 +37,7 @@ const GIT_TIMEOUT_MS = 5000
|
|
|
37
37
|
const MAX_GIT_CHANGES_DISPLAY = 20
|
|
38
38
|
|
|
39
39
|
export const OUTLINE_INJECT_PREFIX = "[System reminder: project dependency outline:"
|
|
40
|
-
export const FILE_MUTATORS = new Set(["write", "edit", "insert_after", "apply_patch", "delete", "hashline_edit"])
|
|
40
|
+
export const FILE_MUTATORS = new Set(["write", "edit", "insert_after", "apply_patch", "delete", "hashline_edit", "file_ops"])
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
43
|
* 工具自报触达面提取**单源谓词**(`docs/core/design/TOOLS.md` §6.17 / D-TO12——批 GUARD-SCHEDULER ·
|
|
@@ -195,6 +195,11 @@ export function wroteSince(agent, mark) {
|
|
|
195
195
|
return Number.isInteger(seq) ? seq !== mark : true
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
+
/** 服务端内置工具(如 Responses API web_search)产生的 tool 消息无对应 assistant.tool_calls,配对修复须原样保留。 */
|
|
199
|
+
function isBuiltinToolCallId(id) {
|
|
200
|
+
return typeof id === "string" && id.startsWith("web_search_call_")
|
|
201
|
+
}
|
|
202
|
+
|
|
198
203
|
/** Repair malformed conversation history: remove orphan tool messages and fill missing tool results */
|
|
199
204
|
export function repairHistory(history) {
|
|
200
205
|
const out = []
|
|
@@ -208,7 +213,8 @@ export function repairHistory(history) {
|
|
|
208
213
|
continue
|
|
209
214
|
}
|
|
210
215
|
// orphan tool message: no matching assistant tool_calls declaration, discard
|
|
211
|
-
|
|
216
|
+
// (server-executed builtin tool results such as web_search_call_* have no assistant.tool_calls)
|
|
217
|
+
if (m.role === "tool" && !knownIds.has(m.tool_call_id) && !isBuiltinToolCallId(m.tool_call_id)) {
|
|
212
218
|
dirty = true
|
|
213
219
|
continue
|
|
214
220
|
}
|
|
@@ -220,8 +226,11 @@ export function repairHistory(history) {
|
|
|
220
226
|
const answered = new Set()
|
|
221
227
|
let j = i + 1
|
|
222
228
|
while (j < history.length && history[j].role === "tool") {
|
|
223
|
-
|
|
224
|
-
|
|
229
|
+
const tid = history[j].tool_call_id
|
|
230
|
+
if (knownIds.has(tid)) {
|
|
231
|
+
answered.add(tid)
|
|
232
|
+
out.push(history[j])
|
|
233
|
+
} else if (isBuiltinToolCallId(tid)) {
|
|
225
234
|
out.push(history[j])
|
|
226
235
|
} else {
|
|
227
236
|
dirty = true // orphan tool result, discard
|
package/agent/offload.mjs
CHANGED
|
@@ -74,7 +74,7 @@ export async function offloadToolResult(text, callId, dir = join(configDir, "too
|
|
|
74
74
|
await writeFile(file, text, "utf8")
|
|
75
75
|
if (!overLimit) return `${text}\n\n[... full content saved to: ${file}\nPage through it with the read tool (offset/limit) if you need the full text later.]`
|
|
76
76
|
return buildDualEndPreview(text, TOOL_RESULT_PREVIEW) + `\n\n[... output too large (${text.length} chars total), full content saved to: ${file}\n` +
|
|
77
|
-
`Page through it with the read tool (offset/limit)
|
|
77
|
+
`Page through it with the read tool (offset/limit) — do NOT re-run the tool blindly.]`
|
|
78
78
|
} catch {
|
|
79
79
|
// 写盘失败不吞报告:>LIMIT 走双端预览 + 原文案;≤LIMIT 正文整段在前(不谎称 truncated)
|
|
80
80
|
const body = overLimit ? buildDualEndPreview(text, TOOL_RESULT_PREVIEW) : text
|