opencode-growth 0.1.2 → 0.1.74

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.
Files changed (48) hide show
  1. package/README.md +72 -13
  2. package/package.json +1 -1
  3. package/src/adapter-opencode/curator-runner.mjs +257 -0
  4. package/src/adapter-opencode/index.mjs +309 -19
  5. package/src/adapter-opencode/install.mjs +329 -52
  6. package/src/adapter-opencode/journey-tool.mjs +57 -0
  7. package/src/adapter-opencode/memory-tool.mjs +57 -5
  8. package/src/adapter-opencode/provider-tools.mjs +237 -0
  9. package/src/adapter-opencode/review-runner.mjs +180 -37
  10. package/src/adapter-opencode/session-search-tool.mjs +66 -0
  11. package/src/adapter-opencode/skill-tool.mjs +221 -0
  12. package/src/cli/commands.mjs +98 -5
  13. package/src/cli/curator-cmd.mjs +149 -0
  14. package/src/cli/journey-cmd.mjs +61 -0
  15. package/src/cli/journey-view.mjs +174 -0
  16. package/src/cli/main.mjs +173 -26
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +87 -0
  19. package/src/cli/skill-cmd.mjs +194 -0
  20. package/src/core/approve.mjs +295 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +114 -2
  23. package/src/core/home.mjs +56 -21
  24. package/src/core/journey.mjs +298 -0
  25. package/src/core/lock.mjs +6 -0
  26. package/src/core/memories.mjs +215 -10
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/paths.mjs +0 -1
  29. package/src/core/session-freshness.mjs +201 -0
  30. package/src/core/session-index.mjs +508 -0
  31. package/src/core/session-query.mjs +161 -0
  32. package/src/core/session-source.mjs +209 -0
  33. package/src/core/session-tool.mjs +189 -0
  34. package/src/core/skill-actions.mjs +391 -0
  35. package/src/core/skill-backup.mjs +95 -0
  36. package/src/core/skill-lifecycle.mjs +277 -0
  37. package/src/core/skill-usage.mjs +119 -0
  38. package/src/core/skills.mjs +30 -3
  39. package/src/core/sqlite-runtime.mjs +35 -0
  40. package/src/core/write-approval.mjs +13 -9
  41. package/src/host/rest-client.mjs +70 -0
  42. package/src/index.mjs +0 -1
  43. package/src/provider/config.mjs +187 -0
  44. package/src/provider/openviking-rest.mjs +742 -0
  45. package/src/provider/runtime.mjs +417 -0
  46. package/src/provider/wiring.mjs +164 -0
  47. package/src/core/budget.mjs +0 -64
  48. package/src/core/retrieve.mjs +0 -127
@@ -3,7 +3,7 @@
3
3
  // 三条纪律:①请求由宿主进程发起("看起来是 opencode 调用的")②工具受限(plan 只读)
4
4
  // ③适配器故障绝不允许浮到宿主进程里。
5
5
  import fs from "node:fs"
6
- import { REVIEW_AGENT, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, parseReviewActions } from "../core/background-review.mjs"
6
+ import { REVIEW_AGENT, REVIEW_SURFACE_MARK, backgroundReviewBead, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, applySkillReviewActions, parseReviewActions } from "../core/background-review.mjs"
7
7
 
8
8
  // 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
