opencode-subagent-magazine 1.7.1 → 1.7.3

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 (53) hide show
  1. package/dist/_version.d.ts +1 -1
  2. package/dist/panel/entry-map.d.ts +29 -0
  3. package/dist/tui.js +166 -19
  4. package/dist/v2.js +145 -22
  5. package/package.json +17 -4
  6. package/dist/_version.js +0 -2
  7. package/dist/clipboard.js +0 -85
  8. package/dist/core/color.js +0 -68
  9. package/dist/core/format.js +0 -113
  10. package/dist/core/index.js +0 -6
  11. package/dist/core/kv.js +0 -64
  12. package/dist/core/state-machine.js +0 -27
  13. package/dist/core/types.js +0 -9
  14. package/dist/core/usage.js +0 -1
  15. package/dist/i18n.js +0 -353
  16. package/dist/index.js +0 -528
  17. package/dist/panel/SubAgentPanel.js +0 -1644
  18. package/dist/panel/entry-map.js +0 -99
  19. package/dist/panel/panel-api.js +0 -1
  20. package/dist/panel/session-routing.js +0 -4
  21. package/dist/panel/store.js +0 -5
  22. package/dist/server.js +0 -14
  23. package/dist/v2/commands.js +0 -434
  24. package/dist/v2/db.js +0 -341
  25. package/dist/v2/index.js +0 -85
  26. package/dist/v2/settings-menu.js +0 -242
  27. package/dist/v2/theme.js +0 -12
  28. package/dist/v2/types.js +0 -6
  29. package/dist/v2/v2-panel-api.js +0 -623
  30. package/src/_version.ts +0 -2
  31. package/src/clipboard.ts +0 -134
  32. package/src/core/color.ts +0 -70
  33. package/src/core/format.ts +0 -105
  34. package/src/core/index.ts +0 -6
  35. package/src/core/kv.ts +0 -78
  36. package/src/core/state-machine.ts +0 -46
  37. package/src/core/types.ts +0 -85
  38. package/src/core/usage.ts +0 -16
  39. package/src/i18n.ts +0 -365
  40. package/src/index.tsx +0 -584
  41. package/src/panel/SubAgentPanel.tsx +0 -1877
  42. package/src/panel/entry-map.ts +0 -116
  43. package/src/panel/panel-api.ts +0 -100
  44. package/src/panel/session-routing.ts +0 -10
  45. package/src/panel/store.ts +0 -8
  46. package/src/server.ts +0 -19
  47. package/src/v2/commands.ts +0 -422
  48. package/src/v2/db.ts +0 -346
  49. package/src/v2/index.tsx +0 -149
  50. package/src/v2/settings-menu.ts +0 -259
  51. package/src/v2/theme.ts +0 -14
  52. package/src/v2/types.ts +0 -167
  53. package/src/v2/v2-panel-api.ts +0 -520
