import { realpath } from "node:fs/promises"; import { setTimeout as delay } from "node:timers/promises"; import { z } from "zod"; import { chatRequests, chatSummarySchema, utf16Length, type ChatOperation, type ChatStreamTarget, type VoiceTarget } from "@openremotecode/protocol"; import { ChatAccessError, ChatUnsupportedError, type ChatAdapter } from "../chat-adapter.js"; import { AnsweredQuestionMemory } from "../chat/answered-questions.js"; import type { ChatStreamReader } from "../chat-stream.js"; import { CursorStore } from "../chat/cursor.js"; import { WorkspaceRegistry, type Workspace } from "../chat/workspace.js"; import type { OpenCodeClient, RequestOptions } from "./client.js"; import { openCodeEvents } from "./event-source.js"; import { buildModels, modelEffortLevels } from "./models.js"; import { fetchPendingQuestion, replyToQuestion } from "./questions.js"; import { buildSnapshot, sessionStatus } from "./snapshot.js"; import type { ChatListReader } from "../chat-list-stream.js"; import { SessionContinuity } from "./session-continuity.js"; // Events fatal to the whole connection, not just one session. const FATAL_EVENT = "location.shutdown"; // The adapter grows one operation at a time. Anything not listed here is not advertised in // the connector's capabilities and, if a client sends it anyway, fails as unsupported_operation. const OPERATIONS = ["project.list", "project.open", "chat.list", "chat.create", "chat.get", "chat.fork", "chat.delete", "chat.snapshot", "chat.subtask.snapshot", "chat.models", "chat.prompt", "chat.abort", "chat.permission.reply", "chat.question.reply", "chat.view"] as const satisfies readonly ChatOperation[]; type Supported = (typeof OPERATIONS)[number] // Capabilities that are not operations: what a snapshot may carry when the client opts in. const CAPABILITIES: readonly string[] = [...OPERATIONS, "chat.permissions", "chat.tools", "chat.shell", "chat.code", "chat.questions", "chat.activities", "chat.images", "chat.prompt.mode", "chat.prompt.model"]; const DEADLINE_MS = 10_000; const PAGE_SIZE = 50; // The content opt-ins a subscription may negotiate, forwarded verbatim into every stream // read. includeTodos is deliberately absent: the snapshot refuses it, and a stream must not fail over // a flag the connector never advertised. const STREAM_OPT_INS = ["includeTools", "includeShell", "includeCode", "includeActivities", "includeSubtasks", "includeImages", "includePermissions", "includeQuestions"] as const satisfies readonly (keyof ChatStreamTarget)[]; /// OpenCode nests an event's session in different places: some carry it at the top of `data`, /// others only inside the `part` or `info` they are about. Matching just one of those would drop /// every message-level event and leave a chat that only refreshes when the session itself /// changes. function eventSessionId(event: { data?: Record }): string | undefined { const data = event.data; if (!data) return undefined; const nested = (value: unknown): string | undefined => typeof value === "object" && value !== null && typeof (value as { sessionID?: unknown }).sessionID === "string" ? (value as { sessionID: string }).sessionID : undefined; if (typeof data.sessionID === "string") return data.sessionID; const info = data.info; return nested(data.part) ?? nested(info) ?? (typeof (info as { id?: unknown } | undefined)?.id === "string" ? (info as { id: string }).id : undefined); } const session = z.object({ id: z.string().check(utf16Length(1, 256)), title: z.string().optional(), parentID: z.string().check(utf16Length(1, 256)).optional(), fork: z.object({ sessionID: z.string().check(utf16Length(1, 256)) }).loose().optional(), // The session's current agent and model, when the server reports them. Read only to avoid a // redundant switch. agent: z.string().check(utf16Length(0, 128)).optional(), model: z.object({ id: z.string(), providerID: z.string(), variant: z.string().optional() }).loose().optional(), time: z.object({ updated: z.number().int().nonnegative(), idle: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(), viewed: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional() }), outcome: z.enum(["succeeded", "failed", "interrupted"]).optional(), location: z.object({ directory: z.string().min(1) }), }); const page = z.object({ data: z.array(session).max(PAGE_SIZE), cursor: z.object({ next: z.string().check(utf16Length(0, 16_000)).nullish() }), }); const active = z.record(z.string(), z.object({ type: z.string() }).loose()); const listCursor = z.object({ exhausted: z.boolean().optional(), native: z.string().optional(), remaining: z.array(z.string()).max(2048).optional() }); export function toChatSummary(value: z.infer, status?: "idle" | "busy" | "retry" | "unknown") { return chatSummarySchema.parse({ id: value.id, title: (value.title ?? "New chat").slice(0, 512), updatedAt: value.time.updated, ...(value.parentID ? { parentId: value.parentID } : {}), ...(status !== undefined || value.time.idle !== undefined ? { activity: { status: status ?? "unknown", ...(value.time.idle !== undefined ? { idleAt: value.time.idle } : {}), ...(value.time.viewed !== undefined ? { viewedAt: value.time.viewed } : {}), ...(value.outcome !== undefined ? { outcome: value.outcome } : {}), } } : {}), }); } /// Chat operations for OpenCode, over the client the TUI plugin context provides. That client /// addresses the same local instance the TUI is attached to; no listener is opened and no /// credential is read from disk. export class OpenCodeChatAdapter implements ChatAdapter, ChatStreamReader { get capabilities(): readonly string[] { const client: Partial = this.#client; return CAPABILITIES.filter((c) => c !== "chat.view" || typeof client.session?.view === "function"); } readonly listReader: ChatListReader = { watch: (projects, signal, changed) => this.#watchList(projects, signal, changed), read: (projects, ids, signal) => this.#readListChanges(projects, ids, signal), }; readonly #client: OpenCodeClient; readonly #registry: WorkspaceRegistry; readonly #cursors = new CursorStore(); readonly #answeredQuestions = new AnsweredQuestionMemory(); readonly #continuity = new SessionContinuity(); readonly #localSessions: ((workspace: Workspace) => readonly string[] | Promise) | undefined; constructor(client: OpenCodeClient, directory: string, additionalDirectories: unknown = [], registry?: WorkspaceRegistry, localSessions?: (workspace: Workspace) => readonly string[] | Promise) { this.#client = client; this.#registry = registry ?? new WorkspaceRegistry(directory, additionalDirectories); this.#localSessions = localSessions; } /// Local host events only schedule authoritative re-reads. Unknown event IDs grant nothing. observeEvent(event: { type: string; data?: Record }): void { if (event.type === "session.moved") { const id = eventSessionId(event); if (id) this.#continuity.moved(id); } if (event.type === "server.connected") this.#continuity.moved(); if (event.type === "session.deleted") { const id = eventSessionId(event); if (id) this.#continuity.forget(id); } } async execute(operation: ChatOperation, body: Record, cancellation?: AbortSignal): Promise { if (!Object.hasOwn(chatRequests, operation)) throw new ChatUnsupportedError(operation); if (!(OPERATIONS as readonly string[]).includes(operation)) throw new ChatUnsupportedError(operation); const result = await this.#run(operation as Supported, body, cancellation); // Do not return content fetched while a local user disabled the folder. // Mutations already admitted to OpenCode are not undone or automatically retried. if (["chat.list", "chat.get", "chat.models", "chat.snapshot", "chat.subtask.snapshot"].includes(operation)) { await this.#registry.get(body.projectId); } return result; } async authorizeVoice(target: VoiceTarget, signal: AbortSignal): Promise { const workspace = await this.#registry.get(target.projectId); if (target.sessionId !== undefined) { const owned = await this.#owned(workspace, target.sessionId, this.#deadline(signal)); if (owned.parentID) throw new ChatAccessError("access_denied"); await this.#continuity.authorize(owned, workspace); } await this.#registry.get(target.projectId); signal.throwIfAborted(); } async #run(operation: Supported, body: Record, cancellation?: AbortSignal): Promise { if (operation === "project.list") { const projects = await this.#registry.listVerified(); return { version: 1, projects: projects.map((w) => this.#registry.public(w)), pathEntry: false }; } if (operation === "project.open") { const workspace = await this.#registry.resolvePath(String(body.path)); return { version: 1, project: this.#registry.public(workspace) }; } const workspace = await this.#registry.get(body.projectId); const deadline = this.#deadline(cancellation); const options = (): RequestOptions => ({ signal: deadline }); if (operation === "chat.models") return buildModels(this.#client, workspace.path, options().signal); if (operation === "chat.list") { return this.#list(workspace, body, deadline); } if (operation === "chat.create") { this.#continuity.ensureRoom(); const created = await this.#client.session.create({ location: { directory: workspace.path } }, options()); try { const owned = await this.#owned(workspace, session.pick({ id: true }).parse(created).id, deadline); return { version: 1, chat: toChatSummary(owned) }; } catch { // Creation already ran; even a concurrent capacity/authorization change is uncertain, // not a definitive refusal that could invite an automatic duplicate create. throw new Error("Created chat could not be confirmed"); } } const sessionId = String(body.sessionId); let parentWorkspace = workspace; if (operation === "chat.subtask.snapshot") { const parent = await this.#owned(workspace, String(body.parentSessionId), deadline); if (parent.parentID) throw new ChatAccessError("access_denied"); parentWorkspace = await this.#continuity.authorize(parent, workspace); } const owned = await this.#owned(parentWorkspace, sessionId, options().signal); const currentWorkspace = await this.#continuity.authorize(owned, parentWorkspace); if (operation === "chat.subtask.snapshot") { const parentSessionId = String(body.parentSessionId); // A subtask is reachable only through its own claimed parent, never as an independent chat. if (owned.parentID !== parentSessionId) throw new ChatAccessError("access_denied"); const snapshot = chatRequests["chat.subtask.snapshot"].parse(body); const signal = this.#deadline(cancellation); return buildSnapshot({ client: this.#client, cursors: this.#cursors, workspace: currentWorkspace, chat: toChatSummary(owned), sessionId, body: snapshot, signal, operation, answeredQuestions: this.#answeredQuestions.get(sessionId), recheck: async () => { await this.#registry.get(workspace.id); const parent = await this.#owned(workspace, parentSessionId, signal); const current = await this.#continuity.authorize(parent, workspace); if ((await this.#owned(current, sessionId, signal)).parentID !== parentSessionId) throw new ChatAccessError("access_denied"); } }); } // Subtask sessions are reachable only through their parent's snapshot, never directly. if (owned.parentID) throw new ChatAccessError("access_denied"); if (operation === "chat.fork" || operation === "chat.delete") { const descendants = operation === "chat.delete" ? await this.#deleteTree(currentWorkspace, sessionId, deadline) : undefined; const tree = descendants ? [...descendants.keys()] : [sessionId]; const running = active.parse(await this.#client.session.active(options())); if (tree.some((id) => running[id])) throw new ChatAccessError("chat_busy"); for (const id of tree) { const checked = await this.#owned(id === sessionId ? workspace : currentWorkspace, id, deadline); if (descendants && checked.parentID !== descendants.get(id)) throw new ChatAccessError("access_denied"); } await this.#registry.get(workspace.id); if (operation === "chat.fork") { this.#continuity.ensureRoom(); let result: unknown; try { result = await this.#client.session.fork({ sessionID: sessionId }, options()); } catch (error) { // An empty session cannot be forked. This is a definitive refusal, // not an uncertain mutation requiring the user to hunt for a fork. if (typeof error === "object" && error !== null && (error as { _tag?: unknown; kind?: unknown })._tag === "InvalidRequestError" && (error as { kind?: unknown }).kind === "empty_session") { throw new ChatAccessError("context_expired"); } throw error; } try { const fork = session.parse(result); if (fork.id === sessionId || fork.parentID || fork.fork?.sessionID !== sessionId) { throw new Error("Fork identity could not be confirmed"); } await this.#assertInWorkspace(fork, currentWorkspace); const confirmed = session.parse(await this.#client.session.get({ sessionID: fork.id }, options())); if (confirmed.id !== fork.id || confirmed.parentID || confirmed.fork?.sessionID !== sessionId) { throw new Error("Fork identity could not be confirmed"); } await this.#assertInWorkspace(confirmed, currentWorkspace); await this.#registry.get(workspace.id); this.#continuity.remember(confirmed, currentWorkspace); return { version: 1, chat: toChatSummary(confirmed) }; } catch { // The native mutation may already have happened. Even an authorization // failure here must not invite a second fork on the phone. throw new Error("Fork could not be confirmed"); } } await this.#client.session.remove({ sessionID: sessionId }, options()); try { await this.#registry.get(workspace.id); for (const id of tree) { try { await this.#client.session.get({ sessionID: id }, options()); } catch (error) { if (typeof error === "object" && error !== null && (error as { _tag?: unknown })._tag === "SessionNotFoundError") continue; throw error; } throw new Error("Deleted session is still present"); } } catch { throw new Error("Deletion could not be confirmed"); } for (const id of tree) this.#continuity.forget(id); return { version: 1, deleted: true }; } if (operation === "chat.view") { if (typeof this.#client.session.view !== "function") throw new ChatUnsupportedError(operation); const { idleAt } = chatRequests["chat.view"].parse(body); if (owned.time.idle === undefined || idleAt > owned.time.idle) throw new ChatAccessError("context_expired"); await this.#registry.get(workspace.id); await this.#client.session.view({ sessionID: sessionId, idle: idleAt }, options()); return { version: 1, accepted: true }; } if (operation === "chat.get") { const running = active.parse(await this.#client.session.active(options())); return { version: 1, chat: toChatSummary(owned, sessionStatus(running[sessionId]?.type)) }; } if (operation === "chat.snapshot") { const snapshot = chatRequests["chat.snapshot"].parse(body); const signal = this.#deadline(cancellation); return buildSnapshot({ client: this.#client, cursors: this.#cursors, workspace: currentWorkspace, chat: toChatSummary(owned), sessionId, body: snapshot, signal, operation, answeredQuestions: this.#answeredQuestions.get(sessionId), recheck: async () => { await this.#registry.get(workspace.id); if ((await this.#owned(workspace, sessionId, signal)).parentID) throw new ChatAccessError("access_denied"); } }); } if (operation === "chat.abort") { await this.#client.session.interrupt({ sessionID: sessionId }, options()); return { version: 1, accepted: true }; } if (operation === "chat.question.reply") { const reply = chatRequests["chat.question.reply"].parse(body); // A form list that cannot be read is not a question to resolve against: it fails the // reply as expired rather than reaching the agent with an unverified answer. const pending = await fetchPendingQuestion(this.#client, sessionId, options().signal).catch(() => undefined); // Resolving against the question the connector itself just observed is what keeps // client-supplied answers from reaching the agent unverified. See ADR 0011 / 0013. if (pending?.id !== reply.questionId) throw new ChatAccessError("context_expired"); await this.#registry.get(workspace.id); const { result, recorded } = await replyToQuestion(this.#client, sessionId, pending, reply, options().signal); this.#answeredQuestions.record(sessionId, recorded); return result; } if (operation === "chat.prompt") { const prompt = chatRequests["chat.prompt"].parse(body); // OpenCode's prompt carries neither an agent nor a model; switching the session's agent or // model is the only way to choose one, and each switch persists. That is equivalent here // because a client names its mode, and its model once one is picked, on every prompt, so // each turn still runs under what it asked for. A prompt that names no model runs on // whatever the session last used, which is also what the desktop TUI shows. Skipped when // the session already runs that agent or model: OpenCode records every switch in the chat's // history, and a client naming them on each prompt would otherwise leave one there per // turn. An unreported agent or model always switches -- the safe direction. See ADR 0013. const switchAgent = prompt.mode !== undefined && owned.agent !== prompt.mode; // The effort is the model's variant; omitting it selects the model's default. An agent // switch may apply that agent's own model, so a requested model is then always re-applied. const model = prompt.model; const switchModel = model !== undefined && (switchAgent || owned.model?.providerID !== model.providerID || owned.model.id !== model.modelID || owned.model.variant !== model.effort); // Validated before anything is switched, so a refused model never leaves the agent changed. // Re-checked against the current model list rather than trusted from the client, even though // the mobile client only offers ids chat.models gave it. A model or effort that is no longer // listed means the client's list is stale, and nothing has been sent: context_expired, not // an uncertain outcome. if (switchModel) { const levels = await modelEffortLevels(this.#client, currentWorkspace.path, model.providerID, model.modelID, options().signal); if (levels === undefined || (model.effort !== undefined && !levels.includes(model.effort))) { throw new ChatAccessError("context_expired"); } } // Switched first and awaited, so the turn cannot start on the old agent or model. if (switchAgent && prompt.mode !== undefined) { await this.#registry.get(workspace.id); await this.#client.session.switchAgent({ sessionID: sessionId, agent: prompt.mode }, options()); } if (switchModel) { await this.#registry.get(workspace.id); await this.#client.session.switchModel({ sessionID: sessionId, model: { id: model.modelID, providerID: model.providerID, ...(model.effort !== undefined ? { variant: model.effort } : {}) } }, options()); } await this.#registry.get(workspace.id); await this.#client.session.prompt({ sessionID: sessionId, text: prompt.text }, options()); return { version: 1, accepted: true }; } // operation === "chat.permission.reply" const reply = chatRequests["chat.permission.reply"].parse(body); // Passed through unchanged so an explicit "always" is never downgraded. await this.#client.permission.reply({ sessionID: sessionId, requestID: reply.permissionId, decision: reply.response }, options()); return { version: 1, accepted: true }; } /// Verifies membership once, then re-reads the current snapshot on every event for the target /// session. Every reconciling read goes through chat.snapshot, so no per-part live overlay is /// required. async watchChat(target: ChatStreamTarget, signal: AbortSignal, changed: (reset: boolean) => void): Promise { if (target.parentSessionId) throw new ChatUnsupportedError("chat.stream.subscribe.subtasks"); const workspace = await this.#registry.get(target.projectId); const owned = await this.#owned(workspace, target.sessionId, this.#deadline(signal)); if (owned.parentID) throw new ChatAccessError("access_denied"); signal.throwIfAborted(); const controller = new AbortController(); const watching = AbortSignal.any([signal, controller.signal]); // Cross-process local revocation must also close an idle stream, without // waiting for a model token or the phone's next renewal. No SDK polling. const monitor = (async () => { while (!watching.aborted) { await delay(1000, undefined, { signal: watching, ref: false }); await this.#registry.get(target.projectId); } })().catch(() => { controller.abort(); }); try { for await (const event of openCodeEvents(this.#client, watching)) { if (watching.aborted) break; this.observeEvent(event); // Unblocks the caller's initial read. if (event.type === "server.connected") { changed(false); continue; } if (event.type === FATAL_EVENT) throw new Error("Chat source disposed"); if (eventSessionId(event) !== target.sessionId) continue; changed(false); } } finally { controller.abort(); await monitor; } if (!signal.aborted) throw new Error("Chat event stream ended"); } async readChat(target: ChatStreamTarget, signal: AbortSignal): Promise { const { projectId, sessionId } = target; // Every content opt-in the subscription negotiated is forwarded, exactly as a direct // chat.snapshot would carry it. A stream read that quietly dropped them would deliver a // thinner snapshot than the one the same client just fetched by hand, and the client // merges updates over its own history: tools, shell, activities, images and subtasks // would disappear as soon as the stream took over, and a pending question -- read as // "none" when it was never asked for -- would become unanswerable while streaming. // includeTodos is the one exception: the snapshot refuses it outright (see buildSnapshot), and // failing the whole stream over a flag the connector never advertised would be worse // than serving the rest of the snapshot without it. return this.execute("chat.snapshot", { version: 1, projectId, sessionId, ...Object.fromEntries(STREAM_OPT_INS.filter((flag) => target[flag] === true).map((flag) => [flag, true])) }, signal); } /// One request deadline, cancelled with the caller. A read whose caller has gone away /// (an expired stream lease, an unsubscribe, a torn-down relay) stops there instead of /// holding an SDK call open for the rest of the timeout. #deadline(cancellation?: AbortSignal): AbortSignal { const timeout = AbortSignal.timeout(DEADLINE_MS); return cancellation ? AbortSignal.any([cancellation, timeout]) : timeout; } /// Collect every child the native delete will cascade to, without a directory /// filter that could hide a foreign child. Bound both the tree and pagination; /// a cycle, missing cursor or unverifiable member aborts before mutation. async #deleteTree(workspace: Workspace, rootId: string, signal: AbortSignal): Promise> { const tree = [rootId]; const seen = new Set(tree); const parents = new Map([[rootId, undefined]]); for (const parent of tree) { const cursors = new Set(); let cursor: string | undefined; for (;;) { const children = page.parse(await this.#client.session.list({ parentID: parent, limit: PAGE_SIZE, ...(cursor ? { cursor } : {}) }, { signal })); for (const child of children.data) { if (child.parentID !== parent || seen.has(child.id)) throw new ChatAccessError("access_denied"); await this.#assertInWorkspace(child, workspace); if (tree.length >= 256) throw new ChatAccessError("context_expired"); seen.add(child.id); tree.push(child.id); parents.set(child.id, parent); } if (children.data.length < PAGE_SIZE) break; const next = children.cursor.next; if (!next || cursors.has(next)) throw new ChatAccessError("context_expired"); cursors.add(next); cursor = next; } } return parents; } async #owned(workspace: Workspace, sessionId: string, signal = AbortSignal.timeout(DEADLINE_MS), locallyOpen = false): Promise> { let raw: unknown; try { raw = await this.#client.session.get({ sessionID: sessionId }, { signal }); } catch (error) { // OpenCode rejects with a plain tagged object, not an Error: { _tag: "SessionNotFoundError", ... }. if (typeof error === "object" && error !== null && (error as { _tag?: unknown })._tag === "SessionNotFoundError") { throw new ChatAccessError("chat_not_found"); } throw error; } const found = session.parse(raw); await this.#registry.get(workspace.id); // Session-by-ID lookups are not scoped to a directory, so membership is checked here. if (found.id !== sessionId) throw new ChatAccessError("access_denied"); const canAdopt = locallyOpen || !this.#continuity.knows(sessionId, workspace) && (await this.#localSessions?.(workspace))?.includes(sessionId); await this.#continuity.authorize(found, workspace, canAdopt); return found; } async #list(workspace: Workspace, body: Record, signal: AbortSignal): Promise { // Only locally open TUI tabs can seed a session that already moved before this adapter // started. A server-wide session cache is deliberately not a source of authorization. const localIds = new Set(await this.#localSessions?.(workspace) ?? []); const cursor = this.#cursors.resolve(body, workspace.id); const state = cursor ? listCursor.parse(JSON.parse(cursor)) : {}; const entries: z.infer[] = []; const remaining = [...state.remaining ?? new Set([...localIds, ...this.#continuity.candidates(workspace)])]; if (remaining.length > 2048) throw new ChatAccessError("context_expired"); // Bound lookahead as well as returned chats. A reconnect can mark every known chat dirty; // an opaque continuation advances even when these chats turn out not to have moved. let checked = 0; while (remaining.length && entries.length < PAGE_SIZE && checked++ < PAGE_SIZE) { const id = remaining.shift(); if (!id) break; try { const entry = await this.#owned(workspace, id, signal, localIds.has(id)); const current = await this.#continuity.authorize(entry, workspace); if (!entry.parentID && current.path !== workspace.path) entries.push(entry); } catch (error) { if (!(error instanceof ChatAccessError) || error.code !== "chat_not_found") throw error; this.#continuity.forget(id); } } const limit = PAGE_SIZE - entries.length; let exhausted = state.exhausted ?? false; let native = state.native; if (limit > 0 && !exhausted) { const result = page.parse(await this.#client.session.list({ directory: workspace.path, parentID: null, limit, ...(native ? { cursor: native } : {}) }, { signal })); if (result.data.length > limit) throw new ChatAccessError("context_expired"); // Initial directory discovery remains strict, even if OpenCode ignores its filter. for (const entry of result.data) await this.#assertInWorkspace(entry, workspace); for (const entry of result.data) this.#continuity.remember(entry, workspace); entries.push(...result.data.filter((entry) => !entry.parentID)); // OpenCode returns a next cursor on its last page too: a short page ends the list. native = result.cursor.next ?? undefined; exhausted = result.data.length < limit || !native; } const next = remaining.length || !exhausted ? JSON.stringify({ remaining, native, exhausted }) : null; const running = active.parse(await this.#client.session.active({ signal })); return { version: 1, chats: entries.map((entry) => toChatSummary(entry, sessionStatus(running[entry.id]?.type))), cursor: this.#cursors.issue(next, workspace.id) }; } async #watchList(projectIds: readonly string[], signal: AbortSignal, changed: (id?: string) => void): Promise { const projects = await Promise.all(projectIds.map((id) => this.#registry.get(id))); const controller = new AbortController(); const watching = AbortSignal.any([signal, controller.signal]); const monitor = (async () => { while (!watching.aborted) { await delay(1000, undefined, { signal: watching, ref: false }); for (const id of projectIds) await this.#registry.get(id); } })().catch(() => { controller.abort(); }); const types = new Set(["session.created", "session.renamed", "session.moved", "session.viewed", "session.status", "session.execution.started", "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted"]); try { for await (const event of openCodeEvents(this.#client, watching)) { const deleted = event.type === "session.deleted" && projects.some((workspace) => this.#continuity.knows(eventSessionId(event) ?? "", workspace)); this.observeEvent(event); if (event.type === FATAL_EVENT) throw new Error("Chat source disposed"); if (event.type === "server.connected" || deleted) changed(); else if (types.has(event.type)) { const id = eventSessionId(event); if (id) changed(id); } } } finally { controller.abort(); await monitor; } if (!signal.aborted) throw new Error("Chat list source ended"); } async #readListChanges(projectIds: readonly string[], ids: readonly string[], signal: AbortSignal) { signal.throwIfAborted(); const projects = await Promise.all(projectIds.map((id) => this.#registry.get(id))); signal.throwIfAborted(); if (ids.length === 0) return []; const running = active.parse(await this.#client.session.active({ signal })); const changes = []; for (const id of ids) { signal.throwIfAborted(); let entry: z.infer; try { entry = session.parse(await this.#client.session.get({ sessionID: id }, { signal })); } catch (error) { if ((error as { _tag?: string })._tag === "SessionNotFoundError") continue; throw error; } if (entry.id !== id || entry.parentID) continue; for (const workspace of projects) { if (entry.location.directory !== workspace.path && !this.#continuity.knows(id, workspace)) continue; await this.#registry.get(workspace.id); await this.#continuity.authorize(entry, workspace); changes.push({ projectId: workspace.id, chat: toChatSummary(entry, sessionStatus(running[id]?.type)) }); } } for (const id of projectIds) await this.#registry.get(id); signal.throwIfAborted(); return changes; } async #assertInWorkspace(entry: z.infer, workspace: Workspace): Promise { const directory = await realpath(entry.location.directory).catch(() => { throw new ChatAccessError("access_denied"); }); if (directory !== workspace.path) throw new ChatAccessError("access_denied"); } }