9
9
  export const REVIEW_INSTRUCTIONS = Object.freeze([
@@ -13,15 +13,35 @@ export const REVIEW_INSTRUCTIONS = Object.freeze([
13
13
  "用户在会话里给出的长期偏好、约定、纠正(「以后都…」「我们的约定是…」「不要…」这类)就是要记的东西,逐条记下来。",
14
14
  "不要把错误日志、堆栈、报错原文抄进来——蒸馏成一条可复用的规则。",
15
15
  "用户抱怨某个做法时,改的是技能,不是往记忆里写牢骚。",
16
+ // 通道④(照 Hermes background_review 的技能面):回合后顺手改进本回合用过的技能。
17
+ "本回合用过/加载过的技能值得顺手改进:把新经验 patch 进那**一个**技能;没有合适技能才 create。",
18
+ "技能面只动 agent-created 技能(用户自建的、外部来源的技能一律不碰)。",
16
19
  "读前写强制:要改动既有内容,先读它。",
17
20
  "不要为一次会话建单独文件;记忆是常驻的、有界的。",
18
21
  "新增可以直接写;改动或删除既有条目一律只提案,等人处置。",
19
22
  ])
20
23
 
21
- const textOf = (m) => (typeof m === "string" ? m : m?.text ?? m?.content ?? JSON.stringify(m))
24
+ // 后台复习吃的是「整份回合会话」,而浮出的通知也是 user 消息(ignored + metadata.ocg)。
25
+ // 主模型上下文与 ③层召回都过滤了它,这里也必须过滤:否则 OCG 会把自己的机器通知当成用户说的话,
26
+ // 再蒸馏进记忆(这正是「不被 OCG 当用户输入」要防的那条路径)。
27
+ const isSurfacePart = (part) => part?.ignored === true || part?.metadata?.ocg === REVIEW_SURFACE_MARK
28
+
29
+ const textOf = (m) => {
30
+ if (typeof m === "string") return m
31
+ const parts = Array.isArray(m?.parts) ? m.parts : null
32
+ if (parts) {
33
+ return parts
34
+ .filter((part) => part && part.type === "text" && typeof part.text === "string" && !isSurfacePart(part))
35
+ .map((part) => part.text)
36
+ .join("\n")
37
+ .trim()
38
+ }
39
+ return m?.text ?? m?.content ?? JSON.stringify(m)
40
+ }
22
41
 
23
42
  export function buildReviewPrompt(history = []) {
24
- const lines = history.map((m) => "- " + textOf(m))
43
+ // 过滤后为空的消息(例如整条都是通知)不占一行:`- ` 空行会让模型以为用户说了句空话。
44
+ const lines = history.map((m) => "- " + textOf(m)).filter((line) => line.trim() !== "-")
25
45
  return [
26
46
  "【本回合会话(整份)】",
27
47
  ...lines,
@@ -34,6 +54,7 @@ export function buildReviewPrompt(history = []) {
34
54
  // 所以把**输出契约**写死:只允许动作行本身,不要标题/编号/解释。没有可记的就输出 none。
35
55
  "输出契约(必须严格遵守):",
36
56
  "- 只输出动作行,一行一条,形如 `add: <一句话规则>` / `update: <既有条目里的唯一子串> → <新内容>` / `remove: <既有条目里的唯一子串>`。",
57
+ "- 技能动作用 `skill: {\"op\":\"create\",\"name\":\"小写连字符名\",\"description\":\"Use when ….\",\"content\":\"Markdown 正文\"}` 或 `skill: {\"op\":\"patch\",\"name\":\"技能名\",\"old_string\":\"唯一命中的原文\",\"new_string\":\"新文\"}`(一行一条,JSON 单行;归档/删除不要提)。",
37
58
  "- 不要标题、不要编号列表、不要解释、不要空行之外的任何其它文字。",
38
59
  "- 没有任何值得记的就只输出 `none`(不要写别的)。",
39
60
  ].join("\n")
@@ -75,26 +96,44 @@ export function normalizeMessages(raw) {
75
96
  return []
76
97
  }
77
98
 
78
- export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000 } = {}) {
99
+ // 可选取消只约束本次宿主等待;不改默认复习语义。取消后不再继续轮询/派发下一步。
100
+ async function abortable(fn, signal) {
101
+ const check = () => { if (signal?.aborted) throw new Error("宿主复习已取消") }
102
+ check()
103
+ if (!signal) return fn()
104
+ let onAbort
105
+ const stopped = new Promise((_, reject) => {
106
+ onAbort = () => reject(new Error("宿主复习已取消"))
107
+ signal.addEventListener("abort", onAbort, { once: true })
108
+ })
109
+ try {
110
+ return await Promise.race([Promise.resolve().then(() => { check(); return fn() }), stopped])
111
+ } finally {
112
+ signal.removeEventListener("abort", onAbort)
113
+ }
114
+ }
115
+
116
+ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null } = {}) {
117
+ const call = (fn) => signal ? abortable(fn, signal) : fn() // 默认路径不增加async跳数
79
118
  return async () => {
80
119
  try {
81
120
  // 有 `promptAsync` 就走它(事件回调里更稳),否则退回同步 `prompt`;两者都没有才算不可用。
82
121
  const canPrompt = typeof client?.session?.promptAsync === "function" || typeof client?.session?.prompt === "function"
83
122
  if (!client?.session?.create || !client?.session?.messages || !canPrompt) return { ok: false, error: "宿主 client 不可用" }
84
123
  // 输入面=整份回合会话(同模型路径)
85
- const main = await client.session.messages({ path: { id: sessionId } })
124
+ const main = await call(() => client.session.messages({ path: { id: sessionId } }))
86
125
  const history = main?.data ?? main ?? []
87
126
  // A131:先问宿主有哪些工具,再按 fail-closed 白名单算出这次运行的 `tools` 面
88
127
  let hostToolIds = null
89
128
  try {
90
- const listed = client?.tool?.list ? await client.tool.list() : null
129
+ const listed = client?.tool?.list ? await call(() => client.tool.list()) : null
91
130
  const rows = listed?.data ?? listed ?? null
92
131
  if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
93
132
  } catch { hostToolIds = null }
94
133
  const restriction = toolRestrictionFor(hostToolIds)
95
134
  if (typeof onRestriction === "function") onRestriction(restriction)
96
135
  // 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
97
- const created = await client.session.create({ body: { parentID: sessionId } })
136
+ const created = await call(() => client.session.create({ body: { parentID: sessionId } }))
98
137
  const childId = created?.data?.id ?? created?.id ?? null
99
138
  if (!childId) return { ok: false, error: "子会话没建起来" }
100
139
  // 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
@@ -104,15 +143,15 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
104
143
  // 走"同步驱动"这条路会卡住自己。改法(照宿主自己的两种姿势):
105
144
  // 优先 `promptAsync`(只入队,立刻返回)→ 轮询 `messages` 等 assistant 产出;
106
145
  // 没有 promptAsync 的宿主再退回同步 prompt(老姿势,风险已知)。
107
- const promptBody = { agent, tools: restriction.tools, parts: [{ type: "text", text: buildReviewPrompt(history) }] }
146
+ const promptBody = { agent, tools: restriction.tools, parts: [{ type: "text", text: prompt ?? buildReviewPrompt(history) }] }
108
147
  if (typeof client.session.promptAsync === "function") {
109
- await client.session.promptAsync({ path: { id: childId }, body: promptBody })
148
+ await call(() => client.session.promptAsync({ path: { id: childId }, body: promptBody }))
110
149
  } else {
111
- await client.session.prompt({ path: { id: childId }, body: promptBody })
150
+ await call(() => client.session.prompt({ path: { id: childId }, body: promptBody }))
112
151
  }
113
152
  // 轮询取回(最多 REVIEW_LIMITS.pollMs,默认 60s):看到 assistant 文本就走
114
153
  const deadline = Date.now() + pollMs
115
- let out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
154
+ let out = normalizeMessages(await call(() => client.session.messages({ path: { id: childId } })))
116
155
  while (Date.now() < deadline) {
117
156
  const msgs = normalizeMessages(out)
118
157
  const hasAssistantText = (Array.isArray(msgs) ? msgs : []).some((m) => {
@@ -123,19 +162,19 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
123
162
  return (Array.isArray(parts) ? parts : []).some((x) => x?.type === "text" && String(x.text ?? "").trim())
124
163
  })
125
164
  if (hasAssistantText) break
126
- await new Promise((r) => setTimeout(r, 1000))
127
- out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
165
+ await call(() => new Promise((r) => setTimeout(r, 1000)))
166
+ out = normalizeMessages(await call(() => client.session.messages({ path: { id: childId } })))
128
167
  }
129
168
  return { ok: true, childId, messages: normalizeMessages(out), restriction }
130
169
  } catch (e) {
131
- return { ok: false, error: String(e?.message ?? e) }
170
+ return { ok: false, error: String(e?.message ?? e), ...(signal?.aborted ? { cancelled: true } : {}) }
132
171
  }
133
172
  }
134
173
  }
135
174
 
136
175
  // 组装:宿主插件入口在回合结束(session.idle)时按**会话**调 onIdle。
137
176
  // 每个会话一份计数与一个 handler(计数要连得上,不能每次重建)。
138
- export function createReviewPipeline({ client, thresholds, store = null, cancelHandshakeMs = 2000, now = () => Date.now(), audit = null, toolsAvailable: declaredTools = null } = {}) {
177
+ export function createReviewPipeline({ client, thresholds, store = null, root = null, skillHostConfig = null, cancelHandshakeMs = 2000, now = () => Date.now(), audit = null, toolsAvailable: declaredTools = null } = {}) {
139
178
  const handlers = new Map()
140
179
  // 每个会话的运行态:在跑的复习子会话 id + 是否已被取消 + 那次作业的句柄。
141
180
  // A129:调度器只会说"取消",真正能对宿主发 abort 的是**执行体**(它持有 client 与子会话 id)。
@@ -161,10 +200,11 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
161
200
  toolAvail = (memory === null && skills === null) ? null : { memory, skills }
162
201
  return toolAvail
163
202
  }
164
- return {
165
- async onIdle(sessionId) {
166
- if (!sessionId) return { handled: false, reason: "no-session" }
167
- if (!handlers.has(sessionId)) {
203
+ // 每会话的处理器(惰性建)。onToolIteration 可能先于第一次 onIdle 到达(第一个回合里的
204
+ // 工具迭代)——创建入口必须两个方法共用,否则第一回合的迭代全被丢掉、阈值门永远差一步。
205
+ async function ensureHandler(sessionId) {
206
+ if (handlers.has(sessionId)) return handlers.get(sessionId)
207
+ {
168
208
  const run = { childId: null, cancelled: false, inflight: null, restriction: null, dispatchedAt: 0, lastUserMessageId: null, lastUserMessageAt: 0 }
169
209
  runs.set(sessionId, run)
170
210
  const review = createHostReview({ client, sessionId, onChild: (id) => { run.childId = id }, onRestriction: (r) => { run.restriction = r } })
@@ -275,6 +315,16 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
275
315
  }
276
316
  return { ...out, ok: false, error: `landing failed: ${String(e?.message ?? e)}` }
277
317
  }
318
+ // S1 通道④:技能车道(skill: 动作行 → SKILL.md)。只动 agent-created、闸门在动作层自认;
319
+ // 拒绝/忽略必须浮出。缺 root 就如实标 skipped(不猜目录、不静默)。
320
+ let skillLanded = { written: 0, staged: 0, ignored: [], refused: [], surface: null, mustSurface: false, skipped: "no-root" }
321
+ if (root) {
322
+ try {
323
+ skillLanded = await applySkillReviewActions({ root, actions, hostConfig: skillHostConfig })
324
+ } catch (e) {
325
+ skillLanded = { written: 0, staged: 0, ignored: [], refused: [{ op: "skill", name: null, error: String(e?.message ?? e) }], surface: `后台复习:技能面落地失败(${String(e?.message ?? e)})`, mustSurface: true }
326
+ }
327
+ }
278
328
  // A131:每次决策留一条**可核条目**——谁跑的、跑的时候工具面是什么、落了什么。
279
329
  // 记账失败不许影响宿主(吞掉),但条目本身要能被机器读。
280
330
  const decision = {
@@ -289,22 +339,57 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
289
339
  written: landed.written ?? 0,
290
340
  staged: landed.staged ?? 0,
291
341
  ignored: (landed.ignored ?? []).map((i) => i.op),
342
+ skillWritten: skillLanded.written ?? 0,
343
+ skillStaged: skillLanded.staged ?? 0,
344
+ skillRefused: (skillLanded.refused ?? []).map((f) => `${f.op}:${f.name ?? "?"}`),
292
345
  surface: landed.surface ?? null,
346
+ skillSurface: skillLanded.surface ?? null,
293
347
  }
348
+ // 提案必须浮出:有人看得见的那一行,发回宿主会话(memory 与技能两条车道的浮出行合并)
349
+ // 通知行=这次复习**做了什么**的摘要(直接写入也要报),不再是「只有提案才说话」。
350
+ const surfaceText = backgroundReviewBead({
351
+ memoryWritten: landed.written ?? 0,
352
+ memoryStaged: landed.staged ?? 0,
353
+ skillWritten: skillLanded.written ?? 0,
354
+ skillStaged: skillLanded.staged ?? 0,
355
+ refused: (skillLanded.refused ?? []).length,
356
+ ignored: (landed.ignored ?? []).length + (skillLanded.ignored ?? []).length,
357
+ })
358
+ const surfaced = surfaceText
359
+ ? await surfaceToHost({ client, sessionId, line: surfaceText, childId: out.childId ?? null })
360
+ : { posted: false, reason: "nothing-to-surface" }
361
+ // 投没投出去是两件事:决策条目里如实记(失败=未投递,不许写成功)
362
+ decision.surfacePosted = surfaced.posted === true
363
+ decision.surfaceReason = surfaced.reason ?? null
364
+ decision.surfaceChannel = surfaced.channel ?? null
294
365
  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 }
366
+ return { ...out, actions: actions.length, ...landed, skillLanded, surfaced, decision }
298
367
  },
299
368
  })
300
369
  handlers.set(sessionId, createTurnEndHandler({ scheduler, review: async () => ({}), sessionId }))
301
- }
370
+ }
371
+ return handlers.get(sessionId)
372
+ }
373
+
374
+ return {
375
+ async onIdle(sessionId) {
376
+ if (!sessionId) return { handled: false, reason: "no-session" }
377
+ await ensureHandler(sessionId)
302
378
  const r = await handlers.get(sessionId).onIdle()
303
379
  const run = runs.get(sessionId)
304
380
  if (r?.pending) run.inflight = r.pending // 交给 onUserTurnStart 握手的那个句柄
305
381
  return { handled: true, ...r }
306
382
  },
307
383
 
384
+ // S1 通道④触发源:宿主工具迭代(wire 按 callID 去重后)推进调度器计数;
385
+ // skill_manage 用过 ⇒ 重置(照 Hermes turn_iteration_prep:用过 skill_manage 就重新攒)。
386
+ async onToolIteration(sessionId, info = {}) {
387
+ if (!sessionId) return { counted: false, reason: "no-session" }
388
+ const h = await ensureHandler(sessionId)
389
+ if (typeof h?.noteIteration !== "function") return { counted: false, reason: "no-counter" }
390
+ return { counted: true, iterations: h.noteIteration({ skillUsed: Boolean(info?.skillUsed) }) }
391
+ },
392
+
308
393
  // 前台新回合开始 ⇒ 取消在跑的复习(照 Hermes `turn_facade.py` 的时机 + 取消握手)。
309
394
  // 返回如实:`settled:false` 表示握手超时、作业可能还在跑(不许假装已经停了)。
310
395
  // 只有**真的新回合**才取消。真机链实测(2026-09-21):宿主在一次回合里会连发多条
@@ -346,24 +431,82 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
346
431
  }
