import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import { RequestError } from "@agentclientprotocol/sdk"; import type { Client, CreateElicitationRequest, CreateElicitationResponse, RequestPermissionRequest, RequestPermissionResponse, SessionNotification, } from "@agentclientprotocol/sdk"; import { HarnessOutputChannel, validateHostApprovalResponse, validateHostQuestionResponse, type CreateSessionInput, type HarnessOutput, type HarnessResult, type HarnessSession, type HostApprovalEffect, type HostApprovalInteraction, type HostCommand, type HostEvent, type HostInteraction, type HostInteractionResponse, type HostItemOutcome, type HostItemSnapshot, type HostQuestionInteraction, type HostThreadSnapshot, type InteractionClosedEvent, type OpenSessionInput, type TurnOutcome, type TurnStartCommand, } from "@codexhost/harness-adapter"; import { hostInteractionIdSchema, type NativeSessionRef, type NativeTurnRef, } from "@codexhost/shared-contracts"; import { AcpTransport } from "./acp-transport.js"; import { capabilities, Configuration } from "./configuration.js"; import { correlatedTurn, readHistory, sessionRef, validateKnownTurns, validateSessionRef, } from "./history.js"; import type { Invocation } from "./installation.js"; import { failure, HARNESS_ID, MiniMaxError, nativeError, nativeId, record } from "./native.js"; import { itemId, toolItems } from "./projection.js"; import { questionnaire, questionnaireRequestId, questionnaireResponse } from "./questionnaire.js"; const CANCEL_GRACE_MS = 5_000; const QUESTION_READY_MS = 5_000; const REALTIME_KINDS = new Set([ "agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", ]); const CANCELLED_PERMISSION = { outcome: { outcome: "cancelled" } } as const; type Turn = { id: TurnStartCommand["turnId"]; messageIds: Set; questionnaireCalls: Map; submittedQuestionnaires: Set; items: Map; tools: Map>; settled?: boolean; cancel?: Promise; cancelTimer?: ReturnType; done?: Promise; }; type PendingInteraction = { interaction: HostInteraction; respond: (response: HostInteractionResponse) => void | Promise; responding?: boolean; cancel: () => void; }; type CommandResult = | { turnId: TurnStartCommand["turnId"] } | { cancellationRequested: true } | { accepted: true } | { completed: true }; export class MiniMaxSession implements HarnessSession { readonly harnessId = HARNESS_ID; readonly initialUsage = null; readonly #output = new HarnessOutputChannel(); readonly outputs = this.#output.outputs; readonly #transport: AcpTransport; readonly #interactions = new Map(); readonly #pastNotifications = new Set(); #configuration = new Configuration(undefined); #sessionId?: string; #nativeRef?: NativeSessionRef; #active: Turn | undefined; #configuring = false; #configUnsupported = false; #closeSession = false; #closing?: Promise; #fault?: MiniMaxError; constructor( readonly cwd: string, readonly root: string, invocation: Invocation, env: NodeJS.ProcessEnv, readonly onClose: () => void, ) { const handler: Client = { sessionUpdate: (params) => this.#update(params), requestPermission: (params) => this.#permission(params), unstable_createElicitation: (params) => this.#question(params), }; this.#transport = new AcpTransport(invocation, cwd, env, handler, (error) => { this.#fault = error; this.#closeInteractions(); if (!this.#active) this.#finishFault(); }); } get initialState() { return this.#state(); } get capabilities() { return capabilities(this.#configuration); } modelCatalog() { return this.#configuration.catalog; } async initialize( version: string, input: Extract, ): Promise { const initialized = await this.#transport.initialize(version); this.#closeSession = initialized.agentCapabilities?.sessionCapabilities?.close != null; if (input.kind === "resume") { if (initialized.agentCapabilities?.loadSession !== true) throw new MiniMaxError("unsupported", "MiniMax Code does not advertise Session load"); const id = validateSessionRef(input.nativeRef, this.root); validateKnownTurns(readHistory(this.root, this.cwd, id), input.knownTurnRefs ?? []); this.#sessionId = id; const response = await this.#transport.rpc( this.#transport.connection.loadSession({ sessionId: id, cwd: this.cwd, mcpServers: [] }), 30_000, ); this.#configuration = new Configuration(response?.configOptions); this.#nativeRef = input.nativeRef; } else if (!input.prewarm) { await this.#create(input); } else { this.#prewarmInput = input; } } #prewarmInput: CreateSessionInput | undefined; async #create(input: CreateSessionInput): Promise { const response = await this.#transport.rpc( this.#transport.connection.newSession({ cwd: this.cwd, mcpServers: [] }), 30_000, ); if (!nativeId(response?.sessionId)) throw new MiniMaxError("protocolError", "MiniMax Code did not return a Session ID"); sessionRef(response.sessionId, this.root); this.#sessionId = response.sessionId; this.#configuration = new Configuration(response.configOptions); if (input.model) await this.#setConfiguration( "model", this.#configuration.select("model", input.model), false, ); if (input.thinkingOptionId) await this.#setConfiguration( "thinkingEffort", this.#configuration.select("thinkingEffort", input.thinkingOptionId), false, ); if (input.permissionModeId) await this.#setConfiguration( "permissionMode", this.#configuration.select("permissionMode", input.permissionModeId), false, ); } #state() { return { ...this.#configuration.state, ...(this.#nativeRef ? { nativeRef: this.#nativeRef } : {}), }; } #event(event: HostEvent): void { this.#output.emit({ kind: "event", event }); } #stateChanged() { this.#event({ type: "session.state.changed", state: this.#state() }); } async readSnapshot(): Promise> { try { const snapshot = this.#nativeRef ? readHistory(this.root, this.cwd, this.#nativeRef.nativeSessionId) : { turns: [] }; return { ok: true, value: { ...snapshot, state: this.#state() } }; } catch (error) { return failure(error); } } execute( command: Extract, ): Promise>; execute( command: Extract, ): Promise>; execute( command: Extract, ): Promise>; execute( command: Extract< HostCommand, { type: "model.select" | "thinking.select" | "permissionMode.select" } >, ): Promise>; async execute(command: HostCommand): Promise> { try { if (this.#fault) throw this.#fault; if (this.#closing) throw new MiniMaxError("invalidState", "MiniMax Code Session is closed"); switch (command.type) { case "turn.start": return { ok: true, value: await this.#start(command) }; case "turn.steer": throw new MiniMaxError("unsupported", "MiniMax Code does not support Turn steering"); case "turn.cancel": { const active = this.#active; if (active?.id !== command.turnId) throw new MiniMaxError("invalidState", "MiniMax Code Turn is not active"); await this.#cancel(active); return { ok: true, value: { cancellationRequested: true } }; } case "interaction.respond": { const pending = this.#interactions.get(command.interactionId); if (!pending) throw new MiniMaxError("invalidState", "MiniMax Code Interaction is not active"); const { interaction } = pending; const { response } = command; const error = interaction.type === "approval" && response.type === "approval" ? validateHostApprovalResponse(interaction, response) : interaction.type === "question" && response.type === "question" ? validateHostQuestionResponse(interaction, response) : nativeError( new MiniMaxError( "invalidRequest", "MiniMax Code Interaction response type does not match", ), ); if (error) return { ok: false, error }; if (pending.responding) throw new MiniMaxError( "sessionBusy", "MiniMax Code Interaction response is in progress", ); pending.responding = true; try { const delivery = pending.respond(response); if (delivery) await delivery; if (this.#interactions.get(interaction.interactionId) !== pending) throw new MiniMaxError( "invalidState", "MiniMax Code Interaction is no longer active", ); this.#closeInteraction(interaction, "responded"); return { ok: true, value: { accepted: true } }; } finally { pending.responding = false; } } case "model.select": await this.#setConfiguration("model", this.#configuration.select("model", command.model)); break; case "thinking.select": await this.#setConfiguration( "thinkingEffort", this.#configuration.select("thinkingEffort", command.thinkingOptionId), ); break; case "permissionMode.select": await this.#setConfiguration( "permissionMode", this.#configuration.select("permissionMode", command.permissionModeId), ); break; } return { ok: true, value: { completed: true } }; } catch (error) { return failure(error); } } async #setConfiguration( id: "model" | "thinkingEffort" | "permissionMode", value: string, emit = true, ): Promise { if (!this.#sessionId) throw new MiniMaxError( "unsupported", "MiniMax Code has no active native Session configuration", ); if (this.#active || this.#configuring) throw new MiniMaxError( "sessionBusy", "MiniMax Code is already performing a Session operation", ); if (this.#configuration.current(id) === value) return; const sessionId = this.#sessionId; const setOption = (wireValue: string) => this.#transport.rpc( this.#transport.connection.setSessionConfigOption({ sessionId, configId: id, value: wireValue, }), 30_000, ); this.#configuring = true; try { let appliedValue = value; const fallback = id === "model" ? this.#configuration.modelVariantFallback(value) : undefined; const response = await setOption(value).catch((error: unknown) => { if ( fallback && error instanceof RequestError && error.code === -32603 && record(error.data)?.details === "Invalid model reasoning" ) { appliedValue = fallback; return setOption(fallback); } throw error; }); if (!Array.isArray(response?.configOptions)) throw new MiniMaxError("protocolError", "Missing MiniMax Code configuration confirmation"); this.#configuration = new Configuration(response.configOptions); if (emit) this.#stateChanged(); if (this.#configuration.current(id) !== appliedValue) throw new MiniMaxError( "invalidState", "MiniMax Code did not apply the requested configuration", ); } catch (error) { if (nativeError(error).code === "unsupported") { this.#configUnsupported = true; this.#configuration.disableWrites(); if (emit) this.#stateChanged(); } else if ( error instanceof MiniMaxError && (error.code === "unavailable" || error.code === "protocolError") ) { this.#transport.fault(error); } throw error; } finally { this.#configuring = false; } } async #start(command: TurnStartCommand): Promise<{ turnId: TurnStartCommand["turnId"] }> { if (this.#active || this.#creating || this.#configuring) throw new MiniMaxError( "sessionBusy", "MiniMax Code is already performing a Session operation", ); if (!command.input.length || !command.input.some(({ text }) => text.trim())) throw new MiniMaxError("invalidRequest", "MiniMax Code needs nonempty text input"); if (this.#prewarmInput) { const input = this.#prewarmInput; this.#prewarmInput = undefined; try { await this.#createForStart(input); } catch (error) { this.#transport.fault( new MiniMaxError(nativeError(error).code, nativeError(error).message), ); throw error; } this.#stateChanged(); } const sessionId = this.#sessionId; if (!sessionId || this.#closing || this.#fault) throw new MiniMaxError("invalidState", "MiniMax Code Session is not available"); const turn: Turn = { id: command.turnId, messageIds: new Set(), questionnaireCalls: new Map(), submittedQuestionnaires: new Set(), items: new Map(), tools: new Map(), }; this.#active = turn; this.#event({ type: "turn.started", turnId: turn.id }); turn.done = this.#run(turn, sessionId, command.input); return { turnId: turn.id }; } #creating = false; async #createForStart(input: CreateSessionInput): Promise { this.#creating = true; try { await this.#create(input); } finally { this.#creating = false; } } async #run(turn: Turn, sessionId: string, prompt: TurnStartCommand["input"]): Promise { let outcome: TurnOutcome; try { const response = await this.#transport.rpc( this.#transport.connection.prompt({ sessionId, prompt }), ); switch (response?.stopReason) { case "end_turn": outcome = { status: "succeeded" }; break; case "cancelled": outcome = { status: "cancelled" }; break; case "refusal": case "max_tokens": case "max_turn_requests": outcome = { status: "failed", error: nativeError( new MiniMaxError("nativeFailure", `MiniMax Code stopped: ${response.stopReason}`), ), }; break; default: outcome = { status: "failed", error: nativeError( new MiniMaxError("protocolError", "Unrecognized MiniMax Code Prompt stop reason"), ), }; } } catch (error) { outcome = { status: "failed", error: nativeError(error) }; } turn.settled = true; for (const id of turn.messageIds) this.#pastNotifications.add(`message:${id}`); for (const id of turn.tools.keys()) this.#pastNotifications.add(`tool:${id}`); for (const id of turn.questionnaireCalls.keys()) this.#pastNotifications.add(`questionnaire:${id}`); clearTimeout(turn.cancelTimer); this.#closeInteractions(); let nativeTurnRef: NativeTurnRef | undefined; const terminal = outcome.status === "succeeded" ? "completed" : outcome.status === "cancelled" ? "aborted" : "failed"; if (turn.messageIds.size || turn.questionnaireCalls.size) { try { const until = Date.now() + 5_000; do { try { nativeTurnRef = correlatedTurn( this.root, this.cwd, sessionId, turn.messageIds, turn.questionnaireCalls, terminal, ); } catch (error) { if (!(error instanceof MiniMaxError) || error.code !== "sessionNotFound") throw error; } if (nativeTurnRef || Date.now() >= until) break; await delay(50); } while (true); } catch (error) { if (outcome.status === "succeeded") outcome = { status: "failed", error: nativeError(error) }; } } if (outcome.status === "succeeded" && !nativeTurnRef) { outcome = { status: "failed", error: nativeError( new MiniMaxError( "protocolError", "MiniMax Code completed without a uniquely correlated durable Turn", ), ), }; } if (!this.#nativeRef) { try { if (nativeTurnRef || readHistory(this.root, this.cwd, sessionId).turns.length) { this.#nativeRef = sessionRef(sessionId, this.root); this.#stateChanged(); } } catch { /* Wait for verified durable history before publishing the Session ref. */ } } for (const snapshot of turn.items.values()) this.#event({ type: "item.completed", turnId: turn.id, snapshot }); this.#active = undefined; this.#event({ type: "turn.completed", turnId: turn.id, outcome, ...(nativeTurnRef ? { nativeTurnRef } : {}), }); if (this.#fault) this.#finishFault(); } #cancel(turn: Turn): Promise { if (turn.settled) return Promise.resolve(); if (turn.cancel) return turn.cancel; turn.cancel = this.#transport.rpc( this.#transport.connection.cancel({ sessionId: this.#sessionId! }), CANCEL_GRACE_MS, ); this.#closeInteractions(); turn.cancelTimer = setTimeout( () => this.#transport.fault( new MiniMaxError("unavailable", "MiniMax Code did not confirm Turn cancellation"), ), CANCEL_GRACE_MS, ); return turn.cancel; } #update(params: SessionNotification): void { try { this.#applyUpdate(params); } catch { this.#transport.fault( new MiniMaxError("protocolError", "Invalid MiniMax Code Session update"), ); } } #applyUpdate(params: SessionNotification): void { const update = record(params?.update); if (!update || !nativeId(params?.sessionId) || !nativeId(update.sessionUpdate)) throw new Error(); if (params.sessionId !== this.#sessionId) return; const kind = update.sessionUpdate; if (kind === "config_option_update") { if (!this.#active && !this.#nativeRef) return; if ( params.update.sessionUpdate !== "config_option_update" || !Array.isArray(params.update.configOptions) ) throw new Error(); this.#configuration = new Configuration(params.update.configOptions); if (this.#configUnsupported) this.#configuration.disableWrites(); this.#stateChanged(); return; } if (!REALTIME_KINDS.has(kind)) return; const turn = this.#active; const textKind = kind === "agent_message_chunk" || kind === "agent_thought_chunk"; const id = textKind ? update.messageId : update.toolCallId; if (!nativeId(id)) throw new Error(); const notificationKey = `${textKind ? "message" : "tool"}:${id}`; const requestId = kind === "tool_call_update" && update.status === "completed" ? questionnaireRequestId(update.rawOutput) : undefined; if (!turn || turn.settled) { this.#pastNotifications.add(notificationKey); if (requestId) this.#pastNotifications.add(`questionnaire:${requestId}`); return; } // A fresh ask_user call can reuse the model's tool ID. Its native request ID is independent. const reusedQuestionTool = !textKind && (kind === "tool_call" ? update.name === "ask_user" : turn.tools.get(id)?.name === "ask_user"); if (this.#pastNotifications.has(notificationKey) && !reusedQuestionTool) return; if (textKind) { turn.messageIds.add(id); const content = record(update.content); if (content?.type !== "text" || typeof content.text !== "string") throw new Error(); const type = kind === "agent_message_chunk" ? "agentMessage" : "reasoning"; const key = itemId(type, id); const previous = turn.items.get(key)?.item; if (previous?.type === type) { turn.items.set(key, { item: { ...previous, text: previous.text + content.text }, outcome: { status: "succeeded" }, }); this.#event({ type: "item.updated", turnId: turn.id, itemId: key, update: { type: "text.append", text: content.text }, }); } else { const item = { type, itemId: key, text: content.text } as const; turn.items.set(key, { item, outcome: { status: "succeeded" } }); this.#event({ type: "item.started", turnId: turn.id, item }); } return; } const previous = turn.tools.get(id); const current = { ...previous, ...update }; turn.tools.set(id, current); const status = current.status; if ( previous?.name === "ask_user" && requestId && !this.#pastNotifications.has(`questionnaire:${requestId}`) ) { const observedCall = turn.questionnaireCalls.get(requestId); if (observedCall && observedCall !== id) throw new Error(); turn.questionnaireCalls.set(requestId, id); } const outcome: HostItemOutcome = status === "failed" ? { status: "failed", error: nativeError(undefined) } : status === "completed" ? { status: "succeeded" } : { status: "cancelled" }; for (const item of toolItems(id, current, this.cwd)) { const previousItem = turn.items.get(item.itemId)?.item; turn.items.set(item.itemId, { item, outcome }); if (!previousItem) this.#event({ type: "item.started", turnId: turn.id, item }); else if (item.type === "toolExecution" && item.output) this.#event({ type: "item.updated", turnId: turn.id, itemId: item.itemId, update: { type: "output.replace", output: item.output }, }); else if (item.type === "fileChange") this.#event({ type: "item.updated", turnId: turn.id, itemId: item.itemId, update: { type: "fileChanges.replace", changes: item.changes }, }); } } #permission( params: RequestPermissionRequest, ): Promise | RequestPermissionResponse { const turn = this.#active; if ( !turn || turn.settled || this.#closing || turn.cancel || params?.sessionId !== this.#sessionId ) return CANCELLED_PERMISSION; if (!Array.isArray(params.options) || !nativeId(params.toolCall?.toolCallId)) { this.#transport.fault( new MiniMaxError("protocolError", "Invalid MiniMax Code Approval request"), ); return CANCELLED_PERMISSION; } const actions: HostApprovalInteraction["actions"] = []; const used = new Set(); for (const option of params.options) { if (!nativeId(option?.optionId) || !nativeId(option?.name) || used.has(option.optionId)) { this.#transport.fault( new MiniMaxError("protocolError", "Invalid MiniMax Code Approval options"), ); return CANCELLED_PERMISSION; } used.add(option.optionId); let effect: HostApprovalEffect; switch (option.kind) { case "allow_once": effect = "allowOnce"; break; case "allow_always": effect = "allowAlways"; break; case "reject_once": case "reject_always": effect = "deny"; break; default: continue; } actions.push({ id: option.optionId, label: option.name, effect }); } if (!actions.length) return CANCELLED_PERMISSION; const interactionId = hostInteractionIdSchema.parse(randomUUID()); const interaction: HostApprovalInteraction = { type: "approval", interactionId, turnId: turn.id, title: nativeId(params.toolCall.title) ? params.toolCall.title : "MiniMax Code requests permission", subject: { type: "nativeAction" }, actions, }; return new Promise((resolve) => { this.#addInteraction({ interaction, respond: (response) => { if (response.type === "approval") resolve({ outcome: { outcome: "selected", optionId: response.actionId } }); }, cancel: () => resolve(CANCELLED_PERMISSION), }); }); } async #waitForQuestionnaire(turn: Turn, sessionId: string, signal: AbortSignal): Promise { const deadline = performance.now() + QUESTION_READY_MS; // MiniMax Code 0.7.1 can queue a reply it cannot admit while the original Turn is active. // The request ID arrives in a separate tool update, sometimes after the form request. do { signal.throwIfAborted(); const calls = [...turn.questionnaireCalls].filter( ([id]) => !turn.submittedQuestionnaires.has(id), ); if (calls.length > 1) throw new MiniMaxError("protocolError", "MiniMax Code Questionnaire identity is ambiguous"); const [call] = calls; if (call) { try { const ready = correlatedTurn( this.root, this.cwd, sessionId, turn.messageIds, new Map([call]), "completed", ); if (ready) return call[0]; } catch (error) { if (!(error instanceof MiniMaxError) || error.code !== "sessionNotFound") throw error; } } await delay(25); } while (performance.now() < deadline); signal.throwIfAborted(); throw new MiniMaxError( "unavailable", "MiniMax Code did not confirm it was ready for the Question response", ); } #question( params: CreateElicitationRequest, ): Promise | CreateElicitationResponse { const turn = this.#active; const sessionId = this.#sessionId; if ( !turn || turn.settled || this.#closing || turn.cancel || !sessionId || !params || !("sessionId" in params) || params.sessionId !== sessionId ) return { action: "cancel" }; const fields = questionnaire(params); if ( !fields || [...this.#interactions.values()].some(({ interaction }) => interaction.type === "question") ) return { action: "decline" }; const abort = new AbortController(); const interaction: HostQuestionInteraction = { type: "question", interactionId: hostInteractionIdSchema.parse(randomUUID()), turnId: turn.id, title: nativeId(params.message) ? params.message : "MiniMax Code needs your input", questions: fields.map(({ question }) => question), }; return new Promise((resolve) => { this.#addInteraction({ interaction, respond: async (response) => { if (response.type !== "question") return; const answer = questionnaireResponse(fields, response); if (answer.action === "accept") { const requestId = await this.#waitForQuestionnaire(turn, sessionId, abort.signal); abort.signal.throwIfAborted(); turn.submittedQuestionnaires.add(requestId); } resolve(answer); }, cancel: () => { abort.abort( new MiniMaxError("invalidState", "MiniMax Code Question is no longer active"), ); resolve({ action: "cancel" }); }, }); }); } #addInteraction(pending: PendingInteraction): void { this.#interactions.set(pending.interaction.interactionId, pending); this.#output.emit({ kind: "interaction", interaction: pending.interaction }); } #closeInteraction(interaction: HostInteraction, reason: InteractionClosedEvent["reason"]): void { const { interactionId, turnId } = interaction; this.#interactions.delete(interactionId); this.#event({ type: "interaction.closed", interactionId, turnId, reason }); } #closeInteractions(): void { for (const pending of this.#interactions.values()) { pending.cancel(); this.#closeInteraction(pending.interaction, "cancelled"); } } #finishFault(): void { if (this.#fault) this.#event({ type: "session.faulted", error: nativeError(this.#fault) }); void this.close(); } close(): Promise { this.#closing ??= this.#close(); return this.#closing; } async #close(): Promise { const turn = this.#active; if (turn && !this.#fault) await this.#cancel(turn).catch(() => {}); if (turn) await turn.done; this.#closeInteractions(); await this.#transport.close(this.#closeSession ? this.#sessionId : undefined); this.#output.end(); this.onClose(); } }