import * as plugins from './plugins.js'; import { controllerMaxDraftTextBytes, controllerRuntimeIdKey, type IControllerDraftAttachment, type IControllerRuntimeId, type IControllerSessionDraft, type IControllerSessionDraftUpdate, type TControllerModelChoice, type TControllerSessionHarnessId, } from '../ts_interfaces/interfaces.js'; import { ControllerDraftManager } from './classes.draftmanager.js'; import { ControllerUploadManager, type IControllerUploadHandle, } from './classes.uploadmanager.js'; import type { IFlexModelChoice } from './interfaces.flexipc.js'; const maximumActiveHarnessOperations = 64; const maximumHarnessOperationsPerSession = 16; const maximumPendingUploadCleanups = 64; const harnessOperationCleanupTimeoutMs = 10_000; export class ControllerHarnessOperationConflictError extends Error { constructor(messageArg: string) { super(messageArg); this.name = 'ControllerHarnessOperationConflictError'; } } export class ControllerHarnessOperationLimitError extends Error { constructor(messageArg: string) { super(messageArg); this.name = 'ControllerHarnessOperationLimitError'; } } export type TControllerHarnessOperationKind = 'send' | 'slash'; export type TControllerHarnessOperationDelivery = 'ordinary' | 'steer'; type TControllerHarnessOperationState = | 'submitting' | 'queued' | 'accepted' | 'outcomeUnknown' | 'cancelled'; interface IControllerHarnessOperationReservationBase { operationId: string; createdAt: number; kind: TControllerHarnessOperationKind; readonly delivery: TControllerHarnessOperationDelivery; projectId: string; sessionId: IControllerRuntimeId; /** Native user-message identity when the harness accepts a caller-selected ID. */ messageId?: IControllerRuntimeId; } export interface IControllerDraftHarnessOperationReservation extends IControllerHarnessOperationReservationBase { source: 'draft'; draft: IControllerSessionDraft; promptSuffix: string; uploadDirectory?: string; } export interface IControllerDirectHarnessOperationReservation extends IControllerHarnessOperationReservationBase { source: 'direct'; kind: 'send'; direct: Readonly<{ text: string; model?: Readonly; providerConnectionId?: string; }>; promptSuffix?: never; uploadDirectory?: never; } export type TControllerHarnessOperationReservation = | IControllerDraftHarnessOperationReservation | IControllerDirectHarnessOperationReservation; export interface IControllerHarnessOperationSnapshot { reservation: TControllerHarnessOperationReservation; state: TControllerHarnessOperationState; inputAccepted: boolean; flexQueueId?: string; flexRunId?: string; flexModel?: IFlexModelChoice; } export interface IControllerHarnessOperationBarrier { token: string; harnessId?: 'opencode' | 'flex' | 'codex'; operationIds: string[]; sessions: Array<{ projectId: string; sessionId: IControllerRuntimeId; }>; } export interface IControllerHarnessOperationManagerOptions { onDraftChanged: ( projectIdArg: string, sessionIdArg: IControllerRuntimeId, updateArg: IControllerSessionDraftUpdate, ) => void; onQueuedOperationCancelled?: ( reservationArg: TControllerHarnessOperationReservation, ) => void; onOperationReleased?: (reservationArg: TControllerHarnessOperationReservation) => void; cleanupTimeoutMs?: number; } interface IActiveHarnessOperation { reservation: TControllerHarnessOperationReservation; harnessAdmissionGeneration: number; state: TControllerHarnessOperationState; inputAccepted: boolean; observedTerminal: boolean; upload?: IControllerUploadHandle; flexQueueKey?: string; flexQueueId?: string; flexRunId?: string; flexModel?: Readonly; releasePromise?: Promise; } interface IPendingUploadCleanup { active: IActiveHarnessOperation; upload: IControllerUploadHandle; cleanupPromise?: Promise; } const cloneDraft = (draftArg: IControllerSessionDraft): IControllerSessionDraft => ({ text: draftArg.text, attachments: draftArg.attachments.map((attachment) => ({ ...attachment })), revision: draftArg.revision, }); const cloneReservation = ( reservationArg: TControllerHarnessOperationReservation, ): TControllerHarnessOperationReservation => { if (reservationArg.source === 'draft') { return { ...reservationArg, sessionId: { ...reservationArg.sessionId }, draft: cloneDraft(reservationArg.draft), }; } const model = reservationArg.direct.model === undefined ? undefined : Object.freeze({ ...reservationArg.direct.model }); return { ...reservationArg, sessionId: { ...reservationArg.sessionId }, direct: Object.freeze({ text: reservationArg.direct.text, ...(model === undefined ? {} : { model }), ...(reservationArg.direct.providerConnectionId === undefined ? {} : { providerConnectionId: reservationArg.direct.providerConnectionId }), }), }; }; export class ControllerHarnessOperationManager { private readonly drafts = new ControllerDraftManager(); private readonly uploads = new ControllerUploadManager(); private readonly operationsBySession = new Map(); private readonly operationsByOpenCodeMessage = new Map(); private readonly operationsByFlexQueue = new Map(); private readonly pendingUploadCleanups = new Map(); private readonly harnessAdmissionGenerations = new Map(); private readonly sealedHarnessAdmissions = new Map(); private activeOperationCount = 0; private operationBarrier?: Pick; private closed = false; private closePromise?: Promise; private readonly cleanupTimeoutMs: number; constructor(private readonly options: IControllerHarnessOperationManagerOptions) { const cleanupTimeoutMs = options.cleanupTimeoutMs ?? harnessOperationCleanupTimeoutMs; if (!Number.isSafeInteger(cleanupTimeoutMs) || cleanupTimeoutMs < 1) { throw new Error('cleanupTimeoutMs must be a positive safe integer.'); } this.cleanupTimeoutMs = cleanupTimeoutMs; } public getDraft(projectIdArg: string, sessionIdArg: IControllerRuntimeId): IControllerSessionDraft { return this.drafts.get(this.sessionKey(projectIdArg, sessionIdArg)); } public updateDraft( projectIdArg: string, sessionIdArg: IControllerRuntimeId, expectedRevisionArg: number, patchArg: { text?: string; attachments?: readonly IControllerDraftAttachment[] }, ): IControllerSessionDraft { if (this.closed) throw new Error('The harness operation manager is closed.'); const result = this.drafts.update( this.sessionKey(projectIdArg, sessionIdArg), expectedRevisionArg, patchArg, ); if (result.update) this.options.onDraftChanged(projectIdArg, sessionIdArg, result.update); return result.draft; } public async reserve( kindArg: TControllerHarnessOperationKind, projectIdArg: string, sessionIdArg: IControllerRuntimeId, draftRevisionArg: number, optionsArg: { allowAttachments: boolean; delivery?: TControllerHarnessOperationDelivery }, ): Promise { if (this.closed) throw new Error('The harness operation manager is closed.'); if (sessionIdArg.harnessId !== 'opencode' && sessionIdArg.harnessId !== 'flex' && sessionIdArg.harnessId !== 'codex') { throw new Error('Only session harnesses may reserve prompt operations.'); } const delivery = optionsArg.delivery ?? 'ordinary'; if (delivery === 'steer' && (kindArg !== 'send' || sessionIdArg.harnessId !== 'codex')) { throw new Error('Only Codex send operations may reserve steering delivery.'); } const harnessId = sessionIdArg.harnessId; const harnessAdmissionGeneration = this.currentHarnessAdmissionGeneration(harnessId); this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration); const key = this.sessionKey(projectIdArg, sessionIdArg); let operations = this.operationsBySession.get(key) ?? []; if (operations.some((operation) => ( operation.reservation.source === 'draft' && operation.reservation.draft.revision === draftRevisionArg ))) { throw new ControllerHarnessOperationConflictError( 'The composer draft revision is already being submitted.', ); } if (this.pendingUploadCleanups.size > 0) { await this.retryPendingUploadCleanups().catch(() => undefined); } if (this.closed) throw new Error('The harness operation manager is closed.'); this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration); operations = this.operationsBySession.get(key) ?? []; if (operations.some((operation) => ( operation.reservation.source === 'draft' && operation.reservation.draft.revision === draftRevisionArg ))) { throw new ControllerHarnessOperationConflictError( 'The composer draft revision is already being submitted.', ); } if ( this.activeOperationCount >= maximumActiveHarnessOperations || operations.length >= maximumHarnessOperationsPerSession || this.pendingUploadCleanups.size >= maximumPendingUploadCleanups ) { throw new ControllerHarnessOperationLimitError( 'The active harness operation limit is exhausted.', ); } const draft = this.drafts.snapshot(key, draftRevisionArg); if (!optionsArg.allowAttachments && draft.attachments.length > 0) { throw new Error('Attachments are not supported by this composer command.'); } const reservation: IControllerDraftHarnessOperationReservation = { operationId: plugins.crypto.randomBytes(16).toString('base64url'), createdAt: Date.now(), kind: kindArg, delivery, projectId: projectIdArg, sessionId: { ...sessionIdArg }, source: 'draft', draft, promptSuffix: '', }; const active: IActiveHarnessOperation = { reservation, harnessAdmissionGeneration, state: 'submitting', inputAccepted: false, observedTerminal: false, }; operations.push(active); this.operationsBySession.set(key, operations); this.activeOperationCount += 1; try { const upload = await this.uploads.create(draft.attachments); if (upload) active.upload = upload; if (this.closed || !this.operationsBySession.get(key)?.includes(active)) { throw new Error('The harness operation reservation closed during upload materialization.'); } this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration); if (upload) { reservation.promptSuffix = upload.promptSuffix; reservation.uploadDirectory = upload.directory; } return cloneReservation(reservation) as IControllerDraftHarnessOperationReservation; } catch (errorArg) { await this.releaseActive(active); throw errorArg; } } public async reserveDirect( projectIdArg: string, sessionIdArg: IControllerRuntimeId, textArg: string, modelArg?: TControllerModelChoice, providerConnectionIdArg?: string, ): Promise { if (this.closed) throw new Error('The harness operation manager is closed.'); if (sessionIdArg.harnessId !== 'opencode' && sessionIdArg.harnessId !== 'flex' && sessionIdArg.harnessId !== 'codex') { throw new Error('Only session harnesses may reserve prompt operations.'); } if ( typeof textArg !== 'string' || textArg.trim().length === 0 || Buffer.byteLength(textArg, 'utf8') > controllerMaxDraftTextBytes || (modelArg !== undefined && modelArg.harnessId !== sessionIdArg.harnessId) || (providerConnectionIdArg !== undefined && modelArg?.harnessId !== 'flex') ) throw new Error('The direct harness prompt is invalid.'); const harnessId = sessionIdArg.harnessId; const harnessAdmissionGeneration = this.currentHarnessAdmissionGeneration(harnessId); this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration); const key = this.sessionKey(projectIdArg, sessionIdArg); if (this.pendingUploadCleanups.size > 0) { await this.retryPendingUploadCleanups().catch(() => undefined); } if (this.closed) throw new Error('The harness operation manager is closed.'); this.assertHarnessAdmission(harnessId, harnessAdmissionGeneration); const operations = this.operationsBySession.get(key) ?? []; if ( this.activeOperationCount >= maximumActiveHarnessOperations || operations.length >= maximumHarnessOperationsPerSession || this.pendingUploadCleanups.size >= maximumPendingUploadCleanups ) { throw new ControllerHarnessOperationLimitError( 'The active harness operation limit is exhausted.', ); } const model = modelArg === undefined ? undefined : Object.freeze({ ...modelArg }); const reservation: IControllerDirectHarnessOperationReservation = { operationId: plugins.crypto.randomBytes(16).toString('base64url'), createdAt: Date.now(), kind: 'send', delivery: 'ordinary', projectId: projectIdArg, sessionId: { ...sessionIdArg }, source: 'direct', direct: Object.freeze({ text: textArg, ...(model === undefined ? {} : { model }), ...(providerConnectionIdArg === undefined ? {} : { providerConnectionId: providerConnectionIdArg }), }), }; operations.push({ reservation, harnessAdmissionGeneration, state: 'submitting', inputAccepted: false, observedTerminal: false, }); this.operationsBySession.set(key, operations); this.activeOperationCount += 1; return cloneReservation(reservation) as IControllerDirectHarnessOperationReservation; } public accept( reservationArg: IControllerDraftHarnessOperationReservation, ): IControllerSessionDraft; public accept( reservationArg: IControllerDirectHarnessOperationReservation, ): undefined; public accept( reservationArg: TControllerHarnessOperationReservation, ): IControllerSessionDraft | undefined; public accept( reservationArg: TControllerHarnessOperationReservation, ): IControllerSessionDraft | undefined { const active = this.requireActive(reservationArg); if (active.state !== 'submitting') { throw new Error('The harness operation is not awaiting submission acceptance.'); } const draft = reservationArg.source === 'draft' ? active.inputAccepted ? this.getDraft(reservationArg.projectId, reservationArg.sessionId) : this.clearReservationDraft(reservationArg) : undefined; active.inputAccepted = true; active.state = 'accepted'; if (active.observedTerminal) void this.releaseActive(active).catch(() => undefined); return draft; } public queueOpenCodeIfBlocked( reservationArg: TControllerHarnessOperationReservation, ): boolean { if (reservationArg.sessionId.harnessId !== 'opencode') throw new Error('Only OpenCode prompt operations may enter this queue.'); return this.queuePromptIfBlocked(reservationArg); } public queuePromptIfBlocked(reservationArg: TControllerHarnessOperationReservation): boolean { const active = this.requireActive(reservationArg); if (reservationArg.sessionId.harnessId !== 'opencode' && reservationArg.sessionId.harnessId !== 'codex') { throw new Error('This harness does not use the controller prompt queue.'); } if (active.state !== 'submitting') { throw new Error('The harness operation is not awaiting prompt submission.'); } const operations = this.operationsBySession.get( this.sessionKey(reservationArg.projectId, reservationArg.sessionId), ); if (operations?.[0] === active) return false; active.state = 'queued'; return true; } /** Called only after the adapter proves that no provider frame was dispatched. */ public returnUndispatchedToQueue(reservationArg: TControllerHarnessOperationReservation): void { const active = this.requireActive(reservationArg); if (active.state !== 'submitting' || !active.inputAccepted) throw new Error('Only an accepted undispatched prompt can return to its queue.'); active.state = 'queued'; } public adoptQueuedHarnessGeneration(harnessIdArg: TControllerSessionHarnessId, generationArg: number): void { if (this.sealedHarnessAdmissions.get(harnessIdArg) !== generationArg) throw new Error('Queued recovery requires the exact sealed harness generation.'); for (const operations of this.operationsBySession.values()) for (const active of operations) { if (active.reservation.sessionId.harnessId === harnessIdArg && active.state === 'queued') active.harnessAdmissionGeneration = generationArg; } } public acceptQueued( reservationArg: IControllerDraftHarnessOperationReservation, ): IControllerSessionDraft; public acceptQueued( reservationArg: IControllerDirectHarnessOperationReservation, ): undefined; public acceptQueued( reservationArg: TControllerHarnessOperationReservation, ): IControllerSessionDraft | undefined; public acceptQueued( reservationArg: TControllerHarnessOperationReservation, ): IControllerSessionDraft | undefined { const active = this.requireActive(reservationArg); if (active.state !== 'queued') { throw new Error('The harness operation is not queued for later submission.'); } if (active.inputAccepted) { throw new Error('The queued harness operation input was already accepted.'); } const draft = reservationArg.source === 'draft' ? this.clearReservationDraft(reservationArg) : undefined; active.inputAccepted = true; return draft; } public beginQueuedSubmission(reservationArg: TControllerHarnessOperationReservation): void { const active = this.requireActive(reservationArg); const operations = this.operationsBySession.get( this.sessionKey(reservationArg.projectId, reservationArg.sessionId), ); if (active.releasePromise || operations?.[0] !== active || active.state !== 'queued') { throw new Error('The harness operation is not the claimable queued session head.'); } active.state = 'submitting'; } public bindOpenCodeMessage( reservationArg: TControllerHarnessOperationReservation, messageIdArg: IControllerRuntimeId, ): void { const active = this.requireActive(reservationArg); if (reservationArg.sessionId.harnessId !== 'opencode' || messageIdArg.harnessId !== 'opencode') { throw new Error('Only OpenCode operations may bind an OpenCode message ID.'); } if (active.reservation.messageId) { throw new Error('The harness operation already has a native message ID.'); } const key = this.openCodeMessageKey( reservationArg.projectId, reservationArg.sessionId, messageIdArg, ); if (this.operationsByOpenCodeMessage.has(key)) { throw new Error('The OpenCode message ID is already bound to another operation.'); } active.reservation.messageId = { ...messageIdArg }; reservationArg.messageId = { ...messageIdArg }; this.operationsByOpenCodeMessage.set(key, active); } public bindCodexMessage(reservationArg: TControllerHarnessOperationReservation, messageIdArg: IControllerRuntimeId): void { const active = this.requireActive(reservationArg); if (reservationArg.sessionId.harnessId !== 'codex' || messageIdArg.harnessId !== 'codex') throw new Error('Codex message binding requires a Codex operation.'); const previous = active.reservation.messageId; if (previous && controllerRuntimeIdKey(previous) !== controllerRuntimeIdKey(messageIdArg)) throw new Error('The Codex operation already has another native user message.'); active.reservation.messageId = { ...messageIdArg }; reservationArg.messageId = { ...messageIdArg }; } private clearReservationDraft( reservationArg: IControllerDraftHarnessOperationReservation, ): IControllerSessionDraft { const result = this.drafts.clearExact( this.sessionKey(reservationArg.projectId, reservationArg.sessionId), reservationArg.draft.revision, ); if (result.update) { this.options.onDraftChanged( reservationArg.projectId, reservationArg.sessionId, result.update, ); } return result.draft; } public markOutcomeUnknown(reservationArg: TControllerHarnessOperationReservation): boolean { const active = this.findActive(reservationArg); if (!active) return false; active.state = 'outcomeUnknown'; if (active.observedTerminal) void this.releaseActive(active).catch(() => undefined); return active.observedTerminal; } public async fail(reservationArg: TControllerHarnessOperationReservation): Promise { const active = this.findActive(reservationArg); if (active) await this.releaseActive(active); else await this.retryPendingUploadCleanup(reservationArg.operationId); } public async complete(reservationArg: TControllerHarnessOperationReservation): Promise { const active = this.findActive(reservationArg); if (active) await this.releaseActive(active); else await this.retryPendingUploadCleanup(reservationArg.operationId); } public bindFlex( reservationArg: TControllerHarnessOperationReservation, queueIdArg: string, runIdArg: string, modelArg: Readonly, ): void { const active = this.requireActive(reservationArg); const queueKey = this.flexQueueKey( reservationArg.projectId, reservationArg.sessionId, queueIdArg, ); if (this.operationsByFlexQueue.has(queueKey)) { throw new Error('The Flex queue entry is already bound to a harness operation.'); } active.flexQueueKey = queueKey; active.flexQueueId = queueIdArg; active.flexRunId = runIdArg; active.flexModel = Object.freeze({ ...modelArg }); this.operationsByFlexQueue.set(queueKey, active); } public bindFlexRun( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, runIdArg: string, ): boolean { const active = this.operationsByFlexQueue.get( this.flexQueueKey(projectIdArg, sessionIdArg, queueIdArg), ); if (!active || active.flexQueueId !== queueIdArg) return false; if (active.flexRunId && active.flexRunId !== runIdArg) { throw new Error('The Flex queue entry was bound to conflicting run IDs.'); } active.flexRunId = runIdArg; return true; } public async completeFlex( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, runIdArg?: string, ): Promise { const queueKey = this.flexQueueKey(projectIdArg, sessionIdArg, queueIdArg); const active = this.operationsByFlexQueue.get(queueKey); if ( !active || active.flexQueueId !== queueIdArg || (active.flexRunId !== undefined && active.flexRunId !== runIdArg) || (active.flexRunId === undefined && runIdArg !== undefined) ) return false; if (active.state === 'submitting') { active.observedTerminal = true; return true; } await this.releaseActive(active); return true; } public ownsFlexRun( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, runIdArg: string, ): boolean { if (sessionIdArg.harnessId !== 'flex') return false; return (this.operationsBySession.get(this.sessionKey(projectIdArg, sessionIdArg)) ?? []) .some((active) => active.flexQueueId === queueIdArg && active.flexRunId === runIdArg); } public getFlexRunModel( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, runIdArg: string, ): IFlexModelChoice | undefined { const active = this.operationsByFlexQueue.get( this.flexQueueKey(projectIdArg, sessionIdArg, queueIdArg), ); if ( !active || active.flexQueueId !== queueIdArg || active.flexRunId !== runIdArg || active.flexModel === undefined ) return undefined; return { ...active.flexModel }; } public async completeOpenCodeMessage( projectIdArg: string, sessionIdArg: IControllerRuntimeId, messageIdArg: IControllerRuntimeId, ): Promise { if (sessionIdArg.harnessId !== 'opencode' || messageIdArg.harnessId !== 'opencode') return false; const active = this.operationsByOpenCodeMessage.get( this.openCodeMessageKey(projectIdArg, sessionIdArg, messageIdArg), ); if (!active) return false; active.observedTerminal = true; if (active.state !== 'submitting') { await this.releaseActive(active); } return true; } public getActive( projectIdArg: string, sessionIdArg: IControllerRuntimeId, ): IControllerHarnessOperationSnapshot | undefined { const active = this.operationsBySession.get( this.sessionKey(projectIdArg, sessionIdArg), )?.[0]; return active ? { reservation: cloneReservation(active.reservation), state: active.state, inputAccepted: active.inputAccepted, ...(active.flexQueueId ? { flexQueueId: active.flexQueueId } : {}), ...(active.flexRunId ? { flexRunId: active.flexRunId } : {}), ...(active.flexModel ? { flexModel: { ...active.flexModel } } : {}), } : undefined; } public getOperation( reservationArg: TControllerHarnessOperationReservation, ): IControllerHarnessOperationSnapshot | undefined { const active = this.findActive(reservationArg); return active ? { reservation: cloneReservation(active.reservation), state: active.state, inputAccepted: active.inputAccepted, ...(active.flexQueueId ? { flexQueueId: active.flexQueueId } : {}), ...(active.flexRunId ? { flexRunId: active.flexRunId } : {}), ...(active.flexModel ? { flexModel: { ...active.flexModel } } : {}), } : undefined; } public listSessionActive( projectIdArg: string, sessionIdArg: IControllerRuntimeId, ): IControllerHarnessOperationSnapshot[] { return (this.operationsBySession.get(this.sessionKey(projectIdArg, sessionIdArg)) ?? []) .map((active) => ({ reservation: cloneReservation(active.reservation), state: active.state, inputAccepted: active.inputAccepted, ...(active.flexQueueId ? { flexQueueId: active.flexQueueId } : {}), ...(active.flexRunId ? { flexRunId: active.flexRunId } : {}), ...(active.flexModel ? { flexModel: { ...active.flexModel } } : {}), })); } public bindFlexMessage( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, runIdArg: string, messageIdArg: IControllerRuntimeId, ): boolean { const active = this.operationsByFlexQueue.get( this.flexQueueKey(projectIdArg, sessionIdArg, queueIdArg), ); if ( !active || active.flexQueueId !== queueIdArg || active.flexRunId !== runIdArg || messageIdArg.harnessId !== 'flex' ) { return false; } if (active.reservation.messageId) { if (controllerRuntimeIdKey(active.reservation.messageId) === controllerRuntimeIdKey(messageIdArg)) { return true; } throw new Error('The Flex queue entry was bound to conflicting message IDs.'); } active.reservation.messageId = { ...messageIdArg }; return true; } public listProjectActive(projectIdArg: string): IControllerHarnessOperationSnapshot[] { const prefix = `${projectIdArg}\0`; return [...this.operationsBySession.entries()] .filter(([key]) => key.startsWith(prefix)) .flatMap(([, operations]) => operations.map((active) => ({ reservation: cloneReservation(active.reservation), state: active.state, inputAccepted: active.inputAccepted, ...(active.flexQueueId ? { flexQueueId: active.flexQueueId } : {}), ...(active.flexRunId ? { flexRunId: active.flexRunId } : {}), ...(active.flexModel ? { flexModel: { ...active.flexModel } } : {}), }))); } public listHarnessActive( harnessIdArg: 'opencode' | 'flex' | 'codex', ): IControllerHarnessOperationSnapshot[] { return [...this.operationsBySession.values()].flat() .filter((active) => active.reservation.sessionId.harnessId === harnessIdArg) .map((active) => ({ reservation: cloneReservation(active.reservation), state: active.state, inputAccepted: active.inputAccepted, ...(active.flexQueueId ? { flexQueueId: active.flexQueueId } : {}), ...(active.flexRunId ? { flexRunId: active.flexRunId } : {}), ...(active.flexModel ? { flexModel: { ...active.flexModel } } : {}), })); } public assertExclusive(reservationArg: TControllerHarnessOperationReservation): void { const active = this.requireActive(reservationArg); const operations = this.operationsBySession.get( this.sessionKey(reservationArg.projectId, reservationArg.sessionId), ) ?? []; if (operations.some((operation) => operation !== active)) { throw new ControllerHarnessOperationConflictError( 'Another harness operation is still active for this conversation.', ); } } public sealHarnessAdmission(harnessIdArg: TControllerSessionHarnessId): number { if (this.closed) throw new Error('The harness operation manager is closed.'); const generation = this.currentHarnessAdmissionGeneration(harnessIdArg) + 1; this.harnessAdmissionGenerations.set(harnessIdArg, generation); this.sealedHarnessAdmissions.set(harnessIdArg, generation); return generation; } public reopenHarnessAdmission( harnessIdArg: TControllerSessionHarnessId, generationArg: number, ): boolean { if ( this.closed || this.currentHarnessAdmissionGeneration(harnessIdArg) !== generationArg || this.sealedHarnessAdmissions.get(harnessIdArg) !== generationArg ) return false; this.sealedHarnessAdmissions.delete(harnessIdArg); return true; } public assertCurrentHarnessAdmission( reservationArg: TControllerHarnessOperationReservation, ): void { const active = this.requireActive(reservationArg); const harnessId = reservationArg.sessionId.harnessId; if (harnessId !== 'opencode' && harnessId !== 'flex' && harnessId !== 'codex') { throw new Error('Only session harnesses may own prompt operations.'); } this.assertHarnessGeneration(harnessId, active.harnessAdmissionGeneration); } public beginOperationBarrier( harnessIdArg?: 'opencode' | 'flex' | 'codex', maximumSessionsArg = 64, ): IControllerHarnessOperationBarrier { if (this.closed) throw new Error('The harness operation manager is closed.'); if (this.operationBarrier) { throw new ControllerHarnessOperationConflictError('Harness prompt admission is already sealed.'); } const token = plugins.crypto.randomBytes(16).toString('base64url'); this.operationBarrier = { token, ...(harnessIdArg ? { harnessId: harnessIdArg } : {}) }; const operations = [...this.operationsBySession.values()].flat().filter((operation) => ( harnessIdArg === undefined || operation.reservation.sessionId.harnessId === harnessIdArg )); const sessionsByKey = new Map(); for (const operation of operations) { const { projectId, sessionId } = operation.reservation; sessionsByKey.set(this.sessionKey(projectId, sessionId), { projectId, sessionId: { ...sessionId }, }); } if (sessionsByKey.size > maximumSessionsArg) { this.operationBarrier = undefined; throw new ControllerHarnessOperationLimitError( 'Too many active sessions are present for a bounded harness handoff.', ); } return { token, ...(harnessIdArg ? { harnessId: harnessIdArg } : {}), operationIds: operations.map((operation) => operation.reservation.operationId), sessions: [...sessionsByKey.values()], }; } public beginUpgradeBarrier(maximumSessionsArg = 64): IControllerHarnessOperationBarrier { return this.beginOperationBarrier(undefined, maximumSessionsArg); } public async waitForOperationBarrier( barrierArg: IControllerHarnessOperationBarrier, timeoutMsArg: number, signalArg?: AbortSignal, ): Promise { this.assertOperationBarrier(barrierArg); const pendingIds = new Set(barrierArg.operationIds); const deadline = Date.now() + timeoutMsArg; while (pendingIds.size > 0 && Date.now() < deadline) { signalArg?.throwIfAborted(); const activeIds = new Set( [...this.operationsBySession.values()].flat() .map((operation) => operation.reservation.operationId), ); for (const operationId of pendingIds) { if (!activeIds.has(operationId)) pendingIds.delete(operationId); } if (pendingIds.size > 0) { await new Promise((resolve) => setTimeout(resolve, 50)); } } signalArg?.throwIfAborted(); return pendingIds.size === 0; } public waitForUpgradeBarrier( barrierArg: IControllerHarnessOperationBarrier, timeoutMsArg: number, signalArg?: AbortSignal, ): Promise { return this.waitForOperationBarrier(barrierArg, timeoutMsArg, signalArg); } public endOperationBarrier(barrierArg: IControllerHarnessOperationBarrier): void { this.assertOperationBarrier(barrierArg); this.operationBarrier = undefined; } public endUpgradeBarrier(barrierArg: IControllerHarnessOperationBarrier): void { this.endOperationBarrier(barrierArg); } public async purgeSession( projectIdArg: string, sessionIdArg: IControllerRuntimeId, ): Promise { const key = this.sessionKey(projectIdArg, sessionIdArg); const operations = [...(this.operationsBySession.get(key) ?? [])]; await Promise.all(operations.map((active) => this.releaseActive(active))); this.drafts.purge(key); } public async releaseSession( projectIdArg: string, sessionIdArg: IControllerRuntimeId, ): Promise { const operations = [ ...(this.operationsBySession.get(this.sessionKey(projectIdArg, sessionIdArg)) ?? []), ]; await Promise.all(operations.map((active) => this.releaseActive(active))); } public async purgeProject(projectIdArg: string): Promise { const prefix = `${projectIdArg}\0`; const operations = [...this.operationsBySession.entries()] .filter(([key]) => key.startsWith(prefix)) .flatMap(([, active]) => active); await Promise.all(operations.map((active) => this.releaseActive(active))); this.drafts.purgePrefix(prefix); } public async releaseHarness(harnessIdArg: 'opencode' | 'flex' | 'codex', preserveQueuedArg = false): Promise { const operations = [...this.operationsBySession.values()].flat().filter( (active) => active.reservation.sessionId.harnessId === harnessIdArg && !(preserveQueuedArg && active.state === 'queued'), ); await Promise.all(operations.map((active) => this.releaseActive(active))); } public async close(): Promise { if (this.closePromise) return this.closePromise; this.closed = true; this.operationBarrier = undefined; const closePromise = (async () => { await Promise.allSettled([...this.operationsBySession.values()].map( (operations) => Promise.all(operations.map((active) => this.releaseActive(active))), )); this.drafts.clear(); const errors: unknown[] = []; try { await this.waitForCleanup( this.uploads.close(), 'Harness upload-manager cleanup exceeded its deadline.', ); } catch (errorArg) { errors.push(errorArg); } try { await this.retryPendingUploadCleanups(); } catch (errorArg) { errors.push(errorArg); } if (errors.length > 0) { throw new AggregateError(errors, 'Harness operation resource cleanup failed.'); } })(); this.closePromise = closePromise; try { await closePromise; } catch (errorArg) { if (this.closePromise === closePromise) this.closePromise = undefined; throw errorArg; } } private sessionKey(projectIdArg: string, sessionIdArg: IControllerRuntimeId): string { return `${projectIdArg}\0${controllerRuntimeIdKey(sessionIdArg)}`; } private assertOperationBarrier(barrierArg: IControllerHarnessOperationBarrier): void { if ( !this.operationBarrier || barrierArg.token !== this.operationBarrier.token || barrierArg.harnessId !== this.operationBarrier.harnessId ) { throw new Error('The harness operation admission barrier is no longer authoritative.'); } } private currentHarnessAdmissionGeneration(harnessIdArg: TControllerSessionHarnessId): number { return this.harnessAdmissionGenerations.get(harnessIdArg) ?? 0; } private assertHarnessAdmission( harnessIdArg: TControllerSessionHarnessId, expectedGenerationArg: number, ): void { this.assertHarnessGeneration(harnessIdArg, expectedGenerationArg); if ( this.sealedHarnessAdmissions.has(harnessIdArg) || ( this.operationBarrier && ( this.operationBarrier.harnessId === undefined || this.operationBarrier.harnessId === harnessIdArg ) ) ) { throw new ControllerHarnessOperationConflictError( 'Harness prompt admission is temporarily sealed.', ); } } private assertHarnessGeneration( harnessIdArg: TControllerSessionHarnessId, expectedGenerationArg: number, ): void { if (this.currentHarnessAdmissionGeneration(harnessIdArg) !== expectedGenerationArg) { throw new ControllerHarnessOperationConflictError( 'The harness prompt belongs to a stale runtime generation.', ); } } private flexQueueKey( projectIdArg: string, sessionIdArg: IControllerRuntimeId, queueIdArg: string, ): string { return `${this.sessionKey(projectIdArg, sessionIdArg)}\0${queueIdArg}`; } private openCodeMessageKey( projectIdArg: string, sessionIdArg: IControllerRuntimeId, messageIdArg: IControllerRuntimeId, ): string { return `${this.sessionKey(projectIdArg, sessionIdArg)}\0${controllerRuntimeIdKey(messageIdArg)}`; } private findActive( reservationArg: TControllerHarnessOperationReservation, ): IActiveHarnessOperation | undefined { const operations = this.operationsBySession.get( this.sessionKey(reservationArg.projectId, reservationArg.sessionId), ); return operations?.find( (active) => active.reservation.operationId === reservationArg.operationId, ); } private requireActive( reservationArg: TControllerHarnessOperationReservation, ): IActiveHarnessOperation { const active = this.findActive(reservationArg); if (!active) throw new Error('The harness operation reservation is no longer active.'); return active; } private async releaseActive(activeArg: IActiveHarnessOperation): Promise { if (activeArg.releasePromise) return activeArg.releasePromise; if (activeArg.state === 'queued') { activeArg.state = 'cancelled'; try { this.options.onQueuedOperationCancelled?.(cloneReservation(activeArg.reservation)); } catch { // Cancellation ownership must not depend on observer behavior. } // Attachment cleanup has independent retry ownership and must not retain // this cancelled operation as the per-session FIFO head. this.finalizeRelease(activeArg); } const releasePromise = (async () => { if (activeArg.upload) await this.cleanupUpload(activeArg, activeArg.upload); this.finalizeRelease(activeArg); })(); activeArg.releasePromise = releasePromise; try { await releasePromise; } finally { if (activeArg.releasePromise === releasePromise) activeArg.releasePromise = undefined; } } private async waitForCleanup(cleanupArg: Promise, messageArg: string): Promise { let timeout: NodeJS.Timeout | undefined; try { await Promise.race([ cleanupArg, new Promise((_resolve, reject) => { timeout = setTimeout(() => reject(new Error(messageArg)), this.cleanupTimeoutMs); }), ]); } finally { if (timeout) clearTimeout(timeout); } } private finalizeRelease(activeArg: IActiveHarnessOperation): void { const key = this.sessionKey(activeArg.reservation.projectId, activeArg.reservation.sessionId); const operations = this.operationsBySession.get(key); const operationIndex = operations?.indexOf(activeArg) ?? -1; const wasActive = operations !== undefined && operationIndex >= 0; if (operations && operationIndex >= 0) { operations.splice(operationIndex, 1); this.activeOperationCount -= 1; if (operations.length === 0) this.operationsBySession.delete(key); } if ( activeArg.flexQueueKey && this.operationsByFlexQueue.get(activeArg.flexQueueKey) === activeArg ) this.operationsByFlexQueue.delete(activeArg.flexQueueKey); const messageId = activeArg.reservation.messageId; if (messageId?.harnessId === 'opencode') { const messageKey = this.openCodeMessageKey( activeArg.reservation.projectId, activeArg.reservation.sessionId, messageId, ); if (this.operationsByOpenCodeMessage.get(messageKey) === activeArg) { this.operationsByOpenCodeMessage.delete(messageKey); } } if (!wasActive) return; queueMicrotask(() => { try { this.options.onOperationReleased?.(cloneReservation(activeArg.reservation)); } catch { // Release ownership must not depend on observer behavior. } }); } private cleanupUpload( activeArg: IActiveHarnessOperation, uploadArg: IControllerUploadHandle, ): Promise { const operationId = activeArg.reservation.operationId; let pending = this.pendingUploadCleanups.get(operationId); if (!pending) { pending = { active: activeArg, upload: uploadArg }; this.pendingUploadCleanups.set(operationId, pending); } if (!pending.cleanupPromise) { const cleanupPromise = pending.upload.cleanup().then(() => { if (pending!.active.upload === pending!.upload) pending!.active.upload = undefined; if (this.pendingUploadCleanups.get(operationId) === pending) { this.pendingUploadCleanups.delete(operationId); } this.finalizeRelease(pending!.active); }).finally(() => { if (pending!.cleanupPromise === cleanupPromise) pending!.cleanupPromise = undefined; }); pending.cleanupPromise = cleanupPromise; } return this.waitForCleanup( pending.cleanupPromise, 'Harness operation upload cleanup exceeded its deadline.', ); } private async retryPendingUploadCleanup(operationIdArg: string): Promise { const pending = this.pendingUploadCleanups.get(operationIdArg); if (pending) await this.releaseActive(pending.active); } private async retryPendingUploadCleanups(): Promise { const results = await Promise.allSettled( [...this.pendingUploadCleanups.values()].map((pending) => this.releaseActive(pending.active)), ); const errors = results .filter((result): result is PromiseRejectedResult => result.status === 'rejected') .map((result) => result.reason); if (errors.length > 0) { throw new AggregateError(errors, 'Harness operation upload cleanup retry failed.'); } } }