347
432
  }
348
433
 
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" } = {}) {
434
+ // 提案浮出(S1,通道已按 1.18.30 源码 + 真 TUI 探针定案):
435
+ // noReply:true ⇒ prompt.ts 直接 return,不进 agent loop(不驱动模型回合、不多花钱)
436
+ // part.ignored ⇒ message-v2 / compaction 都剔除(不进模型上下文与压缩摘要),但 TUI 仍渲染
437
+ // **不设 synthetic** ⇒ TUI 的 UserMessage 只拼 `type==="text" && !synthetic` 的 part,设了整段渲染为空
438
+ // part.metadata.ocg ⇒ 机器判定用,不靠文本前缀猜
439
+ // 只投给**已经有真实用户回合**的会话:标题生成也把「parts 不全是 synthetic 的用户消息」当真实用户消息,
440
+ // 新会话 + 默认标题 + 只收通知这条路会额外发一次模型请求(实测:计数 stub 0 次 vs 真实提示词 1 次)。
441
+ // 发不出去要如实记「未投递」,不许写成功;宿主调用失败一律吞掉(适配器不许弄崩宿主)。
442
+ const SURFACE_DEDUPE_MS = 10 * 60 * 1000
443
+ const surfaceSeen = new Map()
444
+
445
+ const lineDigest = (s) => {
446
+ let h = 2166136261
447
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0 }
448
+ return h.toString(16)
449
+ }
450
+ const seenRecently = (key, nowMs = Date.now()) => {
451
+ const ts = surfaceSeen.get(key)
452
+ return typeof ts === "number" && nowMs - ts <= SURFACE_DEDUPE_MS
453
+ }
454
+ const rememberSurface = (key, nowMs = Date.now()) => {
455
+ surfaceSeen.set(key, nowMs)
456
+ for (const [k, ts] of surfaceSeen) if (nowMs - ts > SURFACE_DEDUPE_MS) surfaceSeen.delete(k)
457
+ while (surfaceSeen.size > 200) surfaceSeen.delete(surfaceSeen.keys().next().value)
458
+ }
459
+
460
+ const isRealUserTurn = (m) => {
461
+ const role = m?.info?.role ?? m?.role
462
+ if (role !== "user") return false
463
+ const parts = Array.isArray(m?.parts) ? m.parts : []
464
+ if (parts.length === 0) return typeof m?.text === "string" && m.text.trim().length > 0
465
+ return parts.some((p) => p && p.type === "text" && typeof p.text === "string" && p.text.trim() && !p.ignored && !p.synthetic && p?.metadata?.ocg !== REVIEW_SURFACE_MARK)
466
+ }
467
+
468
+ async function sessionHasRealTurn(client, sessionId) {
469
+ const res = await client.session.messages({ path: { id: sessionId } })
470
+ const list = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : null
471
+ if (!list) return false
472
+ return list.some(isRealUserTurn)
473
+ }
474
+
475
+ export async function surfaceToHost({ client, sessionId, line, childId = null, mode = "notify" } = {}) {
357
476
  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
- }
477
+ if (mode === "pending-surface") return { posted: false, reason: "non-driving-surface", degraded: false, line }
361
478
  if (!sessionId) return { posted: false, reason: "no-session" }