@@ -1,116 +0,0 @@
1
- import type { SubEntry, SubStatus } from "../core/types"
2
-
3
- export type SubEntryPatch = Omit<SubEntry, "startedAt" | "endedAt"> & {
4
- startedAt?: number
5
- endedAt?: number
6
- }
7
-
8
- export function findSubEntryKey(
9
- entries: ReadonlyMap<string, SubEntry>,
10
- id: string,
11
- sessionId?: string,
12
- ) {
13
- if (sessionId) {
14
- for (const [key, entry] of entries) {
15
- if (entry.sessionId === sessionId) return key
16
- }
17
- }
18
- return entries.has(id) ? id : undefined
19
- }
20
-
21
- export function upsertSubEntry(
22
- entries: ReadonlyMap<string, SubEntry>,
23
- partial: SubEntryPatch,
24
- now = Date.now(),
25
- ) {
26
- const key = findSubEntryKey(entries, partial.id, partial.sessionId) ?? partial.id
27
- const existing = entries.get(key)
28
- const next = new Map(entries)
29
- if (key !== partial.id) next.delete(partial.id)
30
-
31
- const ended = partial.status === "done" || partial.status === "error" || partial.status === "cancelled"
32
- next.set(key, {
33
- ...(existing ?? { startedAt: now }),
34
- ...partial,
35
- id: existing?.id ?? partial.id,
36
- startedAt: existing?.startedAt || partial.startedAt || now,
37
- endedAt: ended ? (existing?.endedAt ?? partial.endedAt ?? now) : undefined,
38
- })
39
- return next
40
- }
41
-
42
- /** running < cancel_requested < 终态(done/error/cancelled)。 */
43
- function statusRank(status: SubStatus): number {
44
- if (status === "running") return 0
45
- if (status === "cancel_requested") return 1
46
- return 2
47
- }
48
-
49
- const isTerminalStatus = (status: SubStatus) => statusRank(status) === 2
50
-
51
- function minDefined(a: number | undefined, b: number | undefined): number | undefined {
52
- if (a === undefined) return b
53
- if (b === undefined) return a
54
- return Math.min(a, b)
55
- }
56
-
57
- function maxDefined(a: number | undefined, b: number | undefined): number | undefined {
58
- if (a === undefined) return b
59
- if (b === undefined) return a
60
- return Math.max(a, b)
61
- }
62
-
63
- /**
64
- * 合并同一子代理条目的两个视图,绝不回退状态。
65
- *
66
- * 持久化存储由多个 TUI 实例写入,每个写入者都可能
67
- * 持有过期快照。终态始终优先于 running /
68
- * cancel_requested,进度计数只增不减,描述性字段
69
- * 则回退到仍保有它的一侧。
70
- */
71
- export function mergeSubEntry(base: SubEntry, incoming: SubEntry): SubEntry {
72
- const successor = statusRank(incoming.status) > statusRank(base.status) ? incoming : base
73
- const status = successor.status
74
- const ended = isTerminalStatus(status)
75
- return {
76
- ...base,
77
- ...incoming,
78
- id: base.id,
79
- status,
80
- sessionId: incoming.sessionId ?? base.sessionId,
81
- startedAt: minDefined(base.startedAt, incoming.startedAt) ?? base.startedAt,
82
- endedAt: ended ? (base.endedAt ?? incoming.endedAt ?? Date.now()) : undefined,
83
- tokens: maxDefined(base.tokens, incoming.tokens),
84
- cost: maxDefined(base.cost, incoming.cost),
85
- model: incoming.model ?? base.model,
86
- todoTotal: maxDefined(base.todoTotal, incoming.todoTotal),
87
- todoDone: maxDefined(base.todoDone, incoming.todoDone),
88
- error: incoming.error ?? base.error,
89
- cancelRequestedAt: minDefined(base.cancelRequestedAt, incoming.cancelRequestedAt),
90
- abortAccepted: base.abortAccepted || incoming.abortAccepted || undefined,
91
- cancelReason: incoming.cancelReason ?? base.cancelReason,
92
- }
93
- }
94
-
95
- /**
96
- * 合并两个条目集合,去重方式与 `upsertSubEntry` 相同
97
- * (先子会话、后条目 id),冲突用 `mergeSubEntry` 合并。
98
- * 所有持久化路径都走这里,避免并发实例以整表写入
99
- * 互相丢弃对方的条目。
100
- */
101
- export function mergeSubEntries(
102
- base: Iterable<SubEntry>,
103
- incoming: Iterable<SubEntry>,
104
- ): Map<string, SubEntry> {
105
- const out = new Map<string, SubEntry>()
106
- for (const entry of base) out.set(entry.id, entry)
107
- for (const entry of incoming) {
108
- const key = findSubEntryKey(out, entry.id, entry.sessionId)
109
- if (!key) {
110
- out.set(entry.id, entry)
111
- continue
112
- }
113
- out.set(key, mergeSubEntry(out.get(key)!, entry))
114
- }
115
- return out
116
- }
@@ -1,100 +0,0 @@
1
- import type { KVApi } from "../core/kv"
2
- import type { UsageReader, TodoStats } from "../core/usage"
3
- import type { Lang, SortOrder, ScrollMode } from "../core/types"
4
-
5
- /** Minimal session shape the panel reads from the host SDK. */
6
- export interface SessionLike {
7
- id?: string
8
- parentID?: string
9
- agent?: string
10
- cost?: number
11
- }
12
-
13
- /** Spawned child session summary (V2 reads it from the local database). */
14
- export interface ChildSessionLike {
15
- id: string
16
- agent?: string
17
- title?: string
18
- model?: string
19
- cost?: number
20
- tokens?: number
21
- timeCreated?: number
22
- timeIdle?: number
23
- idleOutcome?: string
24
- /** Still running: last message is newer than time_idle (resume keeps the old value). */
25
- active?: boolean
26
- }
27
-
28
- export interface SessionStatusLike {
29
- type: string
30
- }
31
-
32
- /**
33
- * Standardized panel events. Adapter layers (V1/V2) translate host events
34
- * into these shapes so the panel component never touches host APIs directly.
35
- */
36
- export type PanelEventType = "part.updated" | "message.updated" | "session.idle" | "session.error"
37
- export type PanelEventScope = "session" | "global"
38
-
39
- export interface PanelEvent {
40
- type: PanelEventType
41
- /** Global V2 events need explicit session ownership checks. */
42
- scope?: PanelEventScope
43
- /** part payload for part.updated; session properties for idle/error. */
44
- payload?: Record<string, unknown>
45
- }
46
-
47
- export interface ToastOptions {
48
- variant?: "success" | "warning" | "error"
49
- title?: string
50
- duration?: number
51
- }
52
-
53
- /**
54
- * The full surface the SubAgentPanel component consumes.
55
- * V1 and V2 each implement this against their host SDK; the panel is agnostic.
56
- * Theme is slot-scoped in both hosts, so it is passed as a panel prop,
57
- * not part of the API.
58
- */
59
- export interface PanelApi {
60
- kv: KVApi
61
- usage: UsageReader
62
- session: {
63
- get(sid: string): SessionLike | undefined
64
- status(sid: string): SessionStatusLike | undefined
65
- /** Raw message list for a session (scan / error extraction). */
66
- messages(sid: string): unknown[] | undefined
67
- /** Raw parts of a message (scan). */
68
- part(messageID: string): unknown[] | undefined
69
- /** Optional host-side fallback: map a subagent tool call to its child session
70
- * when live events/history lack the link (V2 reads the local database). */
71
- resolveChild?(input: {
72
- parentId: string
73
- callId?: string
74
- agent?: string
75
- startedAt?: number
76
- }): string | undefined
77
- /** Optional host-side listing of spawned child sessions. */
78
- listChildren?(parentId: string): ChildSessionLike[] | undefined
79
- }
80
- event: {
81
- on(type: PanelEventType, cb: (e: PanelEvent) => void): () => void
82
- }
83
- client: {
84
- abort(input: { sessionID: string }): Promise<void>
85
- }
86
- route: {
87
- navigateSession(sessionID: string): void
88
- }
89
- ui: {
90
- toast(message: string, opts?: ToastOptions): void
91
- }
92
- settings: {
93
- lang: () => Lang
94
- maxEntries: () => number
95
- sortOrder: () => SortOrder
96
- scrollMode: () => ScrollMode
97
- }
98
- }
99
-
100
- export type { TodoStats }
@@ -1,10 +0,0 @@
1
- import type { SessionLike } from "./panel-api"
2
-
3
- /** Whether an end event belongs to a child tracked by the current panel. */
4
- export function isDirectChildSession(
5
- currentSessionId: string,
6
- eventSessionId: string,
7
- eventSession: SessionLike | undefined,
8
- ): boolean {
9
- return eventSessionId !== currentSessionId && eventSession?.parentID === currentSessionId
10
- }
@@ -1,8 +0,0 @@
1
- import { createSignal } from "solid-js"
2
- import type { SubEntry } from "../core/types"
3
-
4
- /** 模块级缓存:各 session 的 entry 状态独立存储,不随当前视图切换而清除。 */
5
- export const globalEntryCache = new Map<string, Map<string, SubEntry>>()
6
-
7
- /** 模块级刷新信号:外部(如斜杠命令)触发清除后 +1,组件 scan 依赖它以重扫。 */
8
- export const [clearTick, setClearTick] = createSignal(0)
package/src/server.ts DELETED
@@ -1,19 +0,0 @@
1
- import type { Plugin, PluginModule } from "@opencode-ai/plugin"
2
-
3
- const server: Plugin = async () => ({})
4
-
5
- /**
6
- * V2 (opencode2) requires the default export to expose an `id` plus a
7
- * `setup` (or `effect`) function. This plugin has no server-side behavior,
8
- * so an empty setup keeps the module schema-valid and active on V2 while the
9
- * `server` field stays for V1 detection.
10
- */
11
- const setup = async () => {}
12
-
13
- const mod: PluginModule & { setup: () => Promise<void> } = {
14
- id: "opencode-subagent-magazine",
15
- server,
16
- setup,
17
- }
18
-
19
- export default mod
@@ -1,422 +0,0 @@
1
- import type { Context, KeymapCommand } from "./types"
2
- import type { PanelApi } from "../panel/panel-api"
3
- import type { Lang, SharedSignals, SubStatus, TimeFormat } from "../core/types"
4
- import { TIME_FORMATS, TIME_FORMAT_SAMPLES } from "../core/format"
5
- import { KV_PREFIX, SETTING_KEYS, updateSessionData, readTTLDays } from "../core/kv"
6
- import { PLUGIN_VERSION } from "../_version"
7
- import { LANG_META, createT } from "../i18n"
8
- import { globalEntryCache, setClearTick } from "../panel/store"
9
- import { mergeSubEntries } from "../panel/entry-map"
10
- import { openSettingsMenu } from "./settings-menu"
11
-
12
- /** V2 命令(对齐 V1 的 9 个斜杠命令——promise 式对话框)。 */
13
- export function makeCommands(
14
- context: Context,
15
- api: PanelApi,
16
- signals: SharedSignals,
17
- ): KeymapCommand[] {
18
- const t = createT(() => signals.lang())
19
- const kv = api.kv
20
- const clampMax = (n: number) => Math.max(1, Math.min(50, n))
21
- const onOff = (v: boolean) => (v ? t("settings.on") : t("settings.off"))
22
-
23
- const resolveParent = (sid: string): { parentSid: string; isChild: boolean } => {
24
- try {
25
- const session = api.session.get(sid) as any
26
- const parentID = session?.parentID as string | undefined
27
- if (parentID) return { parentSid: parentID, isChild: true }
28
- } catch {}
29
- return { parentSid: sid, isChild: false }
30
- }
31
-
32
- return [
33
- {
34
- id: "opencode-subagent-magazine.subagent.lang",
35
- title: "SubAgent Magazine: Language",
36
- description: "Switch display language (中文 / English / 日本語 / 한국어)",
37
- slash: { name: "subagent-lang" },
38
- palette: true,
39
- run: async () => {
40
- const lang = await context.ui.dialog.select<Lang>({
41
- title: "Language / 语言",
42
- options: LANG_META.map((m) => ({ title: m.label, value: m.code })),
43
- })
44
- if (!lang) return
45
- signals.setLang(lang)
46
- kv.set(SETTING_KEYS.lang, lang)
47
- api.ui.toast("Language: " + (LANG_META.find((m) => m.code === lang)?.label ?? lang))
48
- },
49
- },
50
- {
51
- id: "opencode-subagent-magazine.subagent.order",
52
- title: "SubAgent Magazine: Sort Order",
53
- description: "Set sub-agent entry sort order (desc / asc)",
54
- slash: { name: "subagent-order" },
55
- palette: true,
56
- run: async () => {
57
- const order = await context.ui.dialog.select<"desc" | "asc">({
58
- title: "Sort Order / 排序方式",
59
- options: [
60
- { title: t("order.desc"), value: "desc" },
61
- { title: t("order.asc"), value: "asc" },
62
- ],
63
- })
64
- if (!order) return
65
- signals.setSortOrder(order)
66
- kv.set(SETTING_KEYS.order, order)
67
- api.ui.toast(order === "desc" ? t("order.desc") : t("order.asc"))
68
- },
69
- },
70
- {
71
- id: "opencode-subagent-magazine.subagent.scroll",
72
- title: "SubAgent Magazine: Scroll Mode",
73
- description: "Set scroll mode (wheel / click)",
74
- slash: { name: "subagent-scroll" },
75
- palette: true,
76
- run: async () => {
77
- const mode = await context.ui.dialog.select<"wheel" | "click">({
78
- title: "Scroll Mode / 滚动模式",
79
- options: [
80
- { title: t("scroll.wheel"), value: "wheel" },
81
- { title: t("scroll.click"), value: "click" },
82
- ],
83
- })
84
- if (!mode) return
85
- signals.setScrollMode(mode)
86
- kv.set(SETTING_KEYS.scrollMode, mode)
87
- api.ui.toast(mode === "wheel" ? t("scroll.wheel") : t("scroll.click"))
88
- },
89
- },
90
- {
91
- id: "opencode-subagent-magazine.subagent.max",
92
- title: "SubAgent Magazine: Max Entries",
93
- description: "Set max visible sub-agent entries in sidebar",
94
- slash: { name: "subagent-max" },
95
- palette: true,
96
- run: async () => {
97
- const val = await context.ui.dialog.prompt({
98
- title: "Max Visible Entries",
99
- message: "Number of entries to show in the sidebar (1–50)",
100
- placeholder: String(signals.maxEntries()),
101
- })
102
- if (val === undefined) return
103
- const n = clampMax(parseInt(val, 10) || 10)
104
- signals.setMaxEntries(n)
105
- kv.set(SETTING_KEYS.maxEntries, n)
106
- api.ui.toast(`Max entries: ${n}`)
107
- },
108
- },
109
- {
110
- id: "opencode-subagent-magazine.subagent.config",
111
- title: "SubAgent Magazine: Settings",
112
- description: "Show current settings (change each via its own command)",
113
- slash: { name: "subagent-config" },
114
- palette: true,
115
- run: () => {
116
- const ttl = readTTLDays(kv)
117
- const langLabel = LANG_META.find((m) => m.code === signals.lang())?.label ?? signals.lang()
118
- const message = [
119
- `${t("settings.lang")}: ${langLabel}`,
120
- `${t("settings.max")}: ${signals.maxEntries()}`,
121
- `${t("settings.order")}: ${signals.sortOrder() === "desc" ? t("order.desc") : t("order.asc")}`,
122
- `${t("settings.scroll")}: ${signals.scrollMode() === "wheel" ? t("scroll.wheel") : t("scroll.click")}`,
123
- `${t("settings.ttl")}: ${ttl === 0 ? t("ttl.unlimited") : `${ttl}d`}`,
124
- `${t("settings.border")}: ${onOff(signals.borderVisible())}`,
125
- `${t("settings.showEntryCost")}: ${onOff(signals.showEntryCost())}`,
126
- `${t("settings.showEntryTime")}: ${onOff(signals.showEntryTime())}`,
127
- `${t("settings.showEntryTokens")}: ${onOff(signals.showEntryTokens())}`,
128
- `${t("settings.showOrigin")}: ${onOff(signals.showOrigin())}`,
129
- `${t("settings.timeFormat")}: ${TIME_FORMAT_SAMPLES[signals.timeFormat()]}`,
130
- `${t("settings.dbSync")}: ${onOff(signals.dbSync())}`,
131
- ].join("\n")
132
- context.ui.toast.show({ title: t("settings.title"), message })
133
- },
134
- },
135
- {
136
- id: "opencode-subagent-magazine.subagent.sections",
137
- title: "SubAgent Magazine: Settings Menu",
138
- description: "Open the interactive settings menu (Esc to close)",
139
- slash: { name: "subagent-sections" },
140
- palette: true,
141
- run: () => {
142
- openSettingsMenu(context, api, signals)
143
- },
144
- },
145
- {
146
- id: "opencode-subagent-magazine.subagent.cost",
147
- title: "SubAgent Magazine: Toggle Entry Cost",
148
- description: "Show or hide the per-sub-agent cost in the sidebar",
149
- slash: { name: "subagent-cost" },
150
- palette: true,
151
- run: () => {
152
- const v = !signals.showEntryCost()
153
- signals.setShowEntryCost(v)
154
- kv.set(SETTING_KEYS.showEntryCost, v)
155
- api.ui.toast(`${t("settings.showEntryCost")}: ${onOff(v)}`)
156
- },
157
- },
158
- {
159
- id: "opencode-subagent-magazine.subagent.time",
160
- title: "SubAgent Magazine: Toggle Entry Time",
161
- description: "Show or hide the elapsed time in the sidebar list",
162
- slash: { name: "subagent-time" },
163
- palette: true,
164
- run: () => {
165
- const v = !signals.showEntryTime()
166
- signals.setShowEntryTime(v)
167
- kv.set(SETTING_KEYS.showEntryTime, v)
168
- api.ui.toast(`${t("settings.showEntryTime")}: ${onOff(v)}`)
169
- },
170
- },
171
- {
172
- id: "opencode-subagent-magazine.subagent.time-format",
173
- title: "SubAgent Magazine: Time Format",
174
- description: "Set how elapsed time is displayed (short / decimal / clock / compact / seconds)",
175
- slash: { name: "subagent-time-format" },
176
- palette: true,
177
- run: async () => {
178
- const picked = await context.ui.dialog.select<TimeFormat>({
179
- title: t("settings.timeFormat"),
180
- options: TIME_FORMATS.map((f) => ({ title: `${f} — ${TIME_FORMAT_SAMPLES[f]}`, value: f })),
181
- current: signals.timeFormat(),
182
- })
183
- if (!picked) return
184
- signals.setTimeFormat(picked)
185
- kv.set(SETTING_KEYS.timeFormat, picked)
186
- api.ui.toast(`${t("settings.timeFormat")}: ${TIME_FORMAT_SAMPLES[picked]}`)
187
- },
188
- },
189
- {
190
- id: "opencode-subagent-magazine.subagent.tokens",
191
- title: "SubAgent Magazine: Toggle Entry Tokens",
192
- description: "Show or hide the token count in the sidebar list",
193
- slash: { name: "subagent-tokens" },
194
- palette: true,
195
- run: () => {
196
- const v = !signals.showEntryTokens()
197
- signals.setShowEntryTokens(v)
198
- kv.set(SETTING_KEYS.showEntryTokens, v)
199
- api.ui.toast(`${t("settings.showEntryTokens")}: ${onOff(v)}`)
200
- },
201
- },
202
- {
203
- id: "opencode-subagent-magazine.subagent.origin",
204
- title: "SubAgent Magazine: Toggle Origin Indicators",
205
- description: "Show or hide origin markers (⇢ background / ↳ spawned) in the sidebar list",
206
- slash: { name: "subagent-origin" },
207
- palette: true,
208
- run: () => {
209
- const v = !signals.showOrigin()
210
- signals.setShowOrigin(v)
211
- kv.set(SETTING_KEYS.showOrigin, v)
212
- api.ui.toast(`${t("settings.showOrigin")}: ${onOff(v)}`)
213
- },
214
- },
215
- {
216
- id: "opencode-subagent-magazine.subagent.db",
217
- title: "SubAgent Magazine: Toggle Local DB",
218
- description: "Enrich sub-agent entries from the local OpenCode database (V2)",
219
- slash: { name: "subagent-db" },
220
- palette: true,
221
- run: () => {
222
- const v = !signals.dbSync()
223
- signals.setDbSync(v)
224
- kv.set(SETTING_KEYS.dbSync, v)
225
- api.ui.toast(`${t("settings.dbSync")}: ${onOff(v)}`)
226
- },
227
- },
228
- {
229
- id: "opencode-subagent-magazine.subagent.version",
230
- title: "SubAgent Magazine: Version",
231
- description: "Show plugin version",
232
- slash: { name: "subagent-version" },
233
- palette: true,
234
- run: () => {
235
- api.ui.toast(`opencode-subagent-magazine v${PLUGIN_VERSION}`)
236
- },
237
- },
238
- {
239
- id: "opencode-subagent-magazine.subagent.session",
240
- title: "SubAgent Magazine: Session",
241
- description: "Show current session ID",
242
- slash: { name: "subagent-session" },
243
- palette: true,
244
- run: () => {
245
- api.ui.toast(`Session: ${signals.sessionId}`)
246
- },
247
- },
248
- {
249
- id: "opencode-subagent-magazine.subagent.clear-running",
250
- title: "SubAgent Magazine: Clear Running",
251
- description: "Mark all running sub-agent entries as done (for stuck/zombie entries)",
252
- slash: { name: "subagent-clear-running" },
253
- palette: true,
254
- run: () => {
255
- const sid = signals.sessionId
256
- const entries = globalEntryCache.get(sid)
257
- if (!entries || entries.size === 0) {
258
- api.ui.toast(signals.lang() === "zh" ? "暂无子代理条目" : "No sub-agent entries found")
259
- return
260
- }
261
- let count = 0
262
- for (const [, entry] of entries) {
263
- if (entry.status === "running" || entry.status === "cancel_requested") {
264
- entry.status = "done" as SubStatus
265
- entry.endedAt = Date.now()
266
- count++
267
- }
268
- }
269
- if (count > 0) {
270
- const ok = () => api.ui.toast(signals.lang() === "zh"
271
- ? `已标记 ${count} 个运行中的条目为完成`
272
- : `Marked ${count} running entries as done`)
273
- const fail = () => {
274
- try { api.ui.toast(t("clear.failed")) } catch {}
275
- }
276
- try {
277
- const { parentSid, isChild } = resolveParent(sid)
278
- const done = updateSessionData(kv, (data) => {
279
- // 落定前先把(可能过期的)模块缓存与持久化记录
280
- // merge:其他实例可能有本实例从未见过的条目,
281
- // 这次写入不能把它们丢掉。
282
- if (isChild) {
283
- if (!data[parentSid]) data[parentSid] = { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} }
284
- if (!data[parentSid].children) data[parentSid].children = {}
285
- const prev = data[parentSid].children[sid]?.entries ?? []
286
- const merged = [...mergeSubEntries(prev, entries.values()).values()].map((e) =>
287
- e.status === "running" || e.status === "cancel_requested"
288
- ? { ...e, status: "done" as SubStatus, endedAt: e.endedAt ?? Date.now() }
289
- : e
290
- )
291
- data[parentSid].children[sid] = {
292
- ...(data[parentSid].children[sid] ?? { scroll: 0, expanded: "" }),
293
- entries: merged,
294
- }
295
- } else {
296
- const rec = data[parentSid] ?? { ts: Date.now(), entries: [], scroll: 0, expanded: "", children: {} }
297
- const merged = [...mergeSubEntries(rec.entries ?? [], entries.values()).values()].map((e) =>
298
- e.status === "running" || e.status === "cancel_requested"
299
- ? { ...e, status: "done" as SubStatus, endedAt: e.endedAt ?? Date.now() }
300
- : e
301
- )
302
- data[parentSid] = { ...rec, ts: Date.now(), entries: merged, children: rec.children ?? {} }
303
- }
304
- })
305
- if (done && typeof (done as Promise<void>).then === "function") {
306
- void (done as Promise<void>).then(ok, fail)
307
- } else {
308
- ok()
309
- }
310
- } catch {
311
- fail()
312
- }
313
- } else {
314
- api.ui.toast(signals.lang() === "zh" ? "没有需要清理的运行中条目" : "No running entries to clear")
315
- }
316
- },
317
- },
318
- {
319
- id: "opencode-subagent-magazine.subagent.ttl",
320
- title: "SubAgent Magazine: TTL",
321
- description: "Set session data retention period (days before auto-cleanup)",
322
- slash: { name: "subagent-ttl" },
323
- palette: true,
324
- run: async () => {
325
- const curDays = readTTLDays(kv)
326
- const curLabel = curDays === 0 ? t("ttl.unlimited") : `${curDays}d`
327
- const days = await context.ui.dialog.select<number>({
328
- title: `${t("ttl.label")} (${curLabel})`,
329
- options: [
330
- { title: t("ttl.3d"), value: 3 },
331
- { title: t("ttl.7d"), value: 7 },
332
- { title: t("ttl.14d"), value: 14 },
333
- { title: t("ttl.30d"), value: 30 },
334
- { title: t("ttl.unlimited"), value: 0 },
335
- ],
336
- })
337
- if (days === undefined) return
338
- kv.set(SETTING_KEYS.ttlDays, String(days))
339
- api.ui.toast(days === 0 ? t("ttl.toast_unlimited") : t("ttl.toast", { n: days }))
340
- },
341
- },
342
- {
343
- id: "opencode-subagent-magazine.subagent.clear-entries",
344
- title: "SubAgent Magazine: Clear Entries",
345
- description: "Delete all sub-agent records for the current session (cannot be undone)",
346
- slash: { name: "subagent-clear-entries" },
347
- palette: true,
348
- run: async () => {
349
- const sid = signals.sessionId
350
- const sessionObj = api.session.get(sid)
351
- const parentID = (sessionObj as any)?.parentID as string | undefined
352
- const cached = globalEntryCache.get(sid)
353
- let runningCount = 0
354
- if (cached) {
355
- for (const [, e] of cached) { if (e.status === "running") runningCount++ }
356
- }
357
- const msg = runningCount > 0 ? t("clear.prompt_running", { n: runningCount }) : t("clear.prompt")
358
- const choice = await context.ui.dialog.select<"yes" | "no">({
359
- title: t("clear.title"),
360
- options: [
361
- { title: t("clear.title"), value: "yes" },
362
- { title: t("cancel.label"), value: "no" },
363
- ],
364
- })
365
- if (choice !== "yes") return
366
- try {
367
- let count = 0
368
- const finish = () => {
369
- globalEntryCache.delete(sid)
370
- setClearTick((v) => v + 1)
371
- api.ui.toast(t("clear.done", { n: count }))
372
- }
373
- const done = updateSessionData(kv, (data) => {
374
- if (parentID) {
375
- const child = data[parentID]?.children?.[sid]
376
- if (child) {
377
- const ids = child.entries?.map((e) => e.id) ?? []
378
- count = ids.length
379
- child.entries = []
380
- child.scroll = 0
381
- child.expanded = ""
382
- child.clearedIds = [...new Set([...(child.clearedIds ?? []), ...ids])]
383
- }
384
- } else {
385
- const rec = data[sid]
386
- if (rec) {
387
- const ids = rec.entries?.map((e) => e.id) ?? []
388
- count = ids.length
389
- rec.entries = []
390
- rec.scroll = 0
391
- rec.expanded = ""
392
- rec.clearedIds = [...new Set([...(rec.clearedIds ?? []), ...ids])]
393
- }
394
- }
395
- })
396
- if (done && typeof (done as Promise<void>).then === "function") {
397
- void (done as Promise<void>).then(finish, () => {
398
- try { api.ui.toast(t("clear.failed")) } catch {}
399
- })
400
- } else {
401
- finish()
402
- }
403
- } catch {}
404
- },
405
- },
406
- {
407
- id: "opencode-subagent-magazine.subagent.border",
408
- title: "SubAgent Magazine: Border",
409
- description: "Show or hide the panel border",
410
- slash: { name: "subagent-border" },
411
- palette: true,
412
- run: () => {
413
- const cur = Boolean(kv.get(SETTING_KEYS.border, false))
414
- kv.set(SETTING_KEYS.border, !cur)
415
- signals.setBorderVisible(!cur)
416
- api.ui.toast(!cur ? t("borderShown") : t("borderHidden"))
417
- },
418
- },
419
- ]
420
- }
421
-
422
- export { KV_PREFIX }