opencode-growth 0.1.1 → 0.1.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -30
- package/package.json +3 -3
- package/src/adapter-opencode/curator-runner.mjs +254 -0
- package/src/adapter-opencode/index.mjs +305 -19
- package/src/adapter-opencode/install.mjs +63 -12
- package/src/adapter-opencode/journey-tool.mjs +57 -0
- package/src/adapter-opencode/memory-tool.mjs +57 -5
- package/src/adapter-opencode/provider-tools.mjs +237 -0
- package/src/adapter-opencode/review-runner.mjs +75 -21
- package/src/adapter-opencode/session-search-tool.mjs +66 -0
- package/src/adapter-opencode/skill-tool.mjs +221 -0
- package/src/cli/commands.mjs +74 -1
- package/src/cli/curator-cmd.mjs +147 -0
- package/src/cli/journey-cmd.mjs +61 -0
- package/src/cli/journey-view.mjs +174 -0
- package/src/cli/main.mjs +172 -25
- package/src/cli/memory-cmd.mjs +165 -0
- package/src/cli/session-index-cmd.mjs +74 -0
- package/src/cli/skill-cmd.mjs +192 -0
- package/src/core/approve.mjs +155 -0
- package/src/core/audit.mjs +51 -0
- package/src/core/background-review.mjs +88 -1
- package/src/core/home.mjs +56 -21
- package/src/core/journey.mjs +298 -0
- package/src/core/lock.mjs +6 -0
- package/src/core/memories.mjs +186 -9
- package/src/core/memory-actions.mjs +73 -18
- package/src/core/session-freshness.mjs +201 -0
- package/src/core/session-index.mjs +467 -0
- package/src/core/session-query.mjs +161 -0
- package/src/core/session-source.mjs +202 -0
- package/src/core/session-tool.mjs +181 -0
- package/src/core/skill-actions.mjs +372 -0
- package/src/core/skill-backup.mjs +95 -0
- package/src/core/skill-lifecycle.mjs +265 -0
- package/src/core/skill-usage.mjs +119 -0
- package/src/core/skills.mjs +28 -2
- package/src/core/sqlite-runtime.mjs +35 -0
- package/src/core/write-approval.mjs +13 -9
- package/src/host/rest-client.mjs +70 -0
- package/src/provider/config.mjs +187 -0
- package/src/provider/openviking-rest.mjs +742 -0
- package/src/provider/runtime.mjs +417 -0
- package/src/provider/wiring.mjs +164 -0
|
@@ -30,6 +30,9 @@ export const MEMORY_TOOL_DESCRIPTION = [
|
|
|
30
30
|
"读取与维护跨项目长期记忆(两个库:memory=事实与偏好,user=用户画像)。",
|
|
31
31
|
"add:追加一条;update:按内容子串**唯一命中**地改写;remove:按内容子串**唯一命中**地删除;",
|
|
32
32
|
"list:查看当前内容与用量;pending:查看待批提案。",
|
|
33
|
+
"整理一个库时用 operations(批量):一次给出一串 {action: add|update|remove, text, match},",
|
|
34
|
+
"整批**全成或全败**——任一项没命中/非法/超限,整批不写(可先 free 空间再写,校验只看最终态);",
|
|
35
|
+
"一批只碰一个库(库由 kind 决定,项里不要写 kind)。",
|
|
33
36
|
"注意:改/删在对话里会先请你确认;无人值守的会话里只会排进待批,不会直接生效。",
|
|
34
37
|
].join("")
|
|
35
38
|
|
|
@@ -51,6 +54,13 @@ export function renderResult(r) {
|
|
|
51
54
|
return ["待批提案:", ...r.pending.map((p, i) => `${i + 1}. [${p.origin}] ${p.op} ${p.kind}${p.match ? ` match=${p.match}` : ""}${p.text ? ` text=${p.text}` : ""}`)].join("\n")
|
|
52
55
|
case "add":
|
|
53
56
|
return `已记下(第 ${r.entries} 条)· 当前 ${r.used}/${r.limit} 字符`
|
|
57
|
+
case "batch": {
|
|
58
|
+
const changed = (r.matchedEntries ?? []).filter(Boolean)
|
|
59
|
+
return (
|
|
60
|
+
`整批 ${r.applied} 笔已落定(全成或全败)· 当前 ${r.entries} 条 · ${r.used}/${r.limit} 字符` +
|
|
61
|
+
(changed.length ? `\n被改写的原条目(${changed.length} 条,可据此回退):\n` + changed.map((c, i) => `${i + 1}. ${c}`).join("\n") : "")
|
|
62
|
+
)
|
|
63
|
+
}
|
|
54
64
|
default:
|
|
55
65
|
return `已完成 ${r.action} · 当前 ${r.entries} 条`
|
|
56
66
|
}
|
|
@@ -68,18 +78,32 @@ export function buildMemoryTool({
|
|
|
68
78
|
// **部署方的声明**:这个会话面真的有人能回答确认框吗?
|
|
69
79
|
// 实测无头 `run` 里 `ctx.ask` 会立刻返回(没人看过),所以「有 ask」不能当证据。
|
|
70
80
|
interactive = process.env.OCG_INTERACTIVE === "1",
|
|
81
|
+
// 片 5 接线:可选 provider 运行时(缺席 null ⇒ 行为与接线前完全一致)
|
|
82
|
+
runtime = null,
|
|
71
83
|
} = {}) {
|
|
72
|
-
if (typeof tool !== "function") throw new Error("buildMemoryTool 需要宿主给的 tool 工厂")
|
|
73
84
|
if (!z?.enum || !z?.string) throw new Error("buildMemoryTool 需要宿主给的 z")
|
|
85
|
+
// 真机形状(2026-09-24 trace 实测 hasTool:false):宿主不注入 tool 工厂;tool() 源码即恒等 ⇒ 缺省等价
|
|
86
|
+
const wrap = typeof tool === "function" ? tool : (def) => def
|
|
74
87
|
if (!root) throw new Error("buildMemoryTool 需要 root(D 目录)")
|
|
75
88
|
|
|
76
|
-
return
|
|
89
|
+
return wrap({
|
|
77
90
|
description: MEMORY_TOOL_DESCRIPTION,
|
|
78
91
|
args: {
|
|
79
92
|
action: z.enum(MEMORY_ACTIONS).describe("要做什么"),
|
|
80
93
|
kind: z.enum(["memory", "user"]).optional().describe("哪个库,默认 memory"),
|
|
81
94
|
text: z.string().optional().describe("add/update 的正文"),
|
|
82
95
|
match: z.string().optional().describe("update/remove 的内容子串(必须唯一命中)"),
|
|
96
|
+
// 批量(G3):给了 operations 就忽略 action,整批原子。项形状与单条面同名(action/text/match)。
|
|
97
|
+
operations: z
|
|
98
|
+
.array(
|
|
99
|
+
z.object({
|
|
100
|
+
action: z.enum(["add", "update", "remove"]).describe("这一笔做什么"),
|
|
101
|
+
text: z.string().optional().describe("这一笔 add/update 的正文"),
|
|
102
|
+
match: z.string().optional().describe("这一笔 update/remove 的内容子串(必须唯一命中)"),
|
|
103
|
+
}),
|
|
104
|
+
)
|
|
105
|
+
.optional()
|
|
106
|
+
.describe("批量:一次多笔,全成或全败;与 action 二选一(一批只碰一个库)"),
|
|
83
107
|
// 注意这里**没有** origin / agent / sessionID:
|
|
84
108
|
// 身份由宿主给的 ctx 与部署者的名单决定,模型无从申报(extra#4)。
|
|
85
109
|
},
|
|
@@ -94,6 +118,7 @@ export function buildMemoryTool({
|
|
|
94
118
|
foregroundAgents,
|
|
95
119
|
})
|
|
96
120
|
const r = await runMemoryAction({
|
|
121
|
+
operations: Array.isArray(args?.operations) && args.operations.length ? args.operations : undefined,
|
|
97
122
|
root,
|
|
98
123
|
identity,
|
|
99
124
|
action: args?.action,
|
|
@@ -102,10 +127,37 @@ export function buildMemoryTool({
|
|
|
102
127
|
match: args?.match,
|
|
103
128
|
ask,
|
|
104
129
|
})
|
|
130
|
+
// §6.2-14:只在确认落盘后镜像(门禁在 runtime:applied && !staged && !applyError、writeId 幂等)
|
|
131
|
+
let mirror = null
|
|
132
|
+
if (runtime) {
|
|
133
|
+
try {
|
|
134
|
+
const queued = runtime.onMemoryWrite({
|
|
135
|
+
writeId: `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
136
|
+
action: r.action,
|
|
137
|
+
target: args?.kind ?? "memory",
|
|
138
|
+
content: String(args?.text ?? args?.match ?? ""),
|
|
139
|
+
metadata: { origin: r.origin ?? null },
|
|
140
|
+
applied: r.ok !== false && !r.staged && ["add", "update", "remove"].includes(r.action),
|
|
141
|
+
staged: Boolean(r.staged),
|
|
142
|
+
applyError: r.ok === false,
|
|
143
|
+
})
|
|
144
|
+
// 不阻塞调用方(照 H `_spawn_tracked` 的后台线程语义):踢一次后台镜像就走,
|
|
145
|
+
// 远端慢/卡死由 runtime 的单请求上界与 drain 上界兜住,绝不拖住这个工具回合。
|
|
146
|
+
if (queued) mirror = runtime.kickMirror()
|
|
147
|
+
} catch { /* 镜像失败不影响本地(runtime 侧 best-effort) */ }
|
|
148
|
+
}
|
|
105
149
|
return {
|
|
106
150
|
title: r.ok === false ? "记忆操作未完成" : r.staged ? "已排入待批" : "记忆已更新",
|
|
107
151
|
output: renderResult(r),
|
|
108
|
-
metadata: {
|
|
152
|
+
metadata: {
|
|
153
|
+
ok: r.ok !== false,
|
|
154
|
+
staged: Boolean(r.staged),
|
|
155
|
+
action: r.action ?? null,
|
|
156
|
+
origin: r.origin ?? null,
|
|
157
|
+
// 远端状态**分开报告**(本地写入 vs 远端镜像):queued 表示后台在途,不是失败,
|
|
158
|
+
// 也不许当成已完成(S2「故障不伪装成零命中」)。
|
|
159
|
+
external: mirror ? { queued: mirror.pending } : { queued: 0 },
|
|
160
|
+
},
|
|
109
161
|
}
|
|
110
162
|
},
|
|
111
163
|
})
|
|
@@ -153,14 +205,14 @@ async function loadZod() {
|
|
|
153
205
|
return null
|
|
154
206
|
}
|
|
155
207
|
|
|
156
|
-
export async function registerMemoryTool({ root, z = null, tool = null, backgroundAgents = DEFAULT_BACKGROUND_AGENTS, foregroundAgents = undefined, interactive = undefined } = {}) {
|
|
208
|
+
export async function registerMemoryTool({ root, z = null, tool = null, backgroundAgents = DEFAULT_BACKGROUND_AGENTS, foregroundAgents = undefined, interactive = undefined, runtime = undefined } = {}) {
|
|
157
209
|
try {
|
|
158
210
|
const resolvedZ = z ?? (await loadZod())
|
|
159
211
|
if (!resolvedZ) return { __error: "记忆工具未能注册:拿不到宿主的 zod(会在插件目录或宿主配置根里找)" }
|
|
160
212
|
// C①:**绑定时刻的值**优先(由插件工厂传给我们的那份),拿不到才回退读环境——
|
|
161
213
|
// 免得"进程里后来有人改了环境变量"把已经建好的实例行为改掉(多配置根串用类问题的根)。
|
|
162
214
|
return buildMemoryTool({
|
|
163
|
-
tool: tool ?? identityTool, z: resolvedZ, root, backgroundAgents,
|
|
215
|
+
tool: tool ?? identityTool, z: resolvedZ, root, backgroundAgents, runtime: runtime ?? null,
|
|
164
216
|
...(foregroundAgents !== undefined ? { foregroundAgents } : {}),
|
|
165
217
|
...(interactive !== undefined ? { interactive } : {}),
|
|
166
218
|
})
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// S3 · ③层工具面(照 Hermes 六件:viking_search / viking_read / viking_browse /
|
|
2
|
+
// viking_remember / viking_forget / viking_add_resource)。
|
|
3
|
+
//
|
|
4
|
+
// 对齐口径(锁版本 b9d5e4d1):
|
|
5
|
+
// - **名称/描述/参数逐字照 H** `_TOOL_SCHEMAS`(:390-450 的六个 schema 常量)
|
|
6
|
+
// - 只读三件(search/read/browse)**结果不回灌**(H `_OPENVIKING_RECALL_TOOL_NAMES` 同理:
|
|
7
|
+
// 把召回内容再喂回去会被重新存储)
|
|
8
|
+
// - read 三档照 H `:72-73`:abstract=/api/v1/content/abstract、overview=/content/overview、
|
|
9
|
+
// full=/content/read;摘要档是**目录级**,文件走 fs/stat 探测后退回全文读(H `_read_uri_payload`)
|
|
10
|
+
// - 批读上限照 H `:70-71`:一次最多 3 个 URI;多 URI 时 full 单条限 2500 字符
|
|
11
|
+
// - 工具面**只在 provider 在场时**注册(与 H 同:插件没启用就没有这些工具)
|
|
12
|
+
//
|
|
13
|
+
// 我们的缺口**如实返回**(不假装成功):`add_resource` 走临时上传/资源索引,我们的适配器
|
|
14
|
+
// 尚未实现该面 ⇒ 返回 `{ok:false, gap}`(沿用 provider `update/remove` 的既有先例)。
|
|
15
|
+
import { RECALL_FENCE } from "../provider/runtime.mjs"
|
|
16
|
+
|
|
17
|
+
/** 一次读取的批量上限(照 H `:70`)。 */
|
|
18
|
+
const READ_BATCH_LIMIT = 3
|
|
19
|
+
/** 多 URI 时 full 档单条字符上限(照 H `:71`)。 */
|
|
20
|
+
const READ_BATCH_FULL_LIMIT = 2500
|
|
21
|
+
/** 三档端点(照 H `:72`)。 */
|
|
22
|
+
const LEVEL_ENDPOINTS = { abstract: "/api/v1/content/abstract", overview: "/api/v1/content/overview", full: "/api/v1/content/read" }
|
|
23
|
+
/** 摘要档字符上限(照 H `:73`)。 */
|
|
24
|
+
const LEVEL_MAX_CHARS = { abstract: 1200, overview: 4000 }
|
|
25
|
+
|
|
26
|
+
export const PROVIDER_TOOLS_SOURCE = "hermes:openviking/_TOOL_SCHEMAS@b9d5e4d1"
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 六个工具的定义(描述逐字照 H)。`call` 是 provider 侧的取数函数,返回 {ok, ...}。
|
|
30
|
+
* 单测用替身,运行时用真 OpenVikingRest。
|
|
31
|
+
*/
|
|
32
|
+
export function buildProviderTools({ provider, z, tool = null } = {}) {
|
|
33
|
+
const t = typeof tool === "function" ? tool : (def) => def
|
|
34
|
+
// Hermes 的 parameters 在宿主边界统一转为 OpenCode args;工厂只收一个定义对象。
|
|
35
|
+
const mk = ({ parameters, ...def }) => t({ ...def, args: parameters })
|
|
36
|
+
|
|
37
|
+
const tools = {}
|
|
38
|
+
|
|
39
|
+
tools.viking_search = mk({
|
|
40
|
+
description:
|
|
41
|
+
"Semantic search over the OpenViking knowledge base. Returns ranked results with viking:// URIs for deeper reading. " +
|
|
42
|
+
"Use mode='deep' for complex queries that need reasoning across multiple sources, 'fast' for simple lookups.",
|
|
43
|
+
parameters: {
|
|
44
|
+
query: z.string().describe("Search query."),
|
|
45
|
+
mode: z.enum(["auto", "fast", "deep"]).optional().describe("Search depth (default: auto)."),
|
|
46
|
+
scope: z.string().optional().describe("Viking URI prefix to scope search (e.g. 'viking://resources/docs/')."),
|
|
47
|
+
limit: z.number().optional().describe("Max results (default: 10)."),
|
|
48
|
+
},
|
|
49
|
+
async execute(input = {}) {
|
|
50
|
+
const query = String(input.query ?? "").trim()
|
|
51
|
+
if (!query) return { output: JSON.stringify({ ok: false, error: "query is required" }), metadata: { ok: false } }
|
|
52
|
+
const limit = Number.isFinite(Number(input.limit)) ? Math.max(1, Number(input.limit)) : 10
|
|
53
|
+
const mode = input.mode ?? "auto"
|
|
54
|
+
try {
|
|
55
|
+
const res = await provider.search(query, {
|
|
56
|
+
limit,
|
|
57
|
+
scope: input.scope,
|
|
58
|
+
deep: mode === "deep",
|
|
59
|
+
contextType: ["memory", "resource"],
|
|
60
|
+
})
|
|
61
|
+
// 结果逐条带 uri(③层的来源可追);分数照实给,缺分不编
|
|
62
|
+
return {
|
|
63
|
+
output: JSON.stringify({ ok: true, mode, query, results: res.results ?? [], total: res.results?.length ?? 0 }),
|
|
64
|
+
metadata: { ok: true, hits: res.results?.length ?? 0, mode },
|
|
65
|
+
}
|
|
66
|
+
} catch (e) {
|
|
67
|
+
return { output: JSON.stringify({ ok: false, error: String(e?.message ?? e) }), metadata: { ok: false, state: "error" } }
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
tools.viking_read = mk({
|
|
73
|
+
description:
|
|
74
|
+
"Read one or a few specific viking:// URIs returned by viking_search or viking_browse. Three detail levels:\n" +
|
|
75
|
+
" abstract — ~100 token summary (L0)\n overview — ~2k token key points (L1)\n full — complete content (L2)\n" +
|
|
76
|
+
"Start with abstract/overview, only use full when you need details. For multiple strong candidates, pass uris with up to three URIs.",
|
|
77
|
+
parameters: {
|
|
78
|
+
uri: z.string().optional().describe("Single viking:// URI to read."),
|
|
79
|
+
uris: z.array(z.string()).optional().describe("Optional batch of up to three viking:// URIs to read."),
|
|
80
|
+
level: z.enum(["abstract", "overview", "full"]).optional().describe("Detail level (default: overview)."),
|
|
81
|
+
},
|
|
82
|
+
async execute(input = {}) {
|
|
83
|
+
const level = ["abstract", "overview", "full"].includes(input.level) ? input.level : "overview"
|
|
84
|
+
const raw = Array.isArray(input.uris) && input.uris.length ? input.uris : [input.uri]
|
|
85
|
+
const uris = [...new Set(raw.filter((u) => typeof u === "string" && u.trim()).map((u) => u.trim()))]
|
|
86
|
+
if (!uris.length) return { output: JSON.stringify({ ok: false, error: "uri or uris is required" }), metadata: { ok: false } }
|
|
87
|
+
const selected = uris.slice(0, READ_BATCH_LIMIT)
|
|
88
|
+
const perItem = selected.length > 1 && level === "full" ? READ_BATCH_FULL_LIMIT : null
|
|
89
|
+
const results = []
|
|
90
|
+
for (const uri of selected) {
|
|
91
|
+
try {
|
|
92
|
+
results.push(await readUri(provider, uri, level, perItem))
|
|
93
|
+
} catch (e) {
|
|
94
|
+
results.push({ uri, level, error: String(e?.message ?? e) })
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const payload = selected.length === 1 && !Array.isArray(input.uris)
|
|
98
|
+
? results[0]
|
|
99
|
+
: { level, results, requested: uris.length, returned: results.length, truncated: uris.length > selected.length }
|
|
100
|
+
const failed = results.filter((r) => r.error).length
|
|
101
|
+
return {
|
|
102
|
+
output: JSON.stringify(payload),
|
|
103
|
+
metadata: { ok: failed === 0, level, read: results.length - failed, failed },
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
tools.viking_browse = mk({
|
|
109
|
+
description:
|
|
110
|
+
"Browse the OpenViking knowledge store like a filesystem.\n list — show directory contents\n tree — show hierarchy\n stat — show metadata for a URI",
|
|
111
|
+
parameters: {
|
|
112
|
+
action: z.enum(["tree", "list", "stat"]).describe("Browse action."),
|
|
113
|
+
path: z.string().optional().describe("Viking URI path (default: viking://). Examples: 'viking://resources/', 'viking://~/memories/'."),
|
|
114
|
+
},
|
|
115
|
+
async execute(input = {}) {
|
|
116
|
+
const action = ["tree", "list", "stat"].includes(input.action) ? input.action : "list"
|
|
117
|
+
const p = String(input.path ?? "viking://")
|
|
118
|
+
try {
|
|
119
|
+
if (action === "stat") {
|
|
120
|
+
const res = await provider.stat(p)
|
|
121
|
+
return { output: JSON.stringify(res), metadata: { ok: true, action } }
|
|
122
|
+
}
|
|
123
|
+
const entries = await provider.listNamespace({ uri: p, limit: 50 })
|
|
124
|
+
return {
|
|
125
|
+
output: JSON.stringify({ path: p, entries: entries.slice(0, 50).map((e) => ({
|
|
126
|
+
name: e.rel_path ?? e.name ?? String(e.uri ?? "").split("/").pop(),
|
|
127
|
+
uri: e.uri ?? "",
|
|
128
|
+
type: e.isDir ? "dir" : "file",
|
|
129
|
+
abstract: e.abstract ?? "",
|
|
130
|
+
})) }),
|
|
131
|
+
metadata: { ok: true, action, entries: Math.min(entries.length, 50) },
|
|
132
|
+
}
|
|
133
|
+
} catch (e) {
|
|
134
|
+
return { output: JSON.stringify({ ok: false, action, path: p, error: String(e?.message ?? e) }), metadata: { ok: false, action } }
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
tools.viking_remember = mk({
|
|
140
|
+
description:
|
|
141
|
+
"Submit important long-term information to OpenViking through session memory extraction. Success means the source was " +
|
|
142
|
+
"submitted, not that a distinct memory file was created. OpenViking can add, merge, or skip the final memory. Use this tool " +
|
|
143
|
+
"when OpenViking should decide how to retain the information. Do not use it when an exact memory file or URI is required. " +
|
|
144
|
+
"If the message is accepted but commit fails, it normally remains live and unextracted because server auto-commit is " +
|
|
145
|
+
"disabled by default; follow the returned recovery instructions.",
|
|
146
|
+
parameters: { content: z.string().describe("The information to remember.") },
|
|
147
|
+
async execute(input = {}) {
|
|
148
|
+
const content = String(input.content ?? "").trim()
|
|
149
|
+
if (!content) return { output: JSON.stringify({ ok: false, error: "content is required" }), metadata: { ok: false } }
|
|
150
|
+
// 三态分开报告(S2 口径):提交状态 / 抽取结果 / 可检索状态(后者由调用方后续 search 核对)
|
|
151
|
+
const r = await provider.remember(content)
|
|
152
|
+
return {
|
|
153
|
+
output: JSON.stringify({ ...r, retrievable: "unknown(抽取在服务端;用 viking_search 核对是否可检索)" }),
|
|
154
|
+
metadata: { ok: Boolean(r.ok), status: r.status ?? null, session_id: r.session_id ?? null },
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
tools.viking_forget = mk({
|
|
160
|
+
description:
|
|
161
|
+
"Delete one OpenViking memory file by exact viking:// URI. Use only when the user explicitly asks to forget or delete a " +
|
|
162
|
+
"specific memory and you have the exact memory file URI. Resources, skills, sessions, directories, generated summaries, " +
|
|
163
|
+
"and broad deletes are rejected.",
|
|
164
|
+
parameters: { uri: z.string().describe("Exact viking:// memory file URI ending in .md.") },
|
|
165
|
+
async execute(input = {}) {
|
|
166
|
+
const r = await provider.forget(input.uri)
|
|
167
|
+
return { output: JSON.stringify(r), metadata: { ok: Boolean(r.ok), uri: r.uri ?? null } }
|
|
168
|
+
},
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
tools.viking_add_resource = mk({
|
|
172
|
+
description:
|
|
173
|
+
"Add a remote URL or local file/directory to the OpenViking knowledge base. Remote resources must be public http(s), git, " +
|
|
174
|
+
"or ssh URLs. Local files are uploaded first using OpenViking temp_upload. The system automatically parses, indexes, and " +
|
|
175
|
+
"generates summaries.",
|
|
176
|
+
parameters: {
|
|
177
|
+
url: z.string().describe("Remote URL or local file/directory path to add."),
|
|
178
|
+
reason: z.string().optional().describe("Why this resource is relevant (improves search)."),
|
|
179
|
+
to: z.string().optional().describe("Optional target viking:// URI for the resource."),
|
|
180
|
+
parent: z.string().optional().describe("Optional parent viking:// URI. Cannot be used with to."),
|
|
181
|
+
instruction: z.string().optional().describe("Optional processing instruction for semantic extraction."),
|
|
182
|
+
wait: z.boolean().optional().describe("Whether to wait for processing to complete."),
|
|
183
|
+
timeout: z.number().optional().describe("Timeout in seconds when wait is true."),
|
|
184
|
+
},
|
|
185
|
+
async execute(input = {}) {
|
|
186
|
+
const url = String(input.url ?? "").trim()
|
|
187
|
+
if (!url) return { output: JSON.stringify({ ok: false, error: "url is required" }), metadata: { ok: false } }
|
|
188
|
+
// 实现缺口(如实返回,不假装成功):我们的适配器只覆盖「记忆条目」面,
|
|
189
|
+
// 资源索引面(temp_upload / resources add)未实现 —— 与 update/remove 同款先例。
|
|
190
|
+
return {
|
|
191
|
+
output: JSON.stringify({
|
|
192
|
+
ok: false,
|
|
193
|
+
gap: "viking_add_resource 未实现:资源索引面(temp_upload / 资源新增)不在本适配器的能力面内",
|
|
194
|
+
url,
|
|
195
|
+
}),
|
|
196
|
+
metadata: { ok: false, state: "gap" },
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
return tools
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 单条读取(照 H `_read_uri_payload`:摘要档目录级;文件退回全文读;按档位截断)。 */
|
|
205
|
+
async function readUri(provider, uri, level, maxCharsOverride) {
|
|
206
|
+
const summaryLevel = level === "abstract" || level === "overview"
|
|
207
|
+
let endpoint = LEVEL_ENDPOINTS[level]
|
|
208
|
+
let resolved = uri
|
|
209
|
+
let content = ""
|
|
210
|
+
let usedFallback = false
|
|
211
|
+
if (summaryLevel) {
|
|
212
|
+
const isDir = await provider.isDirectory(uri)
|
|
213
|
+
if (isDir === false) {
|
|
214
|
+
endpoint = "/api/v1/content/read"
|
|
215
|
+
usedFallback = true
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
content = await provider.readByEndpoint(endpoint, resolved)
|
|
220
|
+
} catch (e) {
|
|
221
|
+
if (!summaryLevel || usedFallback) throw e
|
|
222
|
+
content = await provider.readByEndpoint("/api/v1/content/read", uri)
|
|
223
|
+
usedFallback = true
|
|
224
|
+
}
|
|
225
|
+
const maxLen = maxCharsOverride ?? LEVEL_MAX_CHARS[level] ?? 0
|
|
226
|
+
const truncated = Boolean(maxLen) && String(content ?? "").length > maxLen
|
|
227
|
+
const text = truncated ? `${String(content).slice(0, maxLen)}…(已截断 ${String(content).length - maxLen} 字符)` : String(content ?? "")
|
|
228
|
+
return { uri: resolved, level, content: text, ...(usedFallback ? { fell_back_to: "full" } : {}), ...(truncated ? { truncated: true } : {}) }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 工具名清单(注册侧与测试用;与 H `_OPENVIKING_RECALL_TOOL_NAMES` 区分:只读三件不回灌)。 */
|
|
232
|
+
export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget", "viking_add_resource"]
|
|
233
|
+
/** 只读三件:结果不许再喂回记忆面(照 H 的 recall-tool 名单)。 */
|
|
234
|
+
export const PROVIDER_RECALL_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse"]
|
|
235
|
+
|
|
236
|
+
/** 供注册侧使用的字符串 schema 形(z 缺席时的降级说明用,不参与真机注册)。 */
|
|
237
|
+
export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(六件:${PROVIDER_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`
|
|
@@ -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, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, applySkillReviewActions, parseReviewActions } from "../core/background-review.mjs"
|
|
7
7
|
|
|
8
8
|
// 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
|
|
9
9
|
export const REVIEW_INSTRUCTIONS = Object.freeze([
|
|
@@ -13,6 +13,9 @@ 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
|
"新增可以直接写;改动或删除既有条目一律只提案,等人处置。",
|
|
@@ -34,6 +37,7 @@ export function buildReviewPrompt(history = []) {
|
|
|
34
37
|
// 所以把**输出契约**写死:只允许动作行本身,不要标题/编号/解释。没有可记的就输出 none。
|
|
35
38
|
"输出契约(必须严格遵守):",
|
|
36
39
|
"- 只输出动作行,一行一条,形如 `add: <一句话规则>` / `update: <既有条目里的唯一子串> → <新内容>` / `remove: <既有条目里的唯一子串>`。",
|
|
40
|
+
"- 技能动作用 `skill: {\"op\":\"create\",\"name\":\"小写连字符名\",\"description\":\"Use when ….\",\"content\":\"Markdown 正文\"}` 或 `skill: {\"op\":\"patch\",\"name\":\"技能名\",\"old_string\":\"唯一命中的原文\",\"new_string\":\"新文\"}`(一行一条,JSON 单行;归档/删除不要提)。",
|
|
37
41
|
"- 不要标题、不要编号列表、不要解释、不要空行之外的任何其它文字。",
|
|
38
42
|
"- 没有任何值得记的就只输出 `none`(不要写别的)。",
|
|
39
43
|
].join("\n")
|
|
@@ -75,26 +79,44 @@ export function normalizeMessages(raw) {
|
|
|
75
79
|
return []
|
|
76
80
|
}
|
|
77
81
|
|
|
78
|
-
|
|
82
|
+
// 可选取消只约束本次宿主等待;不改默认复习语义。取消后不再继续轮询/派发下一步。
|
|
83
|
+
async function abortable(fn, signal) {
|
|
84
|
+
const check = () => { if (signal?.aborted) throw new Error("宿主复习已取消") }
|
|
85
|
+
check()
|
|
86
|
+
if (!signal) return fn()
|
|
87
|
+
let onAbort
|
|
88
|
+
const stopped = new Promise((_, reject) => {
|
|
89
|
+
onAbort = () => reject(new Error("宿主复习已取消"))
|
|
90
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
91
|
+
})
|
|
92
|
+
try {
|
|
93
|
+
return await Promise.race([Promise.resolve().then(() => { check(); return fn() }), stopped])
|
|
94
|
+
} finally {
|
|
95
|
+
signal.removeEventListener("abort", onAbort)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null } = {}) {
|
|
100
|
+
const call = (fn) => signal ? abortable(fn, signal) : fn() // 默认路径不增加async跳数
|
|
79
101
|
return async () => {
|
|
80
102
|
try {
|
|
81
103
|
// 有 `promptAsync` 就走它(事件回调里更稳),否则退回同步 `prompt`;两者都没有才算不可用。
|
|
82
104
|
const canPrompt = typeof client?.session?.promptAsync === "function" || typeof client?.session?.prompt === "function"
|
|
83
105
|
if (!client?.session?.create || !client?.session?.messages || !canPrompt) return { ok: false, error: "宿主 client 不可用" }
|
|
84
106
|
// 输入面=整份回合会话(同模型路径)
|
|
85
|
-
const main = await client.session.messages({ path: { id: sessionId } })
|
|
107
|
+
const main = await call(() => client.session.messages({ path: { id: sessionId } }))
|
|
86
108
|
const history = main?.data ?? main ?? []
|
|
87
109
|
// A131:先问宿主有哪些工具,再按 fail-closed 白名单算出这次运行的 `tools` 面
|
|
88
110
|
let hostToolIds = null
|
|
89
111
|
try {
|
|
90
|
-
const listed = client?.tool?.list ? await client.tool.list() : null
|
|
112
|
+
const listed = client?.tool?.list ? await call(() => client.tool.list()) : null
|
|
91
113
|
const rows = listed?.data ?? listed ?? null
|
|
92
114
|
if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
|
|
93
115
|
} catch { hostToolIds = null }
|
|
94
116
|
const restriction = toolRestrictionFor(hostToolIds)
|
|
95
117
|
if (typeof onRestriction === "function") onRestriction(restriction)
|
|
96
118
|
// 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
|
|
97
|
-
const created = await client.session.create({ body: { parentID: sessionId } })
|
|
119
|
+
const created = await call(() => client.session.create({ body: { parentID: sessionId } }))
|
|
98
120
|
const childId = created?.data?.id ?? created?.id ?? null
|
|
99
121
|
if (!childId) return { ok: false, error: "子会话没建起来" }
|
|
100
122
|
// 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
|
|
@@ -104,15 +126,15 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
|
|
|
104
126
|
// 走"同步驱动"这条路会卡住自己。改法(照宿主自己的两种姿势):
|
|
105
127
|
// 优先 `promptAsync`(只入队,立刻返回)→ 轮询 `messages` 等 assistant 产出;
|
|
106
128
|
// 没有 promptAsync 的宿主再退回同步 prompt(老姿势,风险已知)。
|
|
107
|
-
const promptBody = { agent, tools: restriction.tools, parts: [{ type: "text", text: buildReviewPrompt(history) }] }
|
|
129
|
+
const promptBody = { agent, tools: restriction.tools, parts: [{ type: "text", text: prompt ?? buildReviewPrompt(history) }] }
|
|
108
130
|
if (typeof client.session.promptAsync === "function") {
|
|
109
|
-
await client.session.promptAsync({ path: { id: childId }, body: promptBody })
|
|
131
|
+
await call(() => client.session.promptAsync({ path: { id: childId }, body: promptBody }))
|
|
110
132
|
} else {
|
|
111
|
-
await client.session.prompt({ path: { id: childId }, body: promptBody })
|
|
133
|
+
await call(() => client.session.prompt({ path: { id: childId }, body: promptBody }))
|
|
112
134
|
}
|
|
113
135
|
// 轮询取回(最多 REVIEW_LIMITS.pollMs,默认 60s):看到 assistant 文本就走
|
|
114
136
|
const deadline = Date.now() + pollMs
|
|
115
|
-
let out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
|
|
137
|
+
let out = normalizeMessages(await call(() => client.session.messages({ path: { id: childId } })))
|
|
116
138
|
while (Date.now() < deadline) {
|
|
117
139
|
const msgs = normalizeMessages(out)
|
|
118
140
|
const hasAssistantText = (Array.isArray(msgs) ? msgs : []).some((m) => {
|
|
@@ -123,19 +145,19 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
|
|
|
123
145
|
return (Array.isArray(parts) ? parts : []).some((x) => x?.type === "text" && String(x.text ?? "").trim())
|
|
124
146
|
})
|
|
125
147
|
if (hasAssistantText) break
|
|
126
|
-
await new Promise((r) => setTimeout(r, 1000))
|
|
127
|
-
out = normalizeMessages(await client.session.messages({ path: { id: childId } }))
|
|
148
|
+
await call(() => new Promise((r) => setTimeout(r, 1000)))
|
|
149
|
+
out = normalizeMessages(await call(() => client.session.messages({ path: { id: childId } })))
|
|
128
150
|
}
|
|
129
151
|
return { ok: true, childId, messages: normalizeMessages(out), restriction }
|
|
130
152
|
} catch (e) {
|
|
131
|
-
return { ok: false, error: String(e?.message ?? e) }
|
|
153
|
+
return { ok: false, error: String(e?.message ?? e), ...(signal?.aborted ? { cancelled: true } : {}) }
|
|
132
154
|
}
|
|
133
155
|
}
|
|
134
156
|
}
|
|
135
157
|
|
|
136
158
|
// 组装:宿主插件入口在回合结束(session.idle)时按**会话**调 onIdle。
|
|
137
159
|
// 每个会话一份计数与一个 handler(计数要连得上,不能每次重建)。
|
|
138
|
-
export function createReviewPipeline({ client, thresholds, store = null, cancelHandshakeMs = 2000, now = () => Date.now(), audit = null, toolsAvailable: declaredTools = null } = {}) {
|
|
160
|
+
export function createReviewPipeline({ client, thresholds, store = null, root = null, skillHostConfig = null, cancelHandshakeMs = 2000, now = () => Date.now(), audit = null, toolsAvailable: declaredTools = null } = {}) {
|
|
139
161
|
const handlers = new Map()
|
|
140
162
|
// 每个会话的运行态:在跑的复习子会话 id + 是否已被取消 + 那次作业的句柄。
|
|
141
163
|
// A129:调度器只会说"取消",真正能对宿主发 abort 的是**执行体**(它持有 client 与子会话 id)。
|
|
@@ -161,10 +183,11 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
|
|
|
161
183
|
toolAvail = (memory === null && skills === null) ? null : { memory, skills }
|
|
162
184
|
return toolAvail
|
|
163
185
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
186
|
+
// 每会话的处理器(惰性建)。onToolIteration 可能先于第一次 onIdle 到达(第一个回合里的
|
|
187
|
+
// 工具迭代)——创建入口必须两个方法共用,否则第一回合的迭代全被丢掉、阈值门永远差一步。
|
|
188
|
+
async function ensureHandler(sessionId) {
|
|
189
|
+
if (handlers.has(sessionId)) return handlers.get(sessionId)
|
|
190
|
+
{
|
|
168
191
|
const run = { childId: null, cancelled: false, inflight: null, restriction: null, dispatchedAt: 0, lastUserMessageId: null, lastUserMessageAt: 0 }
|
|
169
192
|
runs.set(sessionId, run)
|
|
170
193
|
const review = createHostReview({ client, sessionId, onChild: (id) => { run.childId = id }, onRestriction: (r) => { run.restriction = r } })
|
|
@@ -275,6 +298,16 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
|
|
|
275
298
|
}
|
|
276
299
|
return { ...out, ok: false, error: `landing failed: ${String(e?.message ?? e)}` }
|
|
277
300
|
}
|
|
301
|
+
// S1 通道④:技能车道(skill: 动作行 → SKILL.md)。只动 agent-created、闸门在动作层自认;
|
|
302
|
+
// 拒绝/忽略必须浮出。缺 root 就如实标 skipped(不猜目录、不静默)。
|
|
303
|
+
let skillLanded = { written: 0, staged: 0, ignored: [], refused: [], surface: null, mustSurface: false, skipped: "no-root" }
|
|
304
|
+
if (root) {
|
|
305
|
+
try {
|
|
306
|
+
skillLanded = await applySkillReviewActions({ root, actions, hostConfig: skillHostConfig })
|
|
307
|
+
} catch (e) {
|
|
308
|
+
skillLanded = { written: 0, staged: 0, ignored: [], refused: [{ op: "skill", name: null, error: String(e?.message ?? e) }], surface: `后台复习:技能面落地失败(${String(e?.message ?? e)})`, mustSurface: true }
|
|
309
|
+
}
|
|
310
|
+
}
|
|
278
311
|
// A131:每次决策留一条**可核条目**——谁跑的、跑的时候工具面是什么、落了什么。
|
|
279
312
|
// 记账失败不许影响宿主(吞掉),但条目本身要能被机器读。
|
|
280
313
|
const decision = {
|
|
@@ -289,22 +322,43 @@ export function createReviewPipeline({ client, thresholds, store = null, cancelH
|
|
|
289
322
|
written: landed.written ?? 0,
|
|
290
323
|
staged: landed.staged ?? 0,
|
|
291
324
|
ignored: (landed.ignored ?? []).map((i) => i.op),
|
|
325
|
+
skillWritten: skillLanded.written ?? 0,
|
|
326
|
+
skillStaged: skillLanded.staged ?? 0,
|
|
327
|
+
skillRefused: (skillLanded.refused ?? []).map((f) => `${f.op}:${f.name ?? "?"}`),
|
|
292
328
|
surface: landed.surface ?? null,
|
|
329
|
+
skillSurface: skillLanded.surface ?? null,
|
|
293
330
|
}
|
|
294
331
|
if (typeof audit === "function") { try { audit(decision) } catch { /* 记账失败不许把宿主弄崩 */ } }
|
|
295
|
-
//
|
|
296
|
-
const
|
|
297
|
-
|
|
332
|
+
// 提案必须浮出:有人看得见的那一行,发回宿主会话(memory 与技能两条车道的浮出行合并)
|
|
333
|
+
const surfaceText = [landed.surface, skillLanded.surface].filter(Boolean).join(";") || null
|
|
334
|
+
const surfaced = surfaceText ? await surfaceToHost({ client, sessionId, line: surfaceText }) : { posted: false }
|
|
335
|
+
return { ...out, actions: actions.length, ...landed, skillLanded, surfaced, decision }
|
|
298
336
|
},
|
|
299
337
|
})
|
|
300
338
|
handlers.set(sessionId, createTurnEndHandler({ scheduler, review: async () => ({}), sessionId }))
|
|
301
|
-
|
|
339
|
+
}
|
|
340
|
+
return handlers.get(sessionId)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
async onIdle(sessionId) {
|
|
345
|
+
if (!sessionId) return { handled: false, reason: "no-session" }
|
|
346
|
+
await ensureHandler(sessionId)
|
|
302
347
|
const r = await handlers.get(sessionId).onIdle()
|
|
303
348
|
const run = runs.get(sessionId)
|
|
304
349
|
if (r?.pending) run.inflight = r.pending // 交给 onUserTurnStart 握手的那个句柄
|
|
305
350
|
return { handled: true, ...r }
|
|
306
351
|
},
|
|
307
352
|
|
|
353
|
+
// S1 通道④触发源:宿主工具迭代(wire 按 callID 去重后)推进调度器计数;
|
|
354
|
+
// skill_manage 用过 ⇒ 重置(照 Hermes turn_iteration_prep:用过 skill_manage 就重新攒)。
|
|
355
|
+
async onToolIteration(sessionId, info = {}) {
|
|
356
|
+
if (!sessionId) return { counted: false, reason: "no-session" }
|
|
357
|
+
const h = await ensureHandler(sessionId)
|
|
358
|
+
if (typeof h?.noteIteration !== "function") return { counted: false, reason: "no-counter" }
|
|
359
|
+
return { counted: true, iterations: h.noteIteration({ skillUsed: Boolean(info?.skillUsed) }) }
|
|
360
|
+
},
|
|
361
|
+
|
|
308
362
|
// 前台新回合开始 ⇒ 取消在跑的复习(照 Hermes `turn_facade.py` 的时机 + 取消握手)。
|
|
309
363
|
// 返回如实:`settled:false` 表示握手超时、作业可能还在跑(不许假装已经停了)。
|
|
310
364
|
// 只有**真的新回合**才取消。真机链实测(2026-09-21):宿主在一次回合里会连发多条
|
|
@@ -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
|
+
}
|