From 97eadde13b63ddf4619ad043c4c0f39d17b23ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Tue, 24 Nov 2026 11:42:03 +0000 Subject: [PATCH] An editor as the client, device files, and files that are not text shown (spec 3.11.0) The CLI's side of harness spec 3.11.0, on serve --stdio and on the link. - acp/editor.ts: _lembas/complete (one HTTP request with the login the agent holds, the window trimmed, a newer request closes the older one's connection and that one is answered as cancelled), _lembas/edit (one model request with no tools; the stream cleaned of a fence around the whole answer and given the selection's ending; deltas; cancel), _lembas/models, _lembas/editor/settings, the editor block of a prompt, and ACP diff items. - acp/files.ts: _lembas/fs/list, stat, read, write, mkdir, move, copy, delete, search. A path is judged where it really is, symlinks followed first; outside remote.roots, the CLI's own directories and protected paths are refused, and so is a folder that holds them; read-only where the device allows plan mode only. A write is checked against the hash the client last saw, twice for an upload in parts, and put in place whole. A delete goes to the system's trash or is refused until the client says permanent. - tool/buffers.ts: read, write, edit, multiedit and apply_patch take a file's text from the client's editor and write through it where the client offers ACP's fs methods; any failure there is the disk. The call is judged before any of it, as before. An overwrite of text that changed in the editor since it was read is refused. - A tool's preview gives each file's text before and after beside the unified diff; a client that said editor: true gets them as diff items on the approval card and on every finished edit. The texts are kept only for such a client. - tool/show.ts: to a client that said media: true a file that is not text is handed over by a handle (_lembas/show/read), good while the request is open and for that file as it was; a table, an SVG and a notebook are named. On stdio the request also says where the file is. - The hardline, the modes and the rules are untouched; tool/replace.ts is untouched. Tests: tests/acp-editor.test.ts (19), tests/acp-files.test.ts (13), and the conformance areas editor, device_files and show. Co-Authored-By: Claude Fable 5.2 --- src/acp/agent.ts | 284 +++++++++++++++++- src/acp/editor.ts | 470 ++++++++++++++++++++++++++++++ src/acp/files.ts | 551 +++++++++++++++++++++++++++++++++++ src/app.ts | 2 + src/bus/index.ts | 2 +- src/harness.ts | 18 ++ src/lembas/client.ts | 10 +- src/permission/hardline.ts | 8 + src/session/engine.ts | 4 +- src/tool/apply_patch.ts | 27 +- src/tool/buffers.ts | 49 ++++ src/tool/edit.ts | 20 +- src/tool/multiedit.ts | 20 +- src/tool/read.ts | 7 +- src/tool/show.ts | 103 +++++-- src/tool/tool.ts | 33 ++- src/tool/write.ts | 26 +- src/tui/state.ts | 2 +- tests/acp-editor.test.ts | 582 +++++++++++++++++++++++++++++++++++++ tests/acp-files.test.ts | 346 ++++++++++++++++++++++ tests/acp.test.ts | 2 +- tests/conformance.ts | 53 ++++ 22 files changed, 2541 insertions(+), 78 deletions(-) create mode 100644 src/acp/editor.ts create mode 100644 src/acp/files.ts create mode 100644 src/tool/buffers.ts create mode 100644 tests/acp-editor.test.ts create mode 100644 tests/acp-files.test.ts diff --git a/src/acp/agent.ts b/src/acp/agent.ts index ae06631..667942e 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -13,7 +13,7 @@ // block: a directory outside `roots` is refused, a mode beyond `max_mode` is lowered to it, an // untrusted project is refused, and an approval nobody answers in time is a denial. The hardline // applies in every mode, as everywhere. -import { existsSync, readdirSync, statSync } from "node:fs" +import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs" import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path" import { createApp, InteractiveOnlyError, type App, type SessionContext } from "../app.ts" import { INTERACTIVE_REASON } from "../provider/interactive.ts" @@ -48,6 +48,14 @@ import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts" import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts" import { isNote } from "../session/prefix.ts" import { outstandingReason } from "../session/outstanding.ts" +import { CANCELLED, changeBytes, completeBody, completeOnServer, currentLogin, diffContent, diffItems, editorBlock, editorSettings, loginOrRefuse, modelsForPicker, rewriteModel, rewriteParams, runRewrite, settingsToSet, type Login } from "./editor.ts" +import { DeviceFiles, hashFile } from "./files.ts" +import { clientFor, ModelError, resolveModel } from "../provider/index.ts" +import { ProviderError, type ResolvedModel } from "../provider/types.ts" +import { lastModel, startModel } from "../session/lastmodel.ts" +import { readRaw } from "../config/settings.ts" +import { LOOP } from "../harness.ts" +import type { ShowRequest } from "../tool/show.ts" import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, SCHEDULED, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts" export const ACP_VERSION = 1 @@ -355,6 +363,13 @@ export const CAPABILITIES = [ // turn in `status`, takes a steer, makes a prompt wait, hands back `unsent` on its `task` end // and is in `history` with `machine`. "harness_turns", + // Harness spec 3.11.0 (acp.md, *An editor as the client*): autocomplete, the rewrite of a + // selection, the editor block of a prompt, the models for a picker and the person's two model + // settings — and, for a client that said `editor: true`, edits as ACP diff items. + "editor", + // Harness spec 3.11.0: for a client that said `media: true`, the show tool also hands over a file + // that is not text, fetched with `_lembas/show/read`. + "media", ] as const export const STOP: Record = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" } @@ -363,8 +378,13 @@ type AskRequest = Parameters[0] /** `session/request_permission`'s params for an approval — the same card whichever process asks * (the hub for a session a terminal runs). `patient`: a person may answer at the terminal * too, so the instance waits rather than timing the card out. */ -export function permissionParams(sessionId: string, req: AskRequest, o: { patient?: boolean; toolCallId?: string; scheduled?: ScheduledTurn } = {}) { +export function permissionParams(sessionId: string, req: AskRequest, o: { patient?: boolean; toolCallId?: string; scheduled?: ScheduledTurn; editor?: boolean } = {}) { const offerAlways = !req.request.alwaysAsk + // Spec 3.11.0 (acp.md *Edits as diffs*): to a client that said it is an editor the change travels + // as ACP diff items — each file's text now and after — while the texts fit; to any other, and + // beyond that, as the unified diff in one text item. + const files = req.preview?.files + const items = files?.length && diffContent({ editor: o.editor === true, when: "ask", bytes: changeBytes(files) })[0] === "diff" ? diffItems(files) : undefined return { sessionId, toolCall: { @@ -375,7 +395,7 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien kind: toolKind(req.tool), status: "pending", rawInput: req.args, - ...(req.preview?.diff ? { content: [{ type: "content", content: { type: "text", text: req.preview.diff } }] } : {}), + ...(items ? { content: items } : req.preview?.diff ? { content: [{ type: "content", content: { type: "text", text: req.preview.diff } }] } : {}), }, options: [ { optionId: "once", kind: "allow_once", name: "Allow once" }, @@ -463,7 +483,8 @@ export function planReplyFrom(answer: any, maxMode?: Mode): PlanReply { /** Text the expander added to a user message (an @file, an image, a listing, a `!` command's output). */ // What the model was given beside the words typed — attachments, and a session note // (session/prefix.ts) — is not shown as typed. -const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || isNote(t) } +// The editor's block (acp.md *Editor context in a prompt*) is the client's word, not the person's. +const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || t.startsWith("\n") || isNote(t) } /** A stored session as turns the web UI can draw: each person's message, then what the * model said, thought and ran in answer, up to the next one. A message's attachments are chips, @@ -524,6 +545,22 @@ export class AcpAgent { private shows = false /** initialize has been answered: notifications about sessions may go out from now on. */ private ready = false + /** Spec 3.11.0: the client said it is an editor (`editor: true`) — edits travel as diff items. */ + private editorClient = false + /** The client shows files that are not text (`media: true`). */ + private media = false + /** ACP's `clientCapabilities.fs`: the client reads and writes text files for the agent. */ + private clientFs = { read: false, write: false } + /** The login autocomplete is sent with, held between requests: nothing is read per keystroke. */ + private login?: Login + /** The one autocomplete request under way: a newer one stops it. */ + private completion?: { id?: string; abort: AbortController } + /** The rewrites under way that carried an id, by it. */ + private rewrites = new Map() + /** Files handed to the client by the show tool, for `_lembas/show/read`, while their request is open. */ + private handles = new Map() + /** `_lembas/fs/*`: the device's files, on the link only. */ + private files = new DeviceFiles(() => (this.limits ? { roots: this.limits.roots, maxMode: this.limits.maxMode, enabled: this.limits.enabled, sharedOnly: this.limits.sharedOnly } : undefined)) constructor( private peer: Peer, @@ -564,6 +601,23 @@ export class AcpAgent { peer.handle("_lembas/team/findings", (p) => this.tree("team_findings", p)) peer.handle("_lembas/team/stop", (p) => this.tree("team_stop", p)) peer.handle("_lembas/monitor", (p) => this.monitor(p)) + // Spec 3.11.0: an editor as the client, files that are not text shown, and device files. + peer.handle("_lembas/complete", (p) => this.complete(p)) + peer.on("_lembas/complete/cancel", (p) => this.completeCancel(p)) + peer.handle("_lembas/edit", (p) => this.edit(p)) + peer.on("_lembas/edit/cancel", (p) => this.rewrites.get(String(p?.id ?? ""))?.abort()) + peer.handle("_lembas/models", async () => modelsForPicker(loginOrRefuse(currentLogin()))) + peer.handle("_lembas/editor/settings", (p) => this.editorSettings(p)) + peer.handle("_lembas/show/read", (p) => this.showRead(p)) + peer.handle("_lembas/fs/list", (p) => this.files.list(p)) + peer.handle("_lembas/fs/stat", (p) => this.files.stat(p)) + peer.handle("_lembas/fs/read", (p) => this.files.read(p)) + peer.handle("_lembas/fs/write", (p) => this.files.write(p)) + peer.handle("_lembas/fs/mkdir", (p) => this.files.mkdir(p)) + peer.handle("_lembas/fs/move", (p) => this.files.move(p)) + peer.handle("_lembas/fs/copy", (p) => this.files.copy(p)) + peer.handle("_lembas/fs/delete", (p) => this.files.delete(p)) + peer.handle("_lembas/fs/search", (p) => this.files.search(p)) peer.on("_lembas/terminal/input", (p) => this.terminalInput(p)) peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p)) peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? ""))) @@ -582,6 +636,11 @@ export class AcpAgent { hub?.detach(this) if (!hub) for (const s of this.sessions.values()) s.app.cancel() for (const id of [...this.terminals.keys()]) this.terminalClose(id) + // What this client had under way goes with it: its autocomplete, its rewrites, its uploads. + this.completion?.abort.abort() + for (const a of this.rewrites.values()) a.abort() + this.handles.clear() + this.files.close() }) } @@ -590,6 +649,10 @@ export class AcpAgent { this.lembas = Boolean(said) this.clientProtocol = typeof said?.protocol === "number" ? said.protocol : 1 this.shows = said?.show === true + this.editorClient = said?.editor === true + this.media = said?.media === true + const fs = p?.clientCapabilities?.fs + this.clientFs = { read: fs?.readTextFile === true, write: fs?.writeTextFile === true } for (const s of this.sessions.values()) if (s.agent === this) this.equipShow(s) // The sessions this link took over (the hub's) get their command set once the client // knows the agent — after this answer, not before it. @@ -621,7 +684,8 @@ export class AcpAgent { connection: this.instanceConnection ?? null, // "terminal" and "shell" (a terminal says its shell and whether its prompts // are marked) only where remote.terminal allows a terminal at all. - capabilities: [...CAPABILITIES, ...(this.limits?.terminal ? ["terminal", "shell"] : [])], + // "fs" (the device's files) on the link only: an editor on stdio has the disk itself. + capabilities: [...CAPABILITIES, ...(this.limits ? ["fs"] : []), ...(this.limits?.terminal ? ["terminal", "shell"] : [])], }, }, } @@ -899,12 +963,198 @@ export class AcpAgent { private equipShow(s: Session) { const ctx = s.app.engine.o.toolCtx this.equipReport(s) + this.equipEditor(s) // Nobody is looking at a scheduled run (spec 3.5.0): show is not offered there. - if (!this.shows || s.scheduled) return void delete ctx.show + if (!this.shows || s.scheduled) return void (delete ctx.show, delete ctx.showsMedia) + ctx.showsMedia = this.media ctx.show = async (req, callId) => { if (s.agent !== this || this.peer.isClosed) return { shown: false, reason: "the client is not connected" } - const r = (await this.peer.request("_lembas/show", { sessionId: s.id, toolCallId: callId ?? "", ...req }, 30_000)) as { shown?: unknown; reason?: unknown } | undefined - return r?.shown === true ? { shown: true } : { shown: false, reason: typeof r?.reason === "string" && r.reason ? r.reason : "the client did not show it" } + const answer = (r: { shown?: unknown; reason?: unknown } | undefined) => + r?.shown === true ? ({ shown: true } as const) : ({ shown: false, reason: typeof r?.reason === "string" && r.reason ? r.reason : "the client did not show it" } as const) + if (!("file" in req)) return answer(await this.peer.request("_lembas/show", { sessionId: s.id, toolCallId: callId ?? "", ...req }, 30_000)) + return answer(await this.showMedia(s, req, callId)) + } + } + + /** A file that is not text (spec 3.11.0, capability `media`): the client is told what it is and + * given a handle to fetch it by, good while this request is open and for that one file as it + * is now. On `serve --stdio` the client is on this machine, and is told where the file is too. */ + private async showMedia(s: Session, req: Extract, callId?: string) { + const { file, ...said } = req + const st = statSync(file) + const handle = `h_${crypto.randomUUID()}` + this.handles.set(handle, { abs: file, size: st.size, mtimeMs: st.mtimeMs }) + try { + const hash = await hashFile(file) + return (await this.peer.request( + "_lembas/show", + { sessionId: s.id, toolCallId: callId ?? "", ...said, hash, handle, ...(this.limits ? {} : { uri: `file://${file.split("/").map(encodeURIComponent).join("/")}` }) }, + LOOP.files.show.media_wait_seconds * 1000, + )) as { shown?: unknown; reason?: unknown } | undefined + } finally { + this.handles.delete(handle) + } + } + + /** `_lembas/show/read`: a part of a file the show tool handed over — that file and no other, + * only while its `_lembas/show` is unanswered, and only as it was when the tool ran. */ + private showRead(p: any) { + const h = this.handles.get(String(p?.handle ?? "")) + if (!h) throw new RpcError(INVALID_PARAMS, "that file is not being handed over any more — a handle is good until its _lembas/show is answered", { reason: "invalid" }) + let st: ReturnType + try { + st = statSync(h.abs) + } catch { + throw new RpcError(INVALID_PARAMS, "the file is gone from this computer", { reason: "changed" }) + } + if (st.size !== h.size || st.mtimeMs !== h.mtimeMs) throw new RpcError(INVALID_PARAMS, "the file changed on this computer while it was being fetched", { reason: "changed" }) + const max = LOOP.files.chunk_max_bytes + const offset = Number.isInteger(p?.offset) && p.offset > 0 ? (p.offset as number) : 0 + const length = Math.min(max, Number.isInteger(p?.length) && p.length >= 0 ? (p.length as number) : max) + const buf = Buffer.alloc(Math.max(0, Math.min(length, h.size - offset))) + const fd = openSync(h.abs, "r") + let n = 0 + try { + if (buf.length) n = readSync(fd, buf, 0, buf.length, offset) + } finally { + closeSync(fd) + } + return { data: buf.subarray(0, n).toString("base64"), offset, eof: offset + n >= h.size } + } + + /** The client's editor for the file tools of a session it opened (acp.md *Unsaved text*): where + * it offers ACP's fs/read_text_file and fs/write_text_file, a tool starts from its buffer and + * writes through it. Whatever goes wrong there — an error, no answer in time — the tool uses + * the disk, as before. The call was judged before the tool ran: nothing is asked of the client + * that the tool would not have opened itself. */ + private equipEditor(s: Session) { + const ctx = s.app.engine.o.toolCtx + // An editor is told what each edit changed (acp.md *Edits as diffs*): the file tools note it + // here by call. Kept for no other client — the texts of every edit are not carried for nothing. + if (this.editorClient) ctx.changed ??= new Map() + else delete ctx.changed + if (!this.clientFs.read && !this.clientFs.write) return void (delete ctx.editor, delete ctx.editorSeen) + const wait = LOOP.editor.buffers.timeout_seconds * 1000 + const live = () => s.agent === this && !this.peer.isClosed + ctx.editorSeen ??= new Map() + ctx.editor = { + ...(this.clientFs.read + ? { + read: async (abs: string) => { + if (!live()) return undefined + const r = (await this.peer.request("fs/read_text_file", { sessionId: s.id, path: abs }, wait).catch(() => undefined)) as { content?: unknown } | undefined + return typeof r?.content === "string" ? r.content : undefined + }, + } + : {}), + ...(this.clientFs.write + ? { + write: async (abs: string, content: string) => { + if (!live()) return false + return this.peer.request("fs/write_text_file", { sessionId: s.id, path: abs, content }, wait).then( + () => true, + () => false, + ) + }, + } + : {}), + } + } + + /** `_lembas/complete`: autocomplete. One HTTP request to the server with the login this agent + * holds — no session, no project, nothing read — and a newer request stops the older, which is + * answered as cancelled: a result, since nothing went wrong. */ + private async complete(p: any) { + const body = completeBody(p) + const login = loginOrRefuse((this.login ??= currentLogin())) + this.completion?.abort.abort() + const mine = { ...(typeof p?.id === "string" && p.id ? { id: p.id } : {}), abort: new AbortController() } + this.completion = mine + try { + return await completeOnServer(login, body, mine.abort.signal) + } catch (e) { + if (mine.abort.signal.aborted) return CANCELLED + // A sign-in the server no longer takes: read again next time, it may have been made anew. + if (e instanceof RpcError && (e.data as { reason?: string } | undefined)?.reason === "not_logged_in") this.login = undefined + throw e + } finally { + if (this.completion === mine) this.completion = undefined + } + } + + private completeCancel(p: any) { + const id = typeof p?.id === "string" ? p.id : "" + const running = this.completion + if (id && running && running.id === id) running.abort.abort() + } + + /** `_lembas/editor/settings`: the person's two model settings on the server — read, or with + * `set` written first. */ + private async editorSettings(p: any) { + const set = settingsToSet(p) + const settings = await editorSettings(loginOrRefuse(currentLogin()), set) + if (!settings) throw new RpcError(INVALID_PARAMS, "the LLeMbas server this computer is logged in to has no editor settings yet (it needs a newer LLeMbas server)", { reason: "unsupported" }) + return settings + } + + /** `_lembas/edit`: the rewrite of a selection — one model request with no tools, on the main + * model; nothing is read from the disk and nothing written. The client shows the result as a + * diff. Not a turn of any session. */ + private async edit(p: any) { + const params = rewriteParams(p) + const id = typeof p?.id === "string" && p.id ? p.id.slice(0, 100) : undefined + const asked = typeof p?.model === "string" && p.model.trim() ? p.model.trim() : undefined + const sessionId = typeof p?.sessionId === "string" ? p.sessionId : "" + const s = sessionId ? this.sessions.get(sessionId) : undefined + if (sessionId && !s) throw new RpcError(INVALID_PARAMS, "no such session", { reason: "invalid" }) + let model: ResolvedModel + let client: ReturnType + try { + let loaded = s?.app.loaded + let start: string | undefined + if (!loaded) { + // No session: as a new one in `cwd` would start (acp.md, *How a session of the device's own starts*). + let cwd: string | undefined + if (typeof p?.cwd === "string" && p.cwd.trim()) { + cwd = resolve(expandHome(p.cwd.trim())) + if (!isAbsolute(expandHome(p.cwd.trim())) || !existsSync(cwd) || !statSync(cwd).isDirectory()) throw new RpcError(INVALID_PARAMS, `${p.cwd} is not a directory on this machine`, { reason: "invalid" }) + const refused = this.refusal(cwd) + if (refused) throw new RpcError(INVALID_PARAMS, refused, { reason: "outside" }) + } + const project = cwd ? findProject(cwd) : undefined + const trusted = project ? trustOf(project.root) === "trusted" : false + loaded = loadConfig(project ? { projectConfigDir: project.dir, trusted } : {}) + const projectModel = project && trusted && typeof readRaw(join(project.dir, "config.yaml")).model === "string" ? loaded.config.model : undefined + start = startModel({ project: projectModel, directory: cwd && !projectModel ? lastModel(cwd) : undefined, global: projectModel ? undefined : loaded.config.model, served: loaded.refs.map((r) => r.ref) }).model + } + // The person's main model, as the server keeps it — asked only when nothing nearer decides. + const login = asked || s ? undefined : currentLogin() + const main = login ? await editorSettings(login).then((x) => x?.main.model, () => undefined) : undefined + const chosen = rewriteModel({ asked, session: s?.app.engine.model.ref, main, served: loaded.refs.map((r) => r.ref), start }) + model = resolveModel(loaded, chosen.model) + client = clientFor(model) + } catch (e) { + if (e instanceof ModelError) throw new RpcError(INVALID_PARAMS, e.message, { reason: "not_logged_in" }) + throw e + } + const abort = new AbortController() + if (id) this.rewrites.get(id)?.abort(), this.rewrites.set(id, abort) + try { + const text = await runRewrite({ + client, + params, + // A session's rewrite thinks as the session does; without one, as the model does by itself. + effort: s && s.app.engine.model.ref === model.ref ? s.app.engine.effort : null, + signal: abort.signal, + ...(id ? { onDelta: (delta: string) => this.peer.notify("_lembas/edit/delta", { id, delta }) } : {}), + }) + return { text, model: model.ref } + } catch (e) { + if (abort.signal.aborted) return CANCELLED + if (e instanceof ProviderError) throw new RpcError(-32603, e.message) + throw e + } finally { + if (id && this.rewrites.get(id) === abort) this.rewrites.delete(id) } } @@ -1133,6 +1383,10 @@ export class AcpAgent { const scheduled = this.judgeScheduled(p?._meta?.lembas?.scheduled) this.takeContext(s, p) const prepared = preparePrompt(s.app, s.id, p.prompt, { roots: this.limits?.roots }) + // Spec 3.11.0 (capability editor): what the person is looking at, as the client says it — one + // block after their text, an attachment of the message. Nothing is read because of it. + const editor = prepared.kind === "run" ? editorBlock(p?._meta?.lembas?.editor, s.app.project.root) : undefined + if (editor && prepared.kind === "run") prepared.extra.push(editor) // Working already: the prompt waits for the turn to end and runs next. It used to be // refused, and a web UI that had misjudged the session as idle lost its message to an error. const run = async (started: () => void): Promise => { @@ -1649,7 +1903,7 @@ export class AcpAgent { sessionUpdate: "tool_call_update", toolCallId: e.id, status: e.result.isError ? "failed" : "completed", - content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }], + content: [{ type: "content", content: { type: "text", text: e.result.output.slice(0, 20_000) } }, ...this.changed(s, e.id, e.result.isError === true)], }) case "tool_denied": // Refused, not run: `failed` to a plain ACP client, `denied` to one that reads _meta.lembas. @@ -1673,6 +1927,16 @@ export class AcpAgent { } } + /** The files an edit that ran changed, as ACP diff items (acp.md *Edits as diffs*): to a client + * that said it is an editor, after the tool's text, while the texts fit. */ + private changed(s: Session, callId: string, failed: boolean) { + const kept = s.app?.engine.o.toolCtx.changed + const files = kept?.get(callId) + kept?.delete(callId) + if (failed || !files?.length) return [] + return diffContent({ editor: this.editorClient, when: "done", bytes: changeBytes(files) }).includes("diff") ? diffItems(files) : [] + } + /** Approvals go to the client; nobody answering in time is a denial. ask_user and plan_submit * go to it too, as `_lembas/question` and `_lembas/plan` — to a client that said it is * LLeMbas; for any other there is nobody to ask, as before. A card the device stops waiting for @@ -1695,7 +1959,7 @@ export class AcpAgent { // A scheduled turn's approval waits the schedule's wait (spec 3.5.0), and says so. const turn = s.scheduled const timeout = turn ? turn.waitMs : (agent.limits?.approvalTimeoutMs ?? 0) - const params = permissionParams(s.id, req, turn ? { scheduled: turn } : {}) + const params = permissionParams(s.id, req, { ...(turn ? { scheduled: turn } : {}), editor: agent.editorClient }) try { if (agent.peer.isClosed) throw new Error("not linked") const answer = await agent.peer.request("session/request_permission", params, timeout || undefined) diff --git a/src/acp/editor.ts b/src/acp/editor.ts new file mode 100644 index 0000000..020bfe8 --- /dev/null +++ b/src/acp/editor.ts @@ -0,0 +1,470 @@ +// An editor as the client (harness/acp.md, spec 3.11.0, capability `editor`): autocomplete, the +// rewrite of a selection, the editor block of a prompt, edits as ACP diff items, and the person's +// two model settings. The rules are functions here (conformance/editor.json runs them); the +// requests go to the server this machine is logged in to and to nothing else. +// +// Neither autocomplete nor a rewrite runs a tool or reads the disk: they see what the client sent. +// What a model answers is text for the client to insert or to show as a diff — never run here. +import { isAbsolute, relative, resolve } from "node:path" +import { LOOP } from "../harness.ts" +import { apiCall, LembasError, type ServedModel } from "../lembas/client.ts" +import { soleInstance } from "../lembas/personal.ts" +import type { Instance } from "../lembas/login.ts" +import type { Client, ResolvedModel } from "../provider/types.ts" +import type { Level } from "../provider/effort.ts" +import { promptText } from "../prompt/assemble.ts" +import type { FileChange } from "../tool/tool.ts" +import { INTERNAL_ERROR, INVALID_PARAMS, RpcError } from "./rpc.ts" + +const E = LOOP.editor + +// ── autocomplete ──────────────────────────────────────────────────────────────────────────── + +const bytes = (s: string) => Buffer.byteLength(s, "utf8") + +/** The end of `text` that fits in `max` UTF-8 bytes, cut at a character boundary. */ +function tailBytes(text: string, max: number): string { + if (bytes(text) <= max) return text + const b = Buffer.from(text, "utf8") + let at = b.length - max + // Not into the middle of a character: its continuation bytes are 10xxxxxx. + while (at < b.length && (b[at]! & 0xc0) === 0x80) at++ + return b.subarray(at).toString("utf8") +} + +/** The start of `text` that fits in `max` UTF-8 bytes, cut at a character boundary. */ +function headBytes(text: string, max: number): string { + if (bytes(text) <= max) return text + const b = Buffer.from(text, "utf8") + let at = max + while (at > 0 && (b[at]! & 0xc0) === 0x80) at-- + return b.subarray(0, at).toString("utf8") +} + +/** `_lembas/complete`'s window (`kind: trim`): the prefix keeps its end, the suffix its start. */ +export function trimWindow(prefix: string, suffix: string, max = E.complete.max_bytes): { prefix: string; suffix: string } { + return { prefix: tailBytes(prefix, max), suffix: headBytes(suffix, max) } +} + +/** A login to send requests with: the one server this machine is logged in to. */ +export interface Login { + instance: Instance + token: string +} + +const tlsOf = (l: Login) => (l.instance.ca ? { ca: l.instance.ca } : undefined) + +/** The server's own sentence in an error answer (`detail`), when it gave one. */ +const detailOf = (json: any): string | undefined => { + // The /v1 routes answer in OpenAI's shape ({ error: { message } }); others say `detail`. + const said = typeof json?.error?.message === "string" ? json.error.message : typeof json?.detail === "string" ? json.detail : "" + return said.trim() || undefined +} + +export const NOT_LOGGED_IN = "this computer is not logged in to a LLeMbas server (lembas login
)" +const OLDER = (what: string) => `the LLeMbas server this computer is logged in to has no ${what} yet (it needs a newer LLeMbas server)` + +/** The login, or the refusal every editor method gives without one. */ +export function loginOrRefuse(login: Login | undefined): Login { + if (!login) throw new RpcError(INVALID_PARAMS, NOT_LOGGED_IN, { reason: "not_logged_in" }) + return login +} + +export function currentLogin(): Login | undefined { + return soleInstance() +} + +export interface CompleteParams { + prefix: string + suffix: string + path?: string + language?: string + model?: string + max_tokens?: number +} + +/** What `_lembas/complete` sends on from its params: the window trimmed, the tokens capped. */ +export function completeBody(p: any): CompleteParams { + if (typeof p?.prefix !== "string") throw new RpcError(INVALID_PARAMS, "prefix must be the text before the cursor", { reason: "invalid" }) + const w = trimWindow(p.prefix, typeof p.suffix === "string" ? p.suffix : "") + const str = (v: unknown, max: number) => (typeof v === "string" && v.trim() ? v.trim().slice(0, max) : undefined) + const tokens = Number.isFinite(p.max_tokens) && p.max_tokens >= 1 ? Math.min(Math.floor(p.max_tokens), E.complete.max_tokens_cap) : undefined + const path = str(p.path, 1000) + const language = str(p.language, 100) + const model = str(p.model, 300) + return { ...w, ...(path ? { path } : {}), ...(language ? { language } : {}), ...(model ? { model } : {}), ...(tokens ? { max_tokens: tokens } : {}) } +} + +/** One autocomplete request to the server (`POST /v1/lembas/complete`, acp.md *The HTTP API*). + * `signal` closes it — the server stops the model's request when the client goes. */ +export async function completeOnServer(login: Login, body: CompleteParams, signal: AbortSignal): Promise<{ text: string; model: string | null; finish: "stop" | "length" }> { + let r: { status: number; json: any } + try { + r = await apiCall(login.instance.base_url, login.token, tlsOf(login), "POST", "/v1/lembas/complete", { ...body, stream: false }, 60_000, signal) + } catch (e) { + if (signal.aborted) throw e + throw new RpcError(INTERNAL_ERROR, (e as Error).message) + } + const said = detailOf(r.json) + if (r.status === 401) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.status === 409) throw new RpcError(INVALID_PARAMS, said ?? "no autocomplete model is chosen yet — choose one in your settings on the server", { reason: "no_model" }) + if (r.status === 403) throw new RpcError(INVALID_PARAMS, said ?? "that model is not allowed for autocomplete", { reason: "not_allowed" }) + if (r.status === 413) throw new RpcError(INVALID_PARAMS, said ?? "the text around the cursor is too long for autocomplete", { reason: "too_large" }) + // A 404 with the server's sentence is a model that is not this account's; a bare one, no such route. + if (r.status === 404 && said) throw new RpcError(INVALID_PARAMS, said, { reason: "unknown_model" }) + if (r.status === 404 || r.status === 405) throw new RpcError(INVALID_PARAMS, OLDER("autocomplete"), { reason: "unsupported" }) + if (r.status === 429) throw new RpcError(INVALID_PARAMS, said ?? "too many completions at once — the next keystroke will try again", { reason: "busy" }) + if (r.status === 400) throw new RpcError(INVALID_PARAMS, said ?? "the server could not read the completion request", { reason: "invalid" }) + if (r.status >= 400 || typeof r.json?.text !== "string") throw new RpcError(INTERNAL_ERROR, said ?? `autocomplete failed on the server (${r.status})`) + return { text: r.json.text, model: typeof r.json.model === "string" ? r.json.model : null, finish: r.json.finish === "length" ? "length" : "stop" } +} + +/** What a request stopped by a newer one, or by its cancel, is answered: a result, not an error. */ +export const CANCELLED = { text: "", cancelled: true } as const + +// ── the person's two model settings ───────────────────────────────────────────────────────── + +export interface EditorSettings { + autocomplete: { model: string | null; source: "person" | "instance" | null; allowed: string[] | null } + main: { model: string | null } +} + +function settingsOf(json: any): EditorSettings { + const a = json?.autocomplete ?? {} + const str = (v: unknown) => (typeof v === "string" && v ? v : null) + return { + autocomplete: { + model: str(a.model), + source: a.source === "person" || a.source === "instance" ? a.source : null, + allowed: Array.isArray(a.allowed) ? a.allowed.filter((x: unknown): x is string => typeof x === "string") : null, + }, + main: { model: str(json?.main?.model) }, + } +} + +/** `GET /v1/lembas/editor`, after a `PUT` of `set` when one is given. Undefined: a server before + * spec 3.11.0 (only when reading — a write to such a server is refused). */ +export async function editorSettings(login: Login, set?: { autocomplete_model?: string | null; main_model?: string | null }): Promise { + const call = async (method: string, body?: unknown) => { + try { + return await apiCall(login.instance.base_url, login.token, tlsOf(login), method, "/v1/lembas/editor", body, 15_000) + } catch (e) { + throw new RpcError(INTERNAL_ERROR, (e as Error).message) + } + } + const judge = (r: { status: number; json: any }, writing: boolean): EditorSettings | undefined => { + const said = detailOf(r.json) + if (r.status === 401) throw new RpcError(INVALID_PARAMS, said ?? "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.status === 404 && said) throw new RpcError(INVALID_PARAMS, said, { reason: "unknown_model" }) + if (r.status === 404 || r.status === 405) { + if (writing) throw new RpcError(INVALID_PARAMS, OLDER("editor settings"), { reason: "unsupported" }) + return undefined + } + if (r.status >= 400) throw new RpcError(INVALID_PARAMS, said ?? `the server refused the editor settings (${r.status})`, { reason: r.status === 403 ? "not_allowed" : "invalid" }) + return settingsOf(r.json) + } + if (set) { + const written = judge(await call("PUT", set), true) + if (written) return written + } + return judge(await call("GET"), false) +} + +/** The `set` of `_lembas/editor/settings`, or undefined when the request only reads. */ +export function settingsToSet(p: any): { autocomplete_model?: string | null; main_model?: string | null } | undefined { + const s = p?.set + if (s === undefined || s === null) return undefined + if (typeof s !== "object") throw new RpcError(INVALID_PARAMS, "set must name autocomplete_model or main_model", { reason: "invalid" }) + const out: { autocomplete_model?: string | null; main_model?: string | null } = {} + for (const k of ["autocomplete_model", "main_model"] as const) { + if (s[k] === undefined) continue + if (s[k] !== null && (typeof s[k] !== "string" || !s[k].trim())) throw new RpcError(INVALID_PARAMS, `${k} must be a model's id, or null for the instance's`, { reason: "invalid" }) + out[k] = s[k] === null ? null : s[k].trim() + } + if (!Object.keys(out).length) throw new RpcError(INVALID_PARAMS, "set must name autocomplete_model or main_model", { reason: "invalid" }) + return out +} + +/** `_lembas/models`: the login's chat models, each with what it may be picked for. */ +export async function modelsForPicker(login: Login) { + let r: { status: number; json: any } + try { + r = await apiCall(login.instance.base_url, login.token, tlsOf(login), "GET", "/v1/models", undefined, 15_000) + } catch (e) { + throw new RpcError(INTERNAL_ERROR, (e as Error).message) + } + if (r.status === 401) throw new RpcError(INVALID_PARAMS, "the server no longer accepts this sign-in — lembas login again", { reason: "not_logged_in" }) + if (r.status >= 400) throw new RpcError(INTERNAL_ERROR, detailOf(r.json) ?? `listing the models failed (${r.status})`) + const served: ServedModel[] = Array.isArray(r.json?.data) ? r.json.data : [] + const settings = await editorSettings(login) + const allowed = settings?.autocomplete.allowed + const models = served + .filter((m) => m && typeof m.id === "string" && (m.kind === undefined || m.kind === "chat")) + .map((m) => ({ + id: m.id, + name: typeof m.name === "string" && m.name ? m.name : m.id, + // A server before 3.11.0 has no autocomplete: every model is for the main setting alone. + for: settings && (!allowed || allowed.includes(m.id)) ? ["main", "autocomplete"] : ["main"], + ...(m.default === true ? { default: true } : {}), + ...(m.interactive_only === true ? { interactive_only: true } : {}), + })) + return { models, autocomplete: settings?.autocomplete ?? null, main: settings?.main ?? null } +} + +// ── the rewrite of a selection ────────────────────────────────────────────────────────────── + +/** The model a rewrite runs on (`kind: model`): the one asked for; the session's; the person's + * main model while the login serves it; what a new session in the directory would start on. */ +export function rewriteModel(o: { asked?: string; session?: string; main?: string | null; served: readonly string[]; start?: string }): { model: string | undefined; from: "asked" | "session" | "main" | "start" } { + if (o.asked) return { model: o.asked, from: "asked" } + if (o.session) return { model: o.session, from: "session" } + if (o.main && o.served.includes(o.main)) return { model: o.main, from: "main" } + return { model: o.start, from: "start" } +} + +export interface RewriteParams { + text: string + instruction: string + path?: string + language?: string + before?: string + after?: string +} + +/** A rewrite's params, checked: the selection and the instruction are needed, and bounded. */ +export function rewriteParams(p: any): RewriteParams { + if (typeof p?.text !== "string" || !p.text) throw new RpcError(INVALID_PARAMS, "text must be the selected text", { reason: "invalid" }) + if (typeof p.instruction !== "string" || !p.instruction.trim()) throw new RpcError(INVALID_PARAMS, "instruction must say what to do with the selection", { reason: "invalid" }) + if (bytes(p.text) > E.rewrite.selection_max_bytes) + throw new RpcError(INVALID_PARAMS, `the selection is ${Math.round(bytes(p.text) / 1024)} KB; at most ${Math.round(E.rewrite.selection_max_bytes / 1024)} KB can be rewritten at once — select less`, { reason: "too_large" }) + if (p.instruction.length > E.rewrite.instruction_max_chars) + throw new RpcError(INVALID_PARAMS, `the instruction is ${p.instruction.length} characters; at most ${E.rewrite.instruction_max_chars}`, { reason: "too_large" }) + const str = (v: unknown, max: number) => (typeof v === "string" && v.trim() ? oneLine(v).slice(0, max) : undefined) + const path = str(p.path, 1000) + const language = str(p.language, 100) + return { + text: p.text, + instruction: p.instruction.trim(), + ...(path ? { path } : {}), + ...(language ? { language } : {}), + ...(typeof p.before === "string" && p.before ? { before: p.before } : {}), + ...(typeof p.after === "string" && p.after ? { after: p.after } : {}), + } +} + +/** The lines of `text` nearest the selection: its last (`end`) or first ones, within both limits. */ +function contextLines(text: string, end: boolean, maxLines: number, maxBytes: number): string { + const lines = text.split("\n") + // A text ending in a line break has an empty piece after it, which is no line. + const trailing = lines.at(-1) === "" + if (trailing) lines.pop() + const kept: string[] = [] + let size = 0 + const order = end ? [...lines].reverse() : lines + for (const l of order) { + const cost = bytes(l) + 1 + if (kept.length >= maxLines || size + cost > maxBytes) break + kept.push(l) + size += cost + } + if (end) kept.reverse() + if (!kept.length) return "" + return kept.join("\n") + (trailing || kept.length < lines.length ? "\n" : "") +} + +const block = (tag: string, text: string) => `<${tag}>\n${text}${text.endsWith("\n") ? "" : "\n"}` + +/** The user message of a rewrite (`kind: message`). */ +export function rewriteMessage(p: RewriteParams, limits: { context_max_lines?: number; context_max_bytes?: number } = {}): string { + const maxLines = limits.context_max_lines ?? E.rewrite.context_max_lines + const maxBytes = limits.context_max_bytes ?? E.rewrite.context_max_bytes + const out: string[] = [] + if (p.path) out.push(`File: ${p.path}${p.language ? ` (${p.language})` : ""}`) + else if (p.language) out.push(`Language: ${p.language}`) + const before = p.before ? contextLines(p.before, true, maxLines, maxBytes) : "" + if (before) out.push(block("before", before)) + out.push(block("selection", p.text)) + const after = p.after ? contextLines(p.after, false, maxLines, maxBytes) : "" + if (after) out.push(block("after", after)) + out.push(block("instruction", p.instruction)) + return out.join("\n") +} + +const FENCE = /^[ \t]*```[^\n`]*$/ + +/** What a rewrite answers, cleaned as it streams (`kind: output`): a fence around the whole + * answer taken off, and the end made the selection's — a line break exactly when it had one. + * `feed` gives the piece that can be passed on now; `end` the rest. The pieces joined are the + * text. */ +export class RewriteOutput { + private raw = "" + /** How much of `raw` has been judged and is behind us. */ + private at = 0 + private opened: boolean | undefined + private sent = "" + + constructor(private selection: string) {} + + feed(chunk: string): string { + this.raw += chunk + return this.advance(false) + } + + end(): string { + return this.advance(true) + } + + get text(): string { + return this.sent + } + + private advance(done: boolean): string { + // The opening: blank lines, then perhaps a fence — known once that line is whole. + if (this.opened === undefined) { + const blank = /^(?:[ \t]*\n)*/.exec(this.raw)![0].length + const nl = this.raw.indexOf("\n", blank) + const first = nl < 0 ? this.raw.slice(blank) : this.raw.slice(blank, nl) + // Still on the first line: nothing is passed on while it may yet turn out to be a fence. + if (nl < 0 && !done && (/^[ \t]*`{0,3}$/.test(first) || FENCE.test(first))) return "" + this.opened = FENCE.test(first) + if (this.opened) this.at = nl < 0 ? this.raw.length : nl + 1 + } + const lastLine = (t: string) => t.slice(t.lastIndexOf("\n") + 1) + const dropLastLine = (t: string) => (t.includes("\n") ? t.slice(0, t.lastIndexOf("\n")) : "") + // Line breaks at the end wait: whether one stays is the selection's to say. + let ready = this.raw.slice(this.at).replace(/\n+$/, "") + if (this.opened) { + // The closing fence is the last line. While more may come, a last line that is one, or could + // still become one, waits too — passed on, it could not be taken back. + const closing = done ? /^[ \t]*```[ \t]*$/ : /^[ \t]*`{0,3}[ \t]*$/ + if (closing.test(lastLine(ready))) ready = dropLastLine(ready).replace(/\n+$/, "") + } + if (done && ready && this.selection.endsWith("\n")) ready += "\n" + // Only ever more of the same text: what was passed on stays as it was. + if (!ready.startsWith(this.sent)) return "" + const piece = ready.slice(this.sent.length) + this.sent = ready + return piece + } +} + +/** One rewrite: the model's stream cleaned, each piece passed to `onDelta`, the whole returned. */ +export async function runRewrite(o: { client: Client; params: RewriteParams; effort?: Level | null; signal: AbortSignal; onDelta?: (delta: string) => void }): Promise { + const out = new RewriteOutput(o.params.text) + const stream = o.client.stream({ + system: promptText("tasks/rewrite.md"), + messages: [{ role: "user", parts: [{ type: "text", text: rewriteMessage(o.params) }] }], + // No tools at all: a rewrite reads nothing and changes nothing. + tools: [], + effort: o.effort ?? null, + signal: o.signal, + }) + for await (const e of stream) { + if (e.type !== "text") continue + const piece = out.feed(e.text) + if (piece) o.onDelta?.(piece) + } + const rest = out.end() + if (rest) o.onDelta?.(rest) + if (!out.text) throw new RpcError(INTERNAL_ERROR, "the model answered with no text for this selection — try again, or say more in the instruction") + return out.text +} + +export type { ResolvedModel } + +// ── the editor block of a prompt ──────────────────────────────────────────────────────────── + +/** One line of plain text: control characters and line breaks out. */ +const CONTROL = new RegExp("[\\u0000-\\u001f\\u007f\\u2028\\u2029]", "g") +function oneLine(s: string): string { + return s.replace(CONTROL, "") +} + +/** A path as the block says it: one line, no angle brackets (a name cannot close the block), + * relative to the project when inside it. */ +function saidPath(p: unknown, root: string): string | undefined { + if (typeof p !== "string") return undefined + const clean = oneLine(p).replace(/[<>]/g, "").trim().slice(0, 1000) + if (!clean) return undefined + if (!isAbsolute(clean)) return clean + const rel = relative(root, resolve(clean)) + return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : clean +} + +const lineOf = (v: unknown): number | undefined => (Number.isInteger(v) && (v as number) >= 1 ? (v as number) : undefined) + +const SEVERITIES = new Set(["error", "warning", "info", "hint"]) + +/** The block a prompt's `_meta.lembas.editor` becomes (`kind: context`), or undefined for none. + * Nothing is read for it: a path here is a name. */ +export function editorBlock(editor: unknown, root: string, limits: Partial = {}): string | undefined { + if (!editor || typeof editor !== "object" || Array.isArray(editor)) return undefined + const L = { ...E.context, ...limits } + const e = editor as Record + const lines: string[] = [] + const path = saidPath(e.path, root) + const cursor = lineOf(e.cursor?.line) + if (path) lines.push(`Open file: ${path}${cursor ? ` (cursor at line ${cursor})` : ""}`) + else if (cursor) lines.push(`Cursor: line ${cursor}`) + const sel = e.selection && typeof e.selection === "object" ? e.selection : undefined + const start = lineOf(sel?.start) + const end = lineOf(sel?.end) + if (sel && start && end && end >= start) { + const where = saidPath(sel.path, root) ?? path + const range = start === end ? `line ${start}` : `lines ${start}-${end}` + lines.push(`Selection: ${where ? `${where} ` : ""}${range}`) + if (typeof sel.text === "string" && sel.text) { + if (sel.text.length > L.selection_max_chars) lines.push(`(the selection is ${sel.text.length} characters long: read the file for it)`) + else lines.push(`\n${sel.text.replace(/\n$/, "")}\n`) + } + } + const diagnostics = (Array.isArray(e.diagnostics) ? e.diagnostics : []).filter((d: any) => d && typeof d === "object" && typeof d.message === "string" && d.message.trim()) + if (diagnostics.length) { + lines.push("Diagnostics:") + for (const d of diagnostics.slice(0, L.diagnostics_max)) { + const file = saidPath(d.path, root) + const line = lineOf(d.line) + const at = file ? `${file}${line ? `:${line}` : ""}` : line ? `line ${line}` : "" + const severity = SEVERITIES.has(d.severity) ? (d.severity as string) : "" + const head = [at, severity].filter(Boolean).join(" ") + let message = (d.message as string).replace(/\s+/g, " ").trim() + if (message.length > L.diagnostic_max_chars) message = message.slice(0, L.diagnostic_max_chars) + "…" + const source = typeof d.source === "string" && d.source.trim() ? ` (${oneLine(d.source).trim().slice(0, 40)})` : "" + lines.push(`- ${head ? `${head}: ` : ""}${message}${source}`) + } + if (diagnostics.length > L.diagnostics_max) lines.push(`(${diagnostics.length - L.diagnostics_max} more)`) + } + const open = (Array.isArray(e.open) ? e.open : []).map((p: unknown) => saidPath(p, root)).filter((p: string | undefined): p is string => p !== undefined && p !== path) + if (open.length) lines.push(`Other open files: ${open.slice(0, L.open_max).join(", ")}${open.length > L.open_max ? ` (${open.length - L.open_max} more)` : ""}`) + return lines.length ? `\n${lines.join("\n")}\n` : undefined +} + +// ── edits as diffs ────────────────────────────────────────────────────────────────────────── + +export type { FileChange } + +/** The texts of `files` together, in UTF-8 bytes. */ +export function changeBytes(files: readonly FileChange[]): number { + return files.reduce((n, f) => n + bytes(f.oldText ?? "") + bytes(f.newText ?? ""), 0) +} + +/** What the content of an approval card (`ask`) or of a finished edit's update (`done`) is made + * of (`kind: diff`): ACP diff items for a client that said it is an editor, while the texts fit. */ +export function diffContent(o: { editor: boolean; when: "ask" | "done"; bytes: number; max?: number }): ("text" | "diff")[] { + const items = o.editor && o.bytes <= (o.max ?? E.diff.max_bytes) + if (o.when === "ask") return [items ? "diff" : "text"] + return items ? ["text", "diff"] : ["text"] +} + +/** ACP's diff items for `files`. */ +export function diffItems(files: readonly FileChange[]) { + return files.map((f) => ({ + type: "diff" as const, + path: f.path, + oldText: f.oldText, + newText: f.newText ?? "", + ...(f.newText === null ? { _meta: { lembas: { deleted: true } } } : {}), + })) +} + +export { LembasError } diff --git a/src/acp/files.ts b/src/acp/files.ts new file mode 100644 index 0000000..6ac7a56 --- /dev/null +++ b/src/acp/files.ts @@ -0,0 +1,551 @@ +// Device files (harness/acp.md, spec 3.11.0, capability `fs`): `_lembas/fs/*`, the person's own +// hands on the files of this computer from a client's file manager — no model, no tool, no card. +// What bounds them is this device: only inside `remote.roots` with remote work on; a path judged +// where it really is, symlinks followed first; never the CLI's own files, never a protected path; +// read-only where the device allows plan mode only. conformance/device_files.json. +import { closeSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readlinkSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync, chmodSync } from "node:fs" +import { createHash } from "node:crypto" +import { homedir } from "node:os" +import { basename, dirname, isAbsolute, join, resolve } from "node:path" +import { expandHome, globalPaths, paths } from "../config/paths.ts" +import type { Mode } from "../config/schema.ts" +import { LOOP } from "../harness.ts" +import { realPath } from "../permission/evaluate.ts" +import { protectedPath, protectedRoots } from "../permission/hardline.ts" +import { FileIndex } from "../project/files.ts" +import { INVALID_PARAMS, RpcError } from "./rpc.ts" + +const F = LOOP.files + +export type FsReason = "off" | "invalid" | "outside" | "own" | "protected" | "read_only" | "missing" | "exists" | "changed" | "not_a_file" | "not_a_directory" | "no_trash" | "too_large" + +/** `read`: list, stat, read, search, a copy's source. `write`: write, mkdir, a move's or a copy's + * target. `remove`: delete and a move's source — the name itself, a link not followed. */ +export type FsOp = "read" | "write" | "remove" + +const inside = (p: string, dir: string) => p === dir || p.startsWith(dir.endsWith("/") ? dir : dir + "/") + +export interface Judging { + op: FsOp + path: string + roots: readonly string[] + /** The CLI's own directories. */ + own: readonly string[] + /** Whether `p` is a protected path, or under one. */ + guarded: (p: string) => boolean + /** The protected paths themselves, for a method that works on a whole folder. */ + guardedRoots?: readonly string[] + enabled: boolean + sharedOnly?: boolean + maxMode: Mode + /** A path as the file system will see it: symlinks followed. */ + real: (p: string) => string + /** The method works on everything under the path too (a delete, a move, a copy's source). */ + deep?: boolean +} + +/** Whether a method may touch `path`, and where it really is (`kind: path`). The first that + * applies of off, invalid, outside, own, protected, read_only. */ +export function judgePath(o: Judging): { ok: true; real: string } | { refused: FsReason } { + if (!o.enabled || o.sharedOnly || !o.roots.length) return { refused: "off" } + const given = typeof o.path === "string" ? expandHome(o.path.trim()) : "" + if (!given || !isAbsolute(given)) return { refused: "invalid" } + const norm = resolve(given) + const roots = o.roots.map((r) => o.real(resolve(expandHome(r)))) + // A name's own directory is followed; the name is not — deleting a link deletes the link. + const real = o.op === "remove" ? join(o.real(dirname(norm)), basename(norm)) : o.real(norm) + // A root itself is never deleted or moved. + if (o.op === "remove" && roots.some((r) => r === real || r === o.real(norm))) return { refused: "invalid" } + if (!roots.some((r) => inside(real, r))) return { refused: "outside" } + const own = o.own.map((d) => o.real(d)) + const deep = o.deep || o.op === "remove" + if (own.some((d) => inside(real, d) || inside(norm, d) || (deep && inside(d, real)))) return { refused: "own" } + if (o.guarded(norm) || o.guarded(real) || (deep && (o.guardedRoots ?? []).some((g) => inside(o.real(g), real)))) return { refused: "protected" } + if (o.op !== "read" && o.maxMode === "plan") return { refused: "read_only" } + return { ok: true, real } +} + +const HASH = /^sha256:[0-9a-f]{64}$/ + +/** Whether `_lembas/fs/write` writes (`kind: base`): the file must be as the client last saw it. */ +export function baseCheck(o: { base?: unknown; overwrite?: unknown; current: string | null }): { write: true } | { refused: "changed" | "exists" | "invalid" } { + if (o.base === null) return o.current === null ? { write: true } : { refused: "exists" } + if (o.base === undefined) return o.overwrite === true ? { write: true } : { refused: "invalid" } + if (typeof o.base !== "string" || !HASH.test(o.base)) return { refused: "invalid" } + return o.current === o.base ? { write: true } : { refused: "changed" } +} + +/** The link's limits as these methods read them. */ +export interface FsLimits { + roots: string[] + maxMode: Mode + enabled?: boolean + sharedOnly?: boolean +} + +const SENTENCES: Record string> = { + off: () => "this computer does not share its files now — turn remote work on there and give it a folder (lembas remote enable, lembas remote add )", + invalid: (p) => `${p || "that"} is not a path this computer can use here`, + outside: (p) => `${p} is outside the folders this computer shares (remote.roots)`, + own: (p) => `${p} holds LLeMbas CLI's own files on this computer, which are not reached from here`, + protected: (p) => `${p} is a protected path on this computer and is not reached from here`, + read_only: () => "this computer allows remote work in plan mode only (remote.max_mode): its files can be read from here, not changed", + missing: (p) => `${p} does not exist on this computer`, + exists: (p) => `${p} already exists on this computer`, + not_a_file: (p) => `${p} is not a file`, + not_a_directory: (p) => `${p} is not a folder`, +} + +const refuse = (reason: FsReason, path: string, message?: string, extra: Record = {}): never => { + throw new RpcError(INVALID_PARAMS, message ?? SENTENCES[reason]?.(path) ?? `${path}: ${reason}`, { reason, ...extra }) +} + +/** The CLI's own directories: its configuration, data and state — the user's, and local mode's. */ +export function ownDirs(): string[] { + return [...new Set([paths.config, paths.data, paths.state, globalPaths.config, globalPaths.data, globalPaths.state])] +} + +const guarded = (p: string) => protectedPath(p) !== undefined + +/** `sha256:` and the hex digest of a file's content, read in pieces. */ +export async function hashFile(abs: string): Promise { + const h = createHash("sha256") + for await (const chunk of createReadStream(abs)) h.update(chunk as Buffer) + return `sha256:${h.digest("hex")}` +} + +const hashBytes = (b: Uint8Array) => `sha256:${createHash("sha256").update(b).digest("hex")}` + +interface Upload { + id: string + /** Where the file really goes, and the part file beside it. */ + target: string + part: string + fd: number + received: number + base: unknown + overwrite: unknown + timer: ReturnType +} + +export interface Entry { + name: string + path: string + kind: "file" | "dir" | "other" + size: number + mtime: number + link?: string + outside?: true + protected?: true +} + +/** The system's trash for `abs`, when it has one that can take it: the file is moved there. + * False: there is none (another file system, or a platform without one known here). */ +export function moveToTrash(abs: string, env: NodeJS.ProcessEnv = process.env, platform: string = process.platform): boolean { + const name = basename(abs) + const free = (dir: string) => { + let candidate = name + for (let i = 2; existsSync(join(dir, candidate)); i++) candidate = `${name}.${i}` + return candidate + } + try { + if (platform === "darwin") { + const dir = join(homedir(), ".Trash") + if (!existsSync(dir)) return false + renameSync(abs, join(dir, free(dir))) + return true + } + if (platform !== "linux" && platform !== "freebsd" && platform !== "openbsd") return false + // The freedesktop trash of the user's data directory: files/ and info/ side by side. + const data = env.XDG_DATA_HOME && isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : join(homedir(), ".local", "share") + const trash = join(data, "Trash") + const files = join(trash, "files") + const info = join(trash, "info") + mkdirSync(files, { recursive: true, mode: 0o700 }) + mkdirSync(info, { recursive: true, mode: 0o700 }) + const as = free(files) + const record = join(info, `${as}.trashinfo`) + const when = new Date(Date.now() - new Date().getTimezoneOffset() * 60_000).toISOString().slice(0, 19) + writeFileSync(record, `[Trash Info]\nPath=${abs.split("/").map(encodeURIComponent).join("/")}\nDeletionDate=${when}\n`, { mode: 0o600 }) + try { + renameSync(abs, join(files, as)) + } catch { + // Another file system: this trash cannot take it, and nothing is copied behind anyone's back. + rmSync(record, { force: true }) + return false + } + return true + } catch { + return false + } +} + +/** `_lembas/fs/*` for one link. */ +export class DeviceFiles { + private uploads = new Map() + private indexes = new Map() + + constructor(private limits: () => FsLimits | undefined) {} + + /** Where `path` really is for `op`, or the refusal. */ + private judge(op: FsOp, path: unknown, deep = false): string { + const L = this.limits() + const said = typeof path === "string" ? path : "" + if (!L) return refuse("off", said) + const r = judgePath({ op, path: said, roots: L.roots, own: ownDirs(), guarded, guardedRoots: protectedRoots(), enabled: L.enabled !== false, sharedOnly: L.sharedOnly, maxMode: L.maxMode, real: realPath, deep }) + if ("refused" in r) return refuse(r.refused, said) + return r.real + } + + /** Whether an entry is one these methods will not open (the CLI's own, or protected). */ + private closed(abs: string): boolean { + const real = realPath(abs) + return guarded(abs) || guarded(real) || ownDirs().some((d) => inside(real, realPath(d)) || inside(abs, d)) + } + + private isInside(abs: string): boolean { + const L = this.limits() + if (!L) return false + const real = realPath(abs) + return L.roots.some((r) => inside(real, realPath(resolve(expandHome(r))))) + } + + private entry(abs: string): Entry { + const l = lstatSync(abs) + let link: string | undefined + let st = l + if (l.isSymbolicLink()) { + link = readlinkSync(abs) + try { + st = statSync(abs) + } catch {} + } + const outside = link !== undefined && !this.isInside(abs) + return { + name: basename(abs), + path: abs, + kind: st.isDirectory() ? "dir" : st.isFile() ? "file" : "other", + size: st.isFile() ? st.size : 0, + mtime: Math.round(st.mtimeMs), + ...(link !== undefined ? { link } : {}), + ...(outside ? { outside: true as const } : {}), + ...(this.closed(abs) ? { protected: true as const } : {}), + } + } + + list(p: any) { + const L = this.limits() + const wanted = typeof p?.path === "string" ? p.path.trim() : "" + if (!wanted) { + if (!L || L.enabled === false || L.sharedOnly || !L.roots.length) return refuse("off", "") + const roots = [...new Set(L.roots.map((r) => resolve(expandHome(r))))].filter((d) => existsSync(d)) + return { path: "", entries: roots.sort().map((d) => this.entry(d)) } + } + const dir = this.judge("read", wanted) + let st: ReturnType + try { + st = statSync(dir) + } catch { + return refuse("missing", wanted) + } + if (!st.isDirectory()) return refuse("not_a_directory", wanted) + const names = readdirSync(dir).filter((n) => p?.hidden === true || !n.startsWith(".")) + const entries: Entry[] = [] + for (const n of names) { + try { + entries.push(this.entry(join(dir, n))) + } catch {} + } + entries.sort((a, b) => (a.kind === "dir" ? 0 : 1) - (b.kind === "dir" ? 0 : 1) || a.name.localeCompare(b.name)) + const up = dirname(dir) + const parent = up !== dir && this.isInside(up) ? up : "" + return { path: dir, parent, entries: entries.slice(0, F.list_max), ...(entries.length > F.list_max ? { truncated: true } : {}) } + } + + async stat(p: any) { + const abs = this.judge("read", p?.path) + if (!existsSync(abs)) return refuse("missing", String(p?.path)) + const e = this.entry(abs) + return { ...e, ...(p?.hash === true && e.kind === "file" ? { hash: await hashFile(abs) } : {}) } + } + + /** What is at `abs` now, links followed: a folder, something else, or nothing. */ + private kindOf(abs: string): "dir" | "other" | undefined { + try { + return statSync(abs).isDirectory() ? "dir" : "other" + } catch { + return undefined + } + } + + private file(abs: string, said: string) { + let st: ReturnType + try { + st = statSync(abs) + } catch { + return refuse("missing", said) + } + if (!st.isFile()) return refuse("not_a_file", said) + return st + } + + read(p: any) { + const said = String(p?.path ?? "") + const abs = this.judge("read", p?.path) + const st = this.file(abs, said) + const offset = Number.isInteger(p?.offset) && p.offset > 0 ? (p.offset as number) : 0 + const length = Math.max(0, Math.min(F.chunk_max_bytes, Number.isInteger(p?.length) && p.length >= 0 ? (p.length as number) : F.chunk_max_bytes)) + const buf = Buffer.alloc(Math.max(0, Math.min(length, st.size - offset))) + const fd = openSync(abs, "r") + let n = 0 + try { + if (buf.length) n = readSync(fd, buf, 0, buf.length, offset) + } finally { + closeSync(fd) + } + const data = buf.subarray(0, n) + const eof = offset + n >= st.size + return { path: abs, size: st.size, mtime: Math.round(st.mtimeMs), offset, data: data.toString("base64"), eof, ...(offset === 0 && eof ? { hash: hashBytes(data) } : {}) } + } + + private decoded(data: unknown): Buffer { + if (typeof data !== "string") return refuse("invalid", "", "data must be the content, base64") + const b = Buffer.from(data, "base64") + if (b.length > F.chunk_max_bytes) return refuse("too_large", "", `a part may carry at most ${Math.round(F.chunk_max_bytes / 1024)} KB; send the file in parts (more: true)`) + return b + } + + private async current(abs: string): Promise { + try { + if (!statSync(abs).isFile()) return null + } catch { + return null + } + return hashFile(abs) + } + + private async checkBase(u: { target: string; base: unknown; overwrite: unknown }, said: string) { + const current = await this.current(u.target) + const r = baseCheck({ base: u.base, overwrite: u.overwrite, current }) + if ("write" in r) return + if (r.refused === "changed") { + let mtime: number | null = null + try { + mtime = Math.round(statSync(u.target).mtimeMs) + } catch {} + return refuse("changed", said, current === null ? `${said} is gone from the computer since you opened it — nothing was written` : `${said} changed on the computer since you opened it — nothing was written. Open it again, or overwrite it on purpose`, { hash: current, mtime }) + } + if (r.refused === "exists") return refuse("exists", said) + return refuse("invalid", said, "a write says what it expects to find: base (the hash last seen, or null for a new file), or overwrite: true") + } + + private drop(u: Upload) { + clearTimeout(u.timer) + this.uploads.delete(u.id) + try { + closeSync(u.fd) + } catch {} + rmSync(u.part, { force: true }) + } + + private idle(u: Upload) { + clearTimeout(u.timer) + u.timer = setTimeout(() => this.drop(u), F.upload_idle_seconds * 1000) + ;(u.timer as { unref?: () => void }).unref?.() + } + + async write(p: any) { + // A later part of an upload already begun. + if (typeof p?.upload === "string") { + const u = this.uploads.get(p.upload) + if (!u) return refuse("invalid", "", "that upload is not open any more — start the write again") + // Judged again: the limits may have changed since the first part. + this.judge("write", u.target) + const data = this.decoded(p.data) + writeSync(u.fd, data) + u.received += data.length + if (p.more === true) { + this.idle(u) + return { upload: u.id, received: u.received } + } + return this.commit(u, u.target) + } + const said = String(p?.path ?? "") + const target = this.judge("write", p?.path) + if (this.kindOf(target) === "dir") return refuse("not_a_file", said) + if (!existsSync(dirname(target))) return refuse("missing", dirname(said), `the folder ${dirname(said)} does not exist on this computer — make it first`) + const data = this.decoded(p?.data) + await this.checkBase({ target, base: p?.base, overwrite: p?.overwrite }, said) + if (p?.more === true && this.uploads.size >= F.uploads_max) return refuse("too_large", said, `this computer already takes ${F.uploads_max} files at once — wait for one to finish`) + const id = crypto.randomUUID() + const part = join(dirname(target), `.${basename(target)}.${id.slice(0, 8)}.lembas-part`) + const u: Upload = { id, target, part, fd: openSync(part, "wx", 0o600), received: 0, base: p?.base, overwrite: p?.overwrite, timer: setTimeout(() => {}, 0) } + this.uploads.set(id, u) + try { + writeSync(u.fd, data) + u.received = data.length + } catch (e) { + this.drop(u) + throw e + } + if (p?.more === true) { + this.idle(u) + return { upload: id, received: u.received } + } + return this.commit(u, said) + } + + /** The last part is in: the base checked once more, then the file put in place whole. */ + private async commit(u: Upload, said: string) { + try { + closeSync(u.fd) + await this.checkBase(u, said) + // The file keeps its mode; a new one gets the usual. + let mode = 0o644 + try { + mode = statSync(u.target).mode & 0o777 + } catch {} + chmodSync(u.part, mode) + renameSync(u.part, u.target) + } catch (e) { + rmSync(u.part, { force: true }) + throw e + } finally { + clearTimeout(u.timer) + this.uploads.delete(u.id) + } + const st = statSync(u.target) + return { path: u.target, size: st.size, mtime: Math.round(st.mtimeMs), hash: await hashFile(u.target) } + } + + mkdir(p: any) { + const said = String(p?.path ?? "") + const abs = this.judge("write", p?.path) + const there = this.kindOf(abs) + if (there === "dir") return { path: abs } + if (there) return refuse("exists", said, `${said} exists on this computer and is not a folder`) + mkdirSync(abs, { recursive: true }) + return { path: abs } + } + + /** The target of a move or a copy: free, or to be replaced when the client said so — a folder + * is never replaced. */ + private target(to: unknown, overwrite: unknown): string { + const said = String(to ?? "") + const abs = this.judge("write", to, true) + let st: ReturnType | undefined + try { + st = lstatSync(abs) + } catch {} + if (st && (overwrite !== true || st.isDirectory())) return refuse("exists", said) + if (!existsSync(dirname(abs))) return refuse("missing", dirname(said), `the folder ${dirname(said)} does not exist on this computer — make it first`) + return abs + } + + move(p: any) { + const from = this.judge("remove", p?.from) + try { + lstatSync(from) + } catch { + return refuse("missing", String(p?.from)) + } + const to = this.target(p?.to, p?.overwrite) + if (inside(to, from)) return refuse("invalid", String(p?.to), "a folder cannot be moved into itself") + try { + renameSync(from, to) + } catch (e) { + if ((e as { code?: string }).code !== "EXDEV") throw e + // Another file system: copied whole, then the original removed. + cpSync(from, to, { recursive: true, verbatimSymlinks: true, force: true }) + rmSync(from, { recursive: true, force: true }) + } + return { path: to } + } + + copy(p: any) { + const from = this.judge("read", p?.from, true) + if (!existsSync(from)) return refuse("missing", String(p?.from)) + const to = this.target(p?.to, p?.overwrite) + if (inside(to, from)) return refuse("invalid", String(p?.to), "a folder cannot be copied into itself") + // A link is copied as a link, never followed: a copy does not reach what a link points to. + cpSync(from, to, { recursive: true, verbatimSymlinks: true, force: true }) + return { path: to } + } + + delete(p: any) { + const said = String(p?.path ?? "") + const abs = this.judge("remove", p?.path) + try { + lstatSync(abs) + } catch { + return refuse("missing", said) + } + if (p?.permanent !== true) { + if (moveToTrash(abs)) return { deleted: true, trash: true } + return refuse("no_trash", said, `this computer has no trash that can take ${said}: deleting it cannot be undone. Send the delete again with permanent: true once the person has agreed`) + } + rmSync(abs, { recursive: true, force: true }) + return { deleted: true, trash: false } + } + + async search(p: any) { + const said = String(p?.path ?? "") + const root = this.judge("read", p?.path) + const there = this.kindOf(root) + if (!there) return refuse("missing", said) + if (there !== "dir") return refuse("not_a_directory", said) + const query = typeof p?.query === "string" ? p.query : "" + const open = (rel: string) => { + const abs = join(root, rel) + return !this.closed(abs) && this.isInside(abs) + } + if (p?.content !== true) { + const limit = Math.max(1, Math.min(50, Number(p?.limit) || 20)) + let index = this.indexes.get(root) + if (!index) this.indexes.set(root, (index = new FileIndex(root))) + const found = index.search(query, limit).filter((f) => open(f.replace(/\/$/, ""))) + return { root, files: found.map((f) => ({ path: f.replace(/\/$/, ""), kind: f.endsWith("/") ? "dir" : "file" })) } + } + if (!query) return refuse("invalid", said, "query must say what to look for") + if (Bun.which("rg") === null) return refuse("invalid", said, "searching inside files needs ripgrep (rg) on this computer") + const limit = Math.max(1, Math.min(F.search_max, Number(p?.limit) || F.search_max)) + // Gitignored files are left out (ripgrep's own rule); hidden ones are looked into. + const args = ["rg", "--line-number", "--no-heading", "--color", "never", "--hidden", "--glob", "!.git", "--max-columns", "400", "--null", ...(p?.regex === true ? [] : ["--fixed-strings"]), "-e", query, "."] + const proc = Bun.spawn(args, { cwd: root, stdout: "pipe", stderr: "ignore", stdin: "ignore" }) + const timer = setTimeout(() => proc.kill(), 20_000) + const matches: { path: string; line: number; text: string }[] = [] + let truncated = false + let buf = "" + const decoder = new TextDecoder() + try { + for await (const chunk of proc.stdout as unknown as AsyncIterable) { + buf += decoder.decode(chunk, { stream: true }) + let nl: number + while ((nl = buf.indexOf("\n")) >= 0) { + const row = buf.slice(0, nl) + buf = buf.slice(nl + 1) + const nul = row.indexOf("\u0000") + if (nul < 0) continue + const path = row.slice(0, nul).replace(/^\.\//, "") + const m = /^(\d+):(.*)$/s.exec(row.slice(nul + 1)) + if (!m || !open(path)) continue + if (matches.length >= limit) { + truncated = true + break + } + matches.push({ path, line: Number(m[1]), text: m[2]!.slice(0, 400) }) + } + if (truncated) break + } + } finally { + clearTimeout(timer) + proc.kill() + } + return { root, matches, ...(truncated ? { truncated: true } : {}) } + } + + /** The link is gone: unfinished uploads go with it. */ + close() { + for (const u of [...this.uploads.values()]) this.drop(u) + } +} diff --git a/src/app.ts b/src/app.ts index f916812..718b1f9 100644 --- a/src/app.ts +++ b/src/app.ts @@ -646,6 +646,8 @@ export function createApp(o: AppOptions): App { perm: childPerm, toolCtx: { ...baseToolCtx(), + // A subagent reads and writes through the client's editor as its session does (acp.md *Unsaved text*). + ...(engine.o.toolCtx.editor ? { editor: engine.o.toolCtx.editor, editorSeen: engine.o.toolCtx.editorSeen } : {}), ...(at ? { root: at.root, cwd: at.cwd, projectDir: undefined } : {}), jobs: { registry, owner: () => ({ sessionId: childSessionId, job }) }, ...(member ? { team: { runtime: teamRt, as: member.name } } : {}), diff --git a/src/bus/index.ts b/src/bus/index.ts index a6619bd..30f2b09 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -128,7 +128,7 @@ export interface Asker { args: unknown request: PermissionRequest decision: Decision - preview?: { diff?: string; error?: string } + preview?: { diff?: string; error?: string; files?: import("../tool/tool.ts").FileChange[] } /** What the model says the call is for. */ purpose?: string /** Set when a subagent running as a background job asks, so the card can say which — it may diff --git a/src/harness.ts b/src/harness.ts index b7d3861..58ea15b 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -294,6 +294,24 @@ export const LOOP: { /** How long a session waits for its configured MCP servers before its first request. */ mcp_wait_ms: number } + /** Spec 3.11.0 (acp.md, *An editor as the client*): the limits of autocomplete, a rewrite, the + * editor block of a prompt, diff items and a client's buffers. */ + editor: { + complete: { max_bytes: number; max_tokens_default: number; max_tokens_cap: number } + rewrite: { selection_max_bytes: number; context_max_lines: number; context_max_bytes: number; instruction_max_chars: number } + context: { selection_max_chars: number; diagnostics_max: number; diagnostic_max_chars: number; open_max: number } + diff: { max_bytes: number } + buffers: { timeout_seconds: number } + } + /** Spec 3.11.0 (acp.md, *Device files*, `_lembas/show`): chunk, listing, upload and size limits. */ + files: { + chunk_max_bytes: number + list_max: number + uploads_max: number + upload_idle_seconds: number + search_max: number + show: { text_max_bytes: number; media_max_bytes: number; media_wait_seconds: number } + } } = LOOP_JSON /** The `purpose` argument (harness/purpose.json). */ diff --git a/src/lembas/client.ts b/src/lembas/client.ts index 03e23b9..872986d 100644 --- a/src/lembas/client.ts +++ b/src/lembas/client.ts @@ -101,10 +101,12 @@ function untrusted(e: unknown): boolean { return /CERT|SIGNATURE|SELF_SIGNED|UNABLE_TO_GET_ISSUER/.test(code) } -async function call(url: string, init: RequestInit, tls: Tls | undefined, timeoutMs = 15_000): Promise { +async function call(url: string, init: RequestInit, tls: Tls | undefined, timeoutMs = 15_000, signal?: AbortSignal): Promise { try { - return await fetch(url, { ...init, ...tlsInit(tls), signal: AbortSignal.timeout(timeoutMs) } as RequestInit) + return await fetch(url, { ...init, ...tlsInit(tls), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs) } as RequestInit) } catch (e) { + // Stopped by whoever asked (a newer autocomplete request): theirs to handle, not a failure to reach. + if (signal?.aborted) throw e if (untrusted(e)) throw new LembasError(`the TLS certificate of ${new URL(url).host} is not trusted. Pass --ca with the CA that signed it.`) if ((e as Error).name === "TimeoutError") throw new LembasError(`${new URL(url).host} did not answer in time`) throw new LembasError(`cannot reach ${new URL(url).host}: ${(e as Error).message}`) @@ -113,10 +115,10 @@ async function call(url: string, init: RequestInit, tls: Tls | undefined, timeou /** One request to the instance with the device's token, its JSON answer and status (spec 3.5.0: * the schedule routes of /api/v2). A body that is not JSON is null. */ -export async function apiCall(base: string, token: string, tls: Tls | undefined, method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<{ status: number; json: any }> { +export async function apiCall(base: string, token: string, tls: Tls | undefined, method: string, path: string, body?: unknown, timeoutMs = 30_000, signal?: AbortSignal): Promise<{ status: number; json: any }> { const headers: Record = { authorization: `Bearer ${token}`, accept: "application/json" } if (body !== undefined) headers["content-type"] = "application/json" - const res = await call(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }, tls, timeoutMs) + const res = await call(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }, tls, timeoutMs, signal) const json = res.status === 204 ? null : await res.json().catch(() => null) return { status: res.status, json } } diff --git a/src/permission/hardline.ts b/src/permission/hardline.ts index 81c4e00..783a351 100644 --- a/src/permission/hardline.ts +++ b/src/permission/hardline.ts @@ -162,6 +162,14 @@ export function substitutions(line: string): string[] { return out } +/** The protected paths themselves, absolute: what a method that works on a whole folder checks + * the folder against (acp/files.ts) — a folder holding one is not deleted, moved or copied whole. */ +export function protectedRoots(): string[] { + const home = homedir() + const configs = [...new Set([paths.config, globalPaths.config])] + return SPEC.protected_paths.flatMap((g) => (g.path.startsWith("/") ? configs.map((c) => resolve(c, g.path.slice("/".length))) : [g.path.startsWith("~/") ? resolve(home, g.path.slice(2)) : g.path])) +} + /** Paths no tool may write, whatever the mode (the spec's, plus LLeMbas CLI's own connections.yaml). * `/` is guarded in the user's config directory and, in local mode, in the local one too. */ export function protectedPath(abs: string): string | undefined { diff --git a/src/session/engine.ts b/src/session/engine.ts index 54017fd..d28fc7e 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -1313,10 +1313,10 @@ export class Engine { if (decision.action === "deny") return { result: { output: `Denied: ${decision.reason}`, isError: true }, denied: true } if (decision.action === "ask") { // The change itself, so the user sees what they are allowing — not just the file's name. - let preview: { diff?: string; error?: string } | undefined + let preview: { diff?: string; error?: string; files?: import("../tool/tool.ts").FileChange[] } | undefined if (tool.preview) preview = await tool.preview(args, toolCtx).then( - (diff) => ({ diff }), + (p) => p, (e) => ({ error: (e as Error).message }), ) const reply = await this.waiting(this.o.asker.ask({ tool: tool.name, args, request, decision, preview, purpose }), "approval", tool.name) diff --git a/src/tool/apply_patch.ts b/src/tool/apply_patch.ts index 31ee852..b354278 100644 --- a/src/tool/apply_patch.ts +++ b/src/tool/apply_patch.ts @@ -2,15 +2,15 @@ // which GPT-family models are trained on, or a unified diff (unidiff.ts, from LLeMbas's file_edit), // which every model has seen. Context lines locate each change, so unlike edit it does not demand // the file was read first — a wrong context is refused instead. -import { mkdir, rm, stat } from "node:fs/promises" -import { dirname } from "node:path" +import { rm, stat } from "node:fs/promises" import { createTwoFilesPatch } from "diff" import { z } from "zod" import { derive, joinBom, parse, type Hunk } from "./patch.ts" import { applyUnified, isUnified, parseUnified, UnidiffError, type UniFile } from "./unidiff.ts" import { straySkillNote } from "../skill/index.ts" -import { absPath, defineTool, readText, showPath, ToolError, type ToolContext } from "./tool.ts" -import { diffStat } from "./write.ts" +import { absPath, defineTool, showPath, ToolError, type FileChange, type ToolContext } from "./tool.ts" +import { diffStat, stampOf } from "./write.ts" +import { fileText, noteChanges, putText } from "./buffers.ts" import { described } from "../harness.ts" import { hunks, lineCount, sha256, type EditedFile } from "../session/results.ts" @@ -64,7 +64,7 @@ async function planUnified(a: { patch: string; path?: string }, ctx: ToolContext if (!path) throw new ToolError("The diff names no file: give `path`, or start it with --- a/ and +++ b/ lines. Nothing was applied.") const abs = absPath(path, ctx) if (!current.has(abs)) { - const text = await stat(abs).then(() => readText(abs), () => null) + const text = await stat(abs).then(() => fileText(abs, ctx), () => null) original.set(abs, text) current.set(abs, text) } @@ -102,7 +102,7 @@ async function planPatch(a: { patch: string; path?: string }, ctx: ToolContext): const current = new Map() const load = async (abs: string) => { if (!current.has(abs)) { - const text = await stat(abs).then(() => readText(abs), () => null) + const text = await stat(abs).then(() => fileText(abs, ctx), () => null) original.set(abs, text) current.set(abs, text) } @@ -136,6 +136,11 @@ async function planPatch(a: { patch: string; path?: string }, ctx: ToolContext): return opsOf(original, current) } +/** Each file a patch changes, with its text before and after (acp.md *Edits as diffs*). */ +function changesOf(ops: Op[]): FileChange[] { + return ops.map((op) => (op.kind === "delete" ? { path: op.path, oldText: op.before, newText: null } : { path: op.path, oldText: op.created ? null : op.before, newText: op.content })) +} + export const applyPatchTool = defineTool({ ...described("apply_patch"), access: "edit", @@ -145,12 +150,14 @@ export const applyPatchTool = defineTool({ return { permission: "edit", class: "write", patterns: files.length ? files.map((f) => showPath(f, ctx)) : ["*"], paths: files } }, async preview(a, ctx) { - return (await planPatch(a, ctx)) + const ops = await planPatch(a, ctx) + const diff = ops .map((op) => { const shown = showPath(op.path, ctx) return createTwoFilesPatch(shown, op.kind === "delete" ? "/dev/null" : shown, op.before, op.kind === "delete" ? "" : op.content, "", "", { context: 3 }) }) .join("\n") + return { diff, files: changesOf(ops) } }, async run(a, ctx) { const ops = await planPatch(a, ctx) @@ -162,13 +169,13 @@ export const applyPatchTool = defineTool({ patches.push(createTwoFilesPatch(shown, "/dev/null", op.before, "", "", "", { context: 3 })) continue } - await mkdir(dirname(op.path), { recursive: true }) - await Bun.write(op.path, op.content) + await putText(op.path, op.content, ctx) ctx.readFiles.add(op.path) - ctx.fileStamps.set(op.path, (await stat(op.path)).mtimeMs) + ctx.fileStamps.set(op.path, await stampOf(op.path)) patches.push(createTwoFilesPatch(shown, shown, op.before, op.content, "", "", { context: 3 })) } const all = patches.join("\n") + noteChanges(ctx, changesOf(ops)) const { added, removed } = diffStat(all) const names = ops.map((o) => showPath(o.path, ctx)).join(", ") const note = straySkillNote(ops.filter((o) => o.kind === "write").map((o) => o.path), ctx) diff --git a/src/tool/buffers.ts b/src/tool/buffers.ts new file mode 100644 index 0000000..99ce3e5 --- /dev/null +++ b/src/tool/buffers.ts @@ -0,0 +1,49 @@ +// A file's text as the client's editor has it (harness/acp.md, *Unsaved text*, spec 3.11.0). +// Where the client of the session offers ACP's fs/read_text_file and fs/write_text_file, the file +// tools start from its buffer and write through it; anywhere else — and whenever the client does +// not take a request — they use the disk, as before. Nothing here decides whether a call may run: +// permissions were judged before a tool reads or writes anything. +import { mkdir } from "node:fs/promises" +import { dirname } from "node:path" +import { sha256 } from "../session/results.ts" +import { readText, type FileChange, type ToolContext } from "./tool.ts" + +type Ctx = Pick + +/** Note what a call that ran changed, where a client wants to draw it (ToolContext.changed). */ +export function noteChanges(ctx: Pick, files: FileChange[]): void { + if (ctx.changed && ctx.callId) ctx.changed.set(ctx.callId, files) +} + +/** The text of `abs` as the client has it, or undefined when it is the disk's to give. What was + * read is remembered, so a later overwrite can tell whether the text has changed since. */ +export async function editorText(abs: string, ctx: Ctx): Promise { + const text = await ctx.editor?.read?.(abs).catch(() => undefined) + if (text === undefined) return undefined + ctx.editorSeen?.set(abs, sha256(text)) + return text +} + +/** A file's text: the client's buffer where it has one, else the disk — byte-order mark kept. */ +export async function fileText(abs: string, ctx: Ctx): Promise { + return (await editorText(abs, ctx)) ?? (await readText(abs)) +} + +/** Whether the text of `abs` in the client's editor is no longer what this session last read + * there. False where the session never read it through the client, or the client cannot say. */ +export async function changedInEditor(abs: string, ctx: Ctx): Promise { + const seen = ctx.editorSeen?.get(abs) + if (seen === undefined || !ctx.editor?.read) return false + const now = await ctx.editor.read(abs).catch(() => undefined) + return now !== undefined && sha256(now) !== seen +} + +/** Write a file's text: through the client where it takes it, else to the disk. */ +export async function putText(abs: string, content: string, ctx: Ctx): Promise { + const taken = ctx.editor?.write ? await ctx.editor.write(abs, content).catch(() => false) : false + if (!taken) { + await mkdir(dirname(abs), { recursive: true }) + await Bun.write(abs, content) + } + if (ctx.editor?.read) ctx.editorSeen?.set(abs, sha256(content)) +} diff --git a/src/tool/edit.ts b/src/tool/edit.ts index 424dc9e..6684186 100644 --- a/src/tool/edit.ts +++ b/src/tool/edit.ts @@ -1,9 +1,9 @@ -import { stat } from "node:fs/promises" import { createTwoFilesPatch } from "diff" import { z } from "zod" import { replace } from "./replace-text.ts" -import { absPath, defineTool, readText, showPath, ToolError, type ToolContext } from "./tool.ts" -import { diffStat, guardExisting } from "./write.ts" +import { absPath, defineTool, showPath, ToolError, type ToolContext } from "./tool.ts" +import { diffStat, guardExisting, stampOf } from "./write.ts" +import { fileText, noteChanges, putText } from "./buffers.ts" import { described } from "../harness.ts" import { hunks, sha256 } from "../session/results.ts" @@ -11,7 +11,7 @@ async function planEdit(a: { path: string; old: string; new: string; all?: boole const abs = absPath(a.path, ctx) const display = showPath(abs, ctx) if (!(await guardExisting(abs, ctx))) throw new ToolError(`No such file or directory: ${abs}`) - const raw = await readText(abs) + const raw = await fileText(abs, ctx) const crlf = raw.includes("\r\n") const before = crlf ? raw.replaceAll("\r\n", "\n") : raw try { @@ -35,16 +35,18 @@ export const editTool = defineTool({ return { permission: "edit", class: "write", patterns: [showPath(abs, ctx)], paths: [abs] } }, async preview(a, ctx) { - const { display, before, after } = await planEdit(a, ctx) - return createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }) + const { abs, display, before, after, crlf } = await planEdit(a, ctx) + const nl = (t: string) => (crlf ? t.replaceAll("\n", "\r\n") : t) + return { diff: createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }), files: [{ path: abs, oldText: nl(before), newText: nl(after) }] } }, async run(a, ctx) { const { abs, display, before, after, crlf } = await planEdit(a, ctx) - await Bun.write(abs, crlf ? after.replaceAll("\n", "\r\n") : after) - ctx.fileStamps.set(abs, (await stat(abs)).mtimeMs) + const written = crlf ? after.replaceAll("\n", "\r\n") : after + await putText(abs, written, ctx) + ctx.fileStamps.set(abs, await stampOf(abs)) const patch = createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }) const { added, removed } = diffStat(patch) - const written = crlf ? after.replaceAll("\n", "\r\n") : after + noteChanges(ctx, [{ path: abs, oldText: crlf ? before.replaceAll("\n", "\r\n") : before, newText: written }]) return { output: `Edited ${display} (+${added} −${removed}).`, title: `${display} +${added} −${removed}`, meta: { diff: patch }, context: { kind: "edit", files: [{ path: a.path, sha: sha256(written), hunks: hunks(before, after) }] } } }, }) diff --git a/src/tool/multiedit.ts b/src/tool/multiedit.ts index 12616f8..a1bda7c 100644 --- a/src/tool/multiedit.ts +++ b/src/tool/multiedit.ts @@ -1,9 +1,9 @@ -import { stat } from "node:fs/promises" import { createTwoFilesPatch } from "diff" import { z } from "zod" import { replace } from "./replace-text.ts" -import { absPath, defineTool, readText, showPath, ToolError, type ToolContext } from "./tool.ts" -import { diffStat, guardExisting } from "./write.ts" +import { absPath, defineTool, showPath, ToolError, type ToolContext } from "./tool.ts" +import { diffStat, guardExisting, stampOf } from "./write.ts" +import { fileText, noteChanges, putText } from "./buffers.ts" import { described } from "../harness.ts" import { hunks, sha256 } from "../session/results.ts" @@ -11,7 +11,7 @@ async function planEdits(a: { path: string; edits: { old: string; new: string; a const abs = absPath(a.path, ctx) const display = showPath(abs, ctx) if (!(await guardExisting(abs, ctx))) throw new ToolError(`No such file or directory: ${abs}`) - const raw = await readText(abs) + const raw = await fileText(abs, ctx) const crlf = raw.includes("\r\n") const before = crlf ? raw.replaceAll("\r\n", "\n") : raw let after = before @@ -37,16 +37,18 @@ export const multieditTool = defineTool({ return { permission: "edit", class: "write", patterns: [showPath(abs, ctx)], paths: [abs] } }, async preview(a, ctx) { - const { display, before, after } = await planEdits(a, ctx) - return createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }) + const { abs, display, before, after, crlf } = await planEdits(a, ctx) + const nl = (t: string) => (crlf ? t.replaceAll("\n", "\r\n") : t) + return { diff: createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }), files: [{ path: abs, oldText: nl(before), newText: nl(after) }] } }, async run(a, ctx) { const { abs, display, before, after, crlf } = await planEdits(a, ctx) - await Bun.write(abs, crlf ? after.replaceAll("\n", "\r\n") : after) - ctx.fileStamps.set(abs, (await stat(abs)).mtimeMs) + const written = crlf ? after.replaceAll("\n", "\r\n") : after + await putText(abs, written, ctx) + ctx.fileStamps.set(abs, await stampOf(abs)) const patch = createTwoFilesPatch(display, display, before, after, "", "", { context: 3 }) const { added, removed } = diffStat(patch) - const written = crlf ? after.replaceAll("\n", "\r\n") : after + noteChanges(ctx, [{ path: abs, oldText: crlf ? before.replaceAll("\n", "\r\n") : before, newText: written }]) return { output: `Edited ${display}: ${a.edits.length} changes (+${added} −${removed}).`, title: `${display} +${added} −${removed}`, meta: { diff: patch }, context: { kind: "edit", files: [{ path: a.path, sha: sha256(written), hunks: hunks(before, after) }] } } }, }) diff --git a/src/tool/read.ts b/src/tool/read.ts index 83ee80a..4fdb432 100644 --- a/src/tool/read.ts +++ b/src/tool/read.ts @@ -7,6 +7,7 @@ import { absPath, defineTool, showPath, ToolError } from "./tool.ts" import { described } from "../harness.ts" import { byListing } from "./search.ts" import { sha256 } from "../session/results.ts" +import { editorText } from "./buffers.ts" const MAX_LINES = 2000 const MAX_LINE = 2000 @@ -39,8 +40,10 @@ export const readTool = defineTool({ if (bytes.includes(0)) throw new ToolError(`${a.path} is a binary file (${st.size} bytes)`) // Read whole, so only up to a size that fits in memory comfortably; past it, grep or bash. if (st.size > 50_000_000) throw new ToolError(`${a.path} is ${Math.round(st.size / 1e6)} MB — too large to read whole; search it with grep, or look at a part with bash (head, tail, sed -n)`) - const raw = await file.bytes() - const text = new TextDecoder().decode(raw) + // The client's buffer where it has the file open (acp.md *Unsaved text*), else the disk. + const buffer = await editorText(abs, ctx) + const raw = buffer !== undefined ? new TextEncoder().encode(buffer) : await file.bytes() + const text = buffer ?? new TextDecoder().decode(raw) const { body, from, to, of } = readBody(text, a.offset, a.limit) ctx.readFiles.add(abs) ctx.fileStamps.set(abs, st.mtimeMs) diff --git a/src/tool/show.ts b/src/tool/show.ts index 466e429..7ae076d 100644 --- a/src/tool/show.ts +++ b/src/tool/show.ts @@ -2,26 +2,29 @@ // has no such viewer, so the tool is offered only in a session a client opened over the link and // only when that client said it can show files (`show: true`, harness/acp.md `_lembas/show`): the // device reads the file and sends it, since the client cannot reach this disk. -import { statSync } from "node:fs" +import { closeSync, openSync, readSync, statSync } from "node:fs" import { basename, extname, relative } from "node:path" import { z } from "zod" -import { described, TOOL_SPECS } from "../harness.ts" +import { described, LOOP, TOOL_SPECS } from "../harness.ts" import { absPath, defineTool, readText, showPath, ToolError } from "./tool.ts" -/** The most a file may be to be sent (acp.md: at most 1 MB; a larger one is refused before sending). */ -export const SHOW_MAX_BYTES = 1024 * 1024 +/** The most a text file may be to be sent (acp.md: at most 1 MB; a larger one is refused before sending). */ +export const SHOW_MAX_BYTES = LOOP.files.show.text_max_bytes +/** The most a file that is not text may be (spec 3.11.0, capability `media`). */ +export const SHOW_MEDIA_MAX_BYTES = LOOP.files.show.media_max_bytes /** The answer when nothing can be shown (spec `unavailable`), word for word. */ export const SHOW_UNAVAILABLE = TOOL_SPECS.show!.unavailable! -/** What `_lembas/show` carries for one file. */ -export interface ShowRequest { - path: string - kind: "markdown" | "code" | "text" | "html" - language?: string - line?: number - text: string -} +export type TextKind = "markdown" | "code" | "text" | "html" | "table" | "svg" | "notebook" +export type MediaKind = "image" | "pdf" | "audio" | "video" | "model3d" | "archive" | "binary" + +/** What `_lembas/show` carries for one file: a text file with its content, or (spec 3.11.0) a file + * that is not text, which the client fetches — `file` is where it is here, for whoever sends the + * request to make a handle from; it never leaves this process. */ +export type ShowRequest = + | { path: string; kind: TextKind; language?: string; line?: number; text: string } + | { path: string; kind: MediaKind; mimeType: string; size: number; file: string } export type ShowReply = { shown: true } | { shown: false; reason: string } @@ -33,9 +36,21 @@ const LANGUAGES: Record = { xml: "xml", svg: "xml", lua: "lua", zig: "zig", dart: "dart", vue: "vue", svelte: "svelte", } +// Files that are not text, by extension: the kind a client that shows media is told, and the type. +const MEDIA: Record = { + png: ["image", "image/png"], jpg: ["image", "image/jpeg"], jpeg: ["image", "image/jpeg"], gif: ["image", "image/gif"], webp: ["image", "image/webp"], avif: ["image", "image/avif"], + pdf: ["pdf", "application/pdf"], + mp3: ["audio", "audio/mpeg"], wav: ["audio", "audio/wav"], ogg: ["audio", "audio/ogg"], oga: ["audio", "audio/ogg"], flac: ["audio", "audio/flac"], m4a: ["audio", "audio/mp4"], aac: ["audio", "audio/aac"], opus: ["audio", "audio/opus"], + mp4: ["video", "video/mp4"], m4v: ["video", "video/mp4"], webm: ["video", "video/webm"], mkv: ["video", "video/x-matroska"], mov: ["video", "video/quicktime"], avi: ["video", "video/x-msvideo"], + glb: ["model3d", "model/gltf-binary"], gltf: ["model3d", "model/gltf+json"], obj: ["model3d", "model/obj"], stl: ["model3d", "model/stl"], + zip: ["archive", "application/zip"], tar: ["archive", "application/x-tar"], gz: ["archive", "application/gzip"], tgz: ["archive", "application/gzip"], bz2: ["archive", "application/x-bzip2"], xz: ["archive", "application/x-xz"], "7z": ["archive", "application/x-7z-compressed"], +} +// Text kinds a client that shows media is told by name; any other client gets them as text or code. +const NAMED_TEXT: Record = { csv: "table", tsv: "table", svg: "svg", ipynb: "notebook" } + /** The viewer's kind for a file, by its name (acp.md): `.md` markdown, `.html`/`.htm` html, a known * source extension code, anything else text. */ -export function showKind(path: string): { kind: ShowRequest["kind"]; language?: string } { +export function showKind(path: string): { kind: "markdown" | "code" | "text" | "html"; language?: string } { const ext = extname(path).slice(1).toLowerCase() if (ext === "md" || ext === "markdown") return { kind: "markdown" } if (ext === "html" || ext === "htm") return { kind: "html" } @@ -43,6 +58,44 @@ export function showKind(path: string): { kind: ShowRequest["kind"]; language?: return language ? { kind: "code", language } : { kind: "text" } } +export type ShowPlan = + | { kind: TextKind; language?: string; via: "text" } + | { kind: MediaKind; mimeType: string; via: "handle" } + | { refused: "not_text" | "too_large" } + +/** What the show tool sends for a file (conformance `show`): by its name, whether its bytes are + * text, its size, and whether the client said it shows media. The kind is a reading of the name — + * a hint; the client decides from the bytes. */ +export function showPlan(o: { name: string; media: boolean; text: boolean; size: number }): ShowPlan { + const ext = extname(o.name).slice(1).toLowerCase() + if (!o.media) { + if (!o.text) return { refused: "not_text" } + if (o.size > SHOW_MAX_BYTES) return { refused: "too_large" } + return { ...showKind(o.name), via: "text" } + } + const media = MEDIA[ext] + if (o.text && !media) { + if (o.size > SHOW_MAX_BYTES) return { refused: "too_large" } + const named = NAMED_TEXT[ext] + return named ? { kind: named, via: "text" } : { ...showKind(o.name), via: "text" } + } + if (o.size > SHOW_MEDIA_MAX_BYTES) return { refused: "too_large" } + return { kind: media?.[0] ?? "binary", mimeType: media?.[1] ?? "application/octet-stream", via: "handle" } +} + +/** Whether a file's first bytes are text (no NUL among them), as the read tool judges it. */ +function looksText(abs: string): boolean { + const buf = Buffer.alloc(8192) + const fd = openSync(abs, "r") + try { + return !buf.subarray(0, readSync(fd, buf, 0, buf.length, 0)).includes(0) + } finally { + closeSync(fd) + } +} + +const sizeWords = (n: number) => (n >= 1024 * 1024 ? `${Math.round(n / 1024 / 1024)} MB` : `${Math.round(n / 1024)} KB`) + export const showTool = defineTool({ ...described("show"), access: "show", @@ -65,12 +118,26 @@ export const showTool = defineTool({ if (e instanceof ToolError) throw e throw new ToolError(`No such file or directory: ${abs}`) } - if (size > SHOW_MAX_BYTES) throw new ToolError(`${showPath(abs, ctx)} is ${Math.round(size / 1024)} KB; at most 1 MB can be shown. Give the user the path instead.`) - const text = await readText(abs) - if (text.includes("\u0000")) throw new ToolError(`${showPath(abs, ctx)} is not a text file; it cannot be shown. Give the user the path instead.`) + const media = ctx.showsMedia === true + let text = looksText(abs) + const shown = showPath(abs, ctx) const rel = relative(ctx.root, abs) || basename(abs) - const reply = await ctx.show({ path: rel, ...showKind(abs), ...(a.line ? { line: a.line } : {}), text }, ctx.callId) + let plan = showPlan({ name: abs, media, text, size }) + let content: string | undefined + if ("via" in plan && plan.via === "text") { + // The whole of it is looked at, not only its start: a NUL further in is not text either. + content = await readText(abs) + if (content.includes("\u0000")) (text = false), (plan = showPlan({ name: abs, media, text, size })) + } + if ("refused" in plan) { + if (plan.refused === "not_text") throw new ToolError(`${shown} is not a text file; it cannot be shown. Give the user the path instead.`) + throw new ToolError(`${shown} is ${sizeWords(size)}; at most ${sizeWords(text && !(extname(abs).slice(1).toLowerCase() in MEDIA) ? SHOW_MAX_BYTES : media ? SHOW_MEDIA_MAX_BYTES : SHOW_MAX_BYTES)} can be shown. Give the user the path instead.`) + } + const reply = + plan.via === "text" + ? await ctx.show({ path: rel, kind: plan.kind, ...(plan.language ? { language: plan.language } : {}), ...(a.line ? { line: a.line } : {}), text: content! }, ctx.callId) + : await ctx.show({ path: rel, kind: plan.kind, mimeType: plan.mimeType, size, file: abs }, ctx.callId) if (!reply.shown) return { output: `Not shown: ${reply.reason}`, isError: true } - return { output: `Shown to the user: ${showPath(abs, ctx)}${a.line ? ` at line ${a.line}` : ""}.`, title: showPath(abs, ctx) } + return { output: `Shown to the user: ${shown}${a.line && plan.via === "text" ? ` at line ${a.line}` : ""}.`, title: shown } }, }) diff --git a/src/tool/tool.ts b/src/tool/tool.ts index 0fd7e88..125889a 100644 --- a/src/tool/tool.ts +++ b/src/tool/tool.ts @@ -74,6 +74,20 @@ export interface ToolContext { /** Open a file in the user's viewer (the show tool): set only where a client over the link said * it can show files (harness/acp.md, capability `show`). Absent: no display, and show is not offered. */ show?: (req: import("./show.ts").ShowRequest, callId?: string) => Promise + /** The client also shows files that are not text (spec 3.11.0, capability `media`): a picture, + * sound, video, a PDF — handed over by a handle it fetches. Absent: text files only, as before. */ + showsMedia?: boolean + /** The client's editor (acp.md *Unsaved text*): the text of a file as the client has it — its + * buffer when open there — and a write through it. Each answers undefined / false when the + * client did not take it, and the disk is used. Absent: the disk alone. */ + editor?: { read?(abs: string): Promise; write?(abs: string, content: string): Promise } + /** The hash of each file's text as last read through the client's editor, by absolute path: an + * overwrite of one whose text there changed since is refused, as a changed file on disk is. */ + editorSeen?: Map + /** What each edit that ran changed, by call id — each file's text before and after — for a + * client that draws its own diffs (acp.md *Edits as diffs*). Absent: nobody wants them, and + * none are kept. */ + changed?: Map /** A scheduled run's report (harness reports.md): set only in a session a schedule opened for * its run that notifies at all. `active`: the turn running now is the schedule's (not a person * writing into the run's session); `file` keeps the report — the last one written is the @@ -92,6 +106,20 @@ export interface ToolContext { } } +/** One file an edit changes: its text before (null: the call creates it) and after (null: the + * call deletes it). `path` is absolute. */ +export interface FileChange { + path: string + oldText: string | null + newText: string | null +} + +/** A call's change, before it is made. */ +export interface Preview { + diff: string + files?: FileChange[] +} + export interface SpawnOptions { signal?: AbortSignal callId?: string @@ -152,8 +180,9 @@ export interface Tool { * (team_add's name); undefined: the generic answer. */ invalid?(raw: unknown, ctx: ToolContext): string | undefined permission(args: z.infer, ctx: ToolContext): PermissionRequest - /** What the call would change, as a unified diff, shown when the user is asked. Writes nothing. */ - preview?(args: z.infer, ctx: ToolContext): Promise + /** What the call would change, shown when the user is asked: a unified diff, and — for a client + * that draws its own (acp.md *Edits as diffs*) — each file's text before and after. Writes nothing. */ + preview?(args: z.infer, ctx: ToolContext): Promise run(args: z.infer, ctx: ToolContext): Promise } diff --git a/src/tool/write.ts b/src/tool/write.ts index 3691ec6..bf34f48 100644 --- a/src/tool/write.ts +++ b/src/tool/write.ts @@ -1,11 +1,11 @@ -import { mkdir, stat } from "node:fs/promises" -import { dirname } from "node:path" +import { stat } from "node:fs/promises" import { createTwoFilesPatch } from "diff" import { z } from "zod" import { straySkillNote } from "../skill/index.ts" import { absPath, defineTool, showPath, ToolError, type ToolContext } from "./tool.ts" import { described } from "../harness.ts" import { hunks, lineCount, sha256 } from "../session/results.ts" +import { changedInEditor, fileText, noteChanges, putText } from "./buffers.ts" /** Refuse to overwrite a file the model has not read, or one changed on disk since it was read. The * texts are the spec's (filesystem.md, *Errors*), with the absolute path. */ @@ -17,9 +17,17 @@ export async function guardExisting(abs: string, ctx: ToolContext): Promise seen + 1) throw new ToolError(`${abs} changed since you last read it. Read it again before changing it.`) + // The same for text the client's editor holds unsaved: "read it first" follows the text. + if (await changedInEditor(abs, ctx)) throw new ToolError(`${abs} changed since you last read it. Read it again before changing it.`) return true } +/** A file's change time now — or this moment, for one a client's editor holds and has not put on + * disk yet. */ +export async function stampOf(abs: string): Promise { + return (await stat(abs).catch(() => undefined))?.mtimeMs ?? Date.now() +} + export function diffStat(patch: string): { added: number; removed: number } { let added = 0 let removed = 0 @@ -44,21 +52,21 @@ export const writeTool = defineTool({ async preview(a, ctx) { const abs = absPath(a.path, ctx) const display = showPath(abs, ctx) - const before = (await guardExisting(abs, ctx)) ? await Bun.file(abs).text() : "" - return createTwoFilesPatch(display, display, before, a.content, "", "", { context: 3 }) + const existed = await guardExisting(abs, ctx) + const before = existed ? await fileText(abs, ctx) : "" + return { diff: createTwoFilesPatch(display, display, before, a.content, "", "", { context: 3 }), files: [{ path: abs, oldText: existed ? before : null, newText: a.content }] } }, async run(a, ctx) { const abs = absPath(a.path, ctx) const display = showPath(abs, ctx) const existed = await guardExisting(abs, ctx) - const before = existed ? await Bun.file(abs).text() : "" - await mkdir(dirname(abs), { recursive: true }) - await Bun.write(abs, a.content) - const st = await stat(abs) + const before = existed ? await fileText(abs, ctx) : "" + await putText(abs, a.content, ctx) ctx.readFiles.add(abs) - ctx.fileStamps.set(abs, st.mtimeMs) + ctx.fileStamps.set(abs, await stampOf(abs)) const patch = createTwoFilesPatch(display, display, before, a.content, "", "", { context: 3 }) const { added, removed } = diffStat(patch) + noteChanges(ctx, [{ path: abs, oldText: existed ? before : null, newText: a.content }]) const note = straySkillNote([abs], ctx) const sha = sha256(a.content) return { diff --git a/src/tui/state.ts b/src/tui/state.ts index 3df80bc..7346118 100644 --- a/src/tui/state.ts +++ b/src/tui/state.ts @@ -144,7 +144,7 @@ export interface ViewState { // What the model was given beside the words typed — attachments, and a session note // (session/prefix.ts) — is not shown as typed. -const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || isNote(t) } +const ATTACHMENT = { test: (t: string) => /^<(file|directory|shell|image) /.test(t) || t.startsWith("\n") || isNote(t) } /** Running first, then by start — the registry's order. */ const byRunning = (a: JobInfo, b: JobInfo) => Number(b.state === "running") - Number(a.state === "running") || a.started - b.started let seq = 0 diff --git a/tests/acp-editor.test.ts b/tests/acp-editor.test.ts new file mode 100644 index 0000000..02a8af5 --- /dev/null +++ b/tests/acp-editor.test.ts @@ -0,0 +1,582 @@ +// An editor as the client (harness/acp.md, spec 3.11.0): autocomplete, the rewrite of a selection, +// the editor block of a prompt, unsaved text through ACP's fs methods, edits as diff items, the +// models for a picker and the person's two model settings, and files that are not text shown. +// A fake editor is the client; a fake LLeMbas server answers /v1/lembas/*; the model is scripted. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { AcpAgent, type Limits } from "../src/acp/agent.ts" +import { Peer, type Transport } from "../src/acp/rpc.ts" +import { paths } from "../src/config/paths.ts" +import { setTrust } from "../src/project/root.ts" +import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts" + +let fake: Fake | undefined +let stopServer: (() => void) | undefined +const seen: { method: string; path: string; body: any }[] = [] + +const cleanLogin = () => { + rmSync(join(paths.config, "lembas.json"), { force: true }) + rmSync(join(paths.config, "lembas"), { recursive: true, force: true }) + seen.length = 0 +} +beforeEach(cleanLogin) +afterEach(() => { + fake?.stop() + fake = undefined + stopServer?.() + stopServer = undefined + cleanLogin() +}) + +function pair(): [Transport, Transport] { + const make = () => ({ msg: (_: string) => {}, end: () => {} }) + const a = make() + const b = make() + const side = (me: typeof a, other: typeof a): Transport => ({ + send: (t) => queueMicrotask(() => other.msg(t)), + onMessage: (fn) => (me.msg = fn), + onClose: (fn) => (me.end = fn), + close: () => (me.end(), other.end()), + }) + return [side(a, b), side(b, a)] +} + +function config(url: string, extra = "") { + mkdirSync(paths.config, { recursive: true }) + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models: { f/m: {}, f/deep: {} }\n`, { mode: 0o600 }) + writeFileSync(join(paths.config, "config.yaml"), `model: f/m\n${extra}`) +} + +function project(files: Record = {}): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-editor-"))) + Bun.spawnSync(["git", "init", "-q", dir]) + for (const [f, text] of Object.entries(files)) { + mkdirSync(join(dir, f, ".."), { recursive: true }) + writeFileSync(join(dir, f), text) + } + setTrust(dir, "trusted") + return dir +} + +const until = async (ok: () => boolean, what: string) => { + for (let i = 0; i < 300 && !ok(); i++) await Bun.sleep(10) + if (!ok()) throw new Error(`timed out waiting for ${what}`) +} + +const err = (message: string, status: number) => Response.json({ error: { message, type: "invalid_request_error", code: null } }, { status }) + +/** A fake LLeMbas server for the editor routes, and this machine logged in to it. `complete` + * answers each completion (given the body and the request, which aborts when the device closes it). */ +function server(o: { complete?: (body: any, req: Request) => Response | Promise; editor?: boolean; allowed?: string[] | null } = {}) { + const state = { autocomplete: "f/m" as string | null, source: "instance" as string | null, main: null as string | null } + const settings = () => ({ autocomplete: { model: state.autocomplete, source: state.source, allowed: o.allowed ?? null }, main: { model: state.main } }) + const s = Bun.serve({ + port: 0, + async fetch(req) { + const u = new URL(req.url) + if (req.headers.get("authorization") !== "Bearer lmb_key") return new Response("no", { status: 401 }) + const body: any = req.method === "GET" ? null : await req.json().catch(() => null) + seen.push({ method: req.method, path: u.pathname, body }) + if (u.pathname === "/v1/models") return Response.json({ data: [{ id: "f/m", name: "Flash", default: true }, { id: "f/deep", name: "Deep", kind: "chat" }, { id: "f/embed", kind: "embedding" }] }) + if (u.pathname === "/v1/lembas/complete" && o.complete) return o.complete(body, req) + if (u.pathname === "/v1/lembas/editor" && o.editor !== false) { + if (req.method === "PUT") { + if (body.autocomplete_model === "f/nope") return err("f/nope is not one of your models.", 404) + if ("autocomplete_model" in body) (state.autocomplete = body.autocomplete_model ?? "f/m"), (state.source = body.autocomplete_model ? "person" : "instance") + if ("main_model" in body) state.main = body.main_model + } + return Response.json(settings()) + } + return new Response("Not Found", { status: 404 }) + }, + }) + stopServer = () => s.stop(true) + mkdirSync(join(paths.config, "lembas"), { recursive: true }) + writeFileSync(join(paths.config, "lembas", "example.key"), "lmb_key\n", { mode: 0o600 }) + writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: `http://127.0.0.1:${s.port}`, connection: "example", scope: "models memory link", logged_in_at: new Date().toISOString() } } })) + return state +} + +/** A fake editor on `serve --stdio` (no limits), or a client on the link (`limits`). */ +async function editor(o: { limits?: Limits; lembas?: Record | false; fs?: Record; handlers?: Record unknown>; ask?: (p: any) => unknown } = {}) { + const [ta, tb] = pair() + new AcpAgent(new Peer(ta), o.limits) + const c = new Peer(tb) + const updates: any[] = [] + const deltas: any[] = [] + const asked: any[] = [] + c.on("session/update", (p) => void updates.push(p)) + c.on("_lembas/event", () => {}) + c.on("_lembas/edit/delta", (p) => void deltas.push(p)) + c.handle("session/request_permission", (p) => (asked.push(p), o.ask?.(p) ?? { outcome: { outcome: "selected", optionId: "once" } })) + for (const [m, fn] of Object.entries(o.handlers ?? {})) c.handle(m, fn) + const lembas = o.lembas === false ? {} : { _meta: { lembas: o.lembas ?? { editor: true } } } + const init: any = await c.request("initialize", { protocolVersion: 1, clientCapabilities: { ...(o.fs ? { fs: o.fs } : {}), ...lembas } }) + return { c, updates, deltas, asked, init, close: () => tb.close() } +} + +const refusal = async (p: Promise) => p.then(() => ({ message: "(answered)", data: undefined as any }), (e) => ({ message: (e as Error).message, data: (e as any).data })) + +// ── capabilities ──────────────────────────────────────────────────────────────────────────── + +test("initialize: editor and media are listed; fs on the link only", async () => { + fake = fakeProvider([]) + config(fake.url) + const stdio = await editor() + expect(stdio.init._meta.lembas.harness_spec).toBe("3.11.0") + expect(stdio.init._meta.lembas.capabilities).toContain("editor") + expect(stdio.init._meta.lembas.capabilities).toContain("media") + expect(stdio.init._meta.lembas.capabilities).not.toContain("fs") + const root = project() + const link = await editor({ limits: { roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true } }) + expect(link.init._meta.lembas.capabilities).toContain("fs") +}) + +// ── _lembas/complete ──────────────────────────────────────────────────────────────────────── + +test("_lembas/complete: one request to the server, the window trimmed, no session and no chat request", async () => { + fake = fakeProvider([]) + config(fake.url) + server({ complete: (body) => Response.json({ text: "bake()", model: body.model ?? "f/m", finish: "stop", usage: {} }) }) + const { c } = await editor() + const r: any = await c.request("_lembas/complete", { id: "k1", prefix: "const crumbs = ", suffix: "\n", path: "src/waybread.ts", language: "typescript", cwd: "/nowhere/at/all" }) + expect(r).toEqual({ text: "bake()", model: "f/m", finish: "stop" }) + expect(seen).toEqual([{ method: "POST", path: "/v1/lembas/complete", body: { prefix: "const crumbs = ", suffix: "\n", path: "src/waybread.ts", language: "typescript", stream: false } }]) + // The quick switch names a model; max_tokens is capped; a long window is trimmed, not refused. + await c.request("_lembas/complete", { prefix: "x".repeat(70_000) + "END", suffix: "START" + "y".repeat(70_000), model: "f/deep", max_tokens: 9999 }) + const sent = seen[1]!.body + expect(sent.model).toBe("f/deep") + expect(sent.max_tokens).toBe(512) + expect(Buffer.byteLength(sent.prefix)).toBe(65536) + expect(sent.prefix.endsWith("END")).toBe(true) + expect(Buffer.byteLength(sent.suffix)).toBe(65536) + expect(sent.suffix.startsWith("START")).toBe(true) + // Nothing went to the chat endpoint, and no session was made. + expect(fake.requests.length).toBe(0) +}) + +test("_lembas/complete: a newer request cancels the older, which is answered as cancelled; cancel by id", async () => { + fake = fakeProvider([]) + config(fake.url) + const aborted: string[] = [] + server({ + complete: async (body, req) => { + if (body.prefix === "fast") return Response.json({ text: "now", model: "f/m", finish: "stop" }) + // A slow model: answers only if the device does not close the request first. + await new Promise((resolve) => { + const t = setTimeout(resolve, 5000) + req.signal.addEventListener("abort", () => (clearTimeout(t), aborted.push(body.prefix), resolve())) + }) + return Response.json({ text: "late", model: "f/m", finish: "stop" }) + }, + }) + const { c } = await editor() + const first = c.request("_lembas/complete", { id: "a", prefix: "slow one" }) + await until(() => seen.length === 1, "the first request to reach the server") + const second = c.request("_lembas/complete", { id: "b", prefix: "fast" }) + expect(await first).toEqual({ text: "", cancelled: true }) + expect(await second).toEqual({ text: "now", model: "f/m", finish: "stop" }) + // The server saw the first one closed: the model's request is stopped there. + await until(() => aborted.includes("slow one"), "the server to see the request closed") + // _lembas/complete/cancel by the client's own id; another id touches nothing. + const third = c.request("_lembas/complete", { id: "c", prefix: "slow two" }) + await until(() => seen.length === 3, "the third request to reach the server") + c.notify("_lembas/complete/cancel", { id: "zzz" }) + await Bun.sleep(30) + c.notify("_lembas/complete/cancel", { id: "c" }) + expect(await third).toEqual({ text: "", cancelled: true }) +}) + +test("_lembas/complete: every refusal in words, with its reason", async () => { + fake = fakeProvider([]) + config(fake.url) + // Not logged in at all. + const out = await editor() + expect(await refusal(out.c.request("_lembas/complete", { prefix: "x" }))).toMatchObject({ data: { reason: "not_logged_in" } }) + expect((await refusal(out.c.request("_lembas/complete", { suffix: "x" }))).data).toEqual({ reason: "invalid" }) + const answers: Record Response> = { + none: () => err("No autocomplete model is chosen. Choose one under Settings → Editor.", 409), + forbidden: () => err("f/deep is not allowed for autocomplete.", 403), + unknown: () => err("f/nope is not one of your models.", 404), + busy: () => err("Too many completions at once.", 429), + bad: () => err("Nothing to complete.", 400), + broken: () => Response.json({ error: { message: "The model's server failed.", type: "upstream_error" } }, { status: 502 }), + } + server({ complete: (body) => answers[body.prefix]!() }) + const { c } = await editor() + // The server's sentence reaches the editor unchanged. + expect(await refusal(c.request("_lembas/complete", { prefix: "none" }))).toEqual({ message: "No autocomplete model is chosen. Choose one under Settings → Editor.", data: { reason: "no_model" } }) + expect(await refusal(c.request("_lembas/complete", { prefix: "forbidden" }))).toEqual({ message: "f/deep is not allowed for autocomplete.", data: { reason: "not_allowed" } }) + expect(await refusal(c.request("_lembas/complete", { prefix: "unknown" }))).toEqual({ message: "f/nope is not one of your models.", data: { reason: "unknown_model" } }) + expect(await refusal(c.request("_lembas/complete", { prefix: "busy" }))).toMatchObject({ data: { reason: "busy" } }) + expect(await refusal(c.request("_lembas/complete", { prefix: "bad" }))).toMatchObject({ data: { reason: "invalid" } }) + expect((await refusal(c.request("_lembas/complete", { prefix: "broken" }))).message).toBe("The model's server failed.") +}) + +test("_lembas/complete: a server before spec 3.11.0 is said to be older", async () => { + fake = fakeProvider([]) + config(fake.url) + server({}) + const { c } = await editor() + const r = await refusal(c.request("_lembas/complete", { prefix: "x" })) + expect(r.data).toEqual({ reason: "unsupported" }) + expect(r.message).toContain("newer LLeMbas server") +}) + +// ── _lembas/edit ──────────────────────────────────────────────────────────────────────────── + +test("_lembas/edit: one request with no tools; deltas; a fence taken off; nothing written", async () => { + fake = fakeProvider([{ chunks: [delta({ content: "```ts\n return " }), delta({ content: "await crumbs\n" }), delta({ content: "```\n" })] }]) + config(fake.url) + const root = project({ "src/waybread.ts": "function bake() {\n return crumbs\n}\n" }) + const { c, deltas } = await editor() + const r: any = await c.request("_lembas/edit", { id: "e1", cwd: root, path: "src/waybread.ts", language: "typescript", before: "function bake() {\n", text: " return crumbs\n", after: "}\n", instruction: "make it async" }) + expect(r).toEqual({ text: " return await crumbs\n", model: "f/m" }) + expect(deltas.every((d) => d.id === "e1")).toBe(true) + expect(deltas.map((d) => d.delta).join("")).toBe(r.text) + const sent = fake.requests[0] + // No tools at all: a rewrite reads nothing and changes nothing. + expect(sent.tools ?? []).toEqual([]) + expect(sent.messages[0].role).toBe("system") + expect(sent.messages[0].content).toContain("You rewrite a selection") + expect(sent.messages[1].content).toBe("File: src/waybread.ts (typescript)\n\nfunction bake() {\n\n\n return crumbs\n\n\n}\n\n\nmake it async\n") + expect(readFileSync(join(root, "src/waybread.ts"), "utf8")).toBe("function bake() {\n return crumbs\n}\n") +}) + +test("_lembas/edit: the model — asked, the session's, the person's main model, else as a new session", async () => { + const answer = { chunks: [delta({ content: "x" })] } + fake = fakeProvider([answer, answer, answer, answer, answer]) + config(fake.url) + const state = server({}) + const root = project() + const { c } = await editor() + const edit = (extra: Record) => c.request("_lembas/edit", { text: "y", instruction: "i", ...extra }) + // Nothing chosen anywhere: as a new session would start (the global setting here). + expect((await edit({ cwd: root })).model).toBe("f/m") + // The person's main model, kept on the server. + state.main = "f/deep" + expect((await edit({ cwd: root })).model).toBe("f/deep") + // A session's model comes before it — and the rewrite is no turn of the session. + const s: any = await c.request("session/new", { cwd: root, _meta: { model: "f/m" } }) + expect((await edit({ sessionId: s.sessionId })).model).toBe("f/m") + const status: any = await c.request("_lembas/session/history", { sessionId: s.sessionId }) + expect(status.turns).toEqual([]) + // The model asked for comes first of all. + expect((await edit({ sessionId: s.sessionId, model: "f/deep" })).model).toBe("f/deep") + // A main model the login no longer serves is skipped. + state.main = "f/gone" + expect((await edit({})).model).toBe("f/m") + expect(fake.requests.map((r) => r.model)).toEqual(["f/m", "f/deep", "f/m", "f/deep", "f/m"]) +}) + +test("_lembas/edit: cancelled by id; refused without text or instruction, over the limits, for an unknown session, and with no reply", async () => { + fake = fakeProvider([{ chunks: [delta({ content: "slow" }), delta({ content: " answer" })], gapMs: 3000 }, { chunks: [delta({ content: "\n" })] }]) + config(fake.url) + const { c } = await editor() + const running = c.request("_lembas/edit", { id: "e9", text: "y", instruction: "i" }) + await until(() => fake!.requests.length === 1, "the rewrite to reach the model") + c.notify("_lembas/edit/cancel", { id: "e9" }) + expect(await running).toEqual({ text: "", cancelled: true }) + expect((await refusal(c.request("_lembas/edit", { instruction: "i" }))).data).toEqual({ reason: "invalid" }) + expect((await refusal(c.request("_lembas/edit", { text: "y", instruction: " " }))).data).toEqual({ reason: "invalid" }) + expect((await refusal(c.request("_lembas/edit", { text: "y".repeat(300_000), instruction: "i" }))).data).toEqual({ reason: "too_large" }) + expect((await refusal(c.request("_lembas/edit", { text: "y", instruction: "i".repeat(8001) }))).data).toEqual({ reason: "too_large" }) + expect((await refusal(c.request("_lembas/edit", { text: "y", instruction: "i", sessionId: "ses_none" }))).message).toBe("no such session") + expect((await refusal(c.request("_lembas/edit", { text: "y", instruction: "i", cwd: "/no/such/place" }))).data).toEqual({ reason: "invalid" }) + // A model that says nothing: an error in words, not an empty replacement. + expect((await refusal(c.request("_lembas/edit", { text: "y", instruction: "i" }))).message).toContain("no text") +}) + +test("_lembas/edit on the link: a cwd outside the device's roots is refused", async () => { + fake = fakeProvider([]) + config(fake.url) + const root = project() + const other = project() + const { c } = await editor({ limits: { roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true } }) + const r = await refusal(c.request("_lembas/edit", { text: "y", instruction: "i", cwd: other })) + expect(r.data).toEqual({ reason: "outside" }) + expect(fake.requests.length).toBe(0) +}) + +// ── _lembas/models, _lembas/editor/settings ───────────────────────────────────────────────── + +test("_lembas/models and _lembas/editor/settings: the picker's models, the two settings read and set", async () => { + fake = fakeProvider([]) + config(fake.url) + server({ allowed: ["f/m"] }) + const { c } = await editor() + const m: any = await c.request("_lembas/models", {}) + // Chat models only; what each may be picked for comes from `allowed`. + expect(m.models).toEqual([ + { id: "f/m", name: "Flash", for: ["main", "autocomplete"], default: true }, + { id: "f/deep", name: "Deep", for: ["main"] }, + ]) + expect(m.autocomplete).toEqual({ model: "f/m", source: "instance", allowed: ["f/m"] }) + expect(m.main).toEqual({ model: null }) + expect(await c.request("_lembas/editor/settings", {})).toEqual({ autocomplete: { model: "f/m", source: "instance", allowed: ["f/m"] }, main: { model: null } }) + const set: any = await c.request("_lembas/editor/settings", { set: { main_model: "f/deep" } }) + expect(set.main).toEqual({ model: "f/deep" }) + // Only the field named is sent. + expect(seen.find((s) => s.method === "PUT")!.body).toEqual({ main_model: "f/deep" }) + // null: back to the instance's. + const back: any = await c.request("_lembas/editor/settings", { set: { autocomplete_model: null } }) + expect(back.autocomplete.source).toBe("instance") + // The server's refusal, in its words; a set that names nothing. + expect(await refusal(c.request("_lembas/editor/settings", { set: { autocomplete_model: "f/nope" } }))).toEqual({ message: "f/nope is not one of your models.", data: { reason: "unknown_model" } }) + expect((await refusal(c.request("_lembas/editor/settings", { set: {} }))).data).toEqual({ reason: "invalid" }) + expect((await refusal(c.request("_lembas/editor/settings", { set: { main_model: 7 } }))).data).toEqual({ reason: "invalid" }) +}) + +test("_lembas/models and settings against a server before 3.11.0, and logged out", async () => { + fake = fakeProvider([]) + config(fake.url) + const out = await editor() + expect((await refusal(out.c.request("_lembas/models", {}))).data).toEqual({ reason: "not_logged_in" }) + expect((await refusal(out.c.request("_lembas/editor/settings", {}))).data).toEqual({ reason: "not_logged_in" }) + server({ editor: false }) + const { c } = await editor() + const m: any = await c.request("_lembas/models", {}) + expect(m.models.map((x: any) => x.for)).toEqual([["main"], ["main"]]) + expect(m.autocomplete).toBeNull() + expect((await refusal(c.request("_lembas/editor/settings", {}))).data).toEqual({ reason: "unsupported" }) + expect((await refusal(c.request("_lembas/editor/settings", { set: { main_model: "f/m" } }))).data).toEqual({ reason: "unsupported" }) +}) + +// ── editor context in a prompt ────────────────────────────────────────────────────────────── + +test("editor context: one block after the person's text; not part of what was typed; nothing read for it", async () => { + fake = fakeProvider([{ chunks: [delta({ content: "ok" })] }]) + config(fake.url) + const root = project({ "src/waybread.ts": "const crumbs = bake()\n" }) + const { c } = await editor() + const s: any = await c.request("session/new", { cwd: root }) + await c.request("session/prompt", { + sessionId: s.sessionId, + prompt: [{ type: "text", text: "why is this red?" }], + _meta: { lembas: { editor: { path: join(root, "src/waybread.ts"), cursor: { line: 1 }, selection: { start: 1, end: 1, text: "const crumbs = bake()\n" }, diagnostics: [{ line: 1, severity: "error", message: "Cannot find name 'bake'.", source: "ts" }], open: ["/etc/hosts"] } } }, + }) + const user = fake.requests[0].messages.filter((m: any) => m.role === "user").at(-1).content + expect(user).toContain("why is this red?") + expect(user).toContain("\nOpen file: src/waybread.ts (cursor at line 1)\nSelection: src/waybread.ts line 1\n\nconst crumbs = bake()\n\nDiagnostics:\n- line 1 error: Cannot find name 'bake'. (ts)\nOther open files: /etc/hosts\n") + // A path in the block is a name: the file outside the project was not read. + expect(user).not.toContain("localhost") + // The history shows what the person typed, without the block. + const h: any = await c.request("_lembas/session/history", { sessionId: s.sessionId }) + expect(h.turns[0].text).toBe("why is this red?") +}) + +// ── unsaved text ──────────────────────────────────────────────────────────────────────────── + +test("unsaved text: read asks the client's buffer; an edit starts from it and is written through the client", async () => { + fake = fakeProvider([ + { chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] }, + { chunks: [toolCall(0, "w1", "edit", JSON.stringify({ path: "a.txt", old: "unsaved", new: "changed" }))] }, + { chunks: [delta({ content: "done" })] }, + ]) + config(fake.url) + const root = project({ "a.txt": "on disk\n" }) + const file = join(root, "a.txt") + const buffers: Record = { [file]: "unsaved line\n" } + const calls: any[] = [] + const { c, updates } = await editor({ + fs: { readTextFile: true, writeTextFile: true }, + handlers: { + "fs/read_text_file": (p) => (calls.push(["read", p.path]), { content: buffers[p.path] }), + "fs/write_text_file": (p) => (calls.push(["write", p.path]), (buffers[p.path] = p.content), null), + }, + }) + const s: any = await c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "fix it" }] }) + // The model was given the buffer, not the disk. + expect(fake.requests[1].messages.find((m: any) => m.role === "tool").content).toContain("1: unsaved line") + // The edit went to the client; the device did not write the disk behind its back. + expect(buffers[file]).toBe("changed line\n") + expect(readFileSync(file, "utf8")).toBe("on disk\n") + expect(calls.filter((x) => x[0] === "write")).toEqual([["write", file]]) + // The finished edit carries the diff: the buffer's text before, and after. + const done = updates.map((u) => u.update).find((u) => u.sessionUpdate === "tool_call_update" && u.toolCallId === "w1") + expect(done.content[1]).toEqual({ type: "diff", path: file, oldText: "unsaved line\n", newText: "changed line\n" }) +}) + +test("unsaved text: a client that fails falls back to the disk; text changed in the editor since the read refuses an overwrite", async () => { + fake = fakeProvider([ + { chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] }, + { chunks: [toolCall(0, "w1", "write", JSON.stringify({ path: "a.txt", content: "new\n" }))] }, + { chunks: [toolCall(0, "r2", "read", JSON.stringify({ path: "b.txt" }))] }, + { chunks: [toolCall(0, "w2", "write", JSON.stringify({ path: "b.txt", content: "B2\n" }))] }, + { chunks: [delta({ content: "done" })] }, + ]) + config(fake.url) + const root = project({ "a.txt": "A\n", "b.txt": "B\n" }) + let a = "A in the editor\n" + const { c } = await editor({ + fs: { readTextFile: true, writeTextFile: true }, + handlers: { + // b.txt: the client knows nothing of it, and cannot write it either. + "fs/read_text_file": (p) => { + if (p.path.endsWith("b.txt")) throw new Error("not open") + const now = a + // The person keeps typing after the agent read the file. + a = "A typed over since\n" + return { content: now } + }, + "fs/write_text_file": () => { + throw new Error("read-only buffer") + }, + }, + }) + const s: any = await c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "go" }] }) + const tools = fake.requests.at(-1).messages.filter((m: any) => m.role === "tool").map((m: any) => m.content) + expect(tools[0]).toContain("1: A in the editor") + expect(tools[1]).toContain("changed since you last read it") + expect(readFileSync(join(root, "a.txt"), "utf8")).toBe("A\n") + // b.txt: read from the disk, written to the disk. + expect(tools[2]).toContain("1: B") + expect(readFileSync(join(root, "b.txt"), "utf8")).toBe("B2\n") +}) + +test("unsaved text: a protected path is refused before the client is ever asked", async () => { + fake = fakeProvider([{ chunks: [toolCall(0, "w1", "write", JSON.stringify({ path: join(paths.config, "connections.yaml"), content: "x" }))] }, { chunks: [delta({ content: "done" })] }]) + config(fake.url) + const root = project() + const calls: string[] = [] + const { c } = await editor({ fs: { readTextFile: true, writeTextFile: true }, handlers: { "fs/read_text_file": (p) => (calls.push(p.path), { content: "" }), "fs/write_text_file": (p) => (calls.push(p.path), null) } }) + const s: any = await c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "go" }] }) + expect(fake.requests[1].messages.find((m: any) => m.role === "tool").content).toContain("never written by a tool") + expect(calls).toEqual([]) +}) + +// ── edits as diffs ────────────────────────────────────────────────────────────────────────── + +const editScript = () => [ + { chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] }, + { chunks: [toolCall(0, "e1", "edit", JSON.stringify({ path: "a.txt", old: "one", new: "two" }))] }, + { chunks: [toolCall(0, "n1", "write", JSON.stringify({ path: "new.txt", content: "fresh\n" }))] }, + { chunks: [delta({ content: "done" })] }, +] + +test("edits as diffs: in manual mode an editor is asked with diff items, nothing written before; rejected stays unwritten", async () => { + fake = fakeProvider(editScript()) + config(fake.url) + const root = project({ "a.txt": "one\n" }) + const file = join(root, "a.txt") + let onDisk = "" + const { c, asked, updates } = await editor({ + ask: (p) => { + if (p.toolCall.kind !== "edit") return { outcome: { outcome: "selected", optionId: "once" } } + if (p.toolCall.rawInput.path === "a.txt") onDisk = readFileSync(file, "utf8") + // The first edit is accepted, the new file rejected. + return { outcome: { outcome: "selected", optionId: p.toolCall.rawInput.path === "a.txt" ? "once" : "deny" } } + }, + }) + const s: any = await c.request("session/new", { cwd: root, _meta: { mode: "manual" } }) + await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "go" }] }) + const edits = asked.filter((a) => a.toolCall.kind === "edit") + expect(edits[0].toolCall.content).toEqual([{ type: "diff", path: file, oldText: "one\n", newText: "two\n" }]) + // A file the call creates has no old text. + expect(edits[1].toolCall.content).toEqual([{ type: "diff", path: join(root, "new.txt"), oldText: null, newText: "fresh\n" }]) + // Nothing was written before the answer. + expect(onDisk).toBe("one\n") + expect(readFileSync(file, "utf8")).toBe("two\n") + expect(await Bun.file(join(root, "new.txt")).exists()).toBe(false) + // The edit that ran carries the same item after its text. + const done = updates.map((u) => u.update).find((u) => u.sessionUpdate === "tool_call_update" && u.toolCallId === "e1") + expect(done.content.map((x: any) => x.type)).toEqual(["content", "diff"]) + expect(done.content[1]).toEqual({ type: "diff", path: file, oldText: "one\n", newText: "two\n" }) +}) + +test("edits as diffs: auto mode writes as before and the diff comes after; any other client gets what it got", async () => { + fake = fakeProvider([...editScript(), ...editScript()]) + config(fake.url) + const root = project({ "a.txt": "one\n" }) + const ed = await editor() + const s: any = await ed.c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await ed.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "go" }] }) + expect(ed.asked).toEqual([]) + const created = ed.updates.map((u) => u.update).find((u) => u.sessionUpdate === "tool_call_update" && u.toolCallId === "n1") + expect(created.content[1]).toEqual({ type: "diff", path: join(root, "new.txt"), oldText: null, newText: "fresh\n" }) + // A plain ACP client: the unified diff as text on the card, the output alone on the update. + const root2 = project({ "a.txt": "one\n" }) + const plain = await editor({ lembas: false }) + const s2: any = await plain.c.request("session/new", { cwd: root2, _meta: { mode: "manual" } }) + await plain.c.request("session/prompt", { sessionId: s2.sessionId, prompt: [{ type: "text", text: "go" }] }) + const card = plain.asked.find((a) => a.toolCall.kind === "edit") + expect(card.toolCall.content).toHaveLength(1) + expect(card.toolCall.content[0].type).toBe("content") + expect(card.toolCall.content[0].content.text).toContain("-one\n+two") + const done = plain.updates.map((u) => u.update).find((u) => u.sessionUpdate === "tool_call_update" && u.toolCallId === "e1") + expect(done.content.map((x: any) => x.type)).toEqual(["content"]) +}) + +// ── files that are not text, shown ────────────────────────────────────────────────────────── + +const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]), Buffer.alloc(3000, 7)]) + +test("show: a picture is handed to a client that shows media by a handle it fetches while the request is open", async () => { + fake = fakeProvider([{ chunks: [toolCall(0, "s1", "show", JSON.stringify({ path: "out/chart.png" }))] }, { chunks: [delta({ content: "there" })] }]) + config(fake.url) + const root = project() + mkdirSync(join(root, "out")) + writeFileSync(join(root, "out/chart.png"), PNG) + let shown: any + let fetched = Buffer.alloc(0) + let afterwards: Promise | undefined + const ed: any = {} + const made = await editor({ + lembas: { editor: true, show: true, media: true }, + handlers: { + "_lembas/show": async (p) => { + shown = p + // In parts, as a large file would be. + for (let offset = 0; ; ) { + const part: any = await ed.c.request("_lembas/show/read", { handle: p.handle, offset, length: 1000 }) + fetched = Buffer.concat([fetched, Buffer.from(part.data, "base64")]) + offset += Buffer.from(part.data, "base64").length + if (part.eof) break + } + return { shown: true } + }, + }, + }) + ed.c = made.c + const s: any = await made.c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await made.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "show me" }] }) + expect(shown).toMatchObject({ sessionId: s.sessionId, toolCallId: "s1", path: "out/chart.png", kind: "image", mimeType: "image/png", size: PNG.length }) + expect(shown.hash).toMatch(/^sha256:[0-9a-f]{64}$/) + // On stdio the client is on this machine and is told where the file is; the path here never travels as `file`. + expect(shown.uri).toBe(`file://${join(root, "out/chart.png")}`) + expect(shown.file).toBeUndefined() + expect(fetched.equals(PNG)).toBe(true) + expect(fake.requests[1].messages.find((m: any) => m.role === "tool").content).toContain("Shown to the user: out/chart.png") + // Once the request is answered the handle is good for nothing. + afterwards = made.c.request("_lembas/show/read", { handle: shown.handle }) + expect((await refusal(afterwards)).data).toEqual({ reason: "invalid" }) + expect((await refusal(made.c.request("_lembas/show/read", { handle: "h_made_up" }))).data).toEqual({ reason: "invalid" }) +}) + +test("show: a client without media is not handed a picture; a table is named for one with it", async () => { + fake = fakeProvider([ + { chunks: [toolCall(0, "s1", "show", JSON.stringify({ path: "chart.png" }))] }, + { chunks: [delta({ content: "a" })] }, + { chunks: [toolCall(0, "s2", "show", JSON.stringify({ path: "loaves.csv" }))] }, + { chunks: [delta({ content: "b" })] }, + ]) + config(fake.url) + const root = project({ "loaves.csv": "kind,count\nrye,3\n" }) + writeFileSync(join(root, "chart.png"), PNG) + const sent: any[] = [] + const plain = await editor({ lembas: { show: true }, handlers: { "_lembas/show": (p) => (sent.push(p), { shown: true }) } }) + const s: any = await plain.c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await plain.c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "show" }] }) + expect(sent).toEqual([]) + expect(fake.requests[1].messages.find((m: any) => m.role === "tool").content).toContain("is not a text file") + const media = await editor({ lembas: { show: true, media: true }, handlers: { "_lembas/show": (p) => (sent.push(p), { shown: true }) } }) + const s2: any = await media.c.request("session/new", { cwd: root, _meta: { mode: "auto" } }) + await media.c.request("session/prompt", { sessionId: s2.sessionId, prompt: [{ type: "text", text: "show" }] }) + expect(sent[0]).toMatchObject({ path: "loaves.csv", kind: "table", text: "kind,count\nrye,3\n" }) + expect(sent[0].handle).toBeUndefined() +}) diff --git a/tests/acp-files.test.ts b/tests/acp-files.test.ts new file mode 100644 index 0000000..e4a833c --- /dev/null +++ b/tests/acp-files.test.ts @@ -0,0 +1,346 @@ +// Device files (harness/acp.md, spec 3.11.0, capability `fs`): `_lembas/fs/*` on the link — every +// method, and every refusal: outside the roots, through a link that points out, the CLI's own +// files, a protected path, a read-only device, remote work off, and `serve --stdio`. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { createHash } from "node:crypto" +import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs" +import { homedir, tmpdir } from "node:os" +import { join } from "node:path" +import { AcpAgent, type Limits } from "../src/acp/agent.ts" +import { moveToTrash } from "../src/acp/files.ts" +import { Peer, type Transport } from "../src/acp/rpc.ts" +import { paths } from "../src/config/paths.ts" + +function pair(): [Transport, Transport] { + const make = () => ({ msg: (_: string) => {}, end: () => {} }) + const a = make() + const b = make() + const side = (me: typeof a, other: typeof a): Transport => ({ + send: (t) => queueMicrotask(() => other.msg(t)), + onMessage: (fn) => (me.msg = fn), + onClose: (fn) => (me.end = fn), + close: () => (me.end(), other.end()), + }) + return [side(a, b), side(b, a)] +} + +const made: string[] = [] +const temp = (prefix: string) => { + const d = realpathSync(mkdtempSync(join(tmpdir(), prefix))) + made.push(d) + return d +} + +let root: string +let outside: string +let trashHome: string +const oldData = process.env.XDG_DATA_HOME +beforeEach(() => { + root = temp("ph-fs-root-") + outside = temp("ph-fs-out-") + // The trash of the test's own data directory, never the person's. + trashHome = temp("ph-fs-data-") + process.env.XDG_DATA_HOME = trashHome + mkdirSync(join(root, "docs")) + writeFileSync(join(root, "docs/notes.md"), "# Notes\nwaybread\n") + writeFileSync(join(root, "a.txt"), "alpha\n") + writeFileSync(join(root, ".hidden"), "h\n") + writeFileSync(join(outside, "secret.txt"), "not yours\n") +}) +afterEach(() => { + if (oldData === undefined) delete process.env.XDG_DATA_HOME + else process.env.XDG_DATA_HOME = oldData + for (const d of made.splice(0)) rmSync(d, { recursive: true, force: true }) +}) + +const limitsFor = (extra: Partial = {}): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, ...extra }) + +async function link(limits: Limits | "stdio" = limitsFor()) { + const [ta, tb] = pair() + new AcpAgent(new Peer(ta), limits === "stdio" ? undefined : limits) + const c = new Peer(tb) + await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + return { c, close: () => tb.close() } +} + +const refusal = async (p: Promise) => p.then(() => ({ message: "(answered)", reason: undefined as string | undefined, data: undefined as any }), (e) => ({ message: (e as Error).message, reason: (e as any).data?.reason as string | undefined, data: (e as any).data })) +const b64 = (s: string | Uint8Array) => Buffer.from(s).toString("base64") +const hash = (s: string | Uint8Array) => `sha256:${createHash("sha256").update(s).digest("hex")}` + +test("list: the roots without a path; a folder's entries, folders first, hidden ones on request", async () => { + const { c } = await link() + const top: any = await c.request("_lembas/fs/list", {}) + expect(top.path).toBe("") + expect(top.entries.map((e: any) => e.path)).toEqual([root]) + const l: any = await c.request("_lembas/fs/list", { path: root }) + expect(l.path).toBe(root) + expect(l.parent).toBe("") + expect(l.entries.map((e: any) => [e.name, e.kind])).toEqual([["docs", "dir"], ["a.txt", "file"]]) + expect(l.entries[1]).toMatchObject({ path: join(root, "a.txt"), size: 6 }) + expect(typeof l.entries[1].mtime).toBe("number") + const all: any = await c.request("_lembas/fs/list", { path: root, hidden: true }) + expect(all.entries.map((e: any) => e.name)).toContain(".hidden") + const sub: any = await c.request("_lembas/fs/list", { path: join(root, "docs") }) + expect(sub.parent).toBe(root) + expect((await refusal(c.request("_lembas/fs/list", { path: join(root, "a.txt") }))).reason).toBe("not_a_directory") + expect((await refusal(c.request("_lembas/fs/list", { path: join(root, "nope") }))).reason).toBe("missing") +}) + +test("stat and read: a file's size, time and hash; a large file in parts", async () => { + const { c } = await link() + const st: any = await c.request("_lembas/fs/stat", { path: join(root, "a.txt"), hash: true }) + expect(st).toMatchObject({ name: "a.txt", kind: "file", size: 6, hash: hash("alpha\n") }) + expect((await c.request("_lembas/fs/stat", { path: join(root, "docs") })).kind).toBe("dir") + const whole: any = await c.request("_lembas/fs/read", { path: join(root, "a.txt") }) + expect(Buffer.from(whole.data, "base64").toString()).toBe("alpha\n") + expect(whole).toMatchObject({ size: 6, offset: 0, eof: true, hash: hash("alpha\n") }) + // In parts: no hash on a part, eof on the last. + const one: any = await c.request("_lembas/fs/read", { path: join(root, "a.txt"), offset: 0, length: 2 }) + expect(one).toMatchObject({ offset: 0, eof: false }) + expect(one.hash).toBeUndefined() + const two: any = await c.request("_lembas/fs/read", { path: join(root, "a.txt"), offset: 2, length: 100 }) + expect(Buffer.from(one.data, "base64").toString() + Buffer.from(two.data, "base64").toString()).toBe("alpha\n") + expect(two.eof).toBe(true) + expect((await refusal(c.request("_lembas/fs/read", { path: join(root, "docs") }))).reason).toBe("not_a_file") + expect((await refusal(c.request("_lembas/fs/read", { path: join(root, "nope.txt") }))).reason).toBe("missing") + expect((await refusal(c.request("_lembas/fs/read", { path: "a.txt" }))).reason).toBe("invalid") +}) + +test("write: the base is what the client last saw — written, refused when changed, created with null", async () => { + const { c } = await link() + const file = join(root, "a.txt") + // As last seen: written, whole, keeping the file's mode. + const w: any = await c.request("_lembas/fs/write", { path: file, data: b64("beta\n"), base: hash("alpha\n") }) + expect(w).toMatchObject({ path: file, size: 5, hash: hash("beta\n") }) + expect(readFileSync(file, "utf8")).toBe("beta\n") + // Changed since: refused in words, with what is there now; nothing written. + const stale = await refusal(c.request("_lembas/fs/write", { path: file, data: b64("gamma\n"), base: hash("alpha\n") })) + expect(stale.reason).toBe("changed") + expect(stale.message).toContain("changed on the computer since you opened it") + expect(stale.data.hash).toBe(hash("beta\n")) + expect(readFileSync(file, "utf8")).toBe("beta\n") + // A new file: null where there is none; refused where there is one. + await c.request("_lembas/fs/write", { path: join(root, "new.txt"), data: b64("n\n"), base: null }) + expect(readFileSync(join(root, "new.txt"), "utf8")).toBe("n\n") + expect((await refusal(c.request("_lembas/fs/write", { path: file, data: b64("x"), base: null }))).reason).toBe("exists") + // No base said: refused, unless the client says to overwrite. + expect((await refusal(c.request("_lembas/fs/write", { path: file, data: b64("x") }))).reason).toBe("invalid") + await c.request("_lembas/fs/write", { path: file, data: b64("forced\n"), overwrite: true }) + expect(readFileSync(file, "utf8")).toBe("forced\n") + // Gone since it was opened. + rmSync(file) + const gone = await refusal(c.request("_lembas/fs/write", { path: file, data: b64("x"), base: hash("forced\n") })) + expect(gone.reason).toBe("changed") + expect(gone.data.hash).toBeNull() + // A folder is not a file; a folder that is not there is not made on the way. + expect((await refusal(c.request("_lembas/fs/write", { path: join(root, "docs"), data: b64("x"), overwrite: true }))).reason).toBe("not_a_file") + expect((await refusal(c.request("_lembas/fs/write", { path: join(root, "no/such/f.txt"), data: b64("x"), base: null }))).reason).toBe("missing") + // Nothing of a part file is left behind. + expect(readdirSync(root).filter((n) => n.includes("lembas-part"))).toEqual([]) +}) + +test("write: a large file in parts; the base is checked again as it is put in place; an unfinished one goes with the link", async () => { + const { c, close } = await link() + const file = join(root, "big.bin") + const first: any = await c.request("_lembas/fs/write", { path: file, data: b64("part one, "), base: null, more: true }) + expect(first.received).toBe(10) + // Until the last part, the file is not there: a reader never sees half of it. + expect(existsSync(file)).toBe(false) + const mid: any = await c.request("_lembas/fs/write", { upload: first.upload, data: b64("part two, "), more: true }) + expect(mid).toEqual({ upload: first.upload, received: 20 }) + const done: any = await c.request("_lembas/fs/write", { upload: first.upload, data: b64("part three") }) + expect(done).toMatchObject({ path: file, size: 30, hash: hash("part one, part two, part three") }) + expect(readFileSync(file, "utf8")).toBe("part one, part two, part three") + expect((await refusal(c.request("_lembas/fs/write", { upload: first.upload, data: b64("x") }))).reason).toBe("invalid") + // Somebody else writes the file while an upload over it is under way: the last part is refused. + const up: any = await c.request("_lembas/fs/write", { path: file, data: b64("new "), base: done.hash, more: true }) + writeFileSync(file, "changed meanwhile") + expect((await refusal(c.request("_lembas/fs/write", { upload: up.upload, data: b64("content") }))).reason).toBe("changed") + expect(readFileSync(file, "utf8")).toBe("changed meanwhile") + // A part over the limit is refused. + expect((await refusal(c.request("_lembas/fs/write", { path: join(root, "huge"), data: Buffer.alloc(1024 * 1024 + 1).toString("base64"), base: null }))).reason).toBe("too_large") + // An upload left open is dropped when the link goes. + await c.request("_lembas/fs/write", { path: join(root, "left.bin"), data: b64("x"), base: null, more: true }) + expect(readdirSync(root).filter((n) => n.includes("lembas-part")).length).toBe(1) + close() + await Bun.sleep(20) + expect(readdirSync(root).filter((n) => n.includes("lembas-part"))).toEqual([]) + expect(existsSync(join(root, "left.bin"))).toBe(false) +}) + +test("mkdir, move and copy: made with parents; a target that exists is refused unless overwritten; a folder never replaced", async () => { + const { c } = await link() + expect(await c.request("_lembas/fs/mkdir", { path: join(root, "x/y/z") })).toEqual({ path: join(root, "x/y/z") }) + expect(await c.request("_lembas/fs/mkdir", { path: join(root, "x/y/z") })).toEqual({ path: join(root, "x/y/z") }) + expect((await refusal(c.request("_lembas/fs/mkdir", { path: join(root, "a.txt") }))).reason).toBe("exists") + // Copy a folder with all in it; a link inside is copied as a link, not followed. + symlinkSync(join(outside, "secret.txt"), join(root, "docs/out-link")) + await c.request("_lembas/fs/copy", { from: join(root, "docs"), to: join(root, "docs2") }) + expect(readFileSync(join(root, "docs2/notes.md"), "utf8")).toBe("# Notes\nwaybread\n") + expect(lstatSync(join(root, "docs2/out-link")).isSymbolicLink()).toBe(true) + expect((await refusal(c.request("_lembas/fs/copy", { from: join(root, "a.txt"), to: join(root, "docs2") }))).reason).toBe("exists") + expect((await refusal(c.request("_lembas/fs/copy", { from: join(root, "a.txt"), to: join(root, "docs2"), overwrite: true }))).reason).toBe("exists") + expect((await refusal(c.request("_lembas/fs/copy", { from: join(root, "nope"), to: join(root, "n2") }))).reason).toBe("missing") + expect((await refusal(c.request("_lembas/fs/copy", { from: join(root, "docs"), to: join(root, "docs/inner") }))).reason).toBe("invalid") + // Move: a rename; onto a file only with overwrite. + writeFileSync(join(root, "b.txt"), "beta\n") + expect((await refusal(c.request("_lembas/fs/move", { from: join(root, "a.txt"), to: join(root, "b.txt") }))).reason).toBe("exists") + expect(await c.request("_lembas/fs/move", { from: join(root, "a.txt"), to: join(root, "b.txt"), overwrite: true })).toEqual({ path: join(root, "b.txt") }) + expect(readFileSync(join(root, "b.txt"), "utf8")).toBe("alpha\n") + expect(existsSync(join(root, "a.txt"))).toBe(false) + expect((await refusal(c.request("_lembas/fs/move", { from: join(root, "a.txt"), to: join(root, "c.txt") }))).reason).toBe("missing") + expect((await refusal(c.request("_lembas/fs/move", { from: join(root, "b.txt"), to: join(root, "no/dir/c.txt") }))).reason).toBe("missing") + // The root itself is never moved or deleted. + expect((await refusal(c.request("_lembas/fs/move", { from: root, to: join(root, "inside") }))).reason).toBe("invalid") + expect((await refusal(c.request("_lembas/fs/delete", { path: root, permanent: true }))).reason).toBe("invalid") +}) + +test("delete: to the trash where there is one; refused without one until the client says permanent", async () => { + const { c } = await link() + const file = join(root, "a.txt") + const r: any = await c.request("_lembas/fs/delete", { path: file }) + // Same file system as the test's data directory: trashed. Otherwise the refusal below covers it. + if (r.trash) { + expect(r).toEqual({ deleted: true, trash: true }) + expect(existsSync(file)).toBe(false) + expect(readFileSync(join(trashHome, "Trash/files/a.txt"), "utf8")).toBe("alpha\n") + const info = readFileSync(join(trashHome, "Trash/info/a.txt.trashinfo"), "utf8") + expect(info).toContain("[Trash Info]") + expect(info).toContain(`Path=${file}`) + } + expect((await refusal(c.request("_lembas/fs/delete", { path: join(root, "nope") }))).reason).toBe("missing") + // Permanently, on the person's word: a folder with all in it. + expect(await c.request("_lembas/fs/delete", { path: join(root, "docs"), permanent: true })).toEqual({ deleted: true, trash: false }) + expect(existsSync(join(root, "docs"))).toBe(false) +}) + +test("delete: a platform without a trash refuses and says it cannot be undone", () => { + writeFileSync(join(root, "keep.txt"), "k") + expect(moveToTrash(join(root, "keep.txt"), process.env, "win32")).toBe(false) + expect(existsSync(join(root, "keep.txt"))).toBe(true) + // A data directory that cannot be made: no trash either, and the file stays. + expect(moveToTrash(join(root, "keep.txt"), { XDG_DATA_HOME: join(root, "keep.txt", "under-a-file") }, "linux")).toBe(false) + expect(existsSync(join(root, "keep.txt"))).toBe(true) +}) + +test("delete: a link is deleted as a link; what it points to stays", async () => { + const { c } = await link() + symlinkSync(outside, join(root, "way-out")) + await c.request("_lembas/fs/delete", { path: join(root, "way-out"), permanent: true }) + expect(existsSync(join(root, "way-out"))).toBe(false) + expect(readFileSync(join(outside, "secret.txt"), "utf8")).toBe("not yours\n") +}) + +test("search: names as the @ picker finds them; inside files with content", async () => { + const { c } = await link() + const names: any = await c.request("_lembas/fs/search", { path: root, query: "notes" }) + expect(names.root).toBe(root) + expect(names.files).toContainEqual({ path: "docs/notes.md", kind: "file" }) + if (Bun.which("rg") === null) return + const found: any = await c.request("_lembas/fs/search", { path: root, query: "waybread", content: true }) + expect(found.matches).toEqual([{ path: "docs/notes.md", line: 2, text: "waybread" }]) + // As written, unless a pattern is asked for. + writeFileSync(join(root, "re.txt"), "a.c\nabc\n") + expect((await c.request("_lembas/fs/search", { path: root, query: "a.c", content: true })).matches.map((m: any) => m.text)).toEqual(["a.c"]) + expect((await c.request("_lembas/fs/search", { path: root, query: "a.c", content: true, regex: true })).matches.map((m: any) => m.text)).toEqual(["a.c", "abc"]) + const capped: any = await c.request("_lembas/fs/search", { path: root, query: "a", content: true, limit: 1 }) + expect(capped.matches.length).toBe(1) + expect(capped.truncated).toBe(true) + expect((await refusal(c.request("_lembas/fs/search", { path: root, query: "", content: true }))).reason).toBe("invalid") + expect((await refusal(c.request("_lembas/fs/search", { path: join(root, "a.txt"), query: "x" }))).reason).toBe("not_a_directory") +}) + +test("outside the roots: every method refuses, and a link that points out is outside", async () => { + const { c } = await link() + symlinkSync(outside, join(root, "way-out")) + const out = join(outside, "secret.txt") + const through = join(root, "way-out/secret.txt") + for (const path of [out, through]) { + expect((await refusal(c.request("_lembas/fs/stat", { path }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/read", { path }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/write", { path, data: b64("x"), overwrite: true }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/delete", { path, permanent: true }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/copy", { from: path, to: join(root, "stolen.txt") }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/copy", { from: join(root, "a.txt"), to: path, overwrite: true }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/move", { from: path, to: join(root, "stolen.txt") }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/move", { from: join(root, "a.txt"), to: path, overwrite: true }))).reason).toBe("outside") + } + expect((await refusal(c.request("_lembas/fs/list", { path: outside }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/list", { path: join(root, "way-out") }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/mkdir", { path: join(root, "way-out/new") }))).reason).toBe("outside") + expect((await refusal(c.request("_lembas/fs/search", { path: outside, query: "x" }))).reason).toBe("outside") + expect(readFileSync(out, "utf8")).toBe("not yours\n") + expect(existsSync(join(root, "stolen.txt"))).toBe(false) + // The listing names the link and says it leads out; it is not opened. + const l: any = await c.request("_lembas/fs/list", { path: root }) + expect(l.entries.find((e: any) => e.name === "way-out")).toMatchObject({ kind: "dir", link: outside, outside: true }) +}) + +test("the CLI's own files and protected paths: never read, written, moved, copied or deleted, even inside a root", async () => { + // The device shares the folder that holds the CLI's own configuration. + const base = join(paths.config, "..") + mkdirSync(paths.config, { recursive: true }) + writeFileSync(join(paths.config, "connections.yaml"), "connections: {}\n", { mode: 0o600 }) + const { c } = await link(limitsFor({ roots: [base] })) + const own = join(paths.config, "config.yaml") + const guarded = join(paths.config, "connections.yaml") + for (const path of [own, guarded, paths.config]) { + expect((await refusal(c.request("_lembas/fs/read", { path }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/stat", { path }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/write", { path, data: b64("x"), overwrite: true }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/delete", { path, permanent: true }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/copy", { from: path, to: join(base, "copy-of-it") }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/move", { from: path, to: join(base, "moved") }))).reason).toBe("own") + expect((await refusal(c.request("_lembas/fs/copy", { from: join(base, "nothing"), to: path, overwrite: true }))).reason).not.toBeUndefined() + } + expect((await refusal(c.request("_lembas/fs/list", { path: paths.config }))).reason).toBe("own") + expect(readFileSync(guarded, "utf8")).toBe("connections: {}\n") + // The listing above names the folder, marked protected, and no more. + const l: any = await c.request("_lembas/fs/list", { path: base, hidden: true }) + expect(l.entries.find((e: any) => e.path === paths.config)).toMatchObject({ protected: true }) + // A link to the CLI's own files from elsewhere in the root is where it points. + const way = join(base, "way-in") + rmSync(way, { force: true }) + symlinkSync(paths.config, way) + expect((await refusal(c.request("_lembas/fs/read", { path: join(way, "connections.yaml") }))).reason).toBe("own") + rmSync(way, { force: true }) +}) + +test("a protected path inside a root is refused as protected, on the spelling given and the real one", async () => { + // A device that shares the whole home: ~/.ssh is still never reached. Nothing is created there. + const { c } = await link(limitsFor({ roots: [homedir()] })) + const key = join(homedir(), ".ssh", "id_made_up_for_a_test") + expect((await refusal(c.request("_lembas/fs/read", { path: key }))).reason).toBe("protected") + expect((await refusal(c.request("_lembas/fs/write", { path: key, data: b64("x"), base: null }))).reason).toBe("protected") + expect((await refusal(c.request("_lembas/fs/delete", { path: join(homedir(), ".gnupg"), permanent: true }))).reason).toBe("protected") + expect(existsSync(key)).toBe(false) +}) + +test("a device that allows plan mode only is read-only; off, shared-only, no roots and stdio refuse everything", async () => { + const plan = await link(limitsFor({ maxMode: "plan" })) + const file = join(root, "a.txt") + expect(Buffer.from((await plan.c.request("_lembas/fs/read", { path: file })).data, "base64").toString()).toBe("alpha\n") + expect((await plan.c.request("_lembas/fs/list", { path: root })).entries.length).toBe(2) + for (const [m, p] of [ + ["write", { path: file, data: b64("x"), overwrite: true }], + ["mkdir", { path: join(root, "new") }], + ["move", { from: file, to: join(root, "b.txt") }], + ["copy", { from: file, to: join(root, "b.txt") }], + ["delete", { path: file, permanent: true }], + ] as const) { + const r = await refusal(plan.c.request(`_lembas/fs/${m}`, p)) + expect([m, r.reason]).toEqual([m, "read_only"]) + expect(r.message).toContain("plan mode only") + } + expect(readFileSync(file, "utf8")).toBe("alpha\n") + expect(statSync(root).isDirectory()).toBe(true) + const all = ["list", "stat", "read", "write", "mkdir", "delete", "search"] + for (const limits of [limitsFor({ enabled: false }), limitsFor({ sharedOnly: true }), limitsFor({ roots: [] }), "stdio" as const]) { + const { c } = await link(limits) + for (const m of all) expect([m, (await refusal(c.request(`_lembas/fs/${m}`, { path: file, data: b64("x"), overwrite: true, query: "a" }))).reason]).toEqual([m, "off"]) + expect((await refusal(c.request("_lembas/fs/list", {}))).reason).toBe("off") + expect((await refusal(c.request("_lembas/fs/move", { from: file, to: join(root, "b.txt") }))).reason).toBe("off") + expect((await refusal(c.request("_lembas/fs/copy", { from: file, to: join(root, "b.txt") }))).reason).toBe("off") + } + expect(readFileSync(file, "utf8")).toBe("alpha\n") +}) diff --git a/tests/acp.test.ts b/tests/acp.test.ts index 1dbd075..2cc52fd 100644 --- a/tests/acp.test.ts +++ b/tests/acp.test.ts @@ -275,7 +275,7 @@ test("the terminal: a real shell through the link, only where remote.terminal sa config(fake.url) const root = project() const off = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true }) - expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns"]) + expect(off.init._meta.lembas.capabilities).toEqual(["directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", "progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns", "editor", "media", "fs"]) await expect(off.c.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("lembas remote terminal on") const { c, init } = await client({ roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true, terminal: true }) diff --git a/tests/conformance.ts b/tests/conformance.ts index 1c71ddc..adec112 100644 --- a/tests/conformance.ts +++ b/tests/conformance.ts @@ -43,8 +43,21 @@ import { cancelOf, reattach } from "../src/acp/turns.ts" import { outstanding, type OutstandingInput } from "../src/session/outstanding.ts" import { background, scheduledRefusal, twin, type BackgroundCall, type Listed } from "../src/provider/interactive.ts" +import { diffContent, editorBlock, rewriteMessage, rewriteModel, RewriteOutput, trimWindow } from "../src/acp/editor.ts" +import { baseCheck, judgePath, type FsOp } from "../src/acp/files.ts" +import { showPlan } from "../src/tool/show.ts" + type Case = Record +/** A path with the symlinks of a case followed (`links`: path → target), as realPath would. */ +function followLinks(links: Record, path: string, depth = 0): string { + if (depth > 40) return path + const hit = Object.keys(links) + .filter((l) => path === l || path.startsWith(l + "/")) + .sort((a, b) => b.length - a.length)[0] + return hit === undefined ? path : followLinks(links, links[hit]! + path.slice(hit.length), depth + 1) +} + /** Whether a path is at `ro` or above under `grants` (fs_access's rule: the most specific grant on * the path or above it wins; none where nothing is granted). No grants at all: everything readable. */ function readableUnder(grants: Record | undefined, path: string): boolean { @@ -58,6 +71,46 @@ function readableUnder(grants: Record | undefined, path: string) } export const AREAS: Record unknown> = { + // Spec 3.11.0: an editor as the client (src/acp/editor.ts). + editor: (c) => { + if (c.kind === "trim") return trimWindow(c.prefix as string, c.suffix as string, c.max as number) + if (c.kind === "context") return { block: editorBlock(c.editor, c.root as string, (c.limits ?? {}) as Record) ?? null } + if (c.kind === "message") return { message: rewriteMessage(c as unknown as Parameters[0], (c.limits ?? {}) as Record) } + if (c.kind === "output") { + const out = new RewriteOutput(c.selection as string) + const pieces = [...(c.chunks as string[]).map((x) => out.feed(x)), out.end()] + // The pieces sent as deltas, joined, are the result's text. + if (pieces.join("") !== out.text) throw new Error(`editor output: the pieces ${JSON.stringify(pieces)} are not the text ${JSON.stringify(out.text)}`) + return { text: out.text } + } + if (c.kind === "model") { + const r = rewriteModel({ asked: c.asked as string | undefined, session: c.session as string | undefined, main: c.main as string | undefined, served: c.served as string[], start: c.start as string | undefined }) + return { model: r.model, from: r.from } + } + if (c.kind === "diff") return { content: diffContent({ editor: c.editor === true, when: c.when as "ask" | "done", bytes: c.bytes as number, max: c.max as number }) } + throw new Error(`editor: unknown kind ${String(c.kind)}`) + }, + // Spec 3.11.0: device files (src/acp/files.ts). + device_files: (c) => { + if (c.kind === "base") return baseCheck({ ...("base" in c ? { base: c.base } : {}), overwrite: c.overwrite, current: (c.current ?? null) as string | null }) + const guardedRoots = c.protected as string[] + const links = (c.links ?? {}) as Record + return judgePath({ + op: c.op as FsOp, + path: c.path as string, + roots: c.roots as string[], + own: c.own as string[], + guarded: (p) => guardedRoots.some((g) => p === g || p.startsWith(g + "/")), + guardedRoots, + enabled: c.enabled === true, + sharedOnly: c.shared_only === true, + maxMode: c.max_mode as Mode, + real: (p) => followLinks(links, p), + deep: c.deep === true, + }) + }, + // Spec 3.11.0: what the show tool sends for a file (src/tool/show.ts). + show: (c) => showPlan({ name: c.name as string, media: c.media === true, text: c.text === true, size: c.size as number }), // Spec 3.10.0: which turn a `session/cancel` touches (src/acp/turns.ts). cancel: (c) => cancelOf({ turn: c.turn as string | undefined, running: c.running as string | undefined, queued: c.queued as string[] | undefined }), // Spec 3.10.0: what a session still has out when no turn of it runs (src/session/outstanding.ts).