pantheon-opencode 1.4.1 → 1.4.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.
@@ -1,374 +0,0 @@
1
- /**
2
- * Delegation finalize — PULL output from a child session and persist the
3
- * delegation report (markdown) + the terminal board transition.
4
- *
5
- * Completion is NOT pushed: the event hook observes `session.idle` on the
6
- * child session, then calls `finalizeDelegation()` which pulls the child's
7
- * messages via `client.session.messages()`, writes the report atomically
8
- * (tmp + rename) to `.pantheon/delegations/<rootSessionID>/<alias>.md`, and
9
- * moves the job to a terminal board state (persist-before-notify: the report
10
- * file exists before `board.updateStatus` resolves waiters).
11
- *
12
- * Pure TypeScript — zero runtime dependencies beyond Node.js builtins and the
13
- * BackgroundJobBoard. The client is a STRUCTURAL interface (fake-client
14
- * friendly) so this module is testable standalone, without the opencode SDK.
15
- *
16
- * @module delegation-finalize
17
- */
18
-
19
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
20
- import { join } from 'node:path'
21
-
22
- import type { BackgroundJobBoard, BackgroundJobRecord } from './background-job-board.ts'
23
- import type { PermissionTaskConfig } from './permission-globs.ts'
24
- import type { StepCapTracker } from './step-cap.ts'
25
-
26
- // ─── Types ─────────────────────────────────────────────────────────────
27
-
28
- /** A minimal structural view of one message bundle from session.messages(). */
29
- export interface DelegationMessageBundle {
30
- info?: { role?: string; finish?: string; error?: unknown }
31
- parts?: Array<{
32
- type?: string
33
- text?: string
34
- /** Tool name on `tool` parts — used by the activity sampler. */
35
- tool?: string
36
- /** Tool input on `tool` parts (opencode SDK ToolPart.metadata). */
37
- metadata?: { input?: unknown }
38
- }>
39
- }
40
-
41
- /** Minimal structural view of the opencode SDK session client we use. */
42
- export interface DelegationClientSession {
43
- create(input: {
44
- body: { parentID: string; title?: string; model?: { id: string; providerID: string } }
45
- }): Promise<{ id: string }>
46
- promptAsync(input: {
47
- path: { id: string }
48
- body: {
49
- agent: string
50
- model?: { id: string; providerID: string }
51
- parts: Array<{ type: 'text'; text: string }>
52
- }
53
- /** Request cancellation for hosts that support AbortSignal. */
54
- signal?: AbortSignal
55
- }): Promise<unknown>
56
- messages?(input: { path: { id: string } }): Promise<Array<DelegationMessageBundle>>
57
- /** Optional session metadata endpoint (older hosts do not expose it). */
58
- get?(input: { path: { id: string } }): Promise<unknown>
59
- }
60
-
61
- /** The client surface used by the delegation core. */
62
- export interface DelegationClient {
63
- session: DelegationClientSession
64
- }
65
-
66
- /** Tunables for the delegation core (all optional — see DELEGATION_DEFAULTS). */
67
- export interface DelegationOptions {
68
- /** Job timeout before the delegation is finalized as error/timedOut. */
69
- timeoutMs?: number
70
- /** Caller-side cap for pantheon_delegation_read's waitForTerminal. */
71
- readTimeoutMs?: number
72
- /** Base directory for delegation reports (default `.pantheon/delegations`). */
73
- outputDir?: string
74
- /** Explicit root-session allowlist for the depth guard. */
75
- rootSessions?: ReadonlySet<string>
76
- /** Custom depth-guard predicate — overrides rootSessions and the default. */
77
- isRootSession?: (sessionID: string) => boolean
78
- /** SDK-backed child predicate; authoritative when supplied by the plugin. */
79
- isChildSession?: (sessionID: string) => boolean
80
- /**
81
- * Enforce the runtime B2 delegation matrix; createDelegationTools defaults
82
- * this to true. Set false only for an explicitly legacy host that cannot
83
- * provide ToolContext.agent.
84
- */
85
- enforceRuntimeMatrix?: boolean
86
- /** Record a child returned by the SDK session.create call. */
87
- registerChildSession?: (sessionID: string, parentID: string) => void
88
- /**
89
- * Agents whose delegated child sessions are registered as read-only
90
- * (Phase 4 enforcement). Mirrors routing.yml
91
- * background_delegation.read_only_agents. Matching is case-insensitive.
92
- */
93
- readOnlyAgents?: ReadonlySet<string>
94
- /**
95
- * Per-agent model overrides for delegated child sessions, keyed by agent
96
- * name (lowercase, e.g. `apollo`). Values are opencode model IDs in
97
- * `provider/model` form (e.g. `opencode/deepseek-v4-flash-free`), sourced
98
- * from routing.yml agent entries. Higher priority than the active preset.
99
- */
100
- agentModels?: Readonly<Record<string, string>>
101
- /**
102
- * Fase B3: Per-exception delegation budgets. Keys use
103
- * `<parent-agent>-><target-agent>` (for example `athena->apollo`). The
104
- * count is tracked per parent session for this process. It is intentionally
105
- * not persisted across restart because this layer has no reliable store.
106
- * An absent key has no budget limit.
107
- */
108
- delegationBudgets?: ReadonlyMap<string, number>
109
- /**
110
- * Fase B3: Wall-clock timeout (ms) for individual delegation sessions.
111
- * The plugin resolves `PANTHEON_DELEGATION_TIMEOUT_MS` into this option;
112
- * direct callers may provide it here instead.
113
- */
114
- wallClockTimeoutMs?: number
115
- /**
116
- * Env override for the active-preset resolution (see resolveActivePreset).
117
- * Defaults to process.env. Primarily for tests.
118
- */
119
- presetEnv?: Record<string, string | undefined>
120
- /** Warning sink for the no-model fallback (defaults to console). */
121
- logger?: { warn?: (msg: string) => void }
122
- /**
123
- * R4: per-agent step-cap tracker (routing.yml `agents.<name>.max_steps`).
124
- * When an agent reaches max_steps the delegation is forced to
125
- * summarize-and-stop: skipped with a capped summary when already at the
126
- * cap, or the prompt is appended with a stop instruction when the cap is
127
- * hit by this dispatch.
128
- */
129
- stepCapTracker?: StepCapTracker
130
- /**
131
- * O5: permission.task glob rules controlling which subagents may be
132
- * invoked. Denied agents are removed from the delegate tool description
133
- * entirely (not just blocked at call time).
134
- */
135
- permissionTask?: PermissionTaskConfig
136
- /**
137
- * O5: candidate agent names for the delegate tool description. Defaults
138
- * to the canonical 14-agent roster.
139
- */
140
- agentNames?: readonly string[]
141
- /** Bounded post-prompt bootstrap watchdog window. */
142
- bootstrapTimeoutMs?: number
143
- /** Timeout for the promptAsync request itself (including AbortSignal). */
144
- promptTimeoutMs?: number
145
- /** Poll interval used by the bootstrap watchdog. */
146
- bootstrapPollIntervalMs?: number
147
- /** Injectable clock/sleeper for deterministic watchdog tests. */
148
- now?: () => number
149
- sleep?: (ms: number) => Promise<void>
150
- }
151
-
152
- /** Dependencies threaded to the finalize path. */
153
- export interface DelegationDeps {
154
- board: BackgroundJobBoard
155
- client: DelegationClient
156
- options: DelegationOptions
157
- }
158
-
159
- /** Terminal transition requested by the finalize path. */
160
- export interface FinalizeInput {
161
- state: 'completed' | 'error' | 'startup_failed' | 'startup_unknown' | 'cancelled'
162
- error?: string
163
- timedOut?: boolean
164
- }
165
-
166
- /** Defaults matching routing.yml background_delegation (timeout_ms 900000). */
167
- export const DELEGATION_DEFAULTS = {
168
- timeoutMs: 900_000,
169
- readTimeoutMs: 900_000,
170
- outputDir: '.pantheon/delegations',
171
- } as const
172
-
173
- // ─── Output pulling ────────────────────────────────────────────────────
174
-
175
- interface PulledOutput {
176
- text: string
177
- /** True only when the child produced an assistant message or tool activity. */
178
- hasWork: boolean
179
- }
180
-
181
- /** Pull visible text and structurally identify real child work. */
182
- async function pullOutput(client: DelegationClient, childSessionID: string): Promise<PulledOutput> {
183
- if (typeof client.session.messages !== 'function')
184
- return { text: '(child session messages API unavailable)', hasWork: false }
185
- try {
186
- const bundles = await client.session.messages({ path: { id: childSessionID } })
187
- const lines: string[] = []
188
- let hasWork = false
189
- for (const bundle of bundles) {
190
- const hasToolPart = (bundle.parts ?? []).some((part) => part.type === 'tool')
191
- const hasTextPart = (bundle.parts ?? []).some(
192
- (part) => part.type === 'text' && typeof part.text === 'string' && part.text.trim() !== '',
193
- )
194
- if (
195
- bundle.info?.role === 'assistant' &&
196
- bundle.info.error === undefined &&
197
- (hasToolPart || hasTextPart)
198
- ) {
199
- hasWork = true
200
- }
201
- for (const part of bundle.parts ?? []) {
202
- if (
203
- part.type === 'tool' &&
204
- bundle.info?.role === 'assistant' &&
205
- bundle.info.error === undefined
206
- )
207
- hasWork = true
208
- if (part.type === 'text' && typeof part.text === 'string' && part.text.trim() !== '') {
209
- lines.push(part.text)
210
- }
211
- }
212
- }
213
- return { text: lines.join('\n\n'), hasWork }
214
- } catch (err: unknown) {
215
- const reason = err instanceof Error ? err.message : String(err)
216
- return { text: `(failed to pull child session output: ${reason})`, hasWork: false }
217
- }
218
- }
219
-
220
- // ─── Markdown rendering ────────────────────────────────────────────────
221
-
222
- /** Render the delegation report body. Public for tests/Phase 3 reuse. */
223
- export function renderDelegationMarkdown(
224
- job: BackgroundJobRecord,
225
- output: string,
226
- opts: FinalizeInput & { at?: number },
227
- ): string {
228
- const at = opts.at ?? Date.now()
229
- const lines = [
230
- `# Delegation Report — ${job.alias}`,
231
- '',
232
- `- **Task ID**: \`${job.taskID}\``,
233
- `- **Agent**: ${job.agent}`,
234
- `- **Description**: ${job.description}`,
235
- `- **State**: ${opts.state}`,
236
- `- **Timed out**: ${opts.timedOut === true ? 'true' : 'false'}`,
237
- `- **Started**: ${new Date(job.launchedAt).toISOString()}`,
238
- `- **Finalized**: ${new Date(at).toISOString()}`,
239
- '',
240
- '## Output',
241
- '',
242
- output.trim() !== '' ? output : '_No output captured._',
243
- ]
244
- if (opts.error !== undefined) {
245
- lines.push('', `**Error**: ${opts.error}`)
246
- }
247
- if (opts.timedOut === true) {
248
- lines.push('', '[TIMEOUT REACHED]')
249
- }
250
- return `${lines.join('\n')}\n`
251
- }
252
-
253
- /** One-line result summary from the pulled output (for the board record). */
254
- function summarizeOutput(output: string): string {
255
- const firstLine = output
256
- .split('\n')
257
- .map((l) => l.trim())
258
- .find((l) => l !== '')
259
- if (firstLine === undefined) return 'No output captured'
260
- return firstLine.length > 120 ? `${firstLine.slice(0, 120)}…` : firstLine
261
- }
262
-
263
- // ─── Report persistence ────────────────────────────────────────────────
264
-
265
- /**
266
- * Reject session IDs that could escape the delegation output directory.
267
- * `parentSessionID` is embedded in the report path
268
- * `<outputDir>/<parentSessionID>/<alias>.md` — `path.join` does NOT strip
269
- * `..`, so a traversing ID would write outside the sandbox. Called BEFORE any
270
- * path construction (F1 — path traversal hardening).
271
- *
272
- * @throws {Error} When the ID contains `..`, `/`, or `\`.
273
- */
274
- export function assertSafeParentSessionID(parentSessionID: string): void {
275
- if (
276
- parentSessionID.includes('..') ||
277
- parentSessionID.includes('/') ||
278
- parentSessionID.includes('\\')
279
- ) {
280
- throw new Error(`Invalid parentSessionID: ${parentSessionID}`)
281
- }
282
- }
283
-
284
- /** Atomic write (tmp + rename) of the report under <outputDir>/<parent>/<alias>.md. */
285
- async function writeDelegationReport(
286
- outputDir: string,
287
- job: BackgroundJobRecord,
288
- md: string,
289
- ): Promise<string> {
290
- assertSafeParentSessionID(job.parentSessionID)
291
- const dir = join(outputDir, job.parentSessionID)
292
- const filePath = join(dir, `${job.alias}.md`)
293
- const tmpPath = join(dir, `${job.alias}.md.tmp`)
294
- await mkdir(dir, { recursive: true })
295
- await writeFile(tmpPath, md, 'utf-8')
296
- await rename(tmpPath, filePath)
297
- return filePath
298
- }
299
-
300
- /** Read a previously written report; undefined when the file does not exist. */
301
- export async function readDelegationReport(
302
- outputDir: string,
303
- job: BackgroundJobRecord,
304
- ): Promise<string | undefined> {
305
- assertSafeParentSessionID(job.parentSessionID)
306
- const filePath = join(outputDir, job.parentSessionID, `${job.alias}.md`)
307
- try {
308
- return await readFile(filePath, 'utf-8')
309
- } catch (err: unknown) {
310
- if (err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT') {
311
- return undefined
312
- }
313
- throw err
314
- }
315
- }
316
-
317
- // ─── Finalize ──────────────────────────────────────────────────────────
318
-
319
- /**
320
- * Finalize a delegation for a child session: pull output, write the report
321
- * atomically, then move the board job to the requested terminal state.
322
- *
323
- * The board transition is guarded: only `running` → terminal, or an
324
- * idempotent same-terminal re-notify, are applied. A finalize that races a
325
- * timeout (already `error`) never overwrites the terminal state — the report
326
- * file is still (re)written, so the marker reflects the latest observation.
327
- *
328
- * @returns The updated job record, or undefined when the session is unknown.
329
- */
330
- export async function finalizeDelegation(
331
- deps: DelegationDeps,
332
- childSessionID: string,
333
- opts: FinalizeInput,
334
- ): Promise<BackgroundJobRecord | undefined> {
335
- const job = deps.board.get(childSessionID)
336
- if (!job) return undefined
337
-
338
- const pulled = await pullOutput(deps.client, childSessionID)
339
- const output = pulled.text
340
- const effectiveOpts: FinalizeInput =
341
- opts.state === 'completed' && !pulled.hasWork
342
- ? {
343
- state: 'error',
344
- error: opts.error ?? 'Child session produced no assistant or tool output',
345
- ...(opts.timedOut !== undefined ? { timedOut: opts.timedOut } : {}),
346
- }
347
- : opts
348
- const outputDir = deps.options.outputDir ?? DELEGATION_DEFAULTS.outputDir
349
- await writeDelegationReport(outputDir, job, renderDelegationMarkdown(job, output, effectiveOpts))
350
-
351
- const status: {
352
- taskID: string
353
- state: 'completed' | 'error' | 'startup_failed' | 'startup_unknown' | 'cancelled'
354
- error?: string
355
- timedOut?: boolean
356
- resultSummary?: string
357
- } = {
358
- taskID: childSessionID,
359
- state: effectiveOpts.state,
360
- resultSummary: summarizeOutput(output),
361
- }
362
- if (effectiveOpts.error !== undefined) status.error = effectiveOpts.error
363
- if (effectiveOpts.timedOut !== undefined) status.timedOut = effectiveOpts.timedOut
364
-
365
- const current = deps.board.get(childSessionID)
366
- if (current !== undefined) {
367
- if (current.state === 'running' || current.state === effectiveOpts.state) {
368
- await deps.board.updateStatus(status)
369
- }
370
- // Terminal in a DIFFERENT state (e.g. timeout already recorded) — the
371
- // report above still captures this finalize; the board state stands.
372
- }
373
- return deps.board.get(childSessionID) ?? job
374
- }
@@ -1,197 +0,0 @@
1
- /**
2
- * Delegation event wiring — observe background-job lifecycle events and
3
- * route them to finalize. This module is the `event`-hook complement of the
4
- * board: `session.idle`/`session.error` on a child session that is a board
5
- * job → `finalizeDelegation` (Phase 2), which transitions the board and
6
- * fires `onTerminal`.
7
- *
8
- * NOT a notification channel. The user policy is ZERO delegation
9
- * notifications in the chat transcript — no `<task-notification>` block is
10
- * ever injected into a `chat.message` output, and no queued delivery path
11
- * exists. Completion visibility lives in the legitimate channels only:
12
- * the board `[unread]` marker (`pantheon_delegation_list`),
13
- * `pantheon_delegation_read`, TUI toasts (pantheon-hooks, PANTHEON_TOASTS
14
- * gate), and compaction carry-forward. The plugin's `onTerminal` listener
15
- * writes a file-only log line for the on-disk audit trail.
16
- *
17
- * `handleDelegationEvent` wires the `event` hook: `session.idle`/`session.error`
18
- * on a child session that is a board job → `finalizeDelegation` (Phase 2),
19
- * which transitions the board and fires `onTerminal`. Finalize never notifies
20
- * directly, and `markReconciled` does not re-fire onTerminal (reconcile is an
21
- * acknowledgment, not a completion), so every job gets exactly ONE terminal
22
- * transition — never a reconciled echo. Unknown sessions are ignored.
23
- *
24
- * `finalizeIdleChildrenWithoutMd` proactively finalizes children that are
25
- * idle on the board but have no MD report on disk — eliminates the phantom
26
- * "running" window during `pullOutput` (Fix 2 for the TUI stale-running bug).
27
- * Wired into a periodic scan via `startIdleChildScan` (default 30 s cadence).
28
- *
29
- * Pure TypeScript — zero runtime dependencies beyond the board types.
30
- *
31
- * Follow-up (Themis review, Phase 5): `extractErrorMessage` handles the two
32
- * observed `session.error` error shapes (string, { message }). The opencode SDK
33
- * MAY expose other shapes (e.g. Error-like with non-string `message`) — if a
34
- * real session.error ever carries one, the extraction degrades to the generic
35
- * "session error" label. No code change: there is no evidence any other shape
36
- * occurs in practice; revisit if a session.error shows an unexpected payload.
37
- *
38
- * @module delegation-notify
39
- */
40
-
41
- import type { BackgroundJobRecord } from './background-job-board.ts'
42
- import type { FinalizeInput } from './delegation-finalize.ts'
43
-
44
- export type { FinalizeInput } from './delegation-finalize.ts'
45
-
46
- /** Default cadence for the proactive idle-child scan (30 s). */
47
- export const IDLE_SCAN_INTERVAL_MS = 30_000
48
-
49
- // ─── Types ─────────────────────────────────────────────────────────────
50
-
51
- /** Structural view of the event payload the `event` hook receives. */
52
- export interface DelegationEventLike {
53
- type?: string
54
- properties?: Record<string, unknown>
55
- }
56
-
57
- /** Dependencies threaded to handleDelegationEvent (board lookup + finalize). */
58
- export interface DelegationEventDeps {
59
- /** Look up a board job by session ID (child session IDs are task IDs). */
60
- board: { get(taskID: string): BackgroundJobRecord | undefined }
61
- /** Bound Phase 2 finalize — clears the timeout timer + writes the report. */
62
- finalize: (childSessionID: string, opts: FinalizeInput) => Promise<unknown>
63
- }
64
-
65
- // ─── Event → finalize wiring ───────────────────────────────────────────
66
-
67
- function extractErrorMessage(error: unknown): string {
68
- if (typeof error === 'string' && error.trim() !== '') return error
69
- if (error && typeof error === 'object' && 'message' in error) {
70
- const message = (error as { message: unknown }).message
71
- if (typeof message === 'string' && message.trim() !== '') return message
72
- }
73
- return 'session error'
74
- }
75
-
76
- /**
77
- * Handle a lifecycle event for background delegations:
78
- * - `session.idle` on a board job → finalize as completed;
79
- * - `session.error` on a board job → finalize as error (message extracted);
80
- * - any other event, a missing session ID, or an unknown session → no-op.
81
- *
82
- * Finalize transitions the board, which fires `onTerminal` (the plugin's
83
- * file-only audit log — no chat delivery; see module header). The board's
84
- * same-terminal idempotency makes repeated idles harmless (finalize rewrites
85
- * the report but never transitions a terminal job to a different state).
86
- *
87
- * @returns True when the event named a board job (handled).
88
- */
89
- export async function handleDelegationEvent(
90
- ev: DelegationEventLike,
91
- deps: DelegationEventDeps,
92
- ): Promise<boolean> {
93
- const type = ev?.type
94
- if (type !== 'session.idle' && type !== 'session.error') return false
95
- const sessionID = ev.properties?.sessionID
96
- if (typeof sessionID !== 'string' || sessionID === '') return false
97
- if (deps.board.get(sessionID) === undefined) return false
98
-
99
- if (type === 'session.idle') {
100
- await deps.finalize(sessionID, { state: 'completed' })
101
- } else {
102
- await deps.finalize(sessionID, {
103
- state: 'error',
104
- error: extractErrorMessage(ev.properties?.error),
105
- })
106
- }
107
- return true
108
- }
109
-
110
- // ─── Proactive finalize (Fix 2) ────────────────────────────────────────
111
-
112
- /** Dependencies for idle-child scanning. */
113
- export interface IdleChildScanDeps {
114
- /** Look up a board job by session ID (child session IDs are task IDs). */
115
- board: {
116
- get(taskID: string): BackgroundJobRecord | undefined
117
- list(parentSessionID?: string): BackgroundJobRecord[]
118
- }
119
- /** Bound Phase 2 finalize — clears the timeout timer + writes the report. */
120
- finalize: (childSessionID: string, opts: FinalizeInput) => Promise<unknown>
121
- /**
122
- * Check whether an MD report exists for the given board job.
123
- * Receives the full job record so the caller can construct the report
124
- * path from `job.parentSessionID` + `job.alias`.
125
- * If the function throws, the scan skips that child (fail-open).
126
- */
127
- hasReport: (job: BackgroundJobRecord) => boolean
128
- /** Optional logger for diagnostic messages. */
129
- logger?: { info?: (msg: string) => void; warn?: (msg: string) => void }
130
- }
131
-
132
- /**
133
- * Scan running board jobs for children whose sessions are idle but have no MD
134
- * report on disk, and proactively finalize them. This eliminates the phantom
135
- * "running" window that occurs between `session.idle` firing and the
136
- * `pullOutput`→`writeDelegationReport` cycle completing.
137
- *
138
- * Called from the periodic idle-child scan (`startIdleChildScan`, default 30 s).
139
- * The scan is O(N) where N = number of running jobs (typically < 10).
140
- *
141
- * Each child is finalized exactly once — the board's same-terminal idempotency
142
- * ensures repeated scans are harmless. Errors are caught per-child so one
143
- * failure never blocks the rest.
144
- *
145
- * @returns Number of children finalized (for diagnostics).
146
- */
147
- export async function finalizeIdleChildrenWithoutMd(
148
- deps: IdleChildScanDeps,
149
- ): Promise<number> {
150
- const runningJobs = deps.board
151
- .list()
152
- .filter((j: BackgroundJobRecord) => j.state === 'running')
153
-
154
- let finalized = 0
155
- for (const job of runningJobs) {
156
- try {
157
- // If the child already has an MD report, finalize was already handled
158
- // by handleDelegationEvent — skip.
159
- if (deps.hasReport(job)) continue
160
- // Child is idle on the board but has no report — proactively finalize.
161
- await deps.finalize(job.taskID, { state: 'completed' })
162
- finalized++
163
- } catch (err) {
164
- deps.logger?.warn?.(
165
- `[delegation-notify] proactive finalize failed for ${job.taskID}: ${err}`,
166
- )
167
- }
168
- }
169
- return finalized
170
- }
171
-
172
- // ─── Periodic scan launcher ─────────────────────────────────────────────
173
-
174
- /**
175
- * Start a periodic scan that proactively finalizes idle board children
176
- * without MD reports. The scan runs every `intervalMs` (default 30 s) and
177
- * is **unref'd** so it never holds the process open on its own.
178
- *
179
- * The timer is idempotent — calling this function multiple times is safe
180
- * (each call creates an independent timer, but the underlying finalize
181
- * operation is itself idempotent due to the board's same-terminal guard).
182
- *
183
- * @returns A `NodeJS.Timeout` handle that can be cleared with
184
- * `clearInterval(handle)` to stop the scan.
185
- */
186
- export function startIdleChildScan(
187
- deps: IdleChildScanDeps,
188
- intervalMs: number = IDLE_SCAN_INTERVAL_MS,
189
- ): NodeJS.Timeout {
190
- const timer = setInterval(() => {
191
- void finalizeIdleChildrenWithoutMd(deps).catch((err) => {
192
- deps.logger?.warn?.(`[delegation-notify] periodic idle scan failed: ${err}`)
193
- })
194
- }, intervalMs)
195
- timer.unref()
196
- return timer
197
- }
@@ -1,73 +0,0 @@
1
- import type { BackgroundJobRecord } from './background-job-board.ts'
2
-
3
- type ToastCategory = 'errors' | 'delegations' | 'council'
4
-
5
- const toastMode = (process.env.PANTHEON_TOASTS ?? '').trim().toLowerCase()
6
- const enabledToastCategories: ReadonlySet<ToastCategory> = (() => {
7
- switch (toastMode) {
8
- case 'off':
9
- return new Set()
10
- case 'errors':
11
- return new Set(['errors'])
12
- case 'council':
13
- return new Set(['errors', 'council'])
14
- case 'all':
15
- return new Set(['errors', 'delegations', 'council'])
16
- default:
17
- return new Set(['errors', 'delegations', 'council'])
18
- }
19
- })()
20
- const terminalToastsShown = new Set<string>()
21
- const terminalStates = new Set(['completed', 'error', 'cancelled'])
22
-
23
- /** Match the lifecycle toast gate used by pantheon-hooks. */
24
- export function delegationToastEnabled(): boolean {
25
- return enabledToastCategories.has('delegations')
26
- }
27
-
28
- export type ToastClient = {
29
- tui?: {
30
- showToast?: (input: {
31
- body: {
32
- title?: string
33
- message: string
34
- variant: 'info' | 'success' | 'warning' | 'error'
35
- duration: number
36
- }
37
- }) => Promise<unknown>
38
- }
39
- }
40
-
41
- /** Best-effort visual completion signal; never affects board finalization. */
42
- export async function showDelegationTerminalToast(
43
- client: ToastClient,
44
- job: Pick<BackgroundJobRecord, 'taskID' | 'alias' | 'agent' | 'state' | 'timedOut'>,
45
- ): Promise<void> {
46
- try {
47
- if (!delegationToastEnabled()) return
48
- const isTerminal = job.timedOut || terminalStates.has(job.state)
49
- if (isTerminal) {
50
- if (terminalToastsShown.has(job.taskID)) return
51
- terminalToastsShown.add(job.taskID)
52
- }
53
- const showToast = client.tui?.showToast
54
- if (typeof showToast !== 'function') return
55
- const state = job.timedOut ? 'timeout' : job.state
56
- const variant =
57
- state === 'completed'
58
- ? 'success'
59
- : state === 'error' || state === 'timeout'
60
- ? 'error'
61
- : 'warning'
62
- await showToast({
63
- body: {
64
- title: 'Delegação concluída',
65
- message: `${job.alias} (${job.agent}) — ${state}`,
66
- variant,
67
- duration: 4000,
68
- },
69
- })
70
- } catch {
71
- // TUI is optional (and may disappear during shutdown); completion is durable.
72
- }
73
- }