opencode-growth 0.1.2 → 0.1.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +72 -13
  2. package/package.json +1 -1
  3. package/src/adapter-opencode/curator-runner.mjs +257 -0
  4. package/src/adapter-opencode/index.mjs +309 -19
  5. package/src/adapter-opencode/install.mjs +329 -52
  6. package/src/adapter-opencode/journey-tool.mjs +57 -0
  7. package/src/adapter-opencode/memory-tool.mjs +57 -5
  8. package/src/adapter-opencode/provider-tools.mjs +237 -0
  9. package/src/adapter-opencode/review-runner.mjs +180 -37
  10. package/src/adapter-opencode/session-search-tool.mjs +66 -0
  11. package/src/adapter-opencode/skill-tool.mjs +221 -0
  12. package/src/cli/commands.mjs +98 -5
  13. package/src/cli/curator-cmd.mjs +149 -0
  14. package/src/cli/journey-cmd.mjs +61 -0
  15. package/src/cli/journey-view.mjs +174 -0
  16. package/src/cli/main.mjs +173 -26
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +87 -0
  19. package/src/cli/skill-cmd.mjs +194 -0
  20. package/src/core/approve.mjs +295 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +114 -2
  23. package/src/core/home.mjs +56 -21
  24. package/src/core/journey.mjs +298 -0
  25. package/src/core/lock.mjs +6 -0
  26. package/src/core/memories.mjs +215 -10
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/paths.mjs +0 -1
  29. package/src/core/session-freshness.mjs +201 -0
  30. package/src/core/session-index.mjs +508 -0
  31. package/src/core/session-query.mjs +161 -0
  32. package/src/core/session-source.mjs +209 -0
  33. package/src/core/session-tool.mjs +189 -0
  34. package/src/core/skill-actions.mjs +391 -0
  35. package/src/core/skill-backup.mjs +95 -0
  36. package/src/core/skill-lifecycle.mjs +277 -0
  37. package/src/core/skill-usage.mjs +119 -0
  38. package/src/core/skills.mjs +30 -3
  39. package/src/core/sqlite-runtime.mjs +35 -0
  40. package/src/core/write-approval.mjs +13 -9
  41. package/src/host/rest-client.mjs +70 -0
  42. package/src/index.mjs +0 -1
  43. package/src/provider/config.mjs +187 -0
  44. package/src/provider/openviking-rest.mjs +742 -0
  45. package/src/provider/runtime.mjs +417 -0
  46. package/src/provider/wiring.mjs +164 -0
  47. package/src/core/budget.mjs +0 -64
  48. package/src/core/retrieve.mjs +0 -127
