import { isFailedChildResult, MAX_TIMER_MS, normalizeTask, normalizeTimeoutMs } from "../child-runtime/policy.ts"; import { DEFAULT_WRAP_MESSAGE, type ChildControl, type ChildResult } from "../child-runtime/spawn.ts"; import { copyFinalizationProgress, type FinalizationProgress } from "../child-runtime/guard-protocol.ts"; import { assertKind, type Kind } from "./config.ts"; import { copyCapabilities, type CapabilityManifest } from "./capabilities.ts"; import { copyResponseEvidence, type ResponseEvidence } from "../child-runtime/evidence.ts"; import { describeOutcome, type ExecutionOutcome } from "./outcomes.ts"; import { validateResourceGroup, type CapacityBroker, type ResourceGroup, type ResourceLease } from "./capacity.ts"; import type { InheritedLease } from "../child-runtime/lease.ts"; import { applyProgress, createProgress, parseChildProgress, type ActivityItem, type ProgressState, } from "./display.ts"; import { applyTgEvent, createTgMeter, visibleChildTg, type TgMeter } from "./tg.ts"; import type { CompletionHookResult } from "./completion-hook.ts"; export type JobStatus = "queued" | "running" | "done" | "failed"; export type QueueReason = "gpu" | "slot" | "resource"; export type ResourceProgress = ResourceGroup & { state: "waiting" | "held" | "released" | "not-acquired" | "release-unknown"; slot?: number; }; export type JobHandle = { /** Pass to runChild/runPiChild; do not close this borrowed descriptor. */ resourceLease?: InheritedLease; id: string; kind: Kind; model: string; local: boolean; task: string; timeoutMs: number; }; export type JobRun = ( job: JobHandle, signal: AbortSignal, onEvent: (event: unknown) => void, onControl: (ctl: ChildControl) => void, ) => Promise; export type ArchiveRef = { runId: string; sessionFile: string }; export type JobSnapshot = { completionHook?: CompletionHookResult; resource?: ResourceProgress; resourceError?: string; archive?: ArchiveRef; capabilities?: CapabilityManifest; recordingError?: string; id: string; kind: Kind; model: string; reasoning?: string; local: boolean; task: string; status: JobStatus; failed: boolean; reason?: QueueReason; activity: ActivityItem[]; current?: ActivityItem; thinking?: boolean; tg?: string; answer?: string; responseFile?: string; exitCode?: number; stopReason?: string; stderrTail?: string; background: boolean; cancellationRequested?: boolean; wrapped?: boolean; finalization?: FinalizationProgress; outcome?: ExecutionOutcome; quietForMs?: number; queuedAt?: number; startedAt?: number; }; export type EnqueueInput = { /** Explicit server/resource group, never derived from a model ID. Local jobs only. */ resourceGroup?: ResourceGroup; archive?: ArchiveRef; capabilities?: CapabilityManifest; kind: Kind; model: string; reasoning?: string; local: boolean; task: string; timeoutMs: number; run: JobRun; /** Runs once after terminal accounting; independent of notifications and worker status. */ onComplete?: (snap: JobSnapshot) => Promise; background?: boolean; cancelOnAbort?: AbortSignal; }; export type WaitInput = { timeoutMs?: number; quietMs?: number; signal?: AbortSignal; onSnapshot?: (snap: JobSnapshot) => void; }; export type SchedulerLimits = { maxConcurrent: number; maxLocalConcurrent: number; maxQueued: number; }; export type ParsedCall = | { mode: "spawn"; background: boolean; kind: Kind; task: string; timeoutMs: number; cwd?: string; } | { mode: "collect"; jobId: string; peek: boolean; waitMs?: number; wrap?: boolean; cancel?: boolean; }; type InternalJob = { onComplete?: EnqueueInput["onComplete"]; completionHook?: CompletionHookResult; resourceGroup?: ResourceGroup; resourceSlot?: number; resourceError?: string; lease?: ResourceLease; archive?: ArchiveRef; capabilities?: CapabilityManifest; id: string; kind: Kind; model: string; reasoning?: string; local: boolean; task: string; timeoutMs: number; run?: JobRun; status: JobStatus; controller: AbortController; progress: ProgressState; meter: TgMeter; result?: ChildResult; errorMessage?: string; exitCode?: number; stopReason?: string; listeners: Set<(snap: JobSnapshot) => void>; cancelAbort?: { signal: AbortSignal; onAbort: () => void }; background: boolean; terminalEmitted: boolean; accountingSettled: boolean; recordingError?: string; wrapped: boolean; wrapSent: boolean; wrapSending?: boolean; wrapMessage?: string; finalization?: FinalizationProgress; evidence?: ResponseEvidence; queuedAt: number; startedAt?: number; lastEventAt?: number; control?: ChildControl; }; function asRecord(value: unknown): Record { return value && typeof value === "object" ? (value as Record) : {}; } function optionalString(value: unknown): string | undefined { if (typeof value !== "string") return undefined; const trimmed = value.trim(); return trimmed.length > 0 ? trimmed : undefined; } export function parseDelegateCall( params: unknown, config: { maxTaskChars: number; defaultTimeoutMs: number; maxTimeoutMs: number }, ): ParsedCall { const input = asRecord(params); if (Object.hasOwn(input, "model")) { throw new Error("delegate refused: model is not a supported parameter. Configure the role model with /pi-delegate roles."); } // Some providers fill unused optional fields with null or blank strings. const rec = Object.fromEntries(Object.entries(input).filter(([, value]) => value !== null && !(typeof value === "string" && value.trim() === ""))); if (rec.background !== undefined && rec.background !== true && rec.background !== false) { throw new Error("delegate refused: background must be boolean."); } if (rec.wrap !== undefined && rec.wrap !== true && rec.wrap !== false) { throw new Error("delegate refused: wrap must be boolean."); } if (rec.cancel !== undefined && rec.cancel !== true && rec.cancel !== false) { throw new Error("delegate refused: cancel must be boolean."); } const jobId = optionalString(rec.jobId); if ((rec.wrap === true || rec.cancel === true) && !jobId) { throw new Error("delegate refused: wrap/cancel require jobId."); } if (jobId) { if (rec.background === true) throw new Error("delegate refused: jobId cannot combine with background."); if (rec.wrap === true && rec.cancel === true) { throw new Error("delegate refused: wrap cannot combine with cancel."); } if (rec.kind !== undefined || rec.task !== undefined || rec.cwd !== undefined) { throw new Error("delegate refused: jobId cannot combine with spawn fields."); } const raw = rec.timeoutMs; const collect: Extract = { mode: "collect", jobId, peek: false }; if (rec.wrap === true) collect.wrap = true; if (rec.cancel === true) collect.cancel = true; if (raw === undefined || raw === null) return collect; if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw < 0 || raw > MAX_TIMER_MS) { throw new Error(`delegate refused: timeoutMs must be an integer in [0, ${MAX_TIMER_MS}].`); } collect.waitMs = raw; collect.peek = raw === 0; return collect; } const kind = assertKind(rec.kind); const task = normalizeTask(rec.task, config.maxTaskChars, "delegate"); const timeoutMs = normalizeTimeoutMs(rec.timeoutMs, config, "delegate"); const parsed: ParsedCall = { mode: "spawn", background: rec.background !== false, kind, task, timeoutMs, }; const cwd = typeof rec.cwd === "string" ? rec.cwd : undefined; if (cwd !== undefined) parsed.cwd = cwd; return parsed; } export class JobScheduler { private seq = 0; private closed = false; private cancelling = false; private pumping = false; private pumpAgain = false; private readonly jobs: InternalJob[] = []; private readonly hooks = new Set>(); private readonly limits: SchedulerLimits; private readonly capacity?: CapacityBroker; private readonly resourcePollMs: number; private resourceTimer?: ReturnType; private readonly onChange?: (snap?: JobSnapshot) => void; private readonly onTerminal?: (snap: JobSnapshot) => void; private readonly onSettled?: (snap: JobSnapshot) => string | void; constructor(input: SchedulerLimits & { capacity?: CapacityBroker; resourcePollMs?: number; onChange?: (snap?: JobSnapshot) => void; onTerminal?: (snap: JobSnapshot) => void; onSettled?: (snap: JobSnapshot) => string | void }) { this.limits = { maxConcurrent: input.maxConcurrent, maxLocalConcurrent: input.maxLocalConcurrent, maxQueued: input.maxQueued, }; this.capacity = input.capacity; this.resourcePollMs = input.resourcePollMs ?? 250; if (!Number.isSafeInteger(this.resourcePollMs) || this.resourcePollMs < 10 || this.resourcePollMs > 60000) throw new Error("Invalid resource poll interval."); this.onChange = input.onChange; this.onTerminal = input.onTerminal; this.onSettled = input.onSettled; } enqueue(input: EnqueueInput): JobSnapshot { if (this.closed) throw new Error("delegate refused: scheduler shutdown."); let resourceGroup: ResourceGroup | undefined; if (input.local && (this.capacity || input.resourceGroup !== undefined)) { if (!this.capacity) throw new Error("delegate refused: resource group requires a capacity broker."); resourceGroup = validateResourceGroup(input.resourceGroup!); } if (!input.cancelOnAbort?.aborted && !this.canStart(input.local) && this.queuedCount() >= this.limits.maxQueued) { throw new Error( `delegate refused: ${this.queuedCount()} already queued (max ${this.limits.maxQueued}).`, ); } this.seq += 1; const job: InternalJob = { resourceGroup, archive: input.archive, capabilities: copyCapabilities(input.capabilities), id: `d${this.seq.toString(16).padStart(4, "0")}`, kind: input.kind, model: input.model, reasoning: input.reasoning, local: input.local, task: input.task, timeoutMs: input.timeoutMs, run: input.run, onComplete: input.onComplete, status: "queued", controller: new AbortController(), progress: createProgress(), meter: createTgMeter(), listeners: new Set(), background: input.background === true, terminalEmitted: false, accountingSettled: false, wrapped: false, wrapSent: false, queuedAt: Date.now(), }; if (input.cancelOnAbort) { const onAbort = (): void => { this.cancel(job.id); }; if (input.cancelOnAbort.aborted) { this.jobs.push(job); this.cancel(job.id); return this.snapshot(job); } input.cancelOnAbort.addEventListener("abort", onAbort, { once: true }); job.cancelAbort = { signal: input.cancelOnAbort, onAbort }; } this.jobs.push(job); this.pump(); // Shared capacity can refuse after a process slot looked free. // Refuse excess waiters without spawning, retaining runners, or bypassing the queue bound. if (job.status === "queued" && this.queuedCount() > this.limits.maxQueued) { this.jobs.splice(this.jobs.indexOf(job), 1); job.onComplete = undefined; this.releaseRuntime(job); this.armResourcePoll(); this.notify(); throw new Error(job.resourceGroup ? `delegate refused: ${this.queuedCount()} already queued (max ${this.limits.maxQueued}).` : `delegate refused: queue full (max ${this.limits.maxQueued}).`); } this.notify(job); return this.snapshot(job); } get(id: string): JobSnapshot { const job = this.find(id); if (!job) throw new Error(`delegate refused: unknown jobId ${id}.`); return this.snapshot(job); } list(): JobSnapshot[] { return this.jobs.map((job) => this.snapshot(job)); } active(): JobSnapshot[] { return this.jobs.filter((job) => job.status === "queued" || job.status === "running").map((job) => this.snapshot(job)); } async wait(id: string, input: WaitInput = {}): Promise { for (const value of [input.timeoutMs, input.quietMs]) { if (value !== undefined && (!Number.isSafeInteger(value) || value < 0 || value > MAX_TIMER_MS)) { throw new Error(`delegate refused: wait timers must be integers in [0, ${MAX_TIMER_MS}].`); } } const job = this.find(id); if (!job) throw new Error(`delegate refused: unknown jobId ${id}.`); const peek = input.timeoutMs === 0; const waitStartedAt = Date.now(); const snap = this.snapshot(job); this.safeSnapshot(input.onSnapshot, this.snapshot(job)); if (peek || this.terminal(job)) return snap; return new Promise((resolve) => { let settled = false; let timer: ReturnType | undefined; let quietTimer: ReturnType | undefined; const finish = (): void => { if (settled) return; settled = true; cleanup(); resolve(this.snapshot(job)); }; const armQuiet = (): void => { if (quietTimer) { clearTimeout(quietTimer); quietTimer = undefined; } if (!input.quietMs || input.quietMs <= 0) return; if (job.status !== "running" && job.status !== "queued") return; // Old silence must not exhaust a fresh wait, especially just after wrap-up. const last = Math.max(waitStartedAt, job.lastEventAt ?? job.startedAt ?? job.queuedAt); const remaining = input.quietMs - (Date.now() - last); quietTimer = setTimeout(finish, Math.max(0, remaining)); }; const onSnap = (next: JobSnapshot): void => { this.safeSnapshot(input.onSnapshot, next); if (this.terminal(job)) finish(); else armQuiet(); }; const onAbort = (): void => { finish(); }; const cleanup = (): void => { job.listeners.delete(onSnap); input.signal?.removeEventListener("abort", onAbort); if (timer) clearTimeout(timer); if (quietTimer) clearTimeout(quietTimer); }; job.listeners.add(onSnap); if (input.signal) { if (input.signal.aborted) { finish(); return; } input.signal.addEventListener("abort", onAbort, { once: true }); } if (input.timeoutMs !== undefined && input.timeoutMs > 0) { timer = setTimeout(finish, input.timeoutMs); } armQuiet(); if (this.terminal(job)) finish(); }); } promoteBackground(id: string): JobSnapshot { const job = this.find(id); if (!job) throw new Error(`delegate refused: unknown jobId ${id}.`); if (job.controller.signal.aborted || this.terminal(job)) return this.snapshot(job); job.background = true; this.detachAbort(job); this.notify(job); return this.snapshot(job); } wrap(id: string, message?: string): JobSnapshot { const job = this.find(id); if (!job) throw new Error(`delegate refused: unknown jobId ${id}.`); if (this.terminal(job) || job.controller.signal.aborted) return this.snapshot(job); if (job.status === "queued") { this.cancel(id); return this.get(id); } if (!job.wrapped) { const text = message ?? DEFAULT_WRAP_MESSAGE; if (text.length > 20000) throw new Error("delegate refused: wrap message exceeds 20000 chars."); job.wrapped = true; job.wrapMessage = text; } this.sendWrap(job); this.notify(job); return this.snapshot(job); } private sendWrap(job: InternalJob): void { if (!job.control || !job.wrapped || job.wrapSent || job.wrapSending || job.controller.signal.aborted) return; const control = job.control; job.wrapSending = true; try { if (control.wrap(job.wrapMessage)) { job.wrapSent = true; job.wrapMessage = undefined; } } catch { /* Keep the request pending until control becomes ready. */ } finally { job.wrapSending = false; } // A readiness callback can replace a refusing control during its synchronous call. if (!job.wrapSent && job.control !== control) queueMicrotask(() => this.sendWrap(job)); } cancel(id: string): void { const job = this.find(id); if (!job || this.terminal(job)) return; if (job.status === "queued") { job.status = "failed"; job.stopReason = "aborted"; job.exitCode = 1; this.releaseRuntime(job); try { this.notify(job); } finally { try { this.emitTerminal(job); } finally { this.pump(); } } return; } if (job.controller.signal.aborted) return; job.controller.abort(); this.notify(job); } /** Stop outstanding work without closing the scheduler to later parent turns. */ cancelAll(): void { if (this.cancelling) return; this.cancelling = true; try { // Cancelling a queued job pumps the queue; block dispatch for the whole batch. for (const job of [...this.jobs]) this.cancel(job.id); } finally { this.cancelling = false; this.pump(); } } hasPendingHooks(): boolean { return this.hooks.size > 0; } async shutdown(): Promise { this.closed = true; this.clearResourcePoll(); const running: Promise[] = []; for (const job of this.jobs) { if (job.status === "queued") this.cancel(job.id); else if (job.status === "running") { job.controller.abort(); running.push( new Promise((resolve) => { if (this.terminal(job)) { resolve(); return; } const done = (): void => { job.listeners.delete(doneSnap); resolve(); }; const doneSnap = (snap: JobSnapshot): void => { if (snap.status === "done" || snap.status === "failed") done(); }; job.listeners.add(doneSnap); }), ); } } await Promise.all(running); await Promise.all(this.hooks); this.notify(); } private find(id: string): InternalJob | undefined { return this.jobs.find((job) => job.id === id); } private terminal(job: InternalJob): boolean { return job.status === "done" || job.status === "failed"; } private queuedCount(): number { return this.jobs.filter((job) => job.status === "queued").length; } private runningJobs(): InternalJob[] { return this.jobs.filter((job) => job.status === "running"); } private canStart(local: boolean): boolean { if (this.closed || this.cancelling) return false; const running = this.runningJobs(); if (running.length >= this.limits.maxConcurrent) return false; if (local && running.filter((job) => job.local).length >= this.limits.maxLocalConcurrent) return false; return true; } private queueReason(job: InternalJob): QueueReason | undefined { if (job.status !== "queued") return undefined; const running = this.runningJobs(); if (job.local && running.filter((item) => item.local).length >= this.limits.maxLocalConcurrent) return "gpu"; if (running.length >= this.limits.maxConcurrent) return "slot"; return job.resourceGroup ? "resource" : "slot"; } private handle(job: InternalJob): JobHandle { return { ...(job.lease ? { resourceLease: { ...job.lease.inherited } } : {}), id: job.id, kind: job.kind, model: job.model, local: job.local, task: job.task, timeoutMs: job.timeoutMs, }; } private snapshot(job: InternalJob): JobSnapshot { const failed = job.status === "failed" || (job.status === "done" && job.result ? isFailedChildResult(job.result) : false); const tg = job.status === "running" || job.status === "done" || job.status === "failed" ? visibleChildTg(job.model, job.meter, undefined) : undefined; const snap: JobSnapshot = { queuedAt: job.queuedAt, startedAt: job.startedAt, ...(job.archive ? { archive: { ...job.archive } } : {}), id: job.id, kind: job.kind, model: job.model, ...(job.reasoning === undefined ? {} : { reasoning: job.reasoning }), local: job.local, task: job.task, status: job.status, failed, activity: job.progress.done.map(item => ({ ...item })), current: job.status === "running" && job.progress.current ? { ...job.progress.current } : undefined, background: job.background, }; if (job.status === "running" && job.controller.signal.aborted) snap.cancellationRequested = true; if (job.capabilities) snap.capabilities = copyCapabilities(job.capabilities); if (job.resourceGroup) snap.resource = { ...job.resourceGroup, state: job.lease ? "held" : job.status === "queued" ? "waiting" : job.resourceError ? "release-unknown" : job.resourceSlot === undefined ? "not-acquired" : "released", ...(job.resourceSlot !== undefined ? { slot: job.resourceSlot } : {}), }; if (job.resourceError) snap.resourceError = job.resourceError; if (job.recordingError) snap.recordingError = job.recordingError; if (job.completionHook) snap.completionHook = { ...job.completionHook }; if (job.wrapped) snap.wrapped = true; if (job.finalization) snap.finalization = copyFinalizationProgress(job.finalization); if (job.status === "running" || job.status === "queued") { const last = job.lastEventAt ?? job.startedAt ?? job.queuedAt; snap.quietForMs = Math.max(0, Date.now() - last); } const reason = this.queueReason(job); if (reason) snap.reason = reason; if (job.progress.thinking) snap.thinking = true; if (tg) snap.tg = tg; if (job.result) { snap.answer = job.result.text; if (job.result.responseFile) snap.responseFile = job.result.responseFile; snap.exitCode = job.result.exitCode; snap.stopReason = job.result.stopReason; snap.stderrTail = job.result.stderrTail; if (job.result.recordingError) snap.recordingError = [snap.recordingError, job.result.recordingError].filter(Boolean).join("\n"); } else if (job.status === "failed") { snap.exitCode = job.exitCode ?? 1; snap.stopReason = job.stopReason; snap.answer = job.errorMessage; } snap.outcome = describeOutcome({ status: snap.status, stopReason: snap.stopReason, finalization: snap.finalization, evidence: job.evidence }); return snap; } private emit(job: InternalJob): void { for (const listener of [...job.listeners]) { try { listener(this.snapshot(job)); } catch { /* listener errors must not break the scheduler */ } } } private notify(job?: InternalJob): void { if (job && this.terminal(job) && !job.accountingSettled) { job.accountingSettled = true; try { job.recordingError = [job.recordingError, this.onSettled?.(this.snapshot(job))].filter(Boolean).join("\n") || undefined; } catch { job.recordingError = [job.recordingError, "Delegate recording incomplete: terminal accounting callback failed."].filter(Boolean).join("\n"); } } if (job && this.terminal(job) && job.onComplete) this.startCompletionHook(job); if (job) this.emit(job); try { this.onChange?.(job ? this.snapshot(job) : undefined); } catch { /* widget errors must not break the scheduler */ } } private startCompletionHook(job: InternalJob): void { const complete = job.onComplete!; job.onComplete = undefined; // Claim before invoking any code; peeks/cancel/shutdown cannot replay it. job.completionHook = { status: "running", durationMs: 0 }; const snapshot = this.snapshot(job); const pending = Promise.resolve().then(() => complete(snapshot)).then(result => { job.completionHook = { ...result }; }, error => { job.completionHook = { status: "failed", durationMs: 0, error: error instanceof Error ? error.message : String(error) }; }).finally(() => { this.hooks.delete(pending); this.notify(job); }); this.hooks.add(pending); } private safeSnapshot(onSnapshot: ((snap: JobSnapshot) => void) | undefined, snap: JobSnapshot): void { if (!onSnapshot) return; try { onSnapshot(snap); } catch { /* wait observers must not break collect */ } } private detachAbort(job: InternalJob): void { if (!job.cancelAbort) return; job.cancelAbort.signal.removeEventListener("abort", job.cancelAbort.onAbort); job.cancelAbort = undefined; } private releaseRuntime(job: InternalJob): void { this.detachAbort(job); this.releaseLeaseOnly(job); // Keep collectible snapshots, not closures retaining the process and uncapped RPC state. job.control = undefined; job.run = undefined; job.wrapMessage = undefined; } private pump(): void { if (this.pumping) { this.pumpAgain = true; return; } this.pumping = true; this.clearResourcePoll(); try { do { this.pumpAgain = false; const blocked = new Set(); for (const job of this.jobs) { if (job.status !== "queued" || !this.canStart(job.local)) continue; if (job.resourceGroup) { const resourceKey = `${job.resourceGroup.key}/${job.resourceGroup.capacity}`; if (blocked.has(resourceKey)) continue; try { const lease = this.capacity!.tryAcquire({ ...job.resourceGroup }); if (!lease) { blocked.add(resourceKey); continue; } let retained = false; try { const claim = lease.claim, slot = claim.slot; if (claim.key !== job.resourceGroup.key || claim.capacity !== job.resourceGroup.capacity || !Number.isSafeInteger(slot) || slot < 0 || slot >= job.resourceGroup.capacity) { throw new Error("Capacity broker returned a mismatched resource claim."); } // A custom broker can synchronously trigger cancellation/shutdown observers. if (job.status !== "queued" || this.closed || !this.canStart(job.local)) continue; job.lease = lease; job.resourceSlot = slot; retained = true; } finally { if (!retained && !this.releaseLease(job, lease)) throw new Error("Resource acquisition cleanup failed."); } } catch (error) { this.failResource(job, error); continue; } } // A dispatch refusal must not leave this queued job owning shared capacity. if (!this.start(job) && !this.releaseLeaseOnly(job)) this.failResource(job, "Resource acquisition cleanup failed."); } } while (this.pumpAgain); } finally { this.pumping = false; this.armResourcePoll(); } } private failResource(job: InternalJob, error: unknown): void { if (this.terminal(job)) return; job.status = "failed"; job.stopReason = "resource-error"; job.exitCode = 1; job.errorMessage = `Shared resource unavailable: ${String(error)}`; this.releaseRuntime(job); this.notify(job); this.emitTerminal(job); } private releaseLeaseOnly(job: InternalJob): boolean { if (!job.lease) return true; const lease = job.lease; job.lease = undefined; return this.releaseLease(job, lease); } private releaseLease(job: InternalJob, lease: ResourceLease): boolean { try { lease.release(); return true; } catch (error) { job.resourceError = `Resource lease release could not be confirmed: ${String(error)}`; return false; } } private clearResourcePoll(): void { if (this.resourceTimer !== undefined) clearTimeout(this.resourceTimer); this.resourceTimer = undefined; } private armResourcePoll(): void { this.clearResourcePoll(); if (this.closed || !this.jobs.some(job => job.status === "queued" && job.resourceGroup && this.canStart(job.local))) return; this.resourceTimer = setTimeout(() => { this.resourceTimer = undefined; this.pump(); this.notify(); }, this.resourcePollMs); } private start(job: InternalJob): boolean { if (job.status !== "queued" || this.closed) return false; job.status = "running"; job.startedAt = Date.now(); job.lastEventAt = job.startedAt; try { this.notify(job); } finally { void this.execute(job); } return true; } private async execute(job: InternalJob): Promise { try { const run = job.run; if (!run) throw new Error("delegate job has no runner."); const result = await run( this.handle(job), job.controller.signal, (event) => { if (job.status !== "running") return; job.lastEventAt = Date.now(); const progress = event as { type?: unknown; state?: unknown } | undefined; if (progress?.type === "delegate_finalization") { job.finalization = copyFinalizationProgress(progress.state) ?? job.finalization; } const item = parseChildProgress(event); if (item) applyProgress(job.progress, item); if (job.local) applyTgEvent(job.meter, event); this.notify(job); }, (ctl) => { if (job.status === "running" && !job.controller.signal.aborted) { job.control = ctl; this.sendWrap(job); } }, ); if (job.status === "queued") return; // The child runtime owns terminal-cause ordering; recording may await after process exit. job.result = result; job.evidence = copyResponseEvidence(result.evidence); job.finalization = copyFinalizationProgress(result.finalization) ?? job.finalization; job.status = isFailedChildResult(job.result) ? "failed" : "done"; if (result.model) job.model = result.model; } catch (error) { if (job.status !== "failed" || !job.result) { job.status = "failed"; job.stopReason = job.controller.signal.aborted ? "aborted" : "error"; job.errorMessage = error instanceof Error ? error.message : String(error); job.exitCode = 1; } } finally { this.releaseRuntime(job); try { this.notify(job); } finally { try { this.emitTerminal(job); } finally { this.pump(); } } } } private emitTerminal(job: InternalJob): void { if (job.terminalEmitted) return; if (!this.terminal(job)) return; job.terminalEmitted = true; if (this.closed || !this.onTerminal) return; try { this.onTerminal(this.snapshot(job)); } catch { /* notify errors must not break the scheduler */ } } }