opencode-subagent-magazine 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  import type { Context } from "./types"
2
2
  import type { PanelApi, PanelEvent, PanelEventType } from "../panel/panel-api"
3
+ import { SETTING_KEYS } from "../core/kv"
4
+ import { createSessionDbIndex, modelIdOf, statusOfChild } from "./db"
3
5
 
4
6
  const SUBAGENT_TOOL_V2 = "subagent"
5
7
 
@@ -25,7 +27,12 @@ function toV1Part(p: Record<string, any>): Record<string, any> {
25
27
  .filter((t): t is string => typeof t === "string" && t.length > 0)
26
28
  .join("\n")
27
29
  }
28
- return { type: "tool", tool: p.tool ?? p.name, state: st, subagent_type: p.subagent_type, metadata: normalizeMeta(p.metadata) }
30
+ // TUI 数据层把子代理 metadata 放在 part 级,旧缓存形状可能嵌在 state 里——两处合并后再双写。
31
+ const meta = normalizeMeta({
32
+ ...(((st as Record<string, unknown>).metadata ?? {}) as Record<string, unknown>),
33
+ ...((p.metadata ?? {}) as Record<string, unknown>),
34
+ })
35
+ return { type: "tool", id: p.id, tool: p.tool ?? p.name, state: st, subagent_type: p.subagent_type, metadata: meta }
29
36
  }
30
37
  if (p.type === "text") return { type: "text", text: String(p.text ?? "") }
31
38
  if (p.type === "file") return { type: "file", source: p.source ?? {} }
@@ -73,10 +80,72 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
73
80
  const [, mutate] = entry
74
81
  return mutate((d) => { d.value = value })
75
82
  }
83
+ // 原子 read-modify-write:宿主在存储锁内基于最新磁盘值
84
+ // 应用 updater,因此并发 TUI 实例会 merge,
85
+ // 而不是用过期快照互相覆盖。
86
+ const kvUpdate = (key: string, updater: (current: unknown) => unknown): Promise<void> => {
87
+ let entry = kvStore.get(key)
88
+ if (!entry) {
89
+ const created = context.storage.store<Record<string, any>>(`subagent_magazine.${key}`, {
90
+ initial: { value: undefined },
91
+ })
92
+ entry = created as [Record<string, any>, (fn: (d: Record<string, any>) => void) => Promise<void>]
93
+ kvStore.set(key, entry)
94
+ }
95
+ const [, mutate] = entry
96
+ return mutate((d) => { d.value = updater(d.value) })
97
+ }
98
+
99
+ // 本地 opencode.db 索引:补全前台子代理缺失的 sessionId 与用量字段。
100
+ // 数据库不可用、库结构不符或设置项 dbSync 关闭时静默禁用(回退宿主 API)。
101
+ const dbIndex = createSessionDbIndex(() => kvGet<boolean>(SETTING_KEYS.dbSync, true) !== false)
102
+
103
+ /** 事件 metadata 缺少子会话 id 时用本地库按 call id 回填(前台/后台通用)。 */
104
+ const withResolvedSid = (data: Record<string, any>, meta: Record<string, unknown>): Record<string, unknown> => {
105
+ if (meta.sessionID !== undefined) return meta
106
+ try {
107
+ const parent = data.sessionID !== undefined ? String(data.sessionID) : ""
108
+ const callId = data.id !== undefined ? String(data.id) : ""
109
+ const sid = parent && callId ? dbIndex?.resolveCall(parent, callId) : undefined
110
+ if (sid) return normalizeMeta({ ...meta, sessionID: sid })
111
+ } catch {}
112
+ return meta
113
+ }
76
114
 
77
115
  const isSubagentTool = (name: string | undefined): boolean =>
78
116
  name === SUBAGENT_TOOL_V2 || name === "task" || name === "delegate" || name === "call_omo_agent"
79
117
 
