import * as plugins from './plugins.js'; import { ControllerCodexCreationModel, assertCodexCreationRuntime, codexCreationDocumentId, isCodexCreationToken, isCodexThreadId, type ICodexCreationRuntime, type IControllerCodexCreationDocument, } from './classes.codexcreationmodels.js'; import type { IControllerCodexModelChoice } from '../ts_interfaces/index.js'; import { codexQualifiedIdentity, isCodexSessionId } from './functions.codexidentity.js'; export interface ICodexCreationScope { projectIdentityId: string; operationId: string; } export interface IBeginCodexCreationInput extends ICodexCreationScope { connection?: IControllerCodexCreationDocument['connection']; title: string; model?: IControllerCodexModelChoice; } type TStoredCreation = NonNullable>>; const randomUpdateId = () => plugins.crypto.randomBytes(32).toString('base64url'); /** Durable pre-ID intent. This store never retries a provider operation. */ export class ControllerCodexCreationStore { constructor(private readonly issuerId: string) { if (!isCodexCreationToken(issuerId, 32)) throw new Error('Invalid Codex creation issuer.'); } public async begin(inputArg: IBeginCodexCreationInput): Promise { const id = this.id(inputArg); const candidate: IControllerCodexCreationDocument = { id, issuerId: this.issuerId, projectIdentityId: inputArg.projectIdentityId, operationId: inputArg.operationId, title: inputArg.title, state: 'pending', requestedAt: new Date(), updateId: randomUpdateId(), ...(inputArg.model === undefined ? {} : { model: { ...inputArg.model } }), ...(inputArg.connection ? { connection: { ...inputArg.connection } } : {}), }; let stored: TStoredCreation | null; try { stored = (await ControllerCodexCreationModel.exact.insert(candidate)).document; } catch (error) { if (!(error instanceof plugins.smartdata.SmartdataExactPersistenceError) || error.code !== 'ambiguous_write') throw error; stored = await ControllerCodexCreationModel.exact.findStoredOne({ id }); if (!stored) throw new Error('Codex creation intent has an uncertain persistence outcome.', { cause: error }); } const body = this.body(stored, inputArg); if (body.updateId !== candidate.updateId) throw new Error('Codex creation operation already exists; creation must not be replayed.'); return body; } public async get(scopeArg: ICodexCreationScope): Promise { const stored = await ControllerCodexCreationModel.exact.findStoredOne({ id: this.id(scopeArg) }); if (!stored) throw new Error('Codex creation intent was not found.'); return this.body(stored, scopeArg); } public async listOutstanding(projectIdArg: string, signalArg?: AbortSignal): Promise { this.assertProject(projectIdArg); const result: IControllerCodexCreationDocument[] = []; let lastId: string | undefined; while (true) { signalArg?.throwIfAborted(); const page = await ControllerCodexCreationModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdArg, state: { $in: ['pending', 'dispatched', 'bound', 'admitted'] }, ...(lastId === undefined ? {} : { id: { $gt: lastId } }), }, sort: { id: 1 }, limit: 128, signal: signalArg, }); if (page.length > 128 || result.length + page.length > 4096) throw new Error('Codex creation recovery exceeds its bounded capacity.'); if (page.length === 0) return result; for (const entry of page) { const persisted = ControllerCodexCreationModel.exact.toPersisted(entry); const body = this.body(entry, { projectIdentityId: projectIdArg, operationId: persisted.operationId }); if (lastId !== undefined && body.id <= lastId) throw new Error('Codex creation recovery did not advance.'); result.push(body); lastId = body.id; } } } public async findUnmaterialized(projectIdArg: string, nativeIdArg: string): Promise { this.assertProject(projectIdArg); if (!isCodexSessionId(nativeIdArg)) throw new Error('Invalid Codex thread ID.'); const records = await ControllerCodexCreationModel.exact.findStored({ filter: { issuerId: this.issuerId, projectIdentityId: projectIdArg, nativeId: nativeIdArg, state: { $in: ['bound', 'admitted'] } }, limit: 2, }); if (records.length > 1) throw new Error('Multiple Codex creation intents claim one thread.'); if (!records[0]) return undefined; const body = ControllerCodexCreationModel.exact.toPersisted(records[0]); return this.body(records[0], { projectIdentityId: projectIdArg, operationId: body.operationId }); } public completeDeletion(scopeArg: ICodexCreationScope): Promise { return this.transition(scopeArg, (body) => { if (body.state === 'retired') return body; if (body.state !== 'admitted') throw new Error('Codex deletion requires an admitted creation.'); return { ...body, state: 'retired', terminalAt: new Date() }; }); } public dispatch(scopeArg: ICodexCreationScope, runtimeArg: ICodexCreationRuntime): Promise { assertCodexCreationRuntime(runtimeArg); const runtime = structuredClone(runtimeArg); return this.transition(scopeArg, (body) => { if (body.state !== 'pending') throw new Error('Codex creation was already dispatched; it must not be replayed.'); return { ...body, state: 'dispatched', runtime, dispatchedAt: new Date() }; }); } public bind(scopeArg: ICodexCreationScope, generationArg: string, nativeIdArg: string, createdAtArg: number): Promise { if (!isCodexCreationToken(generationArg, 32) || !isCodexSessionId(nativeIdArg) || !Number.isSafeInteger(createdAtArg) || createdAtArg < 0) throw new Error('Invalid assigned Codex identity.'); return this.transition(scopeArg, (body) => { if (body.state !== 'dispatched' || body.runtime?.generation !== generationArg) throw new Error('Codex creation response belongs to another runtime generation.'); return { ...body, state: 'bound', nativeId: nativeIdArg, providerCreatedAt: createdAtArg, ...(body.connection ? { codexOrigin: { version: 2 as const, ...body.connection, rawThreadId: codexQualifiedIdentity(nativeIdArg)?.rawThreadId ?? nativeIdArg } } : {}) }; }); } public admit(scopeArg: ICodexCreationScope, identityIdArg: string): Promise { if (!isCodexCreationToken(identityIdArg, 32)) throw new Error('Invalid managed Codex identity.'); return this.transition(scopeArg, (body) => { if (body.state === 'admitted' && body.sessionIdentityId === identityIdArg) return body; if (body.state !== 'bound') throw new Error('Codex creation is not awaiting managed admission.'); return { ...body, state: 'admitted', sessionIdentityId: identityIdArg }; }); } public finalizeMetadata(scopeArg: ICodexCreationScope): Promise { return this.transition(scopeArg, (body) => { if (body.state !== 'admitted') throw new Error('Codex metadata finalization requires managed admission.'); return body.metadataFinalizedAt ? body : { ...body, metadataFinalizedAt: new Date() }; }); } public recordTurnDispatch(scopeArg: ICodexCreationScope): Promise { return this.transition(scopeArg, (body) => { if (body.state !== 'admitted') throw new Error('Codex thread has not completed managed admission.'); if (!body.metadataFinalizedAt) throw new Error('Codex creation metadata is not finalized.'); return body.turnDispatchedAt ? body : { ...body, turnDispatchedAt: new Date() }; }); } /** Only called while the admission lock proves no first-turn frame was dispatched. */ public cancelUndispatchedTurn(scopeArg: ICodexCreationScope): Promise { return this.transition(scopeArg, (body) => { if (body.state !== 'admitted') throw new Error('Codex first-turn cancellation requires an admitted creation.'); const { turnDispatchedAt: _discarded, ...next } = body; return next; }); } public materialize(scopeArg: ICodexCreationScope): Promise { return this.transition(scopeArg, (body) => { if (body.state === 'materialized') return body; if (body.state !== 'admitted') throw new Error('Codex thread has not completed managed admission.'); if (!body.metadataFinalizedAt) throw new Error('Codex creation metadata is not finalized.'); return { ...body, state: 'materialized', terminalAt: new Date() }; }); } /** Caller must prove any dispatch runtime ended, and retire partial managed identity first. */ public retireUnmaterialized(scopeArg: ICodexCreationScope, endedGenerationArg?: string): Promise { return this.transition(scopeArg, (body) => { if (body.state === 'retired') return body; if (body.state === 'materialized' || body.turnDispatchedAt !== undefined) throw new Error('A Codex thread with a possibly executed turn cannot be retired as empty.'); if (body.runtime && body.runtime.generation !== endedGenerationArg) throw new Error('Codex dispatch generation termination was not proven.'); return { ...body, state: 'retired', terminalAt: new Date() }; }); } private async transition( scopeArg: ICodexCreationScope, changeArg: (bodyArg: IControllerCodexCreationDocument) => IControllerCodexCreationDocument, ): Promise { const id = this.id(scopeArg); const stored = await ControllerCodexCreationModel.exact.findStoredOne({ id }); if (!stored) throw new Error('Codex creation intent was not found.'); const current = this.body(stored, scopeArg); const next = changeArg(structuredClone(current)); next.updateId = randomUpdateId(); try { const result = await ControllerCodexCreationModel.exact.transition({ current: stored, change: (model) => { Object.assign(model, next); if (!Object.hasOwn(next, 'turnDispatchedAt')) delete model.turnDispatchedAt; }, }); if (result.status !== 'transitioned') throw new Error('Codex creation changed concurrently.'); return this.body(result.document, scopeArg); } catch (error) { if (!(error instanceof plugins.smartdata.SmartdataExactPersistenceError) || error.code !== 'ambiguous_write') throw error; const reconciled = await ControllerCodexCreationModel.exact.findStoredOne({ id }); if (reconciled) { const body = this.body(reconciled, scopeArg); if (body.updateId === next.updateId) return body; } throw new Error('Codex creation transition has an uncertain persistence outcome.', { cause: error }); } } private id(scopeArg: ICodexCreationScope): string { return codexCreationDocumentId(this.issuerId, scopeArg.projectIdentityId, scopeArg.operationId); } private assertProject(projectIdArg: string): void { if (!isCodexCreationToken(projectIdArg, 16)) throw new Error('Invalid Codex creation project.'); } private body(storedArg: TStoredCreation, scopeArg: ICodexCreationScope): IControllerCodexCreationDocument { const body = ControllerCodexCreationModel.exact.toPersisted(storedArg); if (body.id !== this.id(scopeArg) || body.issuerId !== this.issuerId || body.projectIdentityId !== scopeArg.projectIdentityId || body.operationId !== scopeArg.operationId) { throw new Error('Codex creation intent escaped its authority scope.'); } return structuredClone(body); } }