362
479
  if (!client?.session?.prompt) return { posted: false, reason: "no-channel" }
480
+ if (mode === "prompt") {
481
+ // 兼容面:显式要求走会驱动模型的那条路(如实标注,调用方自己决定要不要)
482
+ try {
483
+ await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: String(line) }] } })
484
+ return { posted: true, drivesModelTurn: true, channel: "prompt" }
485
+ } catch {
486
+ return { posted: false, reason: "post-failed", channel: "prompt" }
487
+ }
488
+ }
489
+ const key = `${sessionId}|${childId ?? "-"}|${lineDigest(String(line))}`
490
+ if (seenRecently(key)) return { posted: false, reason: "duplicate", channel: "notify", line: String(line) }
491
+ if (typeof client.session.messages !== "function") return { posted: false, reason: "no-session-state", channel: "notify", line: String(line) }
492
+ let real = false
493
+ try {
494
+ real = await sessionHasRealTurn(client, sessionId)
495
+ } catch {
496
+ return { posted: false, reason: "session-state-failed", channel: "notify", line: String(line) }
497
+ }
498
+ if (!real) return { posted: false, reason: "no-real-turn", channel: "notify", line: String(line) }
363
499
  try {
364
- await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: line }] } })
365
- return { posted: true, drivesModelTurn: true } // 如实标注:这条路会驱动一次模型回合
500
+ await client.session.prompt({
501
+ path: { id: sessionId },
502
+ body: {
503
+ noReply: true,
504
+ parts: [{ type: "text", text: String(line), ignored: true, metadata: { ocg: REVIEW_SURFACE_MARK, childId } }],
505
+ },
506
+ })
507
+ rememberSurface(key)
508
+ return { posted: true, drivesModelTurn: false, reason: "posted", channel: "notify", childId, line: String(line) }
366
509
  } catch {
367
- return { posted: false, reason: "post-failed" }
510
+ return { posted: false, reason: "post-failed", channel: "notify", line: String(line) }
368
511
  }
