opencode-growth 0.1.74 → 0.1.76
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/package.json +1 -1
- package/src/adapter-opencode/curator-runner.mjs +11 -1
- package/src/adapter-opencode/index.mjs +5 -71
- package/src/adapter-opencode/memory-tool.mjs +2 -0
- package/src/adapter-opencode/provider-tools.mjs +10 -36
- package/src/adapter-opencode/review-runner.mjs +10 -6
- package/src/adapter-opencode/skill-tool.mjs +7 -0
- package/src/cli/commands.mjs +27 -33
- package/src/cli/main.mjs +24 -5
- package/src/core/approve.mjs +127 -17
- package/src/core/memory-actions.mjs +7 -0
- package/src/core/session-bootstrap.mjs +53 -0
- package/src/core/skill-actions.mjs +171 -1
- package/src/core/subsessions.mjs +65 -0
- package/src/learn/headless.mjs +15 -2
- package/src/provider/config.mjs +1 -1
package/package.json
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import fs from "node:fs"
|
|
17
17
|
import path from "node:path"
|
|
18
18
|
|
|
19
|
-
import { createHostReview } from "./review-runner.mjs"
|
|
19
|
+
import { createHostReview, REVIEW_READ_ONLY_TOOLS } from "./review-runner.mjs"
|
|
20
20
|
import { stampCuratorClock, CLOCK_FILE, applyLifecycleTransitions } from "../core/skill-lifecycle.mjs"
|
|
21
21
|
import { snapshotSkills } from "../core/skill-backup.mjs"
|
|
22
22
|
import { skillsDir, SKILL_FILE, readExternalDirs, readCreatedBy } from "../core/skills.mjs"
|
|
@@ -26,6 +26,14 @@ import { appendAudit } from "../core/audit.mjs"
|
|
|
26
26
|
import { layout } from "../core/paths.mjs"
|
|
27
27
|
|
|
28
28
|
/** 照 Hermes `get_interval_hours()` 的默认(curator.interval_hours=7*24)。 */
|
|
29
|
+
/**
|
|
30
|
+
* 整理 pass 的工具面:只读 + **skill_manage**。
|
|
31
|
+
* 提示词要求「所有落盘都走 skill_manage(入账可回滚)」——若沿用复习面的只读白名单,
|
|
32
|
+
* 唯一落盘通道会被关掉,整理只剩报告(2026-11-20 实测:skill_manage=false)。
|
|
33
|
+
* 原生 `skill` 工具不放行:它绕过 OCG 的所有权/审批/审计。
|
|
34
|
+
*/
|
|
35
|
+
export const CURATOR_TOOL_ALLOWLIST = Object.freeze([...REVIEW_READ_ONLY_TOOLS, "skill_manage"])
|
|
36
|
+
|
|
29
37
|
export const DEFAULT_CURATOR_INTERVAL_HOURS = 168
|
|
30
38
|
|
|
31
39
|
const iso = (d) => (d instanceof Date ? d : new Date(d)).toISOString()
|
|
@@ -238,6 +246,8 @@ export async function runCuratorPass({ client, sessionId, root = null, skills =
|
|
|
238
246
|
const review = createHostReview({
|
|
239
247
|
client,
|
|
240
248
|
sessionId,
|
|
249
|
+
kind: "curator",
|
|
250
|
+
toolsAllow: CURATOR_TOOL_ALLOWLIST,
|
|
241
251
|
...(agent !== undefined ? { agent } : {}),
|
|
242
252
|
onChild: (id) => { childId = id; if (signal?.aborted) abortChild(); if (typeof onChild === "function") onChild(id) },
|
|
243
253
|
onRestriction,
|
|
@@ -23,7 +23,6 @@ import { homedir } from "node:os"
|
|
|
23
23
|
|
|
24
24
|
import { layout } from "../core/paths.mjs"
|
|
25
25
|
import { resolveStoreRoot } from "../core/home.mjs"
|
|
26
|
-
import { resolveProject } from "../core/identity.mjs"
|
|
27
26
|
import { frozenBlockFor, BLOCK_MARKER } from "../core/snapshot.mjs"
|
|
28
27
|
import { bumpSkillUse } from "../core/skill-usage.mjs"
|
|
29
28
|
import { formationGuidanceBlock, SKILL_FORMATION_FENCE } from "../core/skills.mjs"
|
|
@@ -72,24 +71,6 @@ export function isExplicitCorrection(text) {
|
|
|
72
71
|
/** 家目录取不到就当没有(fail closed,解析会退回「拿不到唯一根」而不是猜一个)。 */
|
|
73
72
|
const safeHomedir = () => { try { return homedir() || null } catch { return null } }
|
|
74
73
|
|
|
75
|
-
function appendQueueLine(queuePath, entry) {
|
|
76
|
-
fs.mkdirSync(path.dirname(queuePath), { recursive: true })
|
|
77
|
-
// Append-only: two corrections are two entries, and a crash mid-append can at worst leave a
|
|
78
|
-
// torn last line, which the consumer skips.
|
|
79
|
-
fs.appendFileSync(queuePath, JSON.stringify(entry) + "\n")
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
function resolveProjectId(storeDir, directory) {
|
|
83
|
-
try {
|
|
84
|
-
const L = layout(storeDir)
|
|
85
|
-
fs.mkdirSync(L.state, { recursive: true })
|
|
86
|
-
const project = resolveProject(directory, L.projects)
|
|
87
|
-
return project?.projectId ?? null
|
|
88
|
-
} catch {
|
|
89
|
-
return null
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
74
|
/**
|
|
94
75
|
* Build the hooks. `store` may be null — that is the "not configured" case, not an error.
|
|
95
76
|
* Exported separately from the plugin factory so the behaviour above is testable without an
|
|
@@ -213,7 +194,7 @@ export function createAdapter({
|
|
|
213
194
|
runtime = null,
|
|
214
195
|
providerToolDefs = null,
|
|
215
196
|
providerScenario = null,
|
|
216
|
-
// ③层能力面(S3):`auto`=自动面(召回注入/写镜像),`tools
|
|
197
|
+
// ③层能力面(S3):`auto`=自动面(召回注入/写镜像),`tools`=工具面(五件可用 viking_*)。
|
|
217
198
|
// 缺省(null)=既有行为:两面都开。显式关哪一面只关哪一面 —— 让官方插件接管自动面、
|
|
218
199
|
// 或把工具面交给外部 MCP,而不必连 ①② 与本地技能一起关掉。
|
|
219
200
|
providerCapabilities = null,
|
|
@@ -235,12 +216,6 @@ export function createAdapter({
|
|
|
235
216
|
interactive: binding?.interactive ?? null,
|
|
236
217
|
queuePath: queuePath ?? null,
|
|
237
218
|
})
|
|
238
|
-
const resolvedQueue = queuePath
|
|
239
|
-
?? process.env.OCG_QUEUE
|
|
240
|
-
?? (storeDir ? path.join(storeDir, "state", "learn-queue.jsonl") : null)
|
|
241
|
-
|
|
242
|
-
// One API call per session, not one per fire (the hook fires three times per run).
|
|
243
|
-
const sessionDirs = new Map()
|
|
244
219
|
// ③层查询段要「当前 query」,但 `experimental.chat.system.transform` 的 input **只有**
|
|
245
220
|
// {sessionID, model}(1.18.30 实测;见本文件注入块的实测注记)⇒ 只能由 `chat.message`
|
|
246
221
|
// 在每轮用户消息提交时供给。逐会话存最近一轮文本(照 H「检索只对当前 query」,:1553)。
|
|
@@ -278,23 +253,6 @@ export function createAdapter({
|
|
|
278
253
|
onSkillUse: storeDir ? (n) => { bumpSkillUse(storeDir, n) } : null,
|
|
279
254
|
})
|
|
280
255
|
|
|
281
|
-
async function directoryForSession(sessionId) {
|
|
282
|
-
if (!client?.session?.get || !sessionId) return null
|
|
283
|
-
if (sessionDirs.has(sessionId)) return sessionDirs.get(sessionId)
|
|
284
|
-
let dir = null
|
|
285
|
-
try {
|
|
286
|
-
const res = await client.session.get({ path: { id: sessionId } })
|
|
287
|
-
const found = res?.data?.directory
|
|
288
|
-
if (typeof found === "string" && found.trim()) dir = found
|
|
289
|
-
} catch {
|
|
290
|
-
// **不回退**(审计 A20):拿不到会话自己的目录时,答案只能是 null。
|
|
291
|
-
// 原来这里回退到工厂的 directory —— 而工厂可能属于**另一个**实例/目录,
|
|
292
|
-
// 于是 A 项目的记录会被算进 B 会话的账。宁可不知道,也不要猜错。
|
|
293
|
-
}
|
|
294
|
-
sessionDirs.set(sessionId, dir)
|
|
295
|
-
return dir
|
|
296
|
-
}
|
|
297
|
-
|
|
298
256
|
return {
|
|
299
257
|
/** C① 实例自证:这个适配器绑在哪个 D / 哪个目录 / 值哪来的(多实例并存时可核对)。 */
|
|
300
258
|
binding: () => bindInfo,
|
|
@@ -380,33 +338,9 @@ export function createAdapter({
|
|
|
380
338
|
|
|
381
339
|
event: async ({ event } = {}) => {
|
|
382
340
|
if (idleWire) await idleWire({ event })
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
if (!resolvedQueue) return
|
|
387
|
-
const sessionId = event?.properties?.sessionID ?? event?.sessionID ?? null
|
|
388
|
-
// The message id, so the eventual candidate can be traced back to the utterance that
|
|
389
|
-
// prompted it. Read from every shape OpenCode was seen to use rather than one guess; a
|
|
390
|
-
// missing id is recorded as null, never invented (audit A16).
|
|
391
|
-
const messageId =
|
|
392
|
-
event?.properties?.messageID ??
|
|
393
|
-
event?.properties?.message?.id ??
|
|
394
|
-
event?.properties?.part?.messageID ??
|
|
395
|
-
null
|
|
396
|
-
appendQueueLine(resolvedQueue, {
|
|
397
|
-
state: "pending",
|
|
398
|
-
capturedAt: new Date().toISOString(),
|
|
399
|
-
sessionId,
|
|
400
|
-
messageId,
|
|
401
|
-
projectId: storeDir ? resolveProjectId(storeDir, await directoryForSession(sessionId)) : null,
|
|
402
|
-
excerpt: String(text).slice(0, 400),
|
|
403
|
-
origin: "opencode-capture",
|
|
404
|
-
})
|
|
405
|
-
// Deliberately nothing else: no spawn, no candidate, no publish. The scheduler owns
|
|
406
|
-
// what happens next, because an in-session child would be killed by the parent's exit.
|
|
407
|
-
} catch {
|
|
408
|
-
// Same rule as above: capture failing must not break the host.
|
|
409
|
-
}
|
|
341
|
+
// 纠正捕获**已退役**(欠账收口 · S1):日常学习由回合后的后台复习承担,
|
|
342
|
+
// 旧队列不再接收新行(不再制造无人消费的 state:"pending")。
|
|
343
|
+
// 历史队列、游标、候选、audit 与旧读取器全部保留;升级不重放、不移动游标。
|
|
410
344
|
},
|
|
411
345
|
}
|
|
412
346
|
}
|
|
@@ -448,7 +382,7 @@ export const OcgGrowth = async ({ directory, client, z, tool } = {}) => {
|
|
|
448
382
|
}
|
|
449
383
|
} catch { runtime = null }
|
|
450
384
|
}
|
|
451
|
-
//
|
|
385
|
+
// ③层工具面(五件可用 viking_*;`viking_add_resource` 未实现不注册):**只在 provider 在场、
|
|
452
386
|
// 且工具面归我们时**注册 ——provider 缺席/工具面外让时,宿主看到的工具面与从前逐字相同。
|
|
453
387
|
let providerToolDefs = null
|
|
454
388
|
if (runtime && providerCapabilities?.tools !== false && z?.string) {
|
|
@@ -16,6 +16,7 @@ import path from "node:path"
|
|
|
16
16
|
import { pathToFileURL } from "node:url"
|
|
17
17
|
|
|
18
18
|
import { MEMORY_ACTIONS, identityFor, runMemoryAction } from "../core/memory-actions.mjs"
|
|
19
|
+
import { backgroundSubsessionKind } from "../core/subsessions.mjs"
|
|
19
20
|
|
|
20
21
|
/** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
|
|
21
22
|
const identityTool = (def) => def
|
|
@@ -116,6 +117,7 @@ export function buildMemoryTool({
|
|
|
116
117
|
interactive,
|
|
117
118
|
backgroundAgents,
|
|
118
119
|
foregroundAgents,
|
|
120
|
+
backgroundKind: backgroundSubsessionKind(ctx?.sessionID),
|
|
119
121
|
})
|
|
120
122
|
const r = await runMemoryAction({
|
|
121
123
|
operations: Array.isArray(args?.operations) && args.operations.length ? args.operations : undefined,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
// S3 · ③层工具面(照 Hermes
|
|
2
|
-
//
|
|
1
|
+
// S3 · ③层工具面(照 Hermes 的六件 schema;**注册五件**:viking_search / viking_read /
|
|
2
|
+
// viking_browse / viking_remember / viking_forget)。`viking_add_resource` 的资源索引面
|
|
3
|
+
// 未实现(恒返 gap)⇒ 0.1.75 起**不注册**:模型工具表里不放空壳。
|
|
3
4
|
//
|
|
4
5
|
// 对齐口径(锁版本 b9d5e4d1):
|
|
5
6
|
// - **名称/描述/参数逐字照 H** `_TOOL_SCHEMAS`(:390-450 的六个 schema 常量)
|
|
@@ -10,8 +11,9 @@
|
|
|
10
11
|
// - 批读上限照 H `:70-71`:一次最多 3 个 URI;多 URI 时 full 单条限 2500 字符
|
|
11
12
|
// - 工具面**只在 provider 在场时**注册(与 H 同:插件没启用就没有这些工具)
|
|
12
13
|
//
|
|
13
|
-
//
|
|
14
|
-
//
|
|
14
|
+
// 缺口如实记录而不是注册空壳:`viking_add_resource` 需要 temp_upload + 资源提交/清理,
|
|
15
|
+
// 是独立的产品功能。astrA 评审的推翻条件:同候选包能经已配置 provider 正常导入受支持来源、
|
|
16
|
+
// 拿回资源回执并查回内容,才按真实支持范围重新注册。
|
|
15
17
|
import { RECALL_FENCE } from "../provider/runtime.mjs"
|
|
16
18
|
|
|
17
19
|
/** 一次读取的批量上限(照 H `:70`)。 */
|
|
@@ -168,36 +170,6 @@ export function buildProviderTools({ provider, z, tool = null } = {}) {
|
|
|
168
170
|
},
|
|
169
171
|
})
|
|
170
172
|
|
|
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
173
|
return tools
|
|
202
174
|
}
|
|
203
175
|
|
|
@@ -229,9 +201,11 @@ async function readUri(provider, uri, level, maxCharsOverride) {
|
|
|
229
201
|
}
|
|
230
202
|
|
|
231
203
|
/** 工具名清单(注册侧与测试用;与 H `_OPENVIKING_RECALL_TOOL_NAMES` 区分:只读三件不回灌)。 */
|
|
232
|
-
export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget"
|
|
204
|
+
export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget"]
|
|
205
|
+
/** 未实现、因此**不注册**的工具名(缺口写进文档;别把它当能力面)。 */
|
|
206
|
+
export const PROVIDER_HIDDEN_TOOL_NAMES = ["viking_add_resource"]
|
|
233
207
|
/** 只读三件:结果不许再喂回记忆面(照 H 的 recall-tool 名单)。 */
|
|
234
208
|
export const PROVIDER_RECALL_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse"]
|
|
235
209
|
|
|
236
210
|
/** 供注册侧使用的字符串 schema 形(z 缺席时的降级说明用,不参与真机注册)。 */
|
|
237
|
-
export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}
|
|
211
|
+
export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(五件:${PROVIDER_TOOL_NAMES.join(" / ")};未实现不注册:${PROVIDER_HIDDEN_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// ③适配器故障绝不允许浮到宿主进程里。
|
|
5
5
|
import fs from "node:fs"
|
|
6
6
|
import { REVIEW_AGENT, REVIEW_SURFACE_MARK, backgroundReviewBead, createReviewScheduler, createTurnEndHandler, applyReviewOutcome, applySkillReviewActions, parseReviewActions } from "../core/background-review.mjs"
|
|
7
|
+
import { registerBackgroundSubsession } from "../core/subsessions.mjs"
|
|
7
8
|
|
|
8
9
|
// 照抄 Hermes 的复习提示词约束(第一版逐条对齐,不自造)。
|
|
9
10
|
export const REVIEW_INSTRUCTIONS = Object.freeze([
|
|
@@ -71,19 +72,19 @@ export const REVIEW_READ_ONLY_TOOLS = Object.freeze(["read", "grep", "glob", "li
|
|
|
71
72
|
// 拿不到宿主工具清单时的兜底:至少把这些已知会改盘/会派活的关掉,并如实标 `enumerated:false`。
|
|
72
73
|
const KNOWN_MUTATING_TOOLS = Object.freeze(["write", "edit", "patch", "apply_patch", "multiedit", "bash", "shell", "task", "skill", "question", "plan"])
|
|
73
74
|
|
|
74
|
-
export function toolRestrictionFor(hostToolIds = null) {
|
|
75
|
+
export function toolRestrictionFor(hostToolIds = null, allow = REVIEW_READ_ONLY_TOOLS) {
|
|
75
76
|
if (Array.isArray(hostToolIds) && hostToolIds.length) {
|
|
76
77
|
const map = {}
|
|
77
78
|
for (const id of hostToolIds) {
|
|
78
79
|
if (typeof id !== "string" || !id) continue
|
|
79
|
-
map[id] =
|
|
80
|
+
map[id] = allow.includes(id) // 白名单外(含没见过的)⇒ false
|
|
80
81
|
}
|
|
81
82
|
return { tools: map, enumerated: true, allowed: Object.keys(map).filter((k) => map[k]), denied: Object.keys(map).filter((k) => !map[k]) }
|
|
82
83
|
}
|
|
83
84
|
const map = {}
|
|
84
85
|
for (const id of KNOWN_MUTATING_TOOLS) map[id] = false
|
|
85
|
-
for (const id of
|
|
86
|
-
return { tools: map, enumerated: false, allowed: [...
|
|
86
|
+
for (const id of allow) map[id] = true
|
|
87
|
+
return { tools: map, enumerated: false, allowed: [...allow], denied: Object.keys(map).filter((k) => !map[k]) }
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
// 真宿主 `client.session.messages()` 回来的是**包装对象**(`{data:[…]}`),直连 SDK 时也可能
|
|
@@ -113,7 +114,7 @@ async function abortable(fn, signal) {
|
|
|
113
114
|
}
|
|
114
115
|
}
|
|
115
116
|
|
|
116
|
-
export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null } = {}) {
|
|
117
|
+
export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, kind = "review", onChild = null, onRestriction = null, pollMs = 60000, prompt = null, signal = null, toolsAllow = null } = {}) {
|
|
117
118
|
const call = (fn) => signal ? abortable(fn, signal) : fn() // 默认路径不增加async跳数
|
|
118
119
|
return async () => {
|
|
119
120
|
try {
|
|
@@ -130,12 +131,15 @@ export function createHostReview({ client, sessionId, agent = REVIEW_AGENT, onCh
|
|
|
130
131
|
const rows = listed?.data ?? listed ?? null
|
|
131
132
|
if (Array.isArray(rows)) hostToolIds = rows.map((t) => (typeof t === "string" ? t : t?.id)).filter(Boolean)
|
|
132
133
|
} catch { hostToolIds = null }
|
|
133
|
-
const restriction = toolRestrictionFor(hostToolIds)
|
|
134
|
+
const restriction = toolRestrictionFor(hostToolIds, toolsAllow ?? REVIEW_READ_ONLY_TOOLS)
|
|
134
135
|
if (typeof onRestriction === "function") onRestriction(restriction)
|
|
135
136
|
// 子会话挂在主会话下 ⇒ 结果留在宿主会话体系里,可被取回
|
|
136
137
|
const created = await call(() => client.session.create({ body: { parentID: sessionId } }))
|
|
137
138
|
const childId = created?.data?.id ?? created?.id ?? null
|
|
138
139
|
if (!childId) return { ok: false, error: "子会话没建起来" }
|
|
140
|
+
// S0:建出即登记。工具面用 `ctx.sessionID` 查这张表,子会话里的写入才按后台口径走
|
|
141
|
+
// (agent 名是 `plan`,与用户自己的 plan 会话同名,不能拿它当身份)。
|
|
142
|
+
registerBackgroundSubsession(childId, { kind, parent: sessionId })
|
|
139
143
|
// 交出去:取消要靠**这个** id 对宿主发 abort(执行体是唯一持有它的人)
|
|
140
144
|
if (typeof onChild === "function") onChild(childId)
|
|
141
145
|
// **不要在事件回调里等同步 prompt**:真机链实测(2026-09-21)——子会话真的产出了内容,
|
|
@@ -17,6 +17,7 @@ import { pathToFileURL } from "node:url"
|
|
|
17
17
|
|
|
18
18
|
import { SKILL_ACTIONS, runSkillAction, skillGateFromHostConfig } from "../core/skill-actions.mjs"
|
|
19
19
|
import { identityFor } from "../core/memory-actions.mjs"
|
|
20
|
+
import { backgroundSubsessionKind } from "../core/subsessions.mjs"
|
|
20
21
|
import { readExternalDirs } from "../core/skills.mjs"
|
|
21
22
|
|
|
22
23
|
/** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
|
|
@@ -105,6 +106,8 @@ export function buildSkillTool({
|
|
|
105
106
|
old_string: z.string().optional().describe("patch 用:要替换的原文(必须唯一命中)"),
|
|
106
107
|
new_string: z.string().optional().describe("patch 用:替换后的新文"),
|
|
107
108
|
absorbed_into: z.string().optional().describe("archive 用:合并去向的伞技能名(必须已存在)"),
|
|
109
|
+
file_path: z.string().optional().describe("write_file/remove_file 用:references|scripts|templates|assets 下的相对路径"),
|
|
110
|
+
file_content: z.string().optional().describe("write_file 用:附件正文(UTF-8,≤1MiB)"),
|
|
108
111
|
// 注意这里**没有** origin / agent / created_by:身份与归属由宿主 ctx 和
|
|
109
112
|
// 部署者名单决定(extra#4),created_by 由动作层按身份写进 frontmatter。
|
|
110
113
|
},
|
|
@@ -116,6 +119,8 @@ export function buildSkillTool({
|
|
|
116
119
|
interactive,
|
|
117
120
|
backgroundAgents,
|
|
118
121
|
foregroundAgents,
|
|
122
|
+
// S0:OCG 派发的子会话身份来自**子会话 id**(curator/复习子会话都以 plan 身份跑)。
|
|
123
|
+
backgroundKind: backgroundSubsessionKind(ctx?.sessionID),
|
|
119
124
|
})
|
|
120
125
|
const name = args?.name ?? ""
|
|
121
126
|
const gate = skillGateFromHostConfig({ hostConfig: hostConfig ?? {}, agent: ctx?.agent ?? null, name })
|
|
@@ -129,6 +134,8 @@ export function buildSkillTool({
|
|
|
129
134
|
old_string: args?.old_string,
|
|
130
135
|
new_string: args?.new_string,
|
|
131
136
|
absorbedInto: args?.absorbed_into,
|
|
137
|
+
file_path: args?.file_path ?? null,
|
|
138
|
+
file_content: args?.file_content ?? null,
|
|
132
139
|
ask,
|
|
133
140
|
hostPermission: gate.hostPermission,
|
|
134
141
|
agentSkillEnabled: gate.agentSkillEnabled,
|
package/src/cli/commands.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { installAll, resolveInstallPaths, uninstallAll } from "../adapter-openco
|
|
|
24
24
|
import { storeHashOf } from "../core/memories.mjs"
|
|
25
25
|
import { listPending, approvePending } from "../core/approve.mjs"
|
|
26
26
|
import { doctorSkillsSection, readExternalDirs, skillsDir } from "../core/skills.mjs"
|
|
27
|
+
import { lightUpHistorySearch, historySearchLine } from "../core/session-bootstrap.mjs"
|
|
27
28
|
|
|
28
29
|
const isDir = (p) => {
|
|
29
30
|
try {
|
|
@@ -203,7 +204,7 @@ export function status(opts, ctx) {
|
|
|
203
204
|
*
|
|
204
205
|
* 它**不碰** D 里的记忆与快照:只建目录、写宿主侧的两个文件。
|
|
205
206
|
*/
|
|
206
|
-
export function installCmd(opts, ctx) {
|
|
207
|
+
export async function installCmd(opts, ctx) {
|
|
207
208
|
const { L } = ctx
|
|
208
209
|
try {
|
|
209
210
|
const out = installAll({
|
|
@@ -212,9 +213,13 @@ export function installCmd(opts, ctx) {
|
|
|
212
213
|
queuePath: opts.queue ? String(opts.queue) : null,
|
|
213
214
|
dryRun: Boolean(opts["dry-run"]),
|
|
214
215
|
})
|
|
216
|
+
// 装完顺手点亮历史搜索:有宿主默认库就绑一次,没有就如实说「未启用 + 怎么开」。
|
|
217
|
+
// dry-run 不碰任何东西(计划模式一个字节都不写)。
|
|
218
|
+
const sessionIndex = opts["dry-run"] ? null : await lightUpHistorySearch(L.root)
|
|
219
|
+
const line = historySearchLine(sessionIndex)
|
|
215
220
|
return ok(
|
|
216
221
|
"install",
|
|
217
|
-
opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}
|
|
222
|
+
(opts["dry-run"] ? "dry-run:只是计划,一个字节都没写" : `装好了:${out.shim}${line ? `\n${line}` : ""}`),
|
|
218
223
|
{
|
|
219
224
|
store: out.store,
|
|
220
225
|
...storeProvenance(ctx),
|
|
@@ -229,6 +234,7 @@ export function installCmd(opts, ctx) {
|
|
|
229
234
|
resident: out.resident,
|
|
230
235
|
dryRun: Boolean(opts["dry-run"]),
|
|
231
236
|
plan: out.report,
|
|
237
|
+
sessionIndex,
|
|
232
238
|
},
|
|
233
239
|
)
|
|
234
240
|
} catch (err) {
|
|
@@ -404,51 +410,39 @@ export async function memoryApproveCmd(opts, ctx) {
|
|
|
404
410
|
// ── learn ────────────────────────────────────────────────────────────
|
|
405
411
|
|
|
406
412
|
/**
|
|
407
|
-
*
|
|
413
|
+
* 旧学习链的执行入口**已退役**(欠账收口 · S1)。
|
|
408
414
|
*
|
|
409
|
-
*
|
|
410
|
-
*
|
|
411
|
-
*
|
|
415
|
+
* 退役依据:日常主链已换成「回合结束后台复习」,两条链会处理同一次纠正;旧链的子会话还带着
|
|
416
|
+
* 可写穿常驻记忆的工具面。**只退执行,不退数据**:队列、游标、候选、audit 与旧读取器全部原样,
|
|
417
|
+
* 历史可追溯,升级不重放积压。
|
|
412
418
|
*
|
|
413
|
-
*
|
|
419
|
+
* · `learn run --dry-run` 仍可看积压(只读,不移动游标)。
|
|
420
|
+
* · 普通 `learn run` 明确报退役并**非零退出**(旧调度器靠退出码判断失败,不能让它误报成功)。
|
|
421
|
+
* · 不再 spawn 学习子会话,也不再写了队列没人消费。
|
|
414
422
|
*/
|
|
415
423
|
export async function learnRun(opts, ctx) {
|
|
416
424
|
const { L } = ctx
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
425
|
+
if (!opts["dry-run"]) {
|
|
426
|
+
return fail(
|
|
427
|
+
"learn.run",
|
|
428
|
+
"RETIRED",
|
|
429
|
+
"learn run 已退役:旧学习链不再提炼候选(历史队列与游标原样保留)。用 `learn run --dry-run` 查看积压;学习由回合后的后台复习承担。",
|
|
430
|
+
{ retired: true, pendingOffset: queueOffset(L) },
|
|
431
|
+
)
|
|
420
432
|
}
|
|
421
433
|
|
|
422
434
|
const before = queueOffset(L)
|
|
423
435
|
const res = await consumeQueue(L, {
|
|
424
436
|
projectDir: opts.project ?? L.root,
|
|
425
|
-
|
|
426
|
-
dryRun: Boolean(opts["dry-run"]),
|
|
437
|
+
dryRun: true,
|
|
427
438
|
})
|
|
428
439
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
pending: res.pending,
|
|
433
|
-
torn: res.torn,
|
|
434
|
-
offset: before,
|
|
435
|
-
})
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
const summary = res.processed === 0
|
|
439
|
-
? "nothing new to learn"
|
|
440
|
-
: `${res.processed} correction(s): ${res.succeeded} produced candidates, ${res.failed} failed, ${res.skipped} skipped`
|
|
441
|
-
return ok("learn.run", summary, {
|
|
442
|
-
dryRun: false,
|
|
443
|
-
processed: res.processed,
|
|
444
|
-
succeeded: res.succeeded,
|
|
445
|
-
failed: res.failed,
|
|
446
|
-
skipped: res.skipped,
|
|
440
|
+
return ok("learn.run", `${res.pending} correction(s) waiting (dry run: nothing was learned)`, {
|
|
441
|
+
dryRun: true,
|
|
442
|
+
retired: true,
|
|
447
443
|
pending: res.pending,
|
|
448
444
|
torn: res.torn,
|
|
449
|
-
|
|
450
|
-
offsetAfter: queueOffset(L),
|
|
451
|
-
entries: res.entries,
|
|
445
|
+
offset: before,
|
|
452
446
|
})
|
|
453
447
|
}
|
|
454
448
|
|
package/src/cli/main.mjs
CHANGED
|
@@ -53,9 +53,11 @@ Usage: oc-grow [--store <dir>] [--json] <command> [args]
|
|
|
53
53
|
uninstall [--config <dir>] [--from <manifest>]
|
|
54
54
|
write the host plugin file + register D/skills/;
|
|
55
55
|
changes nothing inside D
|
|
56
|
-
learn run [--
|
|
57
|
-
|
|
58
|
-
candidates
|
|
56
|
+
learn run [--dry-run]
|
|
57
|
+
RETIRED: the old learning chain no longer distils
|
|
58
|
+
candidates (background review owns learning now).
|
|
59
|
+
--dry-run still reports the captured backlog;
|
|
60
|
+
history (queue/offset/candidates/audit) stays as-is
|
|
59
61
|
journey [--since <dur>] [--kind <k>] [--state <s>] [--reveal 0..1]
|
|
60
62
|
[--play] [--fps <n>] [--json]
|
|
61
63
|
what has been learned: a timeline graph (default full
|
|
@@ -270,10 +272,27 @@ function render(command, env) {
|
|
|
270
272
|
].join("\n")
|
|
271
273
|
case "memory.pending": {
|
|
272
274
|
if (!d.pending?.length) return "no staged proposals"
|
|
275
|
+
const flat = (v) => String(v ?? "").split("\n").map((x) => x.trim()).filter(Boolean).join(" ")
|
|
276
|
+
const oldLine = (p) => {
|
|
277
|
+
if (p.matchState === "ambiguous") return `旧:歧义(${p.matchHits} 条命中「${p.match}」)${p.oldCandidates?.length ? `: ${p.oldCandidates.map(flat).join(" | ")}` : ""}`
|
|
278
|
+
if (p.matchState === "not-found") return `旧:未找到(「${p.match}」零命中,批准会失败)`
|
|
279
|
+
return `旧:${flat(p.oldText)}`
|
|
280
|
+
}
|
|
273
281
|
return d.pending
|
|
274
282
|
.map((p) => {
|
|
275
|
-
const
|
|
276
|
-
|
|
283
|
+
const head = ` ${p.file} ${p.op ?? "?"} ${p.kind ?? "?"}${p.label ? ` ${p.label}` : ""}`
|
|
284
|
+
// S5:附属文件动作要能看见「哪个文件、新/覆盖/删除、旧文与新文」,stale 如实标。
|
|
285
|
+
if (p.kind === "skills" && (p.op === "write_file" || p.op === "remove_file")) {
|
|
286
|
+
const state = p.state === "new" ? "新" : p.state === "ok" ? (p.op === "remove_file" ? "删除" : "覆盖") : String(p.state ?? "?")
|
|
287
|
+
const oldTxt = p.state === "new" || !p.fileExists ? "旧:(原先不存在)" : `旧:${flat(p.oldText)}`
|
|
288
|
+
return p.op === "write_file"
|
|
289
|
+
? `${head}\n 文件:${p.filePath}(${state})\n ${oldTxt}\n 新:${flat(p.newText)}`
|
|
290
|
+
: `${head}\n 文件:${p.filePath}(${state})\n ${oldTxt}`
|
|
291
|
+
}
|
|
292
|
+
// 人读行的判据:update/remove 要能看见**被替换/删除的那一条全文**,不是只有新文或定位子串。
|
|
293
|
+
if (p.op === "update") return `${head}\n ${oldLine(p)}\n 新:${flat(p.text)}`
|
|
294
|
+
if (p.op === "remove") return `${head}\n ${oldLine(p)}`
|
|
295
|
+
return `${head} ${flat(p.text ?? p.match ?? "")}`
|
|
277
296
|
})
|
|
278
297
|
.join("\n")
|
|
279
298
|
}
|
package/src/core/approve.mjs
CHANGED
|
@@ -19,12 +19,12 @@ import { withCommitLock } from "./lock.mjs"
|
|
|
19
19
|
import { appendAudit } from "./audit.mjs"
|
|
20
20
|
import { createMemoryStore, storeHashOf } from "./memories.mjs"
|
|
21
21
|
import { sha256 } from "./ids.mjs"
|
|
22
|
-
import { runSkillAction } from "./skill-actions.mjs"
|
|
22
|
+
import { runSkillAction, resolveSupportTarget, applySupportFile } from "./skill-actions.mjs"
|
|
23
23
|
import { snapshotSkills } from "./skill-backup.mjs"
|
|
24
24
|
import { readCreatedBy, SKILL_FILE, skillsDir } from "./skills.mjs"
|
|
25
25
|
|
|
26
26
|
const OPS = ["add", "update", "remove", "batch"]
|
|
27
|
-
const SKILL_OPS = ["create", "patch"]
|
|
27
|
+
const SKILL_OPS = ["create", "patch", "write_file", "remove_file"]
|
|
28
28
|
const KINDS = ["memory", "user", "skills"]
|
|
29
29
|
|
|
30
30
|
const MAX_DIFF_LINES = 200
|
|
@@ -77,6 +77,24 @@ function skillTargetOf(L, name) {
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
|
|
81
|
+
/** 附属文件提案的目标与「当初那份」指纹;路径守卫与写路径同一实现。 */
|
|
82
|
+
function skillSupportOf(L, rec) {
|
|
83
|
+
const skillDir = path.join(skillsDir(L.root), String(rec.name))
|
|
84
|
+
const skillFile = path.join(skillDir, SKILL_FILE)
|
|
85
|
+
if (!fs.existsSync(skillFile)) return { ok: false, error: `技能不存在:${String(rec.name)}` }
|
|
86
|
+
const t = resolveSupportTarget(skillDir, rec.filePath)
|
|
87
|
+
if (!t.ok) return t
|
|
88
|
+
const exists = fs.existsSync(t.abs)
|
|
89
|
+
return {
|
|
90
|
+
ok: true,
|
|
91
|
+
abs: t.abs,
|
|
92
|
+
rel: t.rel,
|
|
93
|
+
exists,
|
|
94
|
+
hash: exists ? sha256(fs.readFileSync(t.abs)) : null,
|
|
95
|
+
createdBy: readCreatedBy(skillFile),
|
|
96
|
+
}
|
|
97
|
+
}
|
|
80
98
|
/** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
|
|
81
99
|
export function listPending(L) {
|
|
82
100
|
const store = createMemoryStore({ root: L.root })
|
|
@@ -98,24 +116,64 @@ export function listPending(L) {
|
|
|
98
116
|
label: origin === "background" ? "[auto]" : null,
|
|
99
117
|
text: raw.text ?? null,
|
|
100
118
|
match: raw.match ?? null,
|
|
119
|
+
proposalHash: raw.proposalHash ?? null,
|
|
101
120
|
// 批量提案:列出条目数与动作分布——人要能一眼看出「在批什么、几笔」
|
|
102
121
|
operations: Array.isArray(raw.operations) ? raw.operations : null,
|
|
103
122
|
ops: Array.isArray(raw.operations) ? raw.operations.length : null,
|
|
104
123
|
stagedAt: raw.stagedAt ?? null,
|
|
105
124
|
}
|
|
125
|
+
// S3:update/remove 的「批的是哪一条」必须能回答 —— 把人要看的**旧条目全文**取出来。
|
|
126
|
+
// 零命中/歧义如实标出,不挑一条当旧文(批准时 updateTrusted 仍会因歧义失败)。
|
|
127
|
+
if ((raw.kind ?? "memory") !== "skills" && (entry.op === "update" || entry.op === "remove")) {
|
|
128
|
+
const kind = raw.kind === "user" ? "user" : "memory"
|
|
129
|
+
const needle = String(raw.match ?? "")
|
|
130
|
+
let resident = []
|
|
131
|
+
try { resident = store.read({ kind }) ?? [] } catch { resident = [] }
|
|
132
|
+
const hits = needle ? resident.filter((e) => e.includes(needle)) : []
|
|
133
|
+
entry.matchHits = hits.length
|
|
134
|
+
entry.matchState = hits.length === 0 ? "not-found" : hits.length > 1 ? "ambiguous" : "ok"
|
|
135
|
+
entry.oldText = hits.length === 1 ? hits[0] : null
|
|
136
|
+
// 歧义时把命中的条目也带上:人得看出「该写成哪一条」才能改提案。
|
|
137
|
+
entry.oldCandidates = hits.length > 1 ? hits : null
|
|
138
|
+
}
|
|
106
139
|
if (raw.kind === "skills") {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
140
|
+
if (raw.op === "write_file" || raw.op === "remove_file") {
|
|
141
|
+
const t = skillSupportOf(L, raw)
|
|
142
|
+
let state = "invalid"
|
|
143
|
+
let oldText = null
|
|
144
|
+
if (t.ok) {
|
|
145
|
+
oldText = t.exists ? fs.readFileSync(t.abs, "utf8") : null
|
|
146
|
+
if (raw.op === "remove_file") state = t.exists && t.hash === raw.baseHash ? "ok" : "stale"
|
|
147
|
+
else if (t.exists) state = t.hash === raw.baseHash ? "ok" : "stale"
|
|
148
|
+
else state = raw.baseHash === null ? "new" : "stale"
|
|
149
|
+
}
|
|
150
|
+
const newText = raw.op === "write_file" ? raw.text ?? "" : null
|
|
151
|
+
Object.assign(entry, {
|
|
152
|
+
name: raw.name ?? null,
|
|
153
|
+
filePath: raw.filePath ?? null,
|
|
154
|
+
fileExists: Boolean(t.ok && t.exists),
|
|
155
|
+
baseHash: raw.baseHash ?? null,
|
|
156
|
+
state,
|
|
157
|
+
oldText,
|
|
158
|
+
newText,
|
|
159
|
+
diff: lineDiff(oldText ?? "", newText ?? ""),
|
|
160
|
+
stale: state === "stale" || state === "invalid",
|
|
161
|
+
detail: t.ok ? null : t.error,
|
|
162
|
+
})
|
|
163
|
+
} else {
|
|
164
|
+
const target = skillTargetOf(L, raw.name)
|
|
165
|
+
const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
|
|
166
|
+
const newText = raw.op === "create" ? raw.text ?? "" : oldText.replace(String(raw.match ?? ""), String(raw.text ?? ""))
|
|
167
|
+
Object.assign(entry, {
|
|
168
|
+
name: raw.name ?? null,
|
|
169
|
+
description: raw.description ?? null,
|
|
170
|
+
oldText,
|
|
171
|
+
newText,
|
|
172
|
+
diff: lineDiff(oldText, newText),
|
|
173
|
+
// 过期预判:人不用等批准才知道提案已经跟不上了
|
|
174
|
+
stale: raw.op === "create" ? target.exists : !target.exists || (raw.baseHash ? target.hash !== raw.baseHash : false),
|
|
175
|
+
})
|
|
176
|
+
}
|
|
119
177
|
}
|
|
120
178
|
return entry
|
|
121
179
|
})
|
|
@@ -145,6 +203,18 @@ function invalidReason(rec) {
|
|
|
145
203
|
if (kind === "skills") {
|
|
146
204
|
if (!SKILL_OPS.includes(rec.op)) return `未知的技能 op:${String(rec.op)}(可用:${SKILL_OPS.join(" / ")})`
|
|
147
205
|
if (typeof rec.name !== "string" || !rec.name.trim()) return "技能提案缺少 name"
|
|
206
|
+
if (rec.op === "write_file" || rec.op === "remove_file") {
|
|
207
|
+
if (typeof rec.filePath !== "string" || !rec.filePath.trim()) return `${rec.op} 提案缺少 filePath`
|
|
208
|
+
if (!("baseHash" in rec)) return `${rec.op} 提案缺少 baseHash`
|
|
209
|
+
if (rec.op === "remove_file") {
|
|
210
|
+
if (typeof rec.text === "string" && rec.text.trim()) return "remove_file 提案不该带新内容(text 必须为空)"
|
|
211
|
+
if (!/^[0-9a-f]{64}$/.test(String(rec.baseHash ?? ""))) return "remove_file 必须带旧字节 sha256"
|
|
212
|
+
} else {
|
|
213
|
+
if (typeof rec.text !== "string") return "write_file 提案缺少 text"
|
|
214
|
+
if (rec.baseHash !== null && !/^[0-9a-f]{64}$/.test(String(rec.baseHash))) return "write_file 的 baseHash 必须是 null 或 sha256"
|
|
215
|
+
}
|
|
216
|
+
return null
|
|
217
|
+
}
|
|
148
218
|
if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
|
|
149
219
|
if (rec.op === "patch" && (typeof rec.match !== "string" || !rec.match.trim())) return "patch 提案缺少 old_string(match)"
|
|
150
220
|
return null
|
|
@@ -168,7 +238,47 @@ function invalidReason(rec) {
|
|
|
168
238
|
* 技能提案:先判过期(源或所有权变了就不许覆盖),再在快照之后按已批准的技能写路径应用。
|
|
169
239
|
* 过期判据是**内容指纹**:create 要求目标仍不存在;patch 要求目标仍存在、内容仍是当初那份、所有权没变。
|
|
170
240
|
*/
|
|
171
|
-
async function approveSkillPending(L, rec, file, who, pendingPath) {
|
|
241
|
+
async function approveSkillPending(L, rec, file, who, pendingPath, expectHash = null) {
|
|
242
|
+
// S5:附属文件动作在批准时重验路径/存在性/旧字节/所有权,失败保留提案。
|
|
243
|
+
if (rec.op === "write_file" || rec.op === "remove_file") {
|
|
244
|
+
const canonical = JSON.stringify({ op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath, baseHash: rec.baseHash, text: rec.text, createdBy: rec.createdBy })
|
|
245
|
+
const expected = sha256(Buffer.from(canonical))
|
|
246
|
+
if (rec.proposalHash && rec.proposalHash !== expected) {
|
|
247
|
+
return { ok: false, reason: "tampered", file, detail: "提案内容与登记时的哈希不符(待批文件被改过)" }
|
|
248
|
+
}
|
|
249
|
+
if (expectHash && expectHash !== expected) {
|
|
250
|
+
return { ok: false, reason: "stale", file, detail: "提案不是预览时的那一份(expectHash 不匹配)" }
|
|
251
|
+
}
|
|
252
|
+
const locked = withCommitLock(L.lock, () => {
|
|
253
|
+
const t = skillSupportOf(L, rec)
|
|
254
|
+
if (!t.ok) return { ok: false, reason: "stale", file, detail: t.error }
|
|
255
|
+
if (rec.op === "remove_file") {
|
|
256
|
+
if (!t.exists) return { ok: false, reason: "stale", file, detail: "附件在待批期间消失" }
|
|
257
|
+
if (t.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "附件在待批期间被改动" }
|
|
258
|
+
} else if (t.exists) {
|
|
259
|
+
if (t.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "附件在待批期间被改动" }
|
|
260
|
+
} else if (rec.baseHash !== null) {
|
|
261
|
+
return { ok: false, reason: "stale", file, detail: "附件在待批期间消失(提案是按覆盖旧字节提的)" }
|
|
262
|
+
}
|
|
263
|
+
if (rec.createdBy && t.createdBy !== rec.createdBy) {
|
|
264
|
+
return { ok: false, reason: "stale", file, detail: `所有权从 ${rec.createdBy} 变成 ${t.createdBy}` }
|
|
265
|
+
}
|
|
266
|
+
const applied = applySupportFile({
|
|
267
|
+
root: L.root, name: rec.name, action: rec.op, filePath: rec.filePath,
|
|
268
|
+
text: rec.text, expectedBaseHash: rec.baseHash, createdBy: rec.createdBy, origin: "foreground",
|
|
269
|
+
})
|
|
270
|
+
if (!applied.ok) return { ok: false, reason: "apply-failed", file, detail: applied.error ?? "附件写入失败" }
|
|
271
|
+
fs.rmSync(pendingPath, { force: true })
|
|
272
|
+
appendAudit(L, {
|
|
273
|
+
event: "approve", file, op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath,
|
|
274
|
+
origin: rec.origin ?? "unknown", approvedBy: who, generation: storeHashOf(L.root),
|
|
275
|
+
})
|
|
276
|
+
return { ok: true, file, op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath,
|
|
277
|
+
origin: rec.origin ?? "unknown", approvedBy: who, pending: listPending(L).length }
|
|
278
|
+
})
|
|
279
|
+
if (!locked.ok) return { ok: false, reason: locked.reason, file }
|
|
280
|
+
return locked.value
|
|
281
|
+
}
|
|
172
282
|
const target = skillTargetOf(L, rec.name)
|
|
173
283
|
if (rec.op === "create" && target.exists) {
|
|
174
284
|
return { ok: false, reason: "stale", file, detail: `同名技能在待批期间出现:${path.relative(L.root, target.file)}` }
|
|
@@ -232,7 +342,7 @@ async function approveSkillPending(L, rec, file, who, pendingPath) {
|
|
|
232
342
|
*
|
|
233
343
|
* @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
|
|
234
344
|
*/
|
|
235
|
-
export async function approvePending(L, ref, { approvedBy = null } = {}) {
|
|
345
|
+
export async function approvePending(L, ref, { approvedBy = null, expectHash = null } = {}) {
|
|
236
346
|
const found = resolvePendingRef(L, ref)
|
|
237
347
|
if (!found.ok) return found
|
|
238
348
|
|
|
@@ -253,7 +363,7 @@ export async function approvePending(L, ref, { approvedBy = null } = {}) {
|
|
|
253
363
|
|
|
254
364
|
const kind = rec.kind ?? "memory"
|
|
255
365
|
// 技能提案:按 kind 分派到技能写路径(不是把批准器放宽成任意写入)。
|
|
256
|
-
if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath)
|
|
366
|
+
if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath, expectHash)
|
|
257
367
|
|
|
258
368
|
const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
|
|
259
369
|
try {
|
|
@@ -21,6 +21,7 @@ import path from "node:path"
|
|
|
21
21
|
|
|
22
22
|
import { createMemoryStore, findEntryIndex } from "./memories.mjs"
|
|
23
23
|
import { decideWrite } from "./write-approval.mjs"
|
|
24
|
+
import { BACKGROUND_SUBSESSION_KINDS } from "./subsessions.mjs"
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* 动作是**封闭枚举**。加动作等于改工具契约——加 `approve` 就等于给了自批的口子。
|
|
@@ -61,7 +62,13 @@ export function identityFor({
|
|
|
61
62
|
interactive = false,
|
|
62
63
|
backgroundAgents = [],
|
|
63
64
|
foregroundAgents = [],
|
|
65
|
+
// S0:OCG 自己派发的子会话按**子会话 id** 登记(core/subsessions.mjs),身份从那里来。
|
|
66
|
+
// 优先级最高:它是「谁派发的」的直接证据,比 agent 名与部署方名单都强。
|
|
67
|
+
backgroundKind = null,
|
|
64
68
|
} = {}) {
|
|
69
|
+
if (typeof backgroundKind === "string" && BACKGROUND_SUBSESSION_KINDS.includes(backgroundKind)) {
|
|
70
|
+
return { origin: "background", agent: `ocg-${backgroundKind}` }
|
|
71
|
+
}
|
|
65
72
|
if (agent && Array.isArray(backgroundAgents) && backgroundAgents.includes(agent)) {
|
|
66
73
|
return { origin: "background", agent }
|
|
67
74
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// 首装点亮历史搜索:装完就该能用「查历史会话」,而不是让用户先学会跑一条 CLI。
|
|
2
|
+
// 判据(照 deferred-and-user-risks §6-P2):**已知默认位置存在 ⇒ 绑定一次**;
|
|
3
|
+
// 不存在就**不猜**、保持 not-configured,但把「未启用 + 怎么启用」说出口。
|
|
4
|
+
import fs from "node:fs"
|
|
5
|
+
import os from "node:os"
|
|
6
|
+
import path from "node:path"
|
|
7
|
+
|
|
8
|
+
import { repairHintFor, statusStore, syncStore } from "./session-index.mjs"
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 宿主 opencode.db 的已知默认位置(不扫盘、不嗅探进程):
|
|
12
|
+
* `OCG_SESSION_SOURCE` 显式给了就用它;否则按平台默认数据目录列。
|
|
13
|
+
*/
|
|
14
|
+
export function hostDbCandidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
|
|
15
|
+
const out = []
|
|
16
|
+
const explicit = env.OCG_SESSION_SOURCE || env.OPENCODE_DB
|
|
17
|
+
if (explicit) out.push(explicit)
|
|
18
|
+
const xdg = env.XDG_DATA_HOME || path.join(home, ".local", "share")
|
|
19
|
+
out.push(path.join(xdg, "opencode", "opencode.db"))
|
|
20
|
+
if (platform === "darwin") out.push(path.join(home, "Library", "Application Support", "opencode", "opencode.db"))
|
|
21
|
+
if (platform === "win32" && env.APPDATA) out.push(path.join(env.APPDATA, "opencode", "opencode.db"))
|
|
22
|
+
return [...new Set(out.map((p) => path.resolve(String(p))))]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 装完那一步:已绑定就不动;有默认库就绑一次;没有就如实说「未启用」。
|
|
27
|
+
* `sync` 是测试注入缝(默认走真 syncStore)。
|
|
28
|
+
*/
|
|
29
|
+
export async function lightUpHistorySearch(root, { env = process.env, platform = process.platform, home = os.homedir(), sync = syncStore } = {}) {
|
|
30
|
+
const before = statusStore({ root })
|
|
31
|
+
if (before.state === "ok") return { state: "already", parts: before.counts?.parts ?? null, source: before.source ?? null }
|
|
32
|
+
const candidates = hostDbCandidates({ env, platform, home })
|
|
33
|
+
const found = candidates.find((p) => {
|
|
34
|
+
try {
|
|
35
|
+
return fs.statSync(p).isFile()
|
|
36
|
+
} catch {
|
|
37
|
+
return false
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
if (!found) return { state: "absent", hint: repairHintFor("not-configured"), candidates }
|
|
41
|
+
const r = await sync({ root, sourcePath: found })
|
|
42
|
+
if (!r?.ok) return { state: "failed", source: found, error: r?.error ?? "绑定失败", candidates }
|
|
43
|
+
return { state: "bound", source: found, parts: r.parts ?? null }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 人读一行:装完到底能不能查历史。 */
|
|
47
|
+
export function historySearchLine(area) {
|
|
48
|
+
if (!area) return null
|
|
49
|
+
if (area.state === "already") return null
|
|
50
|
+
if (area.state === "bound") return `历史搜索已启用:${area.source}${Number.isFinite(area.parts) ? `(${area.parts} 个片段)` : ""}`
|
|
51
|
+
if (area.state === "failed") return `历史搜索未启用:绑定 ${area.source} 失败(${area.error})`
|
|
52
|
+
return `历史搜索未启用(没找到宿主库):${area.hint}`
|
|
53
|
+
}
|
|
@@ -38,9 +38,15 @@ import { decideWrite } from "./write-approval.mjs"
|
|
|
38
38
|
import { scanForThreats } from "./threats.mjs"
|
|
39
39
|
import { readUsage, recordSkillCreated, bumpSkillPatch, bumpSkillView, updateRecord } from "./skill-usage.mjs"
|
|
40
40
|
import { archiveSkill } from "./skill-lifecycle.mjs"
|
|
41
|
+
import { snapshotSkills } from "./skill-backup.mjs"
|
|
41
42
|
|
|
42
43
|
/** 动作是封闭枚举:加动作=改工具契约(照 memory-actions 的 extra#4 纪律,无 approve/apply)。 */
|
|
43
|
-
export const SKILL_ACTIONS = ["create", "patch", "view", "list", "archive"]
|
|
44
|
+
export const SKILL_ACTIONS = ["create", "patch", "view", "list", "archive", "write_file", "remove_file"]
|
|
45
|
+
|
|
46
|
+
/** 附属文件只允许落在这四个子目录(照 Hermes `_SUPPORT_DIRS` 的同形约束)。 */
|
|
47
|
+
export const SUPPORT_DIRS = ["references", "scripts", "templates", "assets"]
|
|
48
|
+
/** 单个附属文件上限:正文上限 100k 字符留给人读手册,附件只装脚本/模板/素材。 */
|
|
49
|
+
export const MAX_SUPPORT_FILE_BYTES = 1024 * 1024
|
|
44
50
|
|
|
45
51
|
/** description 预算:照 Hermes `SKILL_PROMPT_DESC_LIMIT`(新技能不许吃掉索引的路由信号)。 */
|
|
46
52
|
export const MAX_DESCRIPTION_LENGTH = 60
|
|
@@ -118,6 +124,102 @@ function externalHit(name, externalDirs = []) {
|
|
|
118
124
|
return null
|
|
119
125
|
}
|
|
120
126
|
|
|
127
|
+
/** 校验附属文件路径(纯词法):四目录之一 + 至少两段,拒绝对路径/盘符/UNC/`.`/`..`/空段。 */
|
|
128
|
+
export function validateSupportPath(filePath) {
|
|
129
|
+
if (typeof filePath !== "string" || !filePath.length) return "file_path 必填"
|
|
130
|
+
if (filePath.includes("\u0000")) return "file_path 含 NUL"
|
|
131
|
+
if (filePath.startsWith("/") || /^[A-Za-z]:/.test(filePath)) return "只接受技能目录下的相对路径(不许绝对路径/盘符)"
|
|
132
|
+
if (filePath.includes("\\")) return "只接受 POSIX 相对路径(不许反斜杠/UNC)"
|
|
133
|
+
const segs = filePath.split("/")
|
|
134
|
+
if (segs.some((x) => x === "")) return "路径包含空段"
|
|
135
|
+
if (segs.some((x) => x === "." || x === "..")) return "路径不许包含 . 或 .. 段"
|
|
136
|
+
// Windows 会把尾随点/空格、保留名(CON/PRN/AUX/NUL/COM1-9/LPT1-9)别名成别的文件;
|
|
137
|
+
// 这些写法在 Linux 上合法、到 Windows 上会指到意想不到的位置,统一拒绝(不赌平台)。
|
|
138
|
+
for (const seg of segs) {
|
|
139
|
+
if (/[\u0000-\u001f]/.test(seg)) return "路径包含控制字符"
|
|
140
|
+
if (/[<>:"|?*]/.test(seg)) return `路径段含 Windows 禁止字符:${seg}`
|
|
141
|
+
if (/[. ]$/.test(seg)) return `路径段不许以点或空格结尾:${seg}`
|
|
142
|
+
if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$/i.test(seg)) return `路径段是 Windows 保留名:${seg}`
|
|
143
|
+
}
|
|
144
|
+
if (segs.length < 2) return "必须落在 references|scripts|templates|assets 下的文件"
|
|
145
|
+
if (!SUPPORT_DIRS.includes(segs[0])) return `只允许 references|scripts|templates|assets,收到 ${segs[0]}`
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 逐级检查已存在的祖先里有没有符号链接(解析与落盘前共用同一个判定)。 */
|
|
150
|
+
function hasSymlinkComponent(skillDir, rel) {
|
|
151
|
+
let cur = skillDir
|
|
152
|
+
for (const seg of String(rel).split("/")) {
|
|
153
|
+
cur = path.join(cur, seg)
|
|
154
|
+
try { if (fs.lstatSync(cur).isSymbolicLink()) return true } catch { /* 不存在:继续 */ }
|
|
155
|
+
}
|
|
156
|
+
return false
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 解析并校验真实落点:逐级拒绝符号链接,最终路径必须留在 realpath(技能目录) 内。 */
|
|
160
|
+
export function resolveSupportTarget(skillDir, filePath) {
|
|
161
|
+
const bad = validateSupportPath(filePath)
|
|
162
|
+
if (bad) return { ok: false, error: bad }
|
|
163
|
+
const segs = filePath.split("/")
|
|
164
|
+
if (hasSymlinkComponent(skillDir, filePath)) return { ok: false, error: `路径包含符号链接,拒绝写入:${filePath}` }
|
|
165
|
+
const realRoot = fs.realpathSync(skillDir)
|
|
166
|
+
const abs = path.resolve(skillDir, ...segs)
|
|
167
|
+
if (!abs.startsWith(realRoot + path.sep)) return { ok: false, error: `路径逃逸出技能目录:${filePath}` }
|
|
168
|
+
return { ok: true, abs, rel: segs.join("/"), realRoot }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 落盘(同步):批准路径与直写路径共用;调用方负责门控与快照外的并发锁。 */
|
|
172
|
+
export function applySupportFile({ root, name, action, filePath, text = null, expectedBaseHash, createdBy, origin, agent = null }) {
|
|
173
|
+
const location = skillFileOf(root, name)
|
|
174
|
+
if (!fs.existsSync(location)) return fail(action, `技能不存在:${name}`, { name })
|
|
175
|
+
const target = resolveSupportTarget(path.dirname(location), filePath)
|
|
176
|
+
if (!target.ok) return fail(action, target.error, { name, location })
|
|
177
|
+
const exists = fs.existsSync(target.abs)
|
|
178
|
+
if (action === "remove_file" && !exists) return fail(action, `附件不存在:${String(filePath)}`, { name, location })
|
|
179
|
+
const baseHash = action === "write_file" ? (exists ? sha256(fs.readFileSync(target.abs)) : null) : (exists ? sha256(fs.readFileSync(target.abs)) : null)
|
|
180
|
+
if (expectedBaseHash !== undefined && baseHash !== expectedBaseHash) {
|
|
181
|
+
return fail(action, "目标在批准前被改动(baseHash 不匹配)", { name, location })
|
|
182
|
+
}
|
|
183
|
+
const snap = snapshotSkills(root, `skill-file:${name}`)
|
|
184
|
+
if (!snap.ok) return fail(action, snap.error ?? "快照失败,未写入", { name, location })
|
|
185
|
+
if (hasSymlinkComponent(path.dirname(location), target.rel)) {
|
|
186
|
+
return fail(action, `路径包含符号链接,拒绝写入:${filePath}`, { name, location })
|
|
187
|
+
}
|
|
188
|
+
if (action === "write_file") fs.mkdirSync(path.dirname(target.abs), { recursive: true })
|
|
189
|
+
const parentReal = fs.realpathSync(path.dirname(target.abs))
|
|
190
|
+
if (!parentReal.startsWith(target.realRoot + path.sep) && parentReal !== target.realRoot) {
|
|
191
|
+
return fail(action, "目标父目录在写入前逃出了技能目录(符号链接?)", { name, location })
|
|
192
|
+
}
|
|
193
|
+
const dst = path.join(parentReal, path.basename(target.abs))
|
|
194
|
+
const before = fs.statSync(parentReal)
|
|
195
|
+
if (action === "write_file") {
|
|
196
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC |
|
|
197
|
+
(fs.constants.O_NOFOLLOW ?? 0)
|
|
198
|
+
const fd = fs.openSync(dst, flags, 0o600)
|
|
199
|
+
try {
|
|
200
|
+
const after = fs.statSync(parentReal)
|
|
201
|
+
if (after.dev !== before.dev || after.ino !== before.ino) {
|
|
202
|
+
return fail(action, "目标父目录在打开后发生了变化,拒绝写入", { name, location })
|
|
203
|
+
}
|
|
204
|
+
fs.writeFileSync(fd, text)
|
|
205
|
+
} finally { fs.closeSync(fd) }
|
|
206
|
+
} else {
|
|
207
|
+
const after = fs.statSync(parentReal)
|
|
208
|
+
if (after.dev !== before.dev || after.ino !== before.ino) {
|
|
209
|
+
return fail(action, "目标父目录在删除前发生了变化,拒绝删除", { name, location })
|
|
210
|
+
}
|
|
211
|
+
fs.unlinkSync(dst)
|
|
212
|
+
}
|
|
213
|
+
appendAudit(layout(root), {
|
|
214
|
+
event: action === "write_file" ? "skill-file-write" : "skill-file-remove",
|
|
215
|
+
name, filePath: target.rel, createdBy, origin, agent, baseHash, snapshot: snap.id ?? null,
|
|
216
|
+
})
|
|
217
|
+
return {
|
|
218
|
+
ok: true, action, name, location: target.abs, filePath: target.rel, createdBy,
|
|
219
|
+
receipt: receipt("已交付", { name, location: target.abs, createdBy, detail: `${action === "write_file" ? "写入" : "删除"}附件 ${target.rel}` }),
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
121
223
|
/**
|
|
122
224
|
* 跑一个技能动作。返回结构化结果(不抛):成功与失败都带认账 `receipt`。
|
|
123
225
|
*
|
|
@@ -144,6 +246,9 @@ export async function runSkillAction({
|
|
|
144
246
|
content = null,
|
|
145
247
|
old_string = null,
|
|
146
248
|
new_string = null,
|
|
249
|
+
file_path = null,
|
|
250
|
+
file_content = null,
|
|
251
|
+
expectedBaseHash = undefined,
|
|
147
252
|
ask = null,
|
|
148
253
|
hostPermission = null,
|
|
149
254
|
agentSkillEnabled = true,
|
|
@@ -263,6 +368,71 @@ export async function runSkillAction({
|
|
|
263
368
|
}
|
|
264
369
|
}
|
|
265
370
|
|
|
371
|
+
// ── S5 附属文件动作:只动四个子目录里的文件,根 SKILL.md 只读 ──────────────
|
|
372
|
+
if (action === "write_file" || action === "remove_file") {
|
|
373
|
+
if (!name) return fail(action, `${action} 需要 name`, { name })
|
|
374
|
+
if (!fs.existsSync(location)) return fail(action, `技能不存在:${name}`, { name })
|
|
375
|
+
// 后台只动 agent-created(与 patch 同一条规则;user-owned 先 adopt)。
|
|
376
|
+
if (origin === "background" && readCreatedBy(location) !== "agent") {
|
|
377
|
+
return { ok: false, action, error: `回合后通道只动 agent-created 技能:${name} 是 ${readCreatedBy(location)}-owned`, receipt: receipt("未生效", { name, location, detail: "非 agent-created" }) }
|
|
378
|
+
}
|
|
379
|
+
const skillDir = path.dirname(location)
|
|
380
|
+
const target = resolveSupportTarget(skillDir, file_path)
|
|
381
|
+
if (!target.ok) return fail(action, target.error, { name, location })
|
|
382
|
+
const exists = fs.existsSync(target.abs)
|
|
383
|
+
let text = null
|
|
384
|
+
let baseHash = null
|
|
385
|
+
let destructive = false
|
|
386
|
+
if (action === "remove_file") {
|
|
387
|
+
if (!exists) return fail(action, `附件不存在:${String(file_path)}`, { name, location })
|
|
388
|
+
baseHash = sha256(fs.readFileSync(target.abs))
|
|
389
|
+
destructive = true
|
|
390
|
+
} else {
|
|
391
|
+
if (typeof file_content !== "string") return fail(action, "write_file 需要 file_content", { name, location })
|
|
392
|
+
const bytes = Buffer.byteLength(file_content, "utf8")
|
|
393
|
+
if (bytes > MAX_SUPPORT_FILE_BYTES) return fail(action, `附件 ${bytes} 字节,超出 ${MAX_SUPPORT_FILE_BYTES} 上限`, { name, location })
|
|
394
|
+
const hits = scanForThreats(String(file_content), { scope: "strict" })
|
|
395
|
+
if (hits.length) return fail(action, `写入被拒:内容命中威胁模式 ${hits.join(", ")}`, { name, location })
|
|
396
|
+
baseHash = exists ? sha256(fs.readFileSync(target.abs)) : null
|
|
397
|
+
destructive = exists // 覆盖已有附件=破坏动作(闸关 + 后台也必须进待批)
|
|
398
|
+
text = file_content
|
|
399
|
+
}
|
|
400
|
+
const fileDecision = hostPermission === "deny"
|
|
401
|
+
? "deny"
|
|
402
|
+
: approved?.by
|
|
403
|
+
? "apply"
|
|
404
|
+
: decideWrite({ root, subsystem: "skills", origin, destructive, interactive: typeof ask === "function", hostPermission })
|
|
405
|
+
if (fileDecision === "deny") {
|
|
406
|
+
return { ok: false, action, error: "宿主权限闸拒绝了这次写入", receipt: receipt("未生效", { name, location, detail: "permission deny" }) }
|
|
407
|
+
}
|
|
408
|
+
if (fileDecision === "stage") {
|
|
409
|
+
const store = createMemoryStore({ root, identity: { origin, agent: identity?.agent ?? null } })
|
|
410
|
+
const proposal = {
|
|
411
|
+
op: action,
|
|
412
|
+
kind: "skills",
|
|
413
|
+
name,
|
|
414
|
+
filePath: target.rel,
|
|
415
|
+
baseHash,
|
|
416
|
+
text,
|
|
417
|
+
createdBy,
|
|
418
|
+
}
|
|
419
|
+
// 提案内容哈希:预览读到的就是它;批准时可带 expectHash 把「预览的那一份」钉住。
|
|
420
|
+
proposal.proposalHash = sha256(Buffer.from(JSON.stringify(proposal)))
|
|
421
|
+
const file = store.stageProposal(proposal)
|
|
422
|
+
return {
|
|
423
|
+
ok: true,
|
|
424
|
+
action,
|
|
425
|
+
staged: true,
|
|
426
|
+
file,
|
|
427
|
+
receipt: receipt("待批", { name, location: target.abs, detail: `进待批队列(${action} ${target.rel})`, createdBy }),
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return applySupportFile({
|
|
431
|
+
root, name, action, filePath: file_path, text,
|
|
432
|
+
expectedBaseHash, createdBy: readCreatedBy(location), origin, agent: identity?.agent ?? null,
|
|
433
|
+
})
|
|
434
|
+
}
|
|
435
|
+
|
|
266
436
|
let body = null
|
|
267
437
|
if (action === "create") {
|
|
268
438
|
const errs = [validateDescription(description), validateContent(content)].filter(Boolean)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// OCG 自建子会话的身份登记表(S0)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么要它:复习/整理都是**以宿主身份派发的子会话**,提示词里跑的 agent 是 `plan`
|
|
4
|
+
// (`REVIEW_AGENT`),而 `plan` 同时也是用户自己会开的 agent。只按 agent 名判身份,
|
|
5
|
+
// 要么把后台当未知(闸关时改删直接落盘),要么把所有 `plan` 会话一刀切成后台
|
|
6
|
+
// (用户自己在前台 plan 里的写入会被送进待批)。两种都错。
|
|
7
|
+
//
|
|
8
|
+
// 真源是**宿主给的子会话 id**:`createHostReview` 建出子会话的那一刻就知道它是什么,
|
|
9
|
+
// 登记在这里;工具面执行时用 `ctx.sessionID` 查表。进程内、只记 id 与 kind,
|
|
10
|
+
// 不落盘(子会话本身活在宿主里;进程重启后旧的子会话也不会再被派发新回合)。
|
|
11
|
+
const TTL_MS = 6 * 60 * 60 * 1000
|
|
12
|
+
const MAX_ENTRIES = 500
|
|
13
|
+
const registry = new Map()
|
|
14
|
+
|
|
15
|
+
/** 允许登记的来源种类。加新种类=扩身份契约,先想清楚它该不该有写权限。 */
|
|
16
|
+
export const BACKGROUND_SUBSESSION_KINDS = Object.freeze(["review", "curator", "learn"])
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 登记一个 OCG 派发的后台子会话。
|
|
20
|
+
* @returns {{sessionId:string,kind:string,parent:string|null,at:number}|null} 空 id / 未知 kind ⇒ null(不登记)
|
|
21
|
+
*/
|
|
22
|
+
export function registerBackgroundSubsession(sessionId, { kind = "review", parent = null, now = Date.now() } = {}) {
|
|
23
|
+
if (typeof sessionId !== "string" || !sessionId) return null
|
|
24
|
+
if (!BACKGROUND_SUBSESSION_KINDS.includes(kind)) return null
|
|
25
|
+
const at = Number.isFinite(Number(now)) ? Number(now) : Date.now()
|
|
26
|
+
registry.set(sessionId, { kind, parent: parent ?? null, at })
|
|
27
|
+
prune(at)
|
|
28
|
+
return { sessionId, kind, parent: parent ?? null, at }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 查一个会话是不是登记过的后台子会话;过期/未知 ⇒ null。 */
|
|
32
|
+
export function backgroundSubsessionKind(sessionId, { now = Date.now() } = {}) {
|
|
33
|
+
if (typeof sessionId !== "string" || !sessionId) return null
|
|
34
|
+
const rec = registry.get(sessionId)
|
|
35
|
+
if (!rec) return null
|
|
36
|
+
const t = Number(now)
|
|
37
|
+
if (Number.isFinite(t) && t - rec.at > TTL_MS) {
|
|
38
|
+
registry.delete(sessionId)
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
return rec.kind
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 子会话结束/取消时精确移除;不存在 ⇒ false。 */
|
|
45
|
+
export function forgetBackgroundSubsession(sessionId) {
|
|
46
|
+
if (typeof sessionId !== "string" || !sessionId) return false
|
|
47
|
+
return registry.delete(sessionId)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 可核对的当前清单(页面/诊断用;不暴露写口)。 */
|
|
51
|
+
export function listBackgroundSubsessions({ now = Date.now() } = {}) {
|
|
52
|
+
const t = Number(now)
|
|
53
|
+
const out = []
|
|
54
|
+
for (const [sessionId, rec] of registry) {
|
|
55
|
+
if (Number.isFinite(t) && t - rec.at > TTL_MS) { registry.delete(sessionId); continue }
|
|
56
|
+
out.push({ sessionId, kind: rec.kind, parent: rec.parent, at: rec.at })
|
|
57
|
+
}
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function prune(now) {
|
|
62
|
+
for (const [id, rec] of registry) if (now - rec.at > TTL_MS) registry.delete(id)
|
|
63
|
+
// 上限只防失控:正常情况下在途子会话远少于此,超出按插入顺序淘汰最旧的。
|
|
64
|
+
while (registry.size > MAX_ENTRIES) registry.delete(registry.keys().next().value)
|
|
65
|
+
}
|
package/src/learn/headless.mjs
CHANGED
|
@@ -24,8 +24,21 @@ import { makeScope } from "../core/identity.mjs"
|
|
|
24
24
|
export const ORIGIN = "headless-learning"
|
|
25
25
|
|
|
26
26
|
/** Tools the learning session must not hold. `write` is in the list on purpose: denying
|
|
27
|
-
* `edit` alone still leaves a session that can rewrite files it was told to read.
|
|
28
|
-
|
|
27
|
+
* `edit` alone still leaves a session that can rewrite files it was told to read.
|
|
28
|
+
*
|
|
29
|
+
* 欠账收口 · S1:过渡期里这条链若仍被调用,工具面必须在**分发层**就只读——
|
|
30
|
+
* memory(常驻记忆)、skill(技能面)、provider 的写三件(remember/forget/add_resource)
|
|
31
|
+
* 一律 deny。只靠提示词说「不要写」不算判据:宿主按 project permission 从这里删 schema。 */
|
|
32
|
+
export const DENIED_TOOLS = [
|
|
33
|
+
"bash",
|
|
34
|
+
"edit",
|
|
35
|
+
"write",
|
|
36
|
+
"memory",
|
|
37
|
+
"skill",
|
|
38
|
+
"viking_remember",
|
|
39
|
+
"viking_forget",
|
|
40
|
+
"viking_add_resource",
|
|
41
|
+
]
|
|
29
42
|
|
|
30
43
|
export const DEFAULT_OPENCODE_BIN = process.env.OCG_OPENCODE_BIN
|
|
31
44
|
?? path.join(os.homedir(), "opt", "oc-v1", "bin", "opencode")
|
package/src/provider/config.mjs
CHANGED
|
@@ -23,7 +23,7 @@ export const PROVIDERS = Object.freeze({
|
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
25
|
* ③层的**能力面**(S3 四场景共存职责):`auto` 管自动面(起点/查询段召回 + 记忆写镜像),
|
|
26
|
-
* `tools`
|
|
26
|
+
* `tools` 管工具面(五件可用 `viking_*`;`viking_add_resource` 未实现,不注册)。
|
|
27
27
|
*
|
|
28
28
|
* 为什么必须在**同一份配置**里各开各的:官方插件接管 ③ 的自动面、或只有外部 MCP 提供工具时,
|
|
29
29
|
* 「谁负责哪一面」是**用户的显式声明**,不是我们猜出来的(不据包名、不据 MCP 连接推断)。
|