118
+ /** 事件未携带工具名/input 时,从宿主消息缓存中恢复。
119
+ * V2 的 called/progress/success 事件没有 `name`,且
120
+ * input.started 可能被错过(TUI 启动、插件重载、流抖动)——
121
+ * 没有这个回退,运行中的子代理要到完成时才会出现。 */
122
+ const findToolPart = (data: Record<string, any>): { name?: string; input?: Record<string, unknown> } | undefined => {
123
+ const sid = data.sessionID
124
+ const msgID = data.assistantMessageID
125
+ const partID = data.id
126
+ if (sid === undefined || msgID === undefined || partID === undefined) return undefined
127
+ try {
128
+ const raw = context.data.session.message.list(String(sid))
129
+ if (!raw) return undefined
130
+ for (let i = raw.length - 1; i >= 0; i--) {
131
+ const m = raw[i] as Record<string, any>
132
+ if (!m || String(m.id) !== String(msgID)) continue
133
+ const content = Array.isArray(m.content) ? m.content : []
134
+ for (const p of content) {
135
+ const pp = p as Record<string, any>
136
+ if (pp && pp.type === "tool" && String(pp.id) === String(partID)) {
137
+ const st = (pp.state ?? {}) as Record<string, any>
138
+ const input = (st.input && typeof st.input === "object") ? st.input as Record<string, unknown> : undefined
139
+ const name = pp.name ?? pp.tool
140
+ return { name: name !== undefined ? String(name) : undefined, input }
141
+ }
142
+ }
143
+ break
144
+ }
145
+ } catch {}
146
+ return undefined
147
+ }
148
+
80
149
  /** V2 tool 事件 → V1 ToolPart(非 subagent 工具返回 undefined——面板只关心子代理)。
81
150
  * 识别规则(对齐 V2 官方 stream-v2.subagent.ts):
82
151
  * - input.started/called:工具名在 subagent 集合(subagent/task/delegate/call_omo_agent)
@@ -102,39 +171,71 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
102
171
  return { type: "tool", tool: normName(String(data.name)), id: String(data.id), state: { status: "pending", input: {} } }
103
172
  }
104
173
  if (type === "session.tool.called") {
105
- const name = data.name ?? info?.name
174
+ let name: string | undefined = data.name ?? info?.name
175
+ let input: Record<string, unknown> | undefined =
176
+ (data.input as Record<string, unknown> | undefined) ?? info?.input
177
+ if (!name) {
178
+ const resolved = findToolPart(data)
179
+ if (resolved?.name) {
180
+ name = resolved.name
181
+ if (input === undefined) input = resolved.input
182
+ }
183
+ }
106
184
  if (name && !isSubagentTool(name)) return undefined
107
185
  if (!name) return undefined
108
- if (key) toolInfo.set(key, { name: String(name), input: data.input ?? {} })
186
+ if (key) toolInfo.set(key, { name: String(name), input: input ?? {} })
109
187
  return {
110
- type: "tool", tool: normName(String(name)), id: String(data.id), subagent_type: agentOf(data.input),
111
- state: { status: "running", input: data.input ?? {}, metadata: {} },
188
+ type: "tool", tool: normName(String(name)), id: String(data.id), subagent_type: agentOf(input),
189
+ state: { status: "running", input: input ?? {}, metadata: withResolvedSid(data, {}) },
112
190
  }
113
191
  }
114
192
  if (type === "session.tool.progress") {
115
- const name = data.name ?? info?.name
193
+ let name: string | undefined = data.name ?? info?.name
194
+ if (!name) name = findToolPart(data)?.name
116
195
  if (name && !isSubagentTool(name)) return undefined
117
196
  if (!name) return undefined
118
197
  return {
119
198
  type: "tool", tool: normName(String(name)), id: String(data.id), subagent_type: agentOf(info?.input),
120
- state: { status: "running", input: info?.input ?? {}, metadata: normalizeMeta(data.metadata) },
199
+ state: { status: "running", input: info?.input ?? {}, metadata: withResolvedSid(data, normalizeMeta(data.metadata)) },
121
200
  }
122
201
  }
123
202
  if (type === "session.tool.success" || type === "session.tool.failed") {
124
- const meta = normalizeMeta(data.metadata)
125
- if (meta.sessionID === undefined) return undefined
203
+ const eventMeta = normalizeMeta(data.metadata)
204
+ const meta = withResolvedSid(data, eventMeta)
126
205
  // 取消导致的工具失败:metadata.status 是工具被打断时的状态("running")——不是真错误。
127
206
  // 忽略——最终状态由 execution.interrupted → settleOnIdle 裁定 cancelled
128
207
  // (否则 handlePartUpdated 的 error 分支会把 cancel_requested 覆盖成 error)
129
208
  if (type === "session.tool.failed" && meta.status === "running") return undefined
130
- const name = data.name ?? info?.name
209
+ let name: string | undefined = data.name ?? info?.name
210
+ let input: Record<string, unknown> | undefined =
211
+ info?.input ?? (data.input as Record<string, unknown> | undefined)
212
+ if (!name || input === undefined) {
213
+ const resolved = findToolPart(data)
214
+ if (!name && resolved?.name) name = resolved.name
215
+ if (input === undefined && resolved?.input) input = resolved.input
216
+ }
131
217
  if (name && !isSubagentTool(name)) return undefined
132
- const input = info?.input ?? data.input ?? {}
218
+ if (key && name) toolInfo.set(key, { name: String(name), input: input ?? info?.input ?? {} })
219
+ const finalInput = input ?? {}
220
+ // 后台任务缺少子会话 metadata 时无法判定终态,交给扫描/轮询兜底;
221
+ // 前台任务没有 sessionID 也必须回传 completed,否则条目会一直停在 running。
222
+ if (meta.sessionID === undefined && (finalInput.background === true || finalInput.run_in_background === true)) {
223
+ return undefined
224
+ }
225
+ // sid 来自本地库(事件没带)时以库里的 time_idle 为准:库里会话仍在运行
226
+ // 就不提前收尾,交给周期性 reconcile 按真实状态落定(无时间阈值猜测)。
227
+ let status: "completed" | "error" | "running" = type === "session.tool.failed" ? "error" : "completed"
228
+ if (meta.sessionID !== undefined && meta.sessionID !== eventMeta.sessionID) {
229
+ try {
230
+ const childInfo = dbIndex?.info(String(meta.sessionID))
231
+ if (childInfo && statusOfChild(childInfo) === undefined) status = "running"
232
+ } catch {}
233
+ }
133
234
  return {
134
- type: "tool", tool: normName(String(name ?? "task")), id: String(data.id), subagent_type: agentOf(input),
235
+ type: "tool", tool: normName(String(name ?? "task")), id: String(data.id), subagent_type: agentOf(finalInput),
135
236
  state: {
136
- status: type === "session.tool.failed" ? "error" : "completed",
137
- input,
237
+ status,
238
+ input: finalInput,
138
239
  metadata: meta,
139
240
  },
140
241
  }
@@ -159,14 +260,56 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
159
260
  return out
160
261
  }
161
262
 
263
+ // ── usage enrichment(用量补全)──
264
+ // TUI 数据层只为已加载的会话缓存 messages。从 KV 恢复的
265
+ // 子会话通常没有缓存,因此读取依次回退到
266
+ // 会话级聚合值、最后是(限流的)message sync——
267
+ // 结果写入本地缓存,供面板的周期性 enrichment 读取。
268
+ const usageCache = new Map<string, { tokens?: number; cost?: number; model?: string; at: number }>()
269
+ const syncRequestedAt = new Map<string, number>()
270
+ const USAGE_CACHE_TTL_MS = 5000
271
+ const SYNC_THROTTLE_MS = 30000
272
+
273
+ const rememberUsage = (sid: string, patch: { tokens?: number; cost?: number; model?: string }) => {
274
+ const prev = usageCache.get(sid)
275
+ usageCache.set(sid, { ...prev, ...patch, at: Date.now() })
276
+ }
277
+
278
+ const cachedUsage = (sid: string) => {
279
+ const hit = usageCache.get(sid)
280
+ if (!hit) return undefined
281
+ if (Date.now() - hit.at > USAGE_CACHE_TTL_MS) return undefined
282
+ return hit
283
+ }
284
+
285
+ const requestMessageSync = (sid: string) => {
286
+ const last = syncRequestedAt.get(sid) ?? 0
287
+ if (Date.now() - last < SYNC_THROTTLE_MS) return
288
+ syncRequestedAt.set(sid, Date.now())
289
+ try {
290
+ const sync = context.data.session.message.sync
291
+ if (typeof sync === "function") void sync.call(context.data.session.message, sid).catch(() => {})
292
+ } catch {}
293
+ }
294
+
295
+ const listedSession = (sid: string) => {
296
+ try { return context.data.session.list()?.find((s) => s.id === sid) } catch { return undefined }
297
+ }
298
+
162
299
  return {
163
300
  kv: {
164
301
  get: kvGet,
165
302
  set: kvSet as (key: string, value: unknown) => void,
303
+ update: kvUpdate,
166
304
  },
167
305
  usage: {
168
306
  readSessionTokens: (sid: string): number | undefined => {
169
307
  if (!sid) return undefined
308
+ // 本地库优先:宿主数据层缺少该子会话缓存时也能给出用量。
309
+ try {
310
+ const dbTokens = dbIndex?.info(sid)?.tokens
311
+ if (dbTokens !== undefined) { rememberUsage(sid, { tokens: dbTokens }); return dbTokens }
312
+ } catch {}
170
313
  try {
171
314
  const msgs = context.data.session.message.list(sid)
172
315
  if (msgs) {
@@ -181,54 +324,110 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
181
324
  (Number(t.reasoning) || 0) +
182
325
  (Number(t.cache?.read) || 0) +
183
326
  (Number(t.cache?.write) || 0)
184
- if (ctx > 0) return ctx
327
+ if (ctx > 0) { rememberUsage(sid, { tokens: ctx }); return ctx }
185
328
  }
186
329
  }
330
+ // 本地无消息(子会话尚未加载):使用最近同步的值,
331
+ // 否则请数据层同步,稍后重试。
332
+ const cached = cachedUsage(sid)?.tokens
333
+ if (cached !== undefined) return cached
334
+ requestMessageSync(sid)
187
335
  return undefined
188
336
  } catch { return undefined }
189
337
  },
190
338
  readSessionCost: (sid: string): number | undefined => {
191
339
  if (!sid) return undefined
340
+ try {
341
+ const dbCost = dbIndex?.info(sid)?.cost
342
+ if (dbCost !== undefined) { rememberUsage(sid, { cost: dbCost }); return dbCost }
343
+ } catch {}
344
+ try {
345
+ const direct = context.data.session.cost(sid)
346
+ if (typeof direct === "number" && direct > 0) { rememberUsage(sid, { cost: direct }); return direct }
347
+ } catch {}
192
348
  try {
193
349
  const session = context.data.session.get(sid)
194
- if (session?.cost != null && session.cost > 0) return session.cost
350
+ if (session?.cost != null && session.cost > 0) { rememberUsage(sid, { cost: session.cost }); return session.cost }
351
+ const listed = listedSession(sid)
352
+ if (listed?.cost != null && listed.cost > 0) { rememberUsage(sid, { cost: listed.cost }); return listed.cost }
195
353
  const msgs = context.data.session.message.list(sid)
196
- if (!msgs) return undefined
197
- let total = 0
198
- for (const m of msgs as any[]) {
199
- if (m.type === "assistant" && typeof m.cost === "number") total += m.cost
354
+ if (Array.isArray(msgs) && msgs.length > 0) {
355
+ let total = 0
356
+ let sawAssistant = false
357
+ for (const m of msgs as any[]) {
358
+ if (m.type !== "assistant") continue
359
+ sawAssistant = true
360
+ if (typeof m.cost === "number") total += m.cost
361
+ }
362
+ // 已加载的历史是权威来源:assistant 消息 cost 为 0 表示
363
+ // 该会话确实免费(如 budget/test 模型),而非未知。
364
+ if (sawAssistant) { rememberUsage(sid, { cost: total }); return total }
200
365
  }
201
- return total > 0 ? total : undefined
366
+ const cached = cachedUsage(sid)?.cost
367
+ if (cached !== undefined) return cached
368
+ requestMessageSync(sid)
369
+ return undefined
202
370
  } catch { return undefined }
203
371
  },
204
372
  readSessionModel: (sid: string): string | undefined => {
205
373
  if (!sid) return undefined
374
+ try {
375
+ const dbModel = dbIndex?.info(sid)?.model
376
+ if (dbModel !== undefined) { rememberUsage(sid, { model: dbModel }); return dbModel }
377
+ } catch {}
206
378
  try {
207
379
  const msgs = context.data.session.message.list(sid)
208
380
  if (msgs) {
209
381
  for (let i = msgs.length - 1; i >= 0; i--) {
210
382
  const m = msgs[i] as Record<string, any>
211
383
  if (m.type !== "assistant") continue
212
- const model = m.model as { id?: string } | string | undefined
213
- if (typeof model === "string") return model
214
- if (model?.id) return String(model.id)
384
+ const id = modelIdOf(m.model)
385
+ if (id) { rememberUsage(sid, { model: id }); return id }
215
386
  }
216
387
  }
388
+ const sessionModel = modelIdOf(context.data.session.get(sid)?.model)
389
+ if (sessionModel) { rememberUsage(sid, { model: sessionModel }); return sessionModel }
390
+ const listedModel = modelIdOf(listedSession(sid)?.model)
391
+ if (listedModel) { rememberUsage(sid, { model: listedModel }); return listedModel }
392
+ const cached = cachedUsage(sid)?.model
393
+ if (cached !== undefined) return cached
394
+ requestMessageSync(sid)
217
395
  return undefined
218
396
  } catch { return undefined }
219
397
  },
220
398
  readSessionTodo: () => undefined, // V2 无 todo 数据源
221
399
  },
222
400
  session: {
223
- get: (sid) => { try { return context.data.session.get(sid) as any } catch { return undefined } },
401
+ get: (sid) => {
402
+ try {
403
+ const direct = context.data.session.get(sid)
404
+ if (direct) return direct as any
405
+ // 较旧的子会话可能未注入本地缓存;回退到
406
+ // 会话列表,保证基于 parentID 的路由继续工作。
407
+ const list = context.data.session.list?.()
408
+ if (Array.isArray(list)) {
409
+ const found = list.find((s) => (s as any)?.id === sid)
410
+ if (found) return found as any
411
+ }
412
+ return undefined
413
+ } catch { return undefined }
414
+ },
224
415
  status: (sid) => {
225
416
  try {
226
417
  const st = context.data.session.status(sid)
227
- // V2 的 "running" 等价 V1 的 "busy"(cancelEntry 检查 `st.type !== "busy"`——
228
- // 不映射会跳过取消流程直接标记 done)
229
- const type = st === "running" ? "busy" : st ?? ""
230
- return { type }
231
- } catch { return undefined }
418
+ if (st) {
419
+ // V2 的 "running" 等价 V1 的 "busy"(cancelEntry 检查 `st.type !== "busy"`——
420
+ // 不映射会跳过取消流程直接标记 done)
421
+ const type = st === "running" ? "busy" : st
422
+ return { type }
423
+ }
424
+ } catch {}
425
+ // 宿主没有该子会话的实时状态(未加载缓存)时用本地库终态兜底:
426
+ // time_idle 存在即已结束;不存在则不猜测(交给事件/扫描)。
427
+ try {
428
+ if (statusOfChild(dbIndex?.info(sid)) !== undefined) return { type: "idle" }
429
+ } catch {}
430
+ return undefined
232
431
  },
233
432
  messages: (sid) => { try { return normalizeMessages(sid) } catch { return undefined } },
234
433
  part: (messageID) => {
@@ -242,6 +441,13 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
242
441
  }
243
442
  return msg.content.map((p) => toV1Part(p as Record<string, any>))
244
443
  },
444
+ resolveChild: (input) => {
445
+ try {
446
+ const sid = input.callId ? dbIndex?.resolveCall(input.parentId, input.callId) : undefined
447
+ if (sid) return sid
448
+ return dbIndex?.matchChild(input.parentId, input.agent, input.startedAt)
449
+ } catch { return undefined }
450
+ },
245
451
  },
246
452
  event: {
247
453
  on: (type: PanelEventType, cb: (e: PanelEvent) => void) => {
@@ -251,11 +457,13 @@ export function createPanelApi(context: Context, settings: PanelApi["settings"])
251
457
  for (const evt of ["session.tool.input.started", "session.tool.called", "session.tool.progress", "session.tool.success", "session.tool.failed"]) {
252
458
  unsubs.push(context.data.on(evt, (e) => {
253
459
  const part = toolEventToPart((e as Record<string, any>))
254
- if (!part) return
460
+ const evtData = (e as Record<string, any>).data as Record<string, any> | undefined
461
+ if (!part) {
462
+ return
463
+ }
255
464
  // V2 事件流是全局的(跨所有会话);把发起会话 ID 一并传给面板,
256
465
  // 让面板只归账到正在查看的会话(V1 宿主已按会话 scope,无需该字段)。
257
- const evt = (e as Record<string, any>).data as Record<string, any> | undefined
258
- const sid = evt?.sessionID !== undefined ? String(evt.sessionID) : undefined
466
+ const sid = evtData?.sessionID !== undefined ? String(evtData.sessionID) : undefined
259
467
  if (!sid) return
260
468
  cb({ type, scope: "global", payload: { part, sessionID: sid } })
261
469
  }))