// Typed access to the existing WebSocket protocol. Request builders and id // matching live here so the app never constructs frames by hand or invents // divergent field names. Mirrors android/.../data/PipelinesRepository.kt. import { ChatKeys, Protocol } from "./protocol.js"; import { ProtocolError } from "./client.js"; import { DECISIONS } from "./chat.js"; /** The server default history page the app asks for (CHAT_HISTORY_LIMIT, 200). */ export const CHAT_HISTORY_LIMIT = 200; /** * The label this browser client records with a permission answer, so every other * watching client can see which device resolved the request (the Android analogue * is the device name). It is always sent; the server records it with the outcome. */ export const WEB_CHAT_CLIENT = "Web"; /** * The largest shell-output page the server accepts (ChatShellOutputLimit, * 64 KiB). The browser always reads from the page's start and never sends more * than this, so a background task's output can never grow unbounded on the * client. */ export const SHELL_OUTPUT_LIMIT = 64 << 10; export class PipelinesRepository { #client; constructor(client) { this.#client = client; } get connectionState() { return this.#client.state; } connect(validated) { this.#client.connect(validated); } disconnect() { this.#client.disconnect(); } ping() { return this.#client.call({ type: Protocol.PING }); } async listPipelines() { return (await this.#client.call({ type: Protocol.LIST })).pipelines ?? []; } async getPipeline(id, version) { const response = await this.#client.call({ type: Protocol.GET_PIPELINE, pipeline_id: id, version, }); if (!response.detail) { throw new ProtocolError("The server returned no pipeline detail."); } return response.detail; } async listTemplates() { return (await this.#client.call({ type: Protocol.LIST_TEMPLATES })).templates ?? []; } async validate(source) { const response = await this.#client.call({ type: Protocol.VALIDATE, source }); // A server error envelope already rejects inside client.call, so a reply // here is `validated`; a missing graph is still an unusable definition. if (!response.graph) { throw new ProtocolError("The server returned no graph."); } return response.graph; } /** * Creates a new pipeline from a definition `source` (the `submit` command), * create-only, mirroring `PipelinesRepository.createPipeline`: the name must * not already exist, so this can only ever add a draft and never overwrite a * retained pipeline. A blank name is refused before anything is sent, exactly * like the Android client; the sent name is trimmed. No run is started. */ async submit(name, source) { if (!String(name ?? "").trim()) { throw new ProtocolError("Enter a pipeline name."); } const response = await this.#client.call({ type: Protocol.SUBMIT, name: String(name).trim(), source, create_only: true, }); if (!response.detail) { throw new ProtocolError("The server returned no pipeline detail."); } return response.detail; } async listRuns() { const response = await this.#client.call({ type: Protocol.LIST_RUNS }); return { runs: response.runs ?? [], usage: response.usage ?? null }; } async listSchedules(pipelineId = null) { const request = { type: Protocol.LIST_SCHEDULES }; if (pipelineId != null) { if (!Number.isSafeInteger(pipelineId) || pipelineId < 1) throw new ProtocolError("A positive pipeline ID is required."); request.pipeline_id = pipelineId; } const response = await this.#client.call(request); if (response.type !== Protocol.SCHEDULES || (response.schedules != null && !Array.isArray(response.schedules))) { throw new ProtocolError("The server returned no schedules response."); } return response.schedules ?? []; } async saveSchedule(schedule, { requestKey } = {}) { if (!schedule || typeof schedule !== "object" || Array.isArray(schedule)) throw new ProtocolError("A saved schedule is required."); if (requestKey != null && (typeof requestKey !== "string" || requestKey.length > 128)) throw new ProtocolError("Schedule request keys must be strings of at most 128 characters."); const request = { type: Protocol.SAVE_SCHEDULE, schedule }; if (requestKey) request.request_key = requestKey; const response = await this.#client.call(request); if (!response.schedule) throw new ProtocolError("The server returned no saved schedule."); return response.schedule; } async deleteSchedule(id, revision) { if (!Number.isSafeInteger(id) || id < 1 || !Number.isSafeInteger(revision) || revision < 1) { throw new ProtocolError("An exact schedule ID and revision are required."); } const response = await this.#client.call({type:Protocol.DELETE_SCHEDULE,schedule_id:id,expected_revision:revision}); if (response.type !== Protocol.SCHEDULE_DELETED || response.schedule_id !== id) throw new ProtocolError("The server did not confirm deletion of this schedule."); } async getRun(id) { const response = await this.#client.call({ type: Protocol.GET_RUN, run_id: id, }); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } /** Export the exact recorded visit again; never invokes its model or tools. */ async repairSessionExport(id, sequence) { if (!Number.isSafeInteger(id) || id<1 || !Number.isSafeInteger(sequence) || sequence<1) throw new ProtocolError("An exact run and visit are required."); const response=await this.#client.call({type:Protocol.REPAIR_SESSION_EXPORT,run_id:id,export_sequence:sequence}); if (!response.run_detail) throw new ProtocolError("The server returned no run detail."); return response.run_detail; } /** * Asks the server to push this connection the live run state it displays * (R10, also the source of L5's notifications). Send-only, mirroring * `PipelinesRepository.subscribeRuns`: it returns the generated frame id and * never waits for a reply, because the server may not acknowledge a * `subscribe`. The body is exactly `{type:'subscribe', workspace}`; `run_ids` * rides only when ids are given, so a blank workspace with no ids asks for the * server-wide "any workspace" scope — the same `runIds.ifEmpty { null }` shape * the Android client sends. The pushed state arrives as unsolicited * `run_event` frames (client.js surfaces them as `frame` events). */ subscribeRuns(workspace = "", runIds = []) { const request = { type: Protocol.SUBSCRIBE, workspace: String(workspace ?? "") }; if (Array.isArray(runIds) && runIds.length > 0) request.run_ids = runIds; return this.#client.sendOnly(request); } /** * Drops this connection's run-event watch (R10). Send-only like `subscribe`: * the server may ack it, but nothing is awaited. It stops the pushes; a later * `subscribe` re-reads the current state. */ unsubscribeRuns() { return this.#client.sendOnly({ type: Protocol.UNSUBSCRIBE }); } /** * Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from * internal/protocol/search.go: `kind` is the empty string for every kind, and * `limit` is fixed at `0` so the server applies its own default cap * (`SearchDefaultLimit`, 50) and never the client's — `SearchMaxLimit` (200) is * therefore never approached, let alone exceeded. * * Returns `reply.search_results`, the ranked `SearchResponse`, or **null** when * an older server answered without that payload (its default `pong`), which the * caller reports as "this server does not support search" rather than dropping. * An explicit server error is already surfaced by `client.call` as a * `ProtocolError` carrying the server's own text. */ async search(query, kind = "") { const response = await this.#client.call({ type: Protocol.SEARCH, search: { query, kind, limit: 0 }, }); return response.search_results ?? null; } /** * Answers a run's waiting human stage with the chosen `option` and optional * `feedback` (mirrors PipelinesRepository.decideRun). The stage is sent only * when non-blank and the feedback is trimmed, exactly like the Android client; * a refused decision rejects with the server's own reason (a ProtocolError). */ async decideRun(id, { stage, option, feedback } = {}) { const request = { type: Protocol.DECIDE_RUN, run_id: id, option }; if (stage != null && String(stage).trim() !== "") request.stage = stage; const trimmedFeedback = String(feedback ?? "").trim(); if (trimmedFeedback !== "") request.feedback = trimmedFeedback; const response = await this.#client.call(request); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } /** Cancels a run; mirrors PipelinesRepository.cancelRun (exactly run_id). */ /** * Starts a fresh run of one pipeline version. `notifyMode` is auto, on or off; * auto omits the field so the pipeline definition applies. */ async runPipeline({ pipelineId, version, prompt, workspace, notifyMode = "auto", title = "", outputFormat = "", requestKey = newChatOperationId() } = {}) { const request = { type: Protocol.RUN_PIPELINE, pipeline_id: Number(pipelineId), version: Number(version), request_key: requestKey, workspace: String(workspace ?? "").trim(), input: { prompt: String(prompt ?? "") }, }; if (String(title ?? "").trim() !== "") request.title = String(title).trim(); if (outputFormat) request.output_format = outputFormat; const mode = String(notifyMode ?? "auto").trim().toLowerCase(); if (mode === "on" || mode === "off") request.notify_mode = mode; const response = await this.#client.call(request); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } /** Read-only admission reconciliation after a lost launch response. */ async runByRequestKey(requestKey) { if (!String(requestKey ?? "").trim()) throw new ProtocolError("A launch request key is required."); const response = await this.#client.call({ type: Protocol.GET_RUN, request_key: requestKey }); return response.run_detail ?? null; } async cancelRun(id) { const response = await this.#client.call({ type: Protocol.CANCEL_RUN, run_id: id }); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } /** * Retries a terminal failed run. `request_key` is always sent (the retry is * its own idempotent run); `retry_mode` is sent only for an explicit * `restart`, so the server's default (resume) applies exactly as the Android * client's mode-less call. */ async retryRun(id, { mode = null, requestKey } = {}) { const request = { type: Protocol.RETRY_RUN, run_id: id, request_key: requestKey ?? "", }; if (mode === "restart") request.retry_mode = "restart"; const response = await this.#client.call(request); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } /** Renames a run's stored title; mirrors the set_run_title wire command. */ async setRunTitle(id, title) { const response = await this.#client.call({ type: Protocol.SET_RUN_TITLE, run_id: id, title, }); if (!response.run_detail) { throw new ProtocolError("The server returned no run detail."); } return response.run_detail; } // ---- Brokered OpenCode chat (C1/C3/C4) ----------------------------------- // The browser never speaks OpenCode directly and never holds its credentials; // it talks only to the Pipelines server. Mirrors PipelinesRepository.chat*. /** * Lists the sessions this server owns. The server already returns operator * sessions only, so the app never filters the list by ownership. */ async chatSessions() { return (await this.#client.call({ type: Protocol.CHAT_SESSIONS }))[ChatKeys.SESSIONS] ?? []; } /** The installed chat harnesses a new session can use. */ async chatBackends() { return (await this.#client.call({ type: Protocol.CHAT_BACKENDS }))[ChatKeys.BACKENDS] ?? ["opencode"]; } /** The models the session's harness offers for switching. */ async chatModels(sessionId) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } const response = await this.#client.call({ type: Protocol.CHAT_MODELS, [ChatKeys.QUERY]: { session_id: sessionId }, }); return response[ChatKeys.MODELS] ?? []; } /** Switch one session's model for subsequent turns. */ async switchChatModel(sessionId, provider, model) { const session = String(sessionId ?? "").trim(); const providerId = String(provider ?? "").trim(); const modelId = String(model ?? "").trim(); if (session === "") throw new ProtocolError("Select a chat session first."); if (providerId === "" || modelId === "") throw new ProtocolError("Choose a model first."); const response = await this.#client.call({ type: Protocol.CHAT_MODEL, [ChatKeys.MODEL]: { session_id: session, provider: providerId, model: modelId }, }); return response[ChatKeys.MODEL] ?? { session_id: session, provider: providerId, model: modelId }; } /** * Loads a bounded chronological history page. `cursor` is the opaque * continuation the server returned as `next_cursor`; it is passed back * verbatim and never interpreted. The reply is `chat_history` * (`{messages,next_cursor,has_more}`); an older server that only knows * `chat_messages` exposes no continuation, so the page is that list with * `hasMore:false` and an empty cursor — exactly like * PipelinesRepository.chatMessages. */ async chatHistory(sessionId, { limit = CHAT_HISTORY_LIMIT, cursor = "" } = {}) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } const response = await this.#client.call({ type: Protocol.CHAT_MESSAGES, [ChatKeys.QUERY]: { session_id: sessionId, limit, cursor }, }); const page = response[ChatKeys.HISTORY]; if (page) { return { messages: page.messages ?? [], nextCursor: page.next_cursor ?? "", hasMore: Boolean(page.has_more), }; } return { messages: response[ChatKeys.MESSAGES] ?? [], nextCursor: "", hasMore: false }; } /** * Attaches this connection to one session's shared live stream (C5). The body * is exactly `{type:'chat_subscribe', chat_subscribe:{session_id}}` — the * `chat_subscribe` field, not `chat_query` (internal/protocol/message.go); the * server replies with an id-matched echo once the subscription is attached and * then pushes `chat_event` frames without an id, which `client.js` surfaces as a * `frame` event. Any number of clients may watch one session; the session is * never read-only. There is no `chat_unsubscribe`: the server drops a * subscription when the connection closes. */ async subscribeChat(sessionId) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } return this.#client.call({ type: Protocol.CHAT_SUBSCRIBE, [ChatKeys.SUBSCRIBE]: { session_id: sessionId }, }); } /** * Lists the currently verified shells this operator chat session owns (C11), * so the conversation can show a background-tasks bar while one is running. * The body is the session-scoped `chat_query` (like chat_messages); the reply * is `chat_shells`, and an older server that returns none answers with an empty * list. A blank session id is refused here, exactly like * PipelinesRepository.chatShells. */ async chatShells(sessionId) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } const response = await this.#client.call({ type: Protocol.CHAT_SHELLS, [ChatKeys.QUERY]: { session_id: sessionId }, }); return response[ChatKeys.SHELLS] ?? []; } /** * Reads one bounded output page from a verified shell (C11), mirroring * PipelinesRepository.chatShellOutput. The body is exactly * `chat_shell_output_query` — {session_id, shell_id, cursor, limit}, **not** the * `chat_query` the other session commands use — with the cursor always sent so * a refresh rereads from the page's start rather than appending. A blank * session/shell, an out-of-bounds cursor/limit or a reply with no page is * refused with the same reason the Android client uses. */ async chatShellOutput(sessionId, shellId, { cursor = 0, limit = SHELL_OUTPUT_LIMIT } = {}) { if (!String(sessionId ?? "").trim() || !String(shellId ?? "").trim()) { throw new ProtocolError("Select a shell first."); } if (!(cursor >= 0) || !(limit > 0) || limit > SHELL_OUTPUT_LIMIT) { throw new ProtocolError("Shell output bounds are invalid."); } const response = await this.#client.call({ type: Protocol.CHAT_SHELL_OUTPUT, [ChatKeys.SHELL_OUTPUT_QUERY]: { session_id: sessionId, shell_id: shellId, cursor, limit, }, }); const page = response[ChatKeys.SHELL_OUTPUT]; if (!page) { throw new ProtocolError("The server returned no shell output page."); } return page; } /** * Finishes a session and records it closed on the server (nothing is * deleted). The reply echoes the updated session (`chat_session`) and the * close outcome (`chat_close`: the id, the close time and whether an * in-flight turn was interrupted). */ async closeChat(sessionId) { const response = await this.#client.call({ type: Protocol.CHAT_CLOSE, [ChatKeys.QUERY]: { session_id: sessionId }, }); return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null }; } /** * Records the shared star on the server (chat_star), so every browser and * device lists the same Starred group. Returns the updated session row. */ async starChat(sessionId, starred) { const response = await this.#client.call({ type: Protocol.CHAT_STAR, [ChatKeys.QUERY]: { session_id: sessionId, starred: Boolean(starred) }, }); return response[ChatKeys.SESSION] ?? null; } /** * Answers one OpenCode form (the question tool's form). Answers is keyed by * the form field key; the server forwards it to the paused tool call and the * resolved form arrives on the normal chat_event stream. */ async answerChatForm(sessionId, formId, answers, action = "") { return this.#client.call({ type: Protocol.CHAT_ANSWER, [ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers, ...(action ? {action} : {}) }, }); } /** * Records the shared chat title on the server (chat_rename), so every browser * and device lists the same name. Returns the updated session row. */ async renameChat(sessionId, title) { const response = await this.#client.call({ type: Protocol.CHAT_RENAME, [ChatKeys.RENAME]: { session_id: sessionId, title: String(title ?? "").trim() }, }); return response[ChatKeys.SESSION] ?? null; } /** Clears the closed state again, so a finished chat can be resumed. */ async reopenChat(sessionId) { const response = await this.#client.call({ type: Protocol.CHAT_REOPEN, [ChatKeys.QUERY]: { session_id: sessionId }, }); return { session: response[ChatKeys.SESSION] ?? null, close: response[ChatKeys.CLOSE] ?? null }; } // ---- The composer's own commands (C8/C9) --------------------------------- // Mirrors PipelinesRepository.chatPrompt / chatInterrupt / chatCreate. /** * Sends one prompt with its attached file references (mirrors * `PipelinesRepository.chatPrompt`): a blank session or blank text is refused * here rather than sent, the text is trimmed, and `files` is **omitted** when * empty (the shape a text-only prompt has always sent — the Android * `ChatPromptRequest.Files` is `omitempty` too). `operation_id` is the durable * idempotency key for this send. Returns true when the server queued the * prompt behind an in-flight turn (`chat_queued` on the reply), which is the * one signal the composer's queued notice is derived from. * * Browser attachments travel in `attachments` as {name,mime,data} with data * encoded as standard base64. The server writes them to private temporary * files and hands those file:// references to OpenCode; `files` remains the * legacy reference-only field for older clients. */ async chatPrompt(sessionId, text, files = [], operationId = newChatOperationId(), attachments = []) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } const trimmed = String(text ?? "").trim(); if (trimmed === "") { throw new ProtocolError("Enter a message before sending."); } const body = { session_id: sessionId, text: trimmed, operation_id: operationId, native_message_id: nativeChatMessageId(operationId), }; if (files.length > 0) body.files = files; if (attachments.length > 0) body.attachments = attachments; const response = await this.#client.call({ type: Protocol.CHAT_PROMPT, [ChatKeys.PROMPT]: body }); return Boolean(response[ChatKeys.QUEUED]); } /** * Aborts the in-flight turn for a session (mirrors * `PipelinesRepository.chatInterrupt`). The body is the session-scoped * `chat_query`, exactly like the other session commands. */ async chatInterrupt(sessionId) { if (!String(sessionId ?? "").trim()) { throw new ProtocolError("Select a chat session first."); } await this.#client.call({ type: Protocol.CHAT_INTERRUPT, [ChatKeys.QUERY]: { session_id: sessionId }, }); } /** * Lists the directories a new chat can live in (C2), mirroring * `PipelinesRepository.chatDirectories`: a bare `{type:'chat_directories'}` with * no body, replying in `chat_directories` (home first, then recent operator * directories). An older server that returns no field answers with an empty * list; the view still offers home so the picker is never empty. */ async chatDirectories() { const response = await this.#client.call({ type: Protocol.CHAT_DIRECTORIES }); return response[ChatKeys.DIRECTORIES] ?? []; } /** * Creates one session in an explicit directory (mirrors * `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is * never created in whatever directory the server happens to be running in. The * reply's `chat_session` is returned, or a `ProtocolError` when the server did * not return one. * * `ephemeral` creates a verification chat: the server makes and bootstraps the * session but records no operator-registry row, so the chat never appears in * `chat_sessions` for the operator. Automated checks that drive this real page * set it, so a run can never leave a stray "New chat" in the operator's list. */ async chatCreate(title, directory, operationId = newChatOperationId(), { backend = "opencode", ephemeral = false, instructions = "" } = {}) { const response = await this.#client.call({ type: Protocol.CHAT_CREATE, [ChatKeys.CREATE]: { title, directory, operation_id: operationId, ...(backend && backend !== "opencode" ? { backend } : {}), ...(ephemeral ? { ephemeral: true } : {}), ...(String(instructions ?? "").trim() !== "" ? { instructions: String(instructions).trim() } : {}), }, }); const session = response[ChatKeys.SESSION]; if (!session) { throw new ProtocolError("The server did not return the new chat session."); } return session; } /** * Answers one pending permission request (C10). Sends exactly * `{type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}` — * `message` rides only when non-blank (mirrors ChatReplyRequest's omitempty). * A blank session/request/decision, or a decision outside `once`/`always`/ * `reject`, is refused here before anything is sent, so an unaccepted decision * can never reach the server. The server pushes the shared resolution back to * every watching client once the first answer is recorded. */ async chatReply(sessionId, requestId, decision, { message = "", client = WEB_CHAT_CLIENT } = {}) { const session = String(sessionId ?? "").trim(); const request = String(requestId ?? "").trim(); const chosen = String(decision ?? "").trim(); if (session === "") throw new ProtocolError("Select a chat session first."); if (request === "") { throw new ProtocolError("This approval request is no longer available."); } if (!DECISIONS.includes(chosen)) { throw new ProtocolError("Choose once, always or reject."); } const body = { session_id: session, request_id: request, decision: chosen, client: String(client ?? "").trim() || WEB_CHAT_CLIENT, }; const trimmed = String(message ?? "").trim(); if (trimmed !== "") body.message = trimmed; await this.#client.call({ type: Protocol.CHAT_REPLY, [ChatKeys.REPLY]: body }); } } /** * A durable operation id for one chat request intent, retaining the shape of the * Android `newRequestKey`/`newChatCreateOperationId` (a client-prefixed opaque * key). One create/send keeps its id across a retry so the server can dedupe it. */ export function newChatOperationId() { const random = Math.random().toString(36).slice(2, 10); return `web-chat-${Date.now().toString(36)}-${random}`; } /** * The OpenCode message identity carried with a prompt, mirroring the Android * `nativeMessageId`: the operation id's alphanumerics, prefixed `msg_` and capped * at 120 characters. OpenCode persists it in history, so the live user echo and * an authoritative history page can be reconciled; a blank operation id yields an * empty id (the server then supplies its own). */ export function nativeChatMessageId(operationId) { const compact = String(operationId ?? "") .replace(/[^A-Za-z0-9]/g, "") .slice(0, 120); return compact === "" ? "" : `msg_${compact}`; }