369
512
  }
@@ -0,0 +1,66 @@
1
+ // S3b:会话检索工具的**定义**(真机 agent 可调用面)。
2
+ //
3
+ // 与 memory-tool.mjs 同形制:`tool`/`z` 由宿主注入(单测用替身);拿不到宿主 zod 时
4
+ // 注册侧 fail-soft 退回没有工具,不弄挂注入/冻结。工具名 Hermes 同款 `session_search`,
5
+ // 四形状走 `mode`(discover/scroll/read/browse),回执即信封。
6
+ import { createSessionTool } from "../core/session-tool.mjs"
7
+
8
+ const identityTool = (def) => def
9
+
10
+ export const SESSION_SEARCH_TOOL_DESCRIPTION = [
11
+ "跨项目搜回会话逐字原文(记忆②层:会话检索)。四形状:",
12
+ "discover=搜索(limit 3、会话级去重、命中带 match_part_id 可续读);",
13
+ "scroll=从命中点取上下文窗口(match_part_id 锚点,真实字符串 message ID);",
14
+ "read=读会话头尾窗口,或大 part 分块(part_id+part_offset+part_fingerprint,指纹不符报 stale-anchor);",
15
+ "browse=最近会话与计数。",
16
+ "中文 2 字起命中;零命中自动放宽并在结果标 route=relaxed;源不可用时旧命中带 stale、空集只说「未核对」。",
17
+ ].join("")
18
+
19
+ /** OpenCode ToolDefinition:args 进模型 schema,output 字符串承载原有 JSON 信封。 */
20
+ export function registerSessionSearchTool({ root, z, tool = identityTool } = {}) {
21
+ const t = typeof tool === "function" ? tool : identityTool
22
+ return t({
23
+ description: SESSION_SEARCH_TOOL_DESCRIPTION,
24
+ args: {
25
+ mode: z.enum(["discover", "scroll", "read", "browse"]).optional(),
26
+ query: z.string().optional().describe("discover 的查询词(支持 AND/OR/NOT/引号短语/尾*前缀)"),
27
+ session_id: z.string().optional(),
28
+ match_part_id: z.string().optional().describe("scroll 的锚点 part(discover 命中里的 match_part_id)"),
29
+ around_message_id: z.string().optional(),
30
+ part_id: z.string().optional().describe("read 分块读的 part"),
31
+ part_offset: z.number().optional(),
32
+ part_fingerprint: z.string().optional().describe("分块续读指纹(不符报 stale-anchor)"),
33
+ position: z.enum(["head", "tail"]).optional(),
34
+ window: z.number().optional(),
35
+ limit: z.number().optional(),
36
+ role: z.string().optional(),
37
+ since: z.string().optional(),
38
+ until: z.string().optional(),
39
+ includeToolOutput: z.boolean().optional(),
40
+ noRelax: z.boolean().optional(),
41
+ dedupe: z.enum(["session", "none"]).optional(),
42
+ },
43
+ async execute(input) {
44
+ const face = createSessionTool({ root })
45
+ const mode = input?.mode ?? "discover"
46
+ // own-property 判定:face[mode] 走原型链会把 constructor/toString 当成形状方法。
47
+ const named = Object.hasOwn(face, mode)
48
+ const fn = named ? face[mode] : null
49
+ const receipt = named && typeof fn === "function" ? await fn({ ...(input ?? {}) }) : {
50
+ success: false,
51
+ mode: String(mode),
52
+ state: "usage",
53
+ coverage: null,
54
+ as_of: null,
55
+ error: `未知 mode:${mode}`,
56
+ repair_hint: "mode 只能是 discover / scroll / read / browse",
57
+ }
58
+ // 与 memory 工具同形制:核心信封保持原样,宿主消费明确的文本 output。
59
+ return {
60
+ title: receipt.success ? "会话检索" : "会话检索未完成",
61
+ output: JSON.stringify(receipt),
62
+ metadata: { success: receipt.success, mode: receipt.mode, state: receipt.state },
63
+ }
64
+ },
65
+ })
66
+ }
@@ -0,0 +1,221 @@
1
+ // S1 形成面 · `skill` 工具的**定义**(照 `memory-tool.mjs` 形制)。
2
+ //
3
+ // 这一层只做一件事:把宿主给的上下文(谁的会话、有没有确认通道、宿主闸状态)
4
+ // 变成动作层的输入,并**把认账回执渲染出来**。写盘、校验、闸门分流全在
5
+ // `src/core/skill-actions.mjs`,这里不做 IO。
6
+ //
7
+ // 三条与 memory-tool 同款的硬形制:
8
+ // 1. 宿主的 `tool()` 是恒等函数 ⇒ 不 import `@opencode-ai/plugin`;
9
+ // 2. args 里**没有** origin / agent / created_by——模型不能自报身份、不能自贴 agent-created;
10
+ // 3. 注册 fail-soft:拿不到 zod 就返回 `__error`,不炸整个插件(冻结/注入还在)。
11
+ //
12
+ // 认账回执(§6 规则①⑤):成功/失败/待批都渲染 status+name+location/detail——
13
+ // 「跳过认账回执」的变异会让 test/skill-tool.test.mjs ③⑤⑦ 一起红。
14
+ import fs from "node:fs"
15
+ import path from "node:path"
16
+ import { pathToFileURL } from "node:url"
17
+
18
+ import { SKILL_ACTIONS, runSkillAction, skillGateFromHostConfig } from "../core/skill-actions.mjs"
19
+ import { identityFor } from "../core/memory-actions.mjs"
20
+ import { readExternalDirs } from "../core/skills.mjs"
21
+
22
+ /** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
23
+ const identityTool = (def) => def
24
+
25
+ /**
26
+ * 无人值守的 agent 名单。**部署者配置的东西,不是模型能碰的**——
27
+ * 与 memory-tool 同一份名单,同一套身份推导。
28
+ */
29
+ export const DEFAULT_BACKGROUND_AGENTS = ["ocg-learn"]
30
+
31
+ export const SKILL_TOOL_DESCRIPTION = [
32
+ "创建与增长跨项目技能(形制照 Hermes skill_manage):skills/<name>/SKILL.md 一目录一技能。",
33
+ "create:新建技能(name 小写连字符;description 必填 ≤60 字符、`Use when …` 句式;正文为技能手册);",
34
+ "patch:在**同一文件**里定点改写(old_string 必须唯一命中);view:读技能正文(记一笔使用账);list:查看现有技能与触发句;",
35
+ "archive:归档技能(只搬不删,进 skills/.archive/)——**必须**带 absorbed_into=<伞技能名> 点名合并去向(伞须已存在)。",
36
+ "写入前会做静态校验(名称/触发句/布局)并回执认账要素(name+location);",
37
+ "同名已存在、校验不通过、宿主禁用或跨来源同名时会明说「未生效/冲突」,不会谎报已交付。",
38
+ ].join("")
39
+
40
+ /** 把动作结果渲染成一段模型和人都读得懂的话(认账回执的呈现层)。 */
41
+ export function renderSkillResult(r) {
42
+ if (!r || typeof r !== "object") return "技能操作没有返回结果。"
43
+ const rec = r.receipt ?? {}
44
+ const head = `${rec.status ?? (r.ok === false ? "未生效" : "已交付")}`
45
+ if (r.ok === false) {
46
+ return [`技能操作${head}:${r.error ?? r.reason ?? "未知原因"}`,
47
+ rec.name ? `对象:${rec.name}` : null,
48
+ rec.location ? `位置:${rec.location}` : null,
49
+ rec.detail ? `依据:${rec.detail}` : null,
50
+ ].filter(Boolean).join("\n")
51
+ }
52
+ if (r.staged) {
53
+ return `技能提案已排入待批(${r.action}):${rec.name ?? ""}${rec.file ? ` → ${rec.file}` : ""}。它在有人确认前不会生效。`
54
+ }
55
+ switch (r.action) {
56
+ case "list": {
57
+ const items = r.skills ?? []
58
+ if (!items.length) return "没有技能。"
59
+ return [`技能 ${items.length} 个:`, ...items.map((s, i) => `${i + 1}. ${s.name} —— ${s.description ?? "(无 description)"} [${s.location}]`)].join("\n")
60
+ }
61
+ case "view": {
62
+ return [`技能${head}(view)`,
63
+ `对象:${rec.name ?? "?"}`,
64
+ `位置:${rec.location ?? "?"}`,
65
+ "正文:",
66
+ String(r.content ?? ""),
67
+ ].join("\n")
68
+ }
69
+ default:
70
+ return [`技能${head}(${r.action})`,
71
+ `对象:${rec.name ?? "?"}`,
72
+ `位置:${rec.location ?? "?"}`,
73
+ rec.createdBy ? `归属:${rec.createdBy}` : null,
74
+ ].filter(Boolean).join("\n")
75
+ }
76
+ }
77
+
78
+ export function buildSkillTool({
79
+ tool,
80
+ z,
81
+ root,
82
+ backgroundAgents = DEFAULT_BACKGROUND_AGENTS,
83
+ foregroundAgents = (process.env.OCG_FOREGROUND_AGENTS ?? "").split(",").map((x) => x.trim()).filter(Boolean),
84
+ /** 部署方声明:这个会话面真的有人能回答确认框吗(与 memory-tool 同款语义)。 */
85
+ interactive = process.env.OCG_INTERACTIVE === "1",
86
+ /**
87
+ * 宿主配置(opencode.json 的解析结果)。给 null 就按「宿主闸全开」走——
88
+ * 回执认账要素里 hostPermission/agentSkillEnabled 由 `skillGateFromHostConfig` 从它推。
89
+ * 三夹具(permission.skill.<name>=deny / 目标 agent tools.skill:false / 跨来源同名)
90
+ * 就在这条链上被判成「未生效/冲突」。
91
+ */
92
+ hostConfig = null,
93
+ } = {}) {
94
+ if (!z?.enum || !z?.string) throw new Error("buildSkillTool 需要宿主给的 z")
95
+ const wrap = typeof tool === "function" ? tool : identityTool
96
+ if (!root) throw new Error("buildSkillTool 需要 root(D 目录)")
97
+
98
+ return wrap({
99
+ description: SKILL_TOOL_DESCRIPTION,
100
+ args: {
101
+ action: z.enum(SKILL_ACTIONS).describe("要做什么"),
102
+ name: z.string().optional().describe("技能名(小写连字符;create/patch/list 都要)"),
103
+ description: z.string().optional().describe("create 用:`Use when <触发>. <一行行为>.`,≤60 字符"),
104
+ content: z.string().optional().describe("create 用:技能正文(Markdown 手册)"),
105
+ old_string: z.string().optional().describe("patch 用:要替换的原文(必须唯一命中)"),
106
+ new_string: z.string().optional().describe("patch 用:替换后的新文"),
107
+ absorbed_into: z.string().optional().describe("archive 用:合并去向的伞技能名(必须已存在)"),
108
+ // 注意这里**没有** origin / agent / created_by:身份与归属由宿主 ctx 和
109
+ // 部署者名单决定(extra#4),created_by 由动作层按身份写进 frontmatter。
110
+ },
111
+ async execute(args, ctx) {
112
+ const ask = typeof ctx?.ask === "function" ? (input) => ctx.ask(input) : null
113
+ const identity = identityFor({
114
+ agent: ctx?.agent ?? null,
115
+ hasAsk: Boolean(ask),
116
+ interactive,
117
+ backgroundAgents,
118
+ foregroundAgents,
119
+ })
120
+ const name = args?.name ?? ""
121
+ const gate = skillGateFromHostConfig({ hostConfig: hostConfig ?? {}, agent: ctx?.agent ?? null, name })
122
+ const r = await runSkillAction({
123
+ root,
124
+ identity,
125
+ action: args?.action,
126
+ name,
127
+ description: args?.description,
128
+ content: args?.content,
129
+ old_string: args?.old_string,
130
+ new_string: args?.new_string,
131
+ absorbedInto: args?.absorbed_into,
132
+ ask,
133
+ hostPermission: gate.hostPermission,
134
+ agentSkillEnabled: gate.agentSkillEnabled,
135
+ externalDirs: readExternalDirs(root),
136
+ })
137
+ return {
138
+ title: r.ok === false ? "技能操作未完成" : r.staged ? "已排入待批" : "技能已更新",
139
+ output: renderSkillResult(r),
140
+ metadata: {
141
+ ok: r.ok !== false,
142
+ staged: Boolean(r.staged),
143
+ action: r.action ?? null,
144
+ origin: r.origin ?? null,
145
+ receiptStatus: r.receipt?.status ?? null,
146
+ },
147
+ }
148
+ },
149
+ })
150
+ }
151
+
152
+ /**
153
+ * 在插件里注册:**动态** import 宿主 zod,失败不炸整个插件。
154
+ * zod 由宿主装在 `<XDG_CONFIG_HOME>/opencode/node_modules/`(插件目录的上一级),
155
+ * 从仓库 `src/` 直接 import 会失败——解析基线不同(真机探针实测)。
156
+ */
157
+ async function loadZod() {
158
+ try {
159
+ const m = await import("zod")
160
+ const z = m?.z ?? m?.default?.z ?? m?.default
161
+ if (typeof z?.object === "function") return z
162
+ } catch {
163
+ /* 解析基线不对,往下走 */
164
+ }
165
+ const roots = [
166
+ process.env.XDG_CONFIG_HOME,
167
+ process.env.APPDATA,
168
+ process.env.HOME ? path.join(process.env.HOME, ".config") : null,
169
+ ].filter(Boolean)
170
+ for (const r of roots) {
171
+ for (const rel of ["opencode/node_modules/zod/index.cjs", "opencode/node_modules/zod/index.js"]) {
172
+ const p = path.join(r, rel)
173
+ try {
174
+ if (!fs.existsSync(p)) continue
175
+ const m = await import(pathToFileURL(p).href)
176
+ const z = m?.z ?? m?.default?.z ?? m?.default
177
+ if (typeof z?.object === "function") return z
178
+ } catch {
179
+ /* 换下一个 */
180
+ }
181
+ }
182
+ }
183
+ return null
184
+ }
185
+
186
+ /**
187
+ * 宿主配置(`<配置根>/opencode/opencode.json`)的**只读**取用:给认账闸(三夹具)供原料。
188
+ * 读不到 / 坏 JSON ⇒ `{}`(=宿主闸全开),不猜。配置根与 zod 同款(XDG_CONFIG_HOME / APPDATA / ~/.config)。
189
+ */
190
+ export function readHostConfig() {
191
+ const roots = [
192
+ process.env.XDG_CONFIG_HOME,
193
+ process.env.APPDATA,
194
+ process.env.HOME ? path.join(process.env.HOME, ".config") : null,
195
+ ].filter(Boolean)
196
+ for (const r of roots) {
197
+ const p = path.join(r, "opencode", "opencode.json")
198
+ try {
199
+ if (!fs.existsSync(p)) continue
200
+ const cfg = JSON.parse(fs.readFileSync(p, "utf8"))
201
+ if (cfg && typeof cfg === "object") return cfg
202
+ } catch {
203
+ /* 换下一个 / 坏 JSON 当没有 */
204
+ }
205
+ }
206
+ return {}
207
+ }
208
+
209
+ export async function registerSkillTool({ root, z = null, tool = null, backgroundAgents = DEFAULT_BACKGROUND_AGENTS, foregroundAgents = undefined, interactive = undefined, hostConfig = null } = {}) {
210
+ try {
211
+ const resolvedZ = z ?? (await loadZod())
212
+ if (!resolvedZ) return { __error: "技能工具未能注册:拿不到宿主的 zod(会在插件目录或宿主配置根里找)" }
213
+ return buildSkillTool({
214
+ tool: tool ?? identityTool, z: resolvedZ, root, backgroundAgents, hostConfig: hostConfig ?? null,
215
+ ...(foregroundAgents !== undefined ? { foregroundAgents } : {}),
216
+ ...(interactive !== undefined ? { interactive } : {}),
217
+ })
218
+ } catch (err) {
219
+ return { __error: `技能工具未能注册:${err?.message ?? err}` }
220
+ }
221
+ }