opencode-growth 0.1.0
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/LICENSE +202 -0
- package/README.md +52 -0
- package/bin/oc-grow.mjs +14 -0
- package/package.json +35 -0
- package/src/adapter-opencode/index.mjs +300 -0
- package/src/adapter-opencode/install.mjs +387 -0
- package/src/adapter-opencode/memory-tool.mjs +170 -0
- package/src/adapter-opencode/review-runner.mjs +369 -0
- package/src/cli/commands.mjs +421 -0
- package/src/cli/envelope.mjs +64 -0
- package/src/cli/main.mjs +245 -0
- package/src/core/audit.mjs +40 -0
- package/src/core/background-review.mjs +261 -0
- package/src/core/budget.mjs +64 -0
- package/src/core/candidate.mjs +96 -0
- package/src/core/home.mjs +61 -0
- package/src/core/identity.mjs +100 -0
- package/src/core/ids.mjs +22 -0
- package/src/core/lock.mjs +107 -0
- package/src/core/memories.mjs +306 -0
- package/src/core/memory-actions.mjs +222 -0
- package/src/core/paths.mjs +81 -0
- package/src/core/retrieve.mjs +127 -0
- package/src/core/review.mjs +238 -0
- package/src/core/skills.mjs +191 -0
- package/src/core/snapshot.mjs +119 -0
- package/src/core/threats.mjs +50 -0
- package/src/core/write-approval.mjs +74 -0
- package/src/core/writer.mjs +168 -0
- package/src/index.mjs +31 -0
- package/src/learn/consume.mjs +152 -0
- package/src/learn/headless.mjs +364 -0
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
// 后台复习的**执行体**:以宿主身份(插件拿到的 client)建子会话、发一次受限 agent 的请求、取回结果。
|
|
2
|
+
// 对齐 Hermes:复习在同一条模型路径上跑(第一版不换模型)⇒ 输入=**整份回合会话**。
|
|
3
|
+
// 三条纪律:①请求由宿主进程发起("看起来是 opencode 调用的")②工具受限(plan 只读)
|
|
4
|
+
// ③适配器故障绝不允许浮到宿主进程里。
|
|
5
|
+
import fs from "node:fs"
|
|
6
|
+
import { REVIEW_AGENT, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, parseReviewActions } from "../core/background-review.mjs"
|
|
7
|
+
|
|
8
|
+
// 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
|
|
9
|
+
export const REVIEW_INSTRUCTIONS = Object.freeze([
|
|
10
|
+
"你在做一次「后台复习」:把这一回合里值得长期记住的东西蒸馏成规则。",
|
|
11
|
+
// 真机链实测:只说"值得长期记住的"时,模型会连续几轮保守地回 `none`(连会话里明摆着的
|
|
12
|
+
// 偏好/约定都不记)。用户给出的**长期偏好、约定、纠正**就是要记的东西,明确点名。
|
|
13
|
+
"用户在会话里给出的长期偏好、约定、纠正(「以后都…」「我们的约定是…」「不要…」这类)就是要记的东西,逐条记下来。",
|
|
14
|
+
"不要把错误日志、堆栈、报错原文抄进来——蒸馏成一条可复用的规则。",
|
|
15
|
+
"用户抱怨某个做法时,改的是技能,不是往记忆里写牢骚。",
|
|
16
|
+
"读前写强制:要改动既有内容,先读它。",
|
|
17
|
+
"不要为一次会话建单独文件;记忆是常驻的、有界的。",
|
|
18
|
+
"新增可以直接写;改动或删除既有条目一律只提案,等人处置。",
|
|
19
|
+
])
|
|
20
|
+
|
|
21
|
+
const textOf = (m) => (typeof m === "string" ? m : m?.text ?? m?.content ?? JSON.stringify(m))
|
|
22
|
+
|
|
23
|
+
export function buildReviewPrompt(history = []) {
|
|
24
|
+
const lines = history.map((m) => "- " + textOf(m))
|
|
25
|
+
return [
|
|
26
|
+
"【本回合会话(整份)】",
|
|
27
|
+
...lines,
|
|
28
|
+
"",
|
|
29
|
+
"【约束】",
|
|
30
|
+
...REVIEW_INSTRUCTIONS.map((s) => "- " + s),
|
|
31
|
+
"",
|
|
32
|
+
// 【V7 真机链实测的教训】只写"按三类给出"不够:真模型会输出 markdown 标题 + 编号列表
|
|
33
|
+
// (例如 "### add(可直接写)\n1. memory:…"),解析结果会是 0 条动作。
|
|
34
|
+
// 所以把**输出契约**写死:只允许动作行本身,不要标题/编号/解释。没有可记的就输出 none。
|
|
35
|
+
"输出契约(必须严格遵守):",
|
|
36
|
+
"- 只输出动作行,一行一条,形如 `add: <一句话规则>` / `update: <既有条目里的唯一子串> → <新内容>` / `remove: <既有条目里的唯一子串>`。",
|
|
37
|
+
"- 不要标题、不要编号列表、不要解释、不要空行之外的任何其它文字。",
|
|
38
|
+
"- 没有任何值得记的就只输出 `none`(不要写别的)。",
|
|
39
|
+
].join("\n")
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ── A131:运行期工具限制(不是"换个 agent 名"就算限制) ─────────────────────
|
|
43
|
+
// 依据(只读源码):`packages/sdk/js/src/gen/types.gen.ts:2598` —— `POST /session/:id/message`
|
|
44
|
+
// 的请求体有 `tools?: { [key: string]: boolean }`,这是**运行期**的工具面开关;
|
|
45
|
+
// 宿主的工具 id 由 `packages/opencode/src/tool/registry.ts:78 ids()` 列出(HTTP `/tool`)。
|
|
46
|
+
// 策略:**fail-closed 白名单**——只有明确只读的工具为 true,其余(含我们没见过的)一律 false。
|
|
47
|
+
// 换句话说:宿主哪天多一个会写盘的工具,默认状态是"复习拿不到它",而不是"默默拿到"。
|
|
48
|
+
export const REVIEW_READ_ONLY_TOOLS = Object.freeze(["read", "grep", "glob", "list", "lsp", "webfetch", "websearch"])
|
|
49
|
+
|
|
50
|
+
// 拿不到宿主工具清单时的兜底:至少把这些已知会改盘/会派活的关掉,并如实标 `enumerated:false`。
|
|
51
|
+
const KNOWN_MUTATING_TOOLS = Object.freeze(["write", "edit", "patch", "apply_patch", "multiedit", "bash", "shell", "task", "skill", "question", "plan"])
|
|
52
|
+
|
|
53
|
+
export function toolRestrictionFor(hostToolIds = null) {
|
|
54
|
+
if (Array.isArray(hostToolIds) && hostToolIds.length) {
|
|
55
|
+
const map = {}
|
|
56
|
+
for (const id of hostToolIds) {
|
|
57
|
+
if (typeof id !== "string" || !id) continue
|
|
58
|
+
map[id] = REVIEW_READ_ONLY_TOOLS.includes(id) // 白名单外(含没见过的)⇒ false
|
|
59
|
+
}
|
|
60
|
+
return { tools: map, enumerated: true, allowed: Object.keys(map).filter((k) => map[k]), denied: Object.keys(map).filter((k) => !map[k]) }
|
|
61
|
+
}
|
|
62
|
+
const map = {}
|
|
63
|
+
for (const id of KNOWN_MUTATING_TOOLS) map[id] = false
|
|
64
|
+
for (const id of REVIEW_READ_ONLY_TOOLS) map[id] = true
|
|
65
|
+
return { tools: map, enumerated: false, allowed: [...REVIEW_READ_ONLY_TOOLS], denied: [...KNOWN_MUTATING_TOOLS] }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 真宿主 `client.session.messages()` 回来的是**包装对象**(`{data:[…]}`),直连 SDK 时也可能
|
|
69
|
+
// 是 `{messages:[…]}` 或裸数组。真机链实测(2026-09-21):这里不归一化,`[...msgs]` 会当场抛错,
|
|
70
|
+
// 表现是"dispatch-start / review-returned 都记了,之后什么都没有"——最难查的那种断点。
|
|
71
|
+
export function normalizeMessages(raw) {
|
|
72
|
+
if (Array.isArray(raw)) return raw
|
|
73
|
+
if (Array.isArray(raw?.data)) return raw.data
|
|
74
|
+
if (Array.isArray(raw?.messages)) return raw.messages
|
|
75
|
+
return []
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000 } = {}) {
|
|
79
|
+
return async () => {
|
|
80
|
+
try {
|
|
81
|
+
// 有 `promptAsync` 就走它(事件回调里更稳),否则退回同步 `prompt`;两者都没有才算不可用。
|
|
82
|
+
const canPrompt = typeof client?.session?.promptAsync === "function" || typeof client?.session?.prompt === "function"
|
|
83
|
+
if (!client?.session?.create || !client?.session?.messages || !canPrompt) return { ok: false, error: "宿主 client 不可用" }
|
|
84
|
+
// 输入面=整份回合会话(同模型路径)
|
|
85
|
+
const main = await client.session.messages({ path: { id: sessionId } })
|
|
86
|
+
const history = main?.data ?? main ?? []
|
|
87
|
+
// A131:先问宿主有哪些工具,再按 fail-closed 白名单算出这次运行的 `tools` 面
|
|
88
|
+
let hostToolIds = null
|
|
89
|
+
try {
|
|
90
|
+
const listed = client?.tool?.list ? await client.tool.list() : null
|
|
91
|
+
const rows = listed?.data ?? listed ?? null
|
|
92
|
+
if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
|
|
93
|
+
} catch { hostToolIds = null }
|
|
94
|
+
const restriction = toolRestrictionFor(hostToolIds)
|
|
95
|
+
if (typeof onRestriction === "function") onRestriction(restriction)
|
|
96
|
+
// 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
|
|
97
|
+
const created = await client.session.create({ body: { parentID: sessionId } })
|
|
98
|
+
const childId = created?.data?.id ?? created?.id ?? null
|
|
99
|
+
if (!childId) return { ok: false, error: "子会话没建起来" }
|
|
100
|
+
// 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
|
|
101
|
+
if (typeof onChild === "function") onChild(childId)
|
|
102
|
+
// **不要在事件回调里等同步 prompt**:真机链实测(2026-09-21)——子会话真的产出了内容,
|
|
103
|
+
// 但我们这条 `await prompt(...)` 之后的代码一步都没跑(连 trace 都没落)。宿主的事件回调里
|
|
104
|
+
// 走"同步驱动"这条路会卡住自己。改法(照宿主自己的两种姿势):
|
|
105
|
+
// 优先 `promptAsync`(只入队,立刻返回)→ 轮询 `messages` 等 assistant 产出;
|
|
106
|
+
// 没有 promptAsync 的宿主再退回同步 prompt(老姿势,风险已知)。
|
|
107
|
+
const promptBody = { agent, tools: restriction.tools, parts: [{ type: "text", text: buildReviewPrompt(history) }] }
|
|
108
|
+
if (typeof client.session.promptAsync === "function") {
|
|
109
|
+
await client.session.promptAsync({ path: { id: childId }, body: promptBody })
|
|
110
|
+
} else {
|
|
111
|
+
await client.session.prompt({ path: { id: childId }, body: promptBody })
|
|
112
|
+
}
|
|
113
|
+
// 轮询取回(最多 REVIEW_LIMITS.pollMs,默认 60s):看到 assistant 文本就走
|
|
114
|
+
const deadline = Date.now() + pollMs
|
|
115
|
+
let out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
|
|
116
|
+
while (Date.now() < deadline) {
|
|
117
|
+
const msgs = normalizeMessages(out)
|
|
118
|
+
const hasAssistantText = (Array.isArray(msgs) ? msgs : []).some((m) => {
|
|
119
|
+
const role = m?.role ?? m?.info?.role
|
|
120
|
+
if (role !== "assistant") return false
|
|
121
|
+
if (typeof m?.text === "string" && m.text.trim()) return true
|
|
122
|
+
const parts = m?.parts ?? m?.info?.parts ?? []
|
|
123
|
+
return (Array.isArray(parts) ? parts : []).some((x) => x?.type === "text" && String(x.text ?? "").trim())
|
|
124
|
+
})
|
|
125
|
+
if (hasAssistantText) break
|
|
126
|
+
await new Promise((r) => setTimeout(r, 1000))
|
|
127
|
+
out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
|
|
128
|
+
}
|
|
129
|
+
return { ok: true, childId, messages: normalizeMessages(out), restriction }
|
|
130
|
+
} catch (e) {
|
|
131
|
+
return { ok: false, error: String(e?.message ?? e) }
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 组装:宿主插件入口在回合结束(session.idle)时按**会话**调 onIdle。
|
|
137
|
+
// 每个会话一份计数与一个 handler(计数要连得上,不能每次重建)。
|
|
138
|
+
export function createReviewPipeline({ client, thresholds, store = null, cancelHandshakeMs = 2000, now = () => Date.now(), audit = null, toolsAvailable: declaredTools = null } = {}) {
|
|
139
|
+
const handlers = new Map()
|
|
140
|
+
// 每个会话的运行态:在跑的复习子会话 id + 是否已被取消 + 那次作业的句柄。
|
|
141
|
+
// A129:调度器只会说"取消",真正能对宿主发 abort 的是**执行体**(它持有 client 与子会话 id)。
|
|
142
|
+
const runs = new Map()
|
|
143
|
+
// C③:工具可用性**显式**从宿主工具表读一次(照 Hermes:计数只看名单里有没有那个工具)。
|
|
144
|
+
// 读不到就如实标未知 —— 调度器把"未知"当不可用,宁可不触发也不乱触发。
|
|
145
|
+
let toolAvail = null
|
|
146
|
+
// 已知的按**显式声明**(生产里适配器知道自己的记忆工具注册没注册);只有真的读不到名单、也没声明,
|
|
147
|
+
// 才是"未知"。未知时不硬拦(调度器用它的默认值),但把"没枚举到"如实记在决策条目里——
|
|
148
|
+
// 拦与不拦都要说清依据,不许悄悄变成"永远不触发"或"永远触发"。
|
|
149
|
+
const availability = async () => {
|
|
150
|
+
if (toolAvail) return toolAvail
|
|
151
|
+
let ids = null
|
|
152
|
+
try {
|
|
153
|
+
const listed = client?.tool?.list ? await client.tool.list() : null
|
|
154
|
+
const rows = listed?.data ?? listed ?? null
|
|
155
|
+
ids = Array.isArray(rows) ? rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean) : null
|
|
156
|
+
} catch { ids = null }
|
|
157
|
+
const declared = declaredTools ?? {}
|
|
158
|
+
const memory = declared.memory ?? (ids ? ids.includes("memory") : null)
|
|
159
|
+
const skills = declared.skills ?? (ids ? ids.includes("skill") : null)
|
|
160
|
+
// 两边都未知 ⇒ 不传(交给调度器默认),并在结果里标 enumerated:false
|
|
161
|
+
toolAvail = (memory === null && skills === null) ? null : { memory, skills }
|
|
162
|
+
return toolAvail
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
async onIdle(sessionId) {
|
|
166
|
+
if (!sessionId) return { handled: false, reason: "no-session" }
|
|
167
|
+
if (!handlers.has(sessionId)) {
|
|
168
|
+
const run = { childId: null, cancelled: false, inflight: null, restriction: null, dispatchedAt: 0, lastUserMessageId: null, lastUserMessageAt: 0 }
|
|
169
|
+
runs.set(sessionId, run)
|
|
170
|
+
const review = createHostReview({ client, sessionId, onChild: (id) => { run.childId = id }, onRestriction: (r) => { run.restriction = r } })
|
|
171
|
+
const scheduler = createReviewScheduler({
|
|
172
|
+
...(thresholds ? { thresholds } : {}),
|
|
173
|
+
...((await availability()) ? { toolsAvailable: await availability() } : {}),
|
|
174
|
+
// 真中断(不是等它跑完):对在跑的复习子会话发 abort,并记下"已被取消"。
|
|
175
|
+
interrupt: () => {
|
|
176
|
+
// 留痕:真机链上"复习跑完却不落地"的唯一静默路径就是被取消,必须知道是谁取消的
|
|
177
|
+
if (process.env.OCG_REVIEW_TRACE === "1") {
|
|
178
|
+
try {
|
|
179
|
+
fs.appendFileSync(process.env.OCG_TRACE_FILE || "/tmp/ocg-review-trace.log",
|
|
180
|
+
JSON.stringify({ ts: Date.now(), step: "interrupt", sessionId, childId: run.childId ?? null, stack: String(new Error().stack ?? "").split("\n").slice(1, 4).join(" | ") }) + "\n")
|
|
181
|
+
} catch {}
|
|
182
|
+
}
|
|
183
|
+
run.cancelled = true
|
|
184
|
+
const id = run.childId
|
|
185
|
+
if (id && client?.session?.abort) {
|
|
186
|
+
try { Promise.resolve(client.session.abort({ path: { id } })).catch(() => {}) } catch { /* 取消失败不许影响前台 */ }
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
dispatch: async () => {
|
|
190
|
+
run.cancelled = false
|
|
191
|
+
run.childId = null
|
|
192
|
+
run.dispatchedAt = now()
|
|
193
|
+
// 直写文件的留痕(**绕开审计 sink**):真机链上"审计里什么都没有"也可能是 sink 本身坏了,
|
|
194
|
+
// 所以排障用这条通道,直接看代码走到哪一步。
|
|
195
|
+
const fileTrace = (step, extra = {}) => {
|
|
196
|
+
if (process.env.OCG_REVIEW_TRACE !== "1") return
|
|
197
|
+
try {
|
|
198
|
+
fs.appendFileSync(process.env.OCG_TRACE_FILE || "/tmp/ocg-review-trace.log",
|
|
199
|
+
JSON.stringify({ ts: Date.now(), step, sessionId, ...extra }) + "\n")
|
|
200
|
+
} catch { /* 留痕失败不许影响主流程 */ }
|
|
201
|
+
}
|
|
202
|
+
// 逐步留痕:**默认关闭**,`OCG_REVIEW_TRACE=1` 才记。
|
|
203
|
+
// 默认开会让"失败恰好一条审计记录"的不变量变成三条(既有用例钉着那条不变量);
|
|
204
|
+
// 真机链排障时开着它跑一次,就能看到到底停在哪一步。
|
|
205
|
+
const trace = (step, extra = {}) => {
|
|
206
|
+
if (process.env.OCG_REVIEW_TRACE !== "1") return
|
|
207
|
+
const ev = { event: "background-review", sessionId, phase: step, ...extra }
|
|
208
|
+
if (typeof audit === "function") { try { audit(ev) } catch { /* 见 sink 痕迹文件 */ } }
|
|
209
|
+
}
|
|
210
|
+
trace("dispatch-start")
|
|
211
|
+
fileTrace("dispatch-start")
|
|
212
|
+
let out
|
|
213
|
+
try {
|
|
214
|
+
out = await review()
|
|
215
|
+
} catch (e) {
|
|
216
|
+
// 复习体自己抛错也要**留痕**(V7 真机链教训:那次 run 连审计目录都没建,
|
|
217
|
+
// 事后只能靠推断"可能是 dispatch 抛了")。异常照旧往上报,但先记一条。
|
|
218
|
+
const errEvent = { event: "background-review", sessionId, phase: "dispatch", error: String(e?.message ?? e) }
|
|
219
|
+
fileTrace("review-threw", { message: String(e?.message ?? e) })
|
|
220
|
+
if (typeof audit === "function") { try { audit(errEvent) } catch { /* 见 sink 的痕迹文件 */ } }
|
|
221
|
+
throw e
|
|
222
|
+
}
|
|
223
|
+
// **取消之后不落地**:abort 与写入之间不留缝(照 Hermes 取消即不再产出)
|
|
224
|
+
fileTrace("review-returned", { ok: out?.ok ?? null, childId: out?.childId ?? null })
|
|
225
|
+
trace("review-returned", { ok: out?.ok ?? null, childId: out?.childId ?? null, messages: Array.isArray(out?.messages) ? out.messages.length : null, error: out?.error ?? null })
|
|
226
|
+
if (run.cancelled) {
|
|
227
|
+
fileTrace("skipped-landing-cancelled", { childId: out?.childId ?? null })
|
|
228
|
+
return { ...out, cancelled: true, skippedLanding: true, written: 0, staged: 0, surface: null }
|
|
229
|
+
}
|
|
230
|
+
if (!out.ok) {
|
|
231
|
+
// **失败也要留痕**:V7 真机链实测时这里静默吞过一次(子会话建了、产出有、审计空)。
|
|
232
|
+
if (typeof audit === "function") {
|
|
233
|
+
try { audit({ event: "background-review", sessionId, childId: out.childId ?? null, ok: false, error: String(out.error ?? "unknown") }) } catch { /* 记账失败不影响前台 */ }
|
|
234
|
+
}
|
|
235
|
+
return out
|
|
236
|
+
}
|
|
237
|
+
// 取回子会话里最后一条 assistant 文本 = 复习产出
|
|
238
|
+
// ⚠️ 这一段整体包一层:真机链上出现过"review-returned 记了、之后一条都没有"的断点,
|
|
239
|
+
// 说明错误被更外层的 catch 吞了。这里把错误原文直接落进留痕文件,一眼可定位。
|
|
240
|
+
let msgs
|
|
241
|
+
try {
|
|
242
|
+
msgs = normalizeMessages(out.messages)
|
|
243
|
+
} catch (e) {
|
|
244
|
+
fileTrace("normalize-threw", { message: String(e?.message ?? e), raw: typeof out.messages })
|
|
245
|
+
throw e
|
|
246
|
+
}
|
|
247
|
+
// 真宿主的消息形状是 {info:{role}, parts:[{type,text}]},不是 {role, text}
|
|
248
|
+
// —— 这里兼容两种形状(真机链上曾因此解析出 0 条动作)
|
|
249
|
+
const textOfMsg = (m) => {
|
|
250
|
+
if (!m) return ""
|
|
251
|
+
if (typeof m.text === "string") return m.text
|
|
252
|
+
const parts = m.parts ?? m.info?.parts ?? []
|
|
253
|
+
return (Array.isArray(parts) ? parts : []).filter((p) => p?.type === "text").map((p) => p.text ?? "").join("\n")
|
|
254
|
+
}
|
|
255
|
+
const roleOfMsg = (m) => m?.role ?? m?.info?.role ?? null
|
|
256
|
+
const last = [...msgs].reverse().find((m) => roleOfMsg(m) === "assistant") ?? null
|
|
257
|
+
const assistantText = textOfMsg(last)
|
|
258
|
+
fileTrace("parsed-input", { assistantChars: assistantText.length, msgs: msgs.length, textType: typeof assistantText })
|
|
259
|
+
trace("parsed-input", { assistantChars: assistantText.length })
|
|
260
|
+
const actions = parseReviewActions(assistantText)
|
|
261
|
+
// 落地:add 直写;改/删只提案(硬不变量)且提案必须浮出
|
|
262
|
+
// A137:提案要能**唯一定位**目标条目 ⇒ 把既有条目喂给分类器(读不到就如实标 unknown)
|
|
263
|
+
const entries = (() => {
|
|
264
|
+
try {
|
|
265
|
+
const list = store?.read ? store.read({ kind: "memory" }) : null
|
|
266
|
+
return Array.isArray(list) ? list : null
|
|
267
|
+
} catch { return null }
|
|
268
|
+
})()
|
|
269
|
+
let landed
|
|
270
|
+
try {
|
|
271
|
+
landed = store ? applyReviewOutcome({ store, actions, entries }) : { written: 0, staged: 0, surface: null }
|
|
272
|
+
} catch (e) {
|
|
273
|
+
if (typeof audit === "function") {
|
|
274
|
+
try { audit({ event: "background-review", sessionId, childId: out.childId ?? null, ok: false, error: `landing failed: ${String(e?.message ?? e)}` }) } catch { /* ditto */ }
|
|
275
|
+
}
|
|
276
|
+
return { ...out, ok: false, error: `landing failed: ${String(e?.message ?? e)}` }
|
|
277
|
+
}
|
|
278
|
+
// A131:每次决策留一条**可核条目**——谁跑的、跑的时候工具面是什么、落了什么。
|
|
279
|
+
// 记账失败不许影响宿主(吞掉),但条目本身要能被机器读。
|
|
280
|
+
const decision = {
|
|
281
|
+
event: "background-review",
|
|
282
|
+
sessionId,
|
|
283
|
+
childId: out.childId ?? null,
|
|
284
|
+
agent: REVIEW_AGENT,
|
|
285
|
+
toolsEnumerated: run.restriction?.enumerated ?? null,
|
|
286
|
+
toolsAllowed: run.restriction?.allowed ?? null,
|
|
287
|
+
toolsDenied: run.restriction?.denied ?? null,
|
|
288
|
+
actions: actions.length,
|
|
289
|
+
written: landed.written ?? 0,
|
|
290
|
+
staged: landed.staged ?? 0,
|
|
291
|
+
ignored: (landed.ignored ?? []).map((i) => i.op),
|
|
292
|
+
surface: landed.surface ?? null,
|
|
293
|
+
}
|
|
294
|
+
if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
|
|
295
|
+
// 提案必须浮出:有人看得见的那一行,发回宿主会话
|
|
296
|
+
const surfaced = landed.surface ? await surfaceToHost({ client, sessionId, line: landed.surface }) : { posted: false }
|
|
297
|
+
return { ...out, actions: actions.length, ...landed, surfaced, decision }
|
|
298
|
+
},
|
|
299
|
+
})
|
|
300
|
+
handlers.set(sessionId, createTurnEndHandler({ scheduler, review: async () => ({}), sessionId }))
|
|
301
|
+
}
|
|
302
|
+
const r = await handlers.get(sessionId).onIdle()
|
|
303
|
+
const run = runs.get(sessionId)
|
|
304
|
+
if (r?.pending) run.inflight = r.pending // 交给 onUserTurnStart 握手的那个句柄
|
|
305
|
+
return { handled: true, ...r }
|
|
306
|
+
},
|
|
307
|
+
|
|
308
|
+
// 前台新回合开始 ⇒ 取消在跑的复习(照 Hermes `turn_facade.py` 的时机 + 取消握手)。
|
|
309
|
+
// 返回如实:`settled:false` 表示握手超时、作业可能还在跑(不许假装已经停了)。
|
|
310
|
+
// 只有**真的新回合**才取消。真机链实测(2026-09-21):宿主在一次回合里会连发多条
|
|
311
|
+
// "用户消息"事件(45 条 / 10 回合),复习刚在回合结束被派发就被同一回合的尾部事件取消,
|
|
312
|
+
// 落到"取消后不落地"的静默路径——整条链看着跑通、其实一条都没落。
|
|
313
|
+
// 判据:来的是**比派发时刻更晚**的用户消息 ⇒ 取消;取不到证据 ⇒ 不取消(误取消会毁掉真产出)。
|
|
314
|
+
async onUserTurnStart(sessionId, info = {}) {
|
|
315
|
+
if (process.env.OCG_REVIEW_TRACE === "1") {
|
|
316
|
+
try {
|
|
317
|
+
fs.appendFileSync(process.env.OCG_TRACE_FILE || "/tmp/ocg-review-trace.log",
|
|
318
|
+
JSON.stringify({ ts: Date.now(), step: "onUserTurnStart", sessionId, known: handlers.has(sessionId) }) + "\n")
|
|
319
|
+
} catch {}
|
|
320
|
+
}
|
|
321
|
+
const run = runs.get(sessionId)
|
|
322
|
+
const handler = handlers.get(sessionId)
|
|
323
|
+
if (!sessionId || !run || !handler || !run.inflight) return { cancelled: false, reason: "idle" }
|
|
324
|
+
const hasEvidence = Boolean(info?.messageId) || typeof info?.createdAt === "number"
|
|
325
|
+
if (!hasEvidence) return { cancelled: false, reason: "no-evidence" }
|
|
326
|
+
if (typeof info?.createdAt === "number" && run.dispatchedAt) {
|
|
327
|
+
if (info.createdAt <= run.dispatchedAt) return { cancelled: false, reason: "same-turn-event" }
|
|
328
|
+
} else if (info?.messageId && run.lastUserMessageId && info.messageId === run.lastUserMessageId) {
|
|
329
|
+
return { cancelled: false, reason: "same-turn-event" }
|
|
330
|
+
}
|
|
331
|
+
if (info?.messageId) run.lastUserMessageId = info.messageId
|
|
332
|
+
const t0 = now()
|
|
333
|
+
const childId = run.childId
|
|
334
|
+
// 两件事并发,总时长都压在同一个握手上限内(照 Hermes:整段 ≤2.0s):
|
|
335
|
+
// ① 触发调度器的取消 ⇒ interrupt ⇒ 对子会话 abort
|
|
336
|
+
// ② 等那次作业真的落地
|
|
337
|
+
const timeout = (ms) => new Promise((res) => setTimeout(() => res(null), ms))
|
|
338
|
+
const cancelTask = Promise.resolve(handler.onUserTurnStart()).catch((e) => ({ error: String(e?.message ?? e) }))
|
|
339
|
+
const settleTask = Promise.resolve(run.inflight).then(() => true, () => true)
|
|
340
|
+
const settled = (await Promise.race([settleTask, timeout(cancelHandshakeMs).then(() => false)])) === true
|
|
341
|
+
if (settled) run.inflight = null
|
|
342
|
+
const left = Math.max(0, cancelHandshakeMs - (now() - t0))
|
|
343
|
+
const scheduler = await Promise.race([cancelTask, timeout(left).then(() => ({ timeout: true }))])
|
|
344
|
+
return { cancelled: true, childId, settled, elapsedMs: now() - t0, scheduler }
|
|
345
|
+
},
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// 提案浮出:把那一行发到**宿主会话**里,人一眼看得见(后台做事不能悄没声)。
|
|
350
|
+
// 发不出去就吞掉并如实标记——适配器不许把宿主的会话弄崩。
|
|
351
|
+
// A141 更正(照 Hermes background_review.py:640-660 `_action_lines`):浮出**不许**用
|
|
352
|
+
// `session.prompt` —— 那条路等价 POST /session/:id/message,会**真驱动一次模型回合**(人也得多掏一次钱)。
|
|
353
|
+
// 默认走不驱动模型的那条面:待批文件本身(`D/pending/` + 命令面 `/ocg-pending`)已经把提案摆到人眼前;
|
|
354
|
+
// 这里只把那一行**返回给调用方**(宿主日志/进度页可见),并把降级如实标出来。
|
|
355
|
+
// 显式要求 `mode: "prompt"` 时才走会驱动模型的那条(留给将来找到非驱动通道前的兜底)。
|
|
356
|
+
export async function surfaceToHost({ client, sessionId, line, mode = "pending-surface" } = {}) {
|
|
357
|
+
if (!line) return { posted: false, reason: "nothing-to-surface" }
|
|
358
|
+
if (mode !== "prompt") {
|
|
359
|
+
return { posted: false, reason: "non-driving-surface", degraded: false, line }
|
|
360
|
+
}
|
|
361
|
+
if (!sessionId) return { posted: false, reason: "no-session" }
|
|
362
|
+
if (!client?.session?.prompt) return { posted: false, reason: "no-channel" }
|
|
363
|
+
try {
|
|
364
|
+
await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: line }] } })
|
|
365
|
+
return { posted: true, drivesModelTurn: true } // 如实标注:这条路会驱动一次模型回合
|
|
366
|
+
} catch {
|
|
367
|
+
return { posted: false, reason: "post-failed" }
|
|
368
|
+
}
|
|
369
|
+
}
|