@@ -0,0 +1,417 @@
1
+ // W5 · 外部 provider 运行时(56-v2 §6.3 八条硬规则的执行面)。
2
+ //
3
+ // 设计口径(照 Hermes agent/memory_manager.py 的对应物,锚点见 56-v2 §6.2):
4
+ // - 单例:至多一个外部 provider,第二个注册拒绝且不动第一个(H/agent/memory_manager.py:384 原话形状)
5
+ // - 加性:①常驻 ②本地检索 永远在,provider 只是第③层;任何 provider 状态都不许把①②带塌
6
+ // - fail-closed 镜像:只在确认落盘(applied && !staged && !applyError)后入队;writeId 幂等
7
+ // - 召回:围栏 + 来源=宿主可信元数据 + 消毒伪标记 + 超长 spill + 空块不渲染
8
+ // - 卡住就跳过:timeoutMs 预算、在途上限 1、晚到结果不进错轮、timeout 不冒充 recalled=0
9
+ // - drain:守恒 submitted=completed+cancelled+active;dropped 只算 cancelled(不可取消的在途计 active)
10
+ // - home 来自入参:出站身份用实例上下文,不重读全局
11
+ // - 凭据出口脱敏:镜像/诊断过 redact(秘密值取自 home/.env 与环境)
12
+ import fs from "node:fs"
13
+ import path from "node:path"
14
+ import crypto from "node:crypto"
15
+
16
+ import { secretValues, redact } from "./config.mjs"
17
+
18
+ export const RECALL_FENCE = Object.freeze({
19
+ open: "«ocg-recall:start»",
20
+ close: "«ocg-recall:end»",
21
+ })
22
+
23
+ const REQUIRED_HOOKS = ["name", "is_available", "prefetch", "on_memory_write"]
24
+
25
+ function sanitize(text) {
26
+ let s = String(text)
27
+ // 伪围栏标记被内容夹带 ⇒ 消毒(收口标记全文只许出现围栏自己的那一次)
28
+ s = s.split(RECALL_FENCE.close).join("«escaped-close»")
29
+ s = s.split(RECALL_FENCE.open).join("«escaped-open»")
30
+ return s
31
+ }
32
+
33
+ export class ProviderRuntime {
34
+ constructor({ home, resident = "", local = "", timeoutMs = 8000, maxChars = 0 } = {}) {
35
+ if (!home) throw new Error("ProviderRuntime: home 必须来自入参(禁止硬编码/全局回读)")
36
+ this.home = home
37
+ this.resident = resident
38
+ this.local = local
39
+ this.timeoutMs = timeoutMs
40
+ this.maxChars = maxChars
41
+ this.#provider = null
42
+ this.#initialized = false
43
+ this.#inflight = new Map()
44
+ this.#queue = []
45
+ this.#seenWrites = new Set()
46
+ this.#submitted = 0
47
+ }
48
+
49
+ #provider
50
+ #initialized
51
+ #inflight
52
+ #recallCache = new Map() // 旧形制(provider 只有 prefetch)的整轮复放
53
+ #startCache = new Map() // 两段式:会话起点块(每会话取数一次、每请求复放;D84 平台形制)
54
+ #queryCache = new Map() // 两段式:查询段(按 sessionId+query 复放,同 query 逐字相同)
55
+ #queue
56
+ #seenWrites
57
+ #submitted
58
+ #completedCount = 0
59
+ #inflightWrite = false
60
+ #drainPromise = null
61
+ #lastFailure = null
62
+ #late = new Map()
63
+
64
+ get provider() {
65
+ return this.#provider
66
+ }
67
+
68
+ /** 单例规则:第二个拒绝且不动第一个;schema 不合格被拒但不占名额。 */
69
+ register(provider) {
70
+ const missing = REQUIRED_HOOKS.filter((h) => typeof provider?.[h] !== "function")
71
+ if (missing.length) {
72
+ return { ok: false, error: `provider schema invalid: missing hook(s) ${missing.join(", ")}` }
73
+ }
74
+ if (this.#provider) {
75
+ return {
76
+ ok: false,
77
+ error: `Rejected memory provider '${provider.name()}' — external provider '${this.#provider.name()}' is already registered. Only one external memory provider is allowed at a time. Configure which one via 'memory.provider'`,
78
+ }
79
+ }
80
+ this.#provider = provider
81
+ this.#initialized = false
82
+ return { ok: true, error: null }
83
+ }
84
+
85
+ #secrets() {
86
+ try {
87
+ return secretValues(this.home).concat(Object.entries(process.env)
88
+ .filter(([k]) => k.includes("TOKEN") || k.includes("SECRET") || k.includes("CANARY"))
89
+ .map(([, v]) => v).filter(Boolean))
90
+ } catch {
91
+ return []
92
+ }
93
+ }
94
+
95
+ #fence(content, source) {
96
+ return `${RECALL_FENCE.open} source: ${source}\n${content}\n${RECALL_FENCE.close}`
97
+ }
98
+
99
+ /**
100
+ * 一轮召回(§6.2-6;**D84 平台形制**:取数每会话一次、注入每请求一份)。
101
+ * - 召回成功 ⇒ 会话内复放(H 的会话起点块每会话闩一次;OpenCode 每请求各组装 system,
102
+ * 同会话每个请求都要拿到块——只注一次会饿死主请求(真机 J3 实测))
103
+ * - 卡住/失败 ⇒ 不缓存("跳过直至返回":期间共享同一取数、到点 timeout;返回后复放)
104
+ * - 空返回不缓存(下次请求重查);晚到结果只登记不进错轮
105
+ * 返回 { text, status, injected, spill, diagnostics };text 恒含①②层。
106
+ */
107
+ async prefetchTurn({ sessionId, query = "", turnId = "", metadata = {} } = {}) {
108
+ const base = [this.resident, this.local].filter(Boolean).join("\n")
109
+ const none = (status, note, diagnostics = {}) => ({
110
+ text: note ? `${base}\n(${note})` : base,
111
+ status,
112
+ injected: false,
113
+ spill: null,
114
+ diagnostics,
115
+ providerSelfReported: false,
116
+ })
117
+ const p = this.#provider
118
+ if (!p) return none("none", null)
119
+ if (!p.is_available()) return none("unavailable", `provider 不可用:${p.unavailable_reason() || "未说明"}`, { unavailable: true })
120
+
121
+ if (!this.#initialized) {
122
+ try {
123
+ await p.initialize?.(sessionId)
124
+ this.#initialized = true
125
+ } catch {
126
+ return none("error", "provider 初始化失败(常驻与本地检索继续)", { initError: true })
127
+ }
128
+ }
129
+ const source = metadata.source ?? "untrusted"
130
+ const q = String(query ?? "").trim()
131
+ const twoSegment = typeof p.sessionStart === "function" && typeof p.queryRecall === "function"
132
+
133
+ // 旧形制(provider 只有 prefetch):整轮结果每会话复放——行为与本片之前逐位相同
134
+ if (!twoSegment) {
135
+ const cached = this.#recallCache.get(sessionId)
136
+ if (cached) return { ...cached, diagnostics: { ...cached.diagnostics, replayed: true } }
137
+ let inflight = this.#inflight.get(sessionId)
138
+ if (!inflight) {
139
+ inflight = this.#startRecall({ p, sessionId, query, turnId, metadata, base })
140
+ this.#inflight.set(sessionId, inflight)
141
+ }
142
+ const outcome = await inflight
143
+ if (outcome.returned && outcome.result?.injected) this.#recallCache.set(sessionId, outcome.result)
144
+ return outcome.result
145
+ }
146
+
147
+ // 两段式(照 H `:1541-1554`):起点块每会话一次、查询段按当前 query;**注入每请求一份**(D84)
148
+ const key = `${sessionId}\u0000${q}`
149
+ const haveStart = this.#startCache.has(sessionId)
150
+ const haveQuery = this.#queryCache.has(key)
151
+ if (haveStart && (!q || haveQuery)) {
152
+ return this.#assemble({
153
+ base, source, sessionId, turnId,
154
+ start: this.#startCache.get(sessionId),
155
+ queryPart: this.#queryCache.get(key) ?? "",
156
+ replayed: { start: true, query: Boolean(q) },
157
+ sections: this.#sections(p),
158
+ })
159
+ }
160
+ let inflight = this.#inflight.get(sessionId)
161
+ if (!inflight) {
162
+ inflight = this.#startRecall({ p, sessionId, query, turnId, metadata, base })
163
+ this.#inflight.set(sessionId, inflight)
164
+ }
165
+ return (await inflight).result
166
+ }
167
+
168
+ /** provider 的两段状态(旧形制无 sections ⇒ 空对象;不编造)。 */
169
+ #sections(p) {
170
+ try {
171
+ const s = p.diagnostics?.()?.sections
172
+ return s && typeof s === "object" ? s : {}
173
+ } catch {
174
+ return {}
175
+ }
176
+ }
177
+
178
+ /** 取数体(预算有界;晚到只登记不进错轮、返回后才进缓存)。resolve 恒有 {result, returned}。 */
179
+ #startRecall({ p, sessionId, query, turnId, metadata, base }) {
180
+ const source = metadata.source ?? "untrusted"
181
+ const q = String(query ?? "").trim()
182
+ const twoSegment = typeof p.sessionStart === "function" && typeof p.queryRecall === "function"
183
+ const key = `${sessionId}\u0000${q}`
184
+ const ctx = { sessionId, home: this.home, turnId }
185
+ return (async () => {
186
+ let timer
187
+ const budget = new Promise((resolve) => {
188
+ timer = setTimeout(() => resolve({ __timeout: true }), this.timeoutMs)
189
+ })
190
+ const work = (async () => {
191
+ if (!twoSegment) {
192
+ const content = await p.prefetch(query, ctx)
193
+ return { legacy: typeof content === "string" ? content : String(content?.content ?? content?.text ?? "") }
194
+ }
195
+ // 起点块每会话取一次(缓存命中就不打网络);查询段按当前 query 取
196
+ const start = this.#startCache.has(sessionId) ? this.#startCache.get(sessionId) : await p.sessionStart(ctx)
197
+ const queryPart = q && this.#queryCache.has(key) ? this.#queryCache.get(key) : await p.queryRecall(query, ctx)
198
+ return { start: String(start ?? ""), queryPart: String(queryPart ?? "") }
199
+ })()
200
+ const cache = (fetched) => {
201
+ if (!twoSegment) {
202
+ const body = String(fetched?.legacy ?? "").trim()
203
+ if (body) this.#recallCache.set(sessionId, this.#assemble({ base, source, sessionId, turnId, legacy: body, replayed: { start: false, query: false }, sections: this.#sections(p) }))
204
+ return
205
+ }
206
+ if (typeof fetched?.start === "string") this.#startCache.set(sessionId, fetched.start)
207
+ if (q && typeof fetched?.queryPart === "string") this.#queryCache.set(key, fetched.queryPart)
208
+ }
209
+ try {
210
+ const raced = await Promise.race([work, budget])
211
+ if (raced && raced.__timeout) {
212
+ // 晚到结果只登记不进错轮;**返回后**才进缓存(跳过直至返回)
213
+ work
214
+ .then((late) => {
215
+ this.#inflight.delete(sessionId)
216
+ this.#late.set(turnId, late)
217
+ cache(late)
218
+ })
219
+ .catch(() => { this.#inflight.delete(sessionId) })
220
+ clearTimeout(timer)
221
+ const partial = this.#assemble({
222
+ base, source, sessionId, turnId,
223
+ start: this.#startCache.get(sessionId) ?? "",
224
+ queryPart: this.#queryCache.get(key) ?? "",
225
+ replayed: { start: this.#startCache.has(sessionId), query: this.#queryCache.has(key) },
226
+ sections: this.#sections(p),
227
+ })
228
+ return {
229
+ result: partial.injected
230
+ ? { ...partial, status: "recalled", diagnostics: { ...partial.diagnostics, timeoutLate: true } }
231
+ : { text: `${base}\n(本轮无 recall(provider 超时,已跳过))`, status: "timeout", injected: false, spill: null, diagnostics: { timeout: true }, providerSelfReported: false },
232
+ returned: false,
233
+ }
234
+ }
235
+ clearTimeout(timer)
236
+ this.#inflight.delete(sessionId)
237
+ cache(raced)
238
+ const result = this.#assemble({
239
+ base, source, sessionId, turnId,
240
+ legacy: twoSegment ? "" : String(raced?.legacy ?? ""),
241
+ start: twoSegment ? String(raced?.start ?? "") : "",
242
+ queryPart: twoSegment ? String(raced?.queryPart ?? "") : "",
243
+ replayed: { start: false, query: false },
244
+ sections: this.#sections(p),
245
+ })
246
+ return { result, returned: true }
247
+ } catch (e) {
248
+ clearTimeout(timer)
249
+ this.#inflight.delete(sessionId)
250
+ this.#recordFailure("prefetch", e)
251
+ return {
252
+ result: {
253
+ text: `${base}\n(provider 召回失败(常驻与本地检索继续))`,
254
+ status: "error",
255
+ injected: false,
256
+ spill: null,
257
+ diagnostics: { prefetchError: true },
258
+ providerSelfReported: false,
259
+ },
260
+ returned: false,
261
+ }
262
+ }
263
+ })()
264
+ }
265
+
266
+ /**
267
+ * 组装注入文本(两段成序 + 围栏 + 消毒 + 显式兜底)。三态报告口径:
268
+ * - 有内容注入 ⇒ status=recalled;段落级失败另标 `degraded` 并记 lastFailure(**不静默**)
269
+ * - 无内容 ⇒ status=none(`(本轮无 recall)`),不等于「失败」
270
+ * - `maxChars > 0` 且越界 ⇒ 兜底截断 + spill + `diagnostics.overflow`(默认 0=不截断,照 H 由 provider 整条准入)
271
+ */
272
+ #assemble({ base, source, sessionId, turnId, legacy = "", start = "", queryPart = "", replayed = {}, sections = {} }) {
273
+ const parts = [start, queryPart].filter((x) => String(x ?? "").trim())
274
+ const raw = legacy || (parts.length ? `## OpenViking Context\n${parts.join("\n\n")}` : "")
275
+ if (!raw.trim()) {
276
+ return {
277
+ text: `${base}\n(本轮无 recall)`,
278
+ status: "none",
279
+ injected: false,
280
+ spill: null,
281
+ diagnostics: { empty: true, sections, replayed },
282
+ providerSelfReported: false,
283
+ }
284
+ }
285
+ const body = sanitize(raw)
286
+ let text = body
287
+ let spill = null
288
+ let overflow = false
289
+ if (this.maxChars > 0 && body.length > this.maxChars) {
290
+ overflow = true
291
+ spill = `spill-${crypto.createHash("sha1").update(`${sessionId}:${turnId}`).digest("hex").slice(0, 10)}.txt`
292
+ fs.mkdirSync(this.home, { recursive: true })
293
+ fs.writeFileSync(path.join(this.home, spill), body, "utf8")
294
+ text = `${body.slice(0, this.maxChars)}…(超预算已兜底截断,全文见 ${spill})`
295
+ }
296
+ const failed = ["session_start", "search"].filter((k) => sections?.[k] === "failed")
297
+ if (failed.length) this.#recordFailure(`prefetch.${failed.join("+")}`, new Error(`provider 段落失败:${failed.join("+")}`))
298
+ return {
299
+ text: `${base}\n${this.#fence(text, source)}`,
300
+ status: "recalled",
301
+ injected: true,
302
+ spill,
303
+ diagnostics: {
304
+ recalled: true,
305
+ source,
306
+ replayed,
307
+ sections,
308
+ ...(failed.length ? { degraded: true, failedSections: failed } : {}),
309
+ ...(overflow ? { overflow: true } : {}),
310
+ },
311
+ providerSelfReported: false,
312
+ }
313
+ }
314
+
315
+
316
+ /** §6.2-14:只在确认落盘后镜像;writeId 幂等;add-only(首版承诺面)。 */
317
+ onMemoryWrite({ writeId, action, target, content, metadata = {}, applied, staged, applyError } = {}) {
318
+ if (!applied || staged || applyError) return false
319
+ if (this.#seenWrites.has(writeId)) return false
320
+ this.#seenWrites.add(writeId)
321
+ this.#submitted += 1
322
+ const secrets = this.#secrets()
323
+ this.#queue.push({
324
+ writeId,
325
+ action,
326
+ target,
327
+ content: redact(content, secrets),
328
+ metadata: JSON.parse(redact(JSON.stringify({ home: this.home, ...metadata }), secrets)),
329
+ })
330
+ return true
331
+ }
332
+
333
+ /**
334
+ * 串行消费镜像队列——**有界**(S2 判据「写路径有界」)。
335
+ * - 不带参数:老语义不变(等队空;调用方自担无限等)。
336
+ * - `{ waitMs }`:到点即返回 `{completed, pending, timedOut:true}`,**在途/在队条目一件不丢**
337
+ * (放行后下一次 flush 会把它们补完)。照 H 的两级上界形制:单请求上界在 REST 客户端
338
+ * (`requestTimeoutMs`),整体等待上界在这里。
339
+ * 并发安全:同一时刻只有一条 drain(`#drainPromise`),重复调用是**加入**而不是另起一条。
340
+ */
341
+ async flushWrites({ waitMs } = {}) {
342
+ if (!this.#drainPromise) {
343
+ this.#drainPromise = this.#runDrain().finally(() => { this.#drainPromise = null })
344
+ }
345
+ const drain = this.#drainPromise
346
+ if (waitMs === undefined) {
347
+ await drain
348
+ return this.#mirrorReport(false)
349
+ }
350
+ let timer
351
+ const deadline = new Promise((resolve) => { timer = setTimeout(() => resolve("timeout"), waitMs) })
352
+ const why = await Promise.race([drain.then(() => "done"), deadline])
353
+ clearTimeout(timer)
354
+ return this.#mirrorReport(why === "timeout")
355
+ }
356
+
357
+ /**
358
+ * 踢一次后台镜像,**不等**(照 H `_spawn_tracked` 的后台线程语义:工具调用点不被远端拖住)。
359
+ * 返回当下排队/在途件数,供调用方在回执里如实说明「远端状态」。
360
+ */
361
+ kickMirror() {
362
+ const pending = this.#queue.length + (this.#inflightWrite ? 1 : 0)
363
+ if (!this.#drainPromise && pending) void this.flushWrites().catch(() => {})
364
+ return { pending }
365
+ }
366
+
367
+ /** 运行时观测面:最近一次失败(「服务故障」在本地工具面可见,不伪装成零命中)。 */
368
+ diagnostics() {
369
+ return { lastFailure: this.#lastFailure, pending: this.#queue.length + (this.#inflightWrite ? 1 : 0) }
370
+ }
371
+
372
+ #recordFailure(stage, err) {
373
+ this.#lastFailure = {
374
+ stage,
375
+ message: redact(String(err?.message ?? err), this.#secrets()),
376
+ at: new Date().toISOString(),
377
+ }
378
+ }
379
+
380
+ async #runDrain() {
381
+ const p = this.#provider
382
+ while (this.#queue.length) {
383
+ const item = this.#queue.shift()
384
+ if (!p) { this.#completedCount += 1; continue }
385
+ this.#inflightWrite = true
386
+ try {
387
+ await p.on_memory_write(item.action, item.target, item.content, item.metadata)
388
+ } catch (e) {
389
+ this.#recordFailure("mirror", e) // 镜像失败可见但不回滚本地(best-effort)
390
+ }
391
+ this.#inflightWrite = false
392
+ this.#completedCount += 1
393
+ }
394
+ }
395
+
396
+ #mirrorReport(timedOut) {
397
+ return {
398
+ completed: this.#completedCount ?? 0,
399
+ pending: this.#queue.length + (this.#inflightWrite ? 1 : 0),
400
+ timedOut,
401
+ }
402
+ }
403
+
404
+ /** 关闭:有界 drain + 守恒报告(§6.2-11 / §6.3 规则 6)。 */
405
+ async shutdown({ drainMs = 5000 } = {}) {
406
+ this.#completedCount = this.#completedCount ?? 0
407
+ await this.flushWrites({ waitMs: drainMs })
408
+ const rep = {
409
+ submitted: this.#submitted,
410
+ completed: this.#completedCount,
411
+ cancelled: this.#queue.length,
412
+ active: this.#inflightWrite ? 1 : 0,
413
+ }
414
+ rep.dropped = rep.cancelled // 只有被取消排队的才算丢弃;正在执行不可取消的计 active
415
+ return rep
416
+ }
417
+ }
@@ -0,0 +1,164 @@
1
+ // 片 5 · 产品接线(sol high 航向复核推翻条件②的收口面)。
2
+ //
3
+ // 职责:从 ocg 配置(<store>/state/provider.json + ocg home .env)把 ProviderRuntime
4
+ // 搭起来交给适配器(注入走 transform、写走镜像)。三条口径:
5
+ // - **缺席一律回落** {runtime:null, reason} —— provider 永远不许拖塌产品(①②层照常)
6
+ // - 凭据形制照 Hermes:值只住 ocg home .env(原子写 0600,setup 写入);会话侧读回顺序
7
+ // process.env(显式导出优先)→ home .env;两者都没有 ⇒ provider 不可用(fail-closed)
8
+ // - 配置损坏不猜、不覆盖(loadConfig 抛 corrupt ⇒ 这里收成 reason)
9
+ import fs from "node:fs"
10
+
11
+ import { loadConfig, envPath, homeFor, parseCapabilities } from "./config.mjs"
12
+ import { OpenVikingRest } from "./openviking-rest.mjs"
13
+ import { ProviderRuntime } from "./runtime.mjs"
14
+
15
+ /**
16
+ * 会话侧凭据读回:process.env 优先,home .env 回落;都没有 ⇒ null(调用方按缺席处理)。
17
+ */
18
+ export function readSecretEnv(home, varName) {
19
+ const v = process.env[varName]
20
+ if (v) return v
21
+ try {
22
+ for (const l of fs.readFileSync(envPath(home), "utf8").split("\n")) {
23
+ if (l.startsWith(`${varName}=`)) {
24
+ const val = l.slice(varName.length + 1)
25
+ if (val) return val
26
+ }
27
+ }
28
+ } catch { /* 没有 .env */ }
29
+ return null
30
+ }
31
+
32
+ /**
33
+ * 缺席/故障的**可辨词汇表**(S2 判据「五分可辨」,机器可核的那一半)。
34
+ *
35
+ * 照 Hermes 形制:H 的 provider `is_available()` 只查配置、不联网(memory_provider.py:91-114),
36
+ * 配置态与运行时故障是两回事;H 把「配置态」放 status(`cmd_status` 的
37
+ * `Status: available ✓ / not available ✗`),把「运行时故障」放调用期告警。
38
+ * ocg 把两者摊平成同一组 code(多出的 `unreachable` 只能靠**有界探活**观测,见 `memory status --probe`):
39
+ *
40
+ * no-store / corrupt —— 既有两态(占位面本身不在)
41
+ * unconfigured —— 从未配置(没有 active 键)
42
+ * disabled —— 显式关闭(`memory off` 写过 active:"off")
43
+ * incomplete —— 配了但字段/secretEnvs 不全,或端点形制不合法
44
+ * missing-credential —— env 变量没给(fail-closed;点名变量)
45
+ * unreachable —— 探活失败(服务故障;**观测**,不是配置态)
46
+ * invalid-provider —— 注册失败(provider 钩子不全)
47
+ *
48
+ * 前五态各自**维持既有行为**:不建 runtime(①②层照旧),只是原因分得开。
49
+ * 与 Hermes 的差异记 D 决策:H 没有 `disabled`(它只有「不配=不选」),ocg 的 `memory off`
50
+ * 是 W5 已建的显式开关,故把它与「未配置」分开(D96 的执行面)。
51
+ */
52
+ export const ABSENCE_CODES = Object.freeze([
53
+ "no-store",
54
+ "corrupt",
55
+ "unconfigured",
56
+ "disabled",
57
+ "incomplete",
58
+ "missing-credential",
59
+ "unreachable",
60
+ "invalid-provider",
61
+ ])
62
+
63
+ /** 自动召回的**总等待**默认值(毫秒)=既有行为(未配置时不许因改接线而变)。 */
64
+ export const DEFAULT_RECALL_BUDGET_MS = 8000
65
+
66
+ /**
67
+ * 场景标签(只做**导出/诊断**用,不是新状态实体):由 `active` + `capabilities` 推导,
68
+ * 让页面上/回执里能一眼看出「这个实例现在哪一面归谁」。四场景的映射见 docs/reuse-matrix 与 S3 证据。
69
+ */
70
+ export const SCENARIOS = Object.freeze([
71
+ "no-store", "corrupt", "no-provider", "provider-disabled", "unavailable",
72
+ "ocg-managed", "ocg-auto-only", "ocg-tools-only", "ocg-none",
73
+ ])
74
+
75
+ const NO_CAPABILITIES = Object.freeze({ auto: false, tools: false })
76
+
77
+ export function buildProviderRuntime({
78
+ store,
79
+ home = homeFor(),
80
+ resident = "",
81
+ local = "",
82
+ timeoutMs = null,
83
+ maxChars = 0, // 0=不截断(照 H:③ 段准入在 provider 侧整条进行;显式给上限才兜底截断+spill)
84
+ fetchImpl = fetch,
85
+ } = {}) {
86
+ if (!store) {
87
+ return { runtime: null, provider: null, reasonCode: "no-store", reason: "no-store", capabilities: NO_CAPABILITIES, scenario: "no-store" }
88
+ }
89
+ let cfg
90
+ try {
91
+ cfg = loadConfig(store)
92
+ } catch (e) {
93
+ const code = e?.corrupt ? "corrupt" : "incomplete"
94
+ return {
95
+ runtime: null,
96
+ provider: null,
97
+ reasonCode: code,
98
+ reason: e?.corrupt ? "provider config unreadable (corrupt)" : String(e?.message ?? e),
99
+ capabilities: NO_CAPABILITIES,
100
+ scenario: e?.corrupt ? "corrupt" : "unavailable",
101
+ }
102
+ }
103
+ // 能力面:坏值/未知键 ⇒ **fail-closed 两面皆关**(配置读不懂时宁可少做,也不许重复自动处理)。
104
+ const cap = parseCapabilities(cfg.capabilities)
105
+ const name = cfg.active
106
+ if (!name) {
107
+ return { runtime: null, provider: null, reasonCode: "unconfigured", reason: "未配置外部 provider(内建记忆照旧)", capabilities: NO_CAPABILITIES, scenario: "no-provider" }
108
+ }
109
+ if (name === "off") {
110
+ // 官方插件/外部接管 ③ 的既有表达:配置与后端内容都保留,我们停用重叠的自动行为(①②照旧)。
111
+ return { runtime: null, provider: null, reasonCode: "disabled", reason: "外部 provider 已显式关闭(内建记忆照旧)", capabilities: NO_CAPABILITIES, scenario: "provider-disabled" }
112
+ }
113
+ if (!cap.ok) {
114
+ return { runtime: null, provider: null, reasonCode: "incomplete", reason: cap.error, capabilities: NO_CAPABILITIES, scenario: "unavailable" }
115
+ }
116
+ const fields = cfg.providers?.[name]
117
+ // setup 写入形制是数组(cfg.secretEnvs[provider] = [...]);历史字符串形制兼容。多变量取首项。
118
+ const rawVar = cfg.secretEnvs?.[name]
119
+ const tokenVar = Array.isArray(rawVar) ? rawVar[0] : rawVar
120
+ if (!fields || !tokenVar) {
121
+ return { runtime: null, provider: null, reasonCode: "incomplete", reason: `provider '${name}' 配置不全(缺字段或 secretEnvs)`, capabilities: cap.capabilities, scenario: "unavailable" }
122
+ }
123
+ const token = readSecretEnv(home, tokenVar)
124
+ if (!token) {
125
+ return {
126
+ runtime: null,
127
+ provider: null,
128
+ reasonCode: "missing-credential",
129
+ reason: `缺凭据环境变量 ${tokenVar}(home .env 与 process.env 均无)`,
130
+ capabilities: cap.capabilities,
131
+ scenario: "unavailable",
132
+ }
133
+ }
134
+ let provider
135
+ const recallFields = fields.recall ?? cfg.recall ?? {}
136
+ try {
137
+ provider = new OpenVikingRest({
138
+ endpoint: fields.endpoint,
139
+ account: fields.account,
140
+ user: fields.user,
141
+ actor: fields.actor,
142
+ token,
143
+ // 召回九键从 provider.json 的 `recall` 段读(省略即 H 默认值);键名/默认值口径见 62-S3 §5
144
+ recall: recallFields,
145
+ fetchImpl,
146
+ })
147
+ } catch (e) {
148
+ return { runtime: null, provider: null, reasonCode: "incomplete", reason: String(e?.message ?? e), capabilities: cap.capabilities, scenario: "unavailable" }
149
+ }
150
+ // 自动召回的**总等待**预算:显式入参 > 配置 `recall.timeout_seconds` > 既有默认 8s。
151
+ // 与单请求上界是**两个**界(前者管"这一轮等多久",后者管"一次出站多久");从前这里写死 8000,
152
+ // 于是 provider.json 里的 timeout_seconds 只喂了 sessionStart 里一行死代码(S1 实测缺口)。
153
+ const configuredMs = Number(recallFields?.timeout_seconds)
154
+ const budgetMs = Number.isFinite(timeoutMs) && timeoutMs > 0
155
+ ? Math.round(timeoutMs)
156
+ : (Number.isFinite(configuredMs) && configuredMs > 0 ? Math.round(configuredMs * 1000) : DEFAULT_RECALL_BUDGET_MS)
157
+ const runtime = new ProviderRuntime({ home, resident, local, timeoutMs: budgetMs, maxChars })
158
+ const reg = runtime.register(provider)
159
+ if (!reg.ok) return { runtime: null, provider: null, reasonCode: "invalid-provider", reason: reg.error, capabilities: cap.capabilities, scenario: "unavailable" }
160
+ const { auto, tools } = cap.capabilities
161
+ const scenario = auto && tools ? "ocg-managed" : auto ? "ocg-auto-only" : tools ? "ocg-tools-only" : "ocg-none"
162
+ return { runtime, provider, reasonCode: null, reason: null, capabilities: cap.capabilities, scenario }
163
+ }
164
+
@@ -1,64 +0,0 @@
1
- // Read-path budgets (R2 §2.5, §4): count / per-entry characters / total tokens.
2
- //
3
- // Two rules this module exists to make explicit:
4
- // 1. Over-limit means *dropped whole*. A truncated body can lose "only in staging" or a
5
- // negation and change the meaning of what was learned, so nothing here ever slices text.
6
- // 2. The total budget is measured on the **wrapped** text (envelope + attributes + body),
7
- // never on bodies alone — otherwise the wrapper silently eats the budget.
8
-
9
- export const DEFAULT_BUDGET = Object.freeze({
10
- maxEntries: 12, // how many entries may be injected at once
11
- maxCharsPerEntry: 1200, // per-entry character ceiling (the rendered entry, envelope-free)
12
- totalTokens: 3000, // ceiling for the whole injected text, envelope included
13
- })
14
-
15
- /** Refuse nonsense instead of clamping it: a silently clamped budget is a silent behaviour change. */
16
- export function normalizeBudget(input = {}) {
17
- const out = { ...DEFAULT_BUDGET }
18
- const unknown = Object.keys(input).filter((k) => !(k in DEFAULT_BUDGET))
19
- if (unknown.length) throw new Error(`unknown budget key(s): ${unknown.join(", ")}`)
20
- for (const key of Object.keys(DEFAULT_BUDGET)) {
21
- const value = input[key]
22
- if (value === undefined) continue
23
- if (!Number.isInteger(value) || value < 0) {
24
- throw new Error(`budget.${key} must be a non-negative integer, got ${JSON.stringify(value)}`)
25
- }
26
- out[key] = value
27
- }
28
- return out
29
- }
30
-
31
- /** Wide ranges: CJK, kana, hangul, full-width punctuation, emoji. */
32
- function isWide(cp) {
33
- return (
34
- (cp >= 0x2e80 && cp <= 0x9fff) ||
35
- (cp >= 0xac00 && cp <= 0xd7a3) ||
36
- (cp >= 0xf900 && cp <= 0xfaff) ||
37
- (cp >= 0xfe30 && cp <= 0xfe4f) ||
38
- (cp >= 0xff00 && cp <= 0xff60) ||
39
- (cp >= 0xffe0 && cp <= 0xffe6) ||
40
- (cp >= 0x1f300 && cp <= 0x1faff)
41
- )
42
- }
43
-
44
- /**
45
- * Conservative **estimate**, never a measurement.
46
- *
47
- * No tokenizer is available offline and the real prompt-cache/token accounting is still an
48
- * unverified item in the design, so the read path must not pretend to know exact token counts.
49
- * Wide characters (CJK and friends) are counted at a full token each — character counts are
50
- * never a valid token count for Chinese; every other run of non-space characters is charged
51
- * one token per three characters, which over-counts plain ASCII rather than under-counting it.
52
- */
53
- export function estimateTokens(text) {
54
- const source = String(text ?? "")
55
- let wide = 0
56
- let narrow = 0
57
- for (const ch of source) {
58
- const cp = ch.codePointAt(0)
59
- if (cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d) continue
60
- if (isWide(cp)) wide += 1
61
- else narrow += 1
62
- }
63
- return wide + Math.ceil(narrow / 3)
64
- }