import { existsSync } from "node:fs"; import { createDurableAcpTask, AcpSessionDoc, validateAcpSession } from "./durable-acp-task"; import { rm } from "node:fs/promises"; import { randomUUID } from "node:crypto"; import { join } from "node:path"; import { homedir } from "node:os"; import * as v from "valibot"; import { BACKGROUND_CONTEXT, type Context } from "@earendil-works/chord/context"; import { getSupportedThinkingLevels, clampThinkingLevel, type Models } from "@earendil-works/pi-ai"; import { builtinModels } from "@earendil-works/pi-ai/providers/all"; import { registerBunOAuthFlows } from "@earendil-works/pi-ai/bun-oauth"; import { Harness, createRegistry, defineExtension, defineTool, type Conversation, type ConversationWatch, type ConversationView, type LiveState, LiveDoc, type Storage, type EntryId, type Cursor, type EntryRecord, } from "@earendil-works/pi-durable"; import type { ExecutionEnv } from "@earendil-works/pi-durable/env"; import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node"; import { openNodeJsonlStorage } from "@earendil-works/pi-durable/storage/jsonl/node"; import { createReadTool } from "@earendil-works/pi-durable/tools"; import type { AgentHarnessAdapter, ThreadModelDefaults, AgentHarnessOptions, AgentHarnessConnection, AgentHarnessResult, AgentHarnessEvent, } from "@cueloop/schema"; import { THREAD_MODEL_DEFAULTS } from "@cueloop/schema"; import { PiAnswerProjection } from "./pi/answer-projection"; import { PiToolProjection } from "./pi/tool-projection"; import { ownerCredentialStore } from "./pi/owner-credentials"; export interface ThreadHarnessOptions { backend?: AgentHarnessAdapter; home: string; models?: Models; defaults?: (cwd: string) => ThreadModelDefaults; registry?: () => ReturnType; credentialsPath?: string; sourceCredentialsPath?: string; removeStorage?: (sessionId: string) => Promise; storage?: (sessionId: string, context: Context) => Promise; env?: (cwd: string) => ExecutionEnv; prepareAcp?: (processKey: string, cwd: string) => Promise; createAcp?: ( connection: () => Promise, publish: (event: AgentHarnessEvent) => void, processKey: string, ) => ReturnType; onRemove?: (sessionId: string) => Promise; } const context: Context = BACKGROUND_CONTEXT; /** Each Thread owns its durable conversation; execution and model capabilities are host supplied. */ export function createThreadHarness(config: ThreadHarnessOptions): AgentHarnessAdapter { // OAuth's variable imports cannot resolve modules inside a standalone binary. registerBunOAuthFlows(); const models = config.models ?? builtinModels({ credentials: ownerCredentialStore( config.credentialsPath ?? join(config.home, "model-credentials.json"), config.sourceCredentialsPath ?? join(homedir(), ".pi", "agent", "auth.json"), ), }); return { id: config.backend?.id ?? "pi", label: config.backend?.label ?? "pi", recovery: "durable", connect: (options) => new ThreadHarnessConnection(config, models, options), remove: async (sessionId) => { if (config.onRemove) await config.onRemove(sessionId); if (config.removeStorage) await config.removeStorage(sessionId); else if (!config.storage) await rm(conversationDirectory(config.home, sessionId), { recursive: true, force: true, }); }, }; } class ThreadHarnessConnection implements AgentHarnessConnection { private readonly sessionId: string; private harness?: Harness; private storage?: Storage; private starting?: Promise; private closePending?: Promise; private conversation?: Conversation; private stream?: ConversationWatch; private closing = false; private backend?: AgentHarnessConnection; private readonly backendReady = Promise.withResolvers(); private readonly acp: ReturnType; constructor( private readonly config: ThreadHarnessOptions, private readonly models: Models, private readonly options: AgentHarnessOptions, ) { this.sessionId = options.sessionId ?? randomUUID(); const publish = (event: AgentHarnessEvent) => options.onEvent(event); const connection = () => this.backendReady.promise; this.acp = config.createAcp ? config.createAcp(connection, publish, this.sessionId) : createDurableAcpTask(connection, publish); void this.backendReady.promise.catch(() => {}); } start(): Promise { if (this.closing) return Promise.reject(new Error("Pi conversation is closed")); this.starting ??= this.initialize().catch((error) => { this.backendReady.reject(error); throw error; }); return this.starting; } private async initialize(): Promise { const registry = (this.config.registry ?? createRegistry)(); const tools = (this.options.tools?.definitions ?? []).map((definition) => defineTool({ name: definition.name, description: definition.description, parameters: definition.inputSchema, replay: "unsafe" as const, execute: async (args) => ({ output: [ { type: "text" as const, text: await this.options.tools!.call(definition.name, JSON.stringify(args)), }, ], }), }), ); registry.install( defineExtension({ name: "cueloop", tools: [createReadTool(), ...tools], tasks: [this.acp.task], }), ); const existed = existsSync(conversationDirectory(this.config.home, this.sessionId)); this.storage = await (this.config.storage ? this.config.storage(this.sessionId, context) : openNodeJsonlStorage(conversationDirectory(this.config.home, this.sessionId), context)); if (this.closing) { await this.storage.close(context); throw new Error("Pi conversation is closed"); } this.harness = await Harness.open( this.storage, { models: this.models, registry, env: ({ cwd }) => (this.config.env ?? ((directory) => new NodeExecutionEnv({ cwd: directory })))( cwd ?? this.options.cwd, ), settings: { retry: { maxRetries: 2 }, toolExecution: "sequential" }, onReport: (report) => this.options.onEvent({ kind: "diagnostic", severity: "warning", title: "Pi runtime notice", text: String(report.error), source: "protocol", }), }, context, ); if (this.closing) throw new Error("Pi conversation is closed"); const preparing = this.config.backend && this.config.prepareAcp ? this.config.prepareAcp(this.sessionId, this.options.cwd) : undefined; // Root opens storage while the relay starts. A rejection is awaited below. preparing?.catch(() => undefined); this.conversation = await this.harness.root(context, { agent: { cwd: this.options.cwd } }); if (this.config.backend) { if (preparing) await preparing; const saved = await this.harness.snapshot(AcpSessionDoc, this.conversation.id, context); if (saved) validateAcpSession(saved); const harnessOptions: AgentHarnessOptions = { ...this.options, sessionId: saved?.sessionId ?? (!existed ? this.options.sessionId : undefined), onEvent: (event) => this.acp.onEvent(event), }; if (this.config.prepareAcp) harnessOptions.agentProcessKey = this.sessionId; this.backend = this.config.backend.connect(harnessOptions); const sessionId = await this.backend.start(); this.backendReady.resolve(this.backend); await this.conversation.commit(async (tx) => { (await tx.doc(AcpSessionDoc, this.conversation!.id)).sessionId = sessionId; }, context); return this.sessionId; } await this.configureInitialModel(); if (this.closing) throw new Error("Pi conversation is closed"); await this.publishConfiguration(); return this.sessionId; } private async configureInitialModel() { const available = await this.models.getAvailable(); const current = (await this.conversation!.agent(context)).model; const defaults = this.config.defaults?.(this.options.cwd) ?? THREAD_MODEL_DEFAULTS.pi; const preferred = available.find((model) => `${model.provider}/${model.id}` === defaults.model); const initial = preferred ?? (this.config.models && !this.config.defaults ? available[0] : undefined); const selected = current ?? (initial ? { provider: initial.provider, modelId: initial.id } : undefined); if (!current && !selected && available.length) throw new Error( `Thread default model is not available to the owner account: ${defaults.model}`, ); if (selected && !current) await this.conversation!.configure( { model: selected, thinkingLevel: defaults.effort }, context, ); return { available, selected }; } private async publishConfiguration(): Promise { const available = await this.models.getAvailable(); const agent = await this.conversation!.agent(context); const selected = available.find( (model) => model.provider === agent.model?.provider && model.id === agent.model.modelId, ); const provider = agent.model?.provider ?? ""; const providerName = provider === "openai-codex" ? "Codex subscription" : (this.models.getProvider(provider)?.name ?? provider); const levels = selected ? getSupportedThinkingLevels(selected) : []; this.options.onEvent({ kind: "config", options: [ { id: "provider", name: "Provider", category: "model", currentValue: provider, options: [{ value: provider, name: providerName }], }, { id: "model", name: "Model", category: "model", currentValue: agent.model ? `${provider}/${agent.model.modelId}` : "", options: available.map((model) => ({ value: `${model.provider}/${model.id}`, name: model.name, })), }, ...(selected ? [ { id: "effort", name: "Reasoning", category: "thought_level", currentValue: clampThinkingLevel(selected, agent.thinkingLevel), options: levels.map((level) => ({ value: level, name: level })), }, ] : []), ], }); } async configure(id: string, value: string): Promise { if (this.backend?.configure) return this.backend.configure(id, value); if (!this.conversation) throw new Error("Pi configuration option is unavailable"); const available = await this.models.getAvailable(); const agent = await this.conversation.agent(context); if (id === "model") { const model = available.find((model) => `${model.provider}/${model.id}` === value); if (!model) throw new Error("Pi model is not available to the owner account"); await this.conversation.configure( { model: { provider: model.provider, modelId: model.id }, thinkingLevel: clampThinkingLevel(model, agent.thinkingLevel), }, context, ); } else if (id === "effort") { const model = available.find( (model) => model.provider === agent.model?.provider && model.id === agent.model.modelId, ); const level = model && getSupportedThinkingLevels(model).find((level) => level === value); if (!level) throw new Error("Pi reasoning effort is not available for the current model"); await this.conversation.configure({ thinkingLevel: level }, context); } else { throw new Error("Pi configuration option is unavailable"); } await this.publishConfiguration(); } async prompt(text: string, requestId = randomUUID()): Promise { const conversation = this.conversation; const harness = this.harness; if (!conversation || !harness || this.closing) throw new Error("Pi conversation is not ready"); if (this.backend) return this.acp.prompt(harness, conversation, text, requestId, context); const input = await conversation.submit( { type: "input", content: text, requestId, whenBusy: "followUp" }, context, ); const record = await input.status(context); const projection = new PiAnswerProjection(record.entry); let publishedText: string | undefined; const publish = () => { const text = projection.text(); if (text === publishedText || (!text && publishedText === undefined)) return; publishedText = text; this.options.onEvent({ kind: "message", id: `pi-answer-${requestId}`, text, replace: true, }); }; const stream = await conversation.watch(context); const tools = record.status === "done" || record.status === "unanswered" ? undefined : new PiToolProjection(); let inputEntry = record.entry; let newestEntry: EntryId | undefined; const update = async (view: ConversationView) => { const current = await input.status(context); const lastEntry = view.entries.at(-1)?.id; if (!current.entry || !lastEntry || lastEntry < current.entry) return; const missingPrefix = !newestEntry || (view.before !== undefined && view.before > newestEntry); const entries = inputEntry !== current.entry || missingPrefix ? await this.answerEntries(current.entry, lastEntry) : view.entries; // SAFETY: The registered LiveDoc owns the state published under its durable document kind. const live = view.docs[LiveDoc.definition.kind] as Readonly | undefined; inputEntry = current.entry; newestEntry = lastEntry; projection.restore(entries, live, inputEntry); publish(); for (const event of tools?.restore(entries, live, inputEntry) ?? []) this.options.onEvent(event); }; this.stream = stream; try { await update(stream.value); stream.start(async (call) => { if (call.kind === "value") await update(call.value); }); const result = await input.wait(context); await stream.stop(); if (result.entry) { const entries = await this.answerEntries(result.entry, result.answer); projection.restore(entries, undefined, result.entry); for (const event of tools?.restore(entries, undefined, result.entry) ?? []) this.options.onEvent(event); } if (projection.text()) publish(); if (result.status === "unanswered") { if (result.reason === "aborted") return { outcome: "cancelled" }; const parsed = v.safeParse(v.string(), result.detail); const detail = parsed.success ? parsed.output : JSON.stringify(result.detail); throw new Error(detail ?? `Pi input was not answered: ${result.reason}`); } return { outcome: result.status === "done" ? "completed" : "incomplete" }; } finally { await stream.stop(); this.stream = undefined; } } cancel(): void { this.acp.cancel(); this.backend?.cancel(); void this.conversation?.abort(context).catch(this.options.onExit); } permission(requestId: string, optionId?: string): void { if (this.backend) return this.backend.permission(requestId, optionId); throw new Error("Pi conversation has no pending permission"); } close(): Promise { this.closing = true; this.backendReady.reject(new Error("Thread harness is closed")); this.closePending ??= this.finishClose(); return this.closePending; } private async finishClose(): Promise { await this.starting?.catch(() => {}); try { await this.backend?.close(); } finally { try { await this.harness?.close(context); } finally { await this.stream?.stop(); } } } private async answerEntries(inputId: EntryId, answerId?: EntryId): Promise { const entries: EntryRecord[] = []; let cursor: Cursor | undefined; do { const page = await this.storage!.scanEntries( { conversationId: this.conversation!.id, minEntryId: inputId, maxEntryId: answerId }, 128, cursor, context, ); entries.unshift(...page.items.slice().reverse()); cursor = page.next; } while (cursor); return entries; } } function conversationDirectory(home: string, sessionId: string): string { if (!sessionId || sessionId === "." || sessionId === "..") throw new Error("Unsafe Pi conversation ID"); return join(home, "pi-conversations", encodeURIComponent(sessionId)); }