Device files judged again after every wait; files that run code behind a device setting; unsaved text kept
ci / check (push) Canceled after 0s

After an independent review of the spec 3.11.0 work.

- acp/files.ts: a write judged its path, waited for the base hash, then
  opened and renamed by name - a move in between could swap a link in and
  send the write out of remote.roots. Changes now run one at a time for
  every link of the process, a path is judged again after each wait and
  must be the same place, the part file is proved to lie in the target's
  own directory before the rename, and hashes and reads go through an open
  descriptor. A part file is never removed by a name that may lead
  elsewhere. Copy, delete and the listing of names for a search no longer
  block; uploads are capped in all; a listing is cut before its entries
  are looked at; names are kept for four folders; part files are hidden,
  journalled and swept at start.
- remote.files_that_run_code (off by default; lembas remote
  files-that-run-code on|off): off, _lembas/fs write, mkdir, move, copy
  and delete refuse git's own directory, a project's agent configuration
  and the user's start-up files with the reason runs_code. Said in the
  limits.
- tool/buffers.ts: a file read through the editor is never read or written
  from the disk behind it; previews record nothing; a write the client
  never answered is not repeated. The client's fs capabilities are read on
  stdio only.
- Rewrites are tracked from the start, capped at four, stopped with the
  client; the id is read one way. show's handle is an open descriptor.
- A typed message beginning like the editor's block is shown; a closing
  tag in a diagnostic or a selection cannot end the block.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-24 12:06:03 +00:00
1 parent e8a6cbeb06
commit dd5b6e3faf
21 files changed
+1012 -211

No files matched your search

+11 -1
View File
@@ -25,7 +25,8 @@ not text shown in a chat.
- **Unsaved text**: where the editor offers ACP's `fs/read_text_file` and
`fs/write_text_file`, the agent reads the editor's buffers and writes through them. A file
you changed in the editor after the agent read it is not overwritten: the agent is told to
read it again.
read it again. Text it read from the editor is never replaced with the text on disk — if the
editor stops answering, the edit is refused rather than worked out from the saved file.
- **Edits as diffs**: when an edit is asked about (always in manual mode) the approval carries
each file's text before and after, so the editor shows the diff itself; every finished edit
carries the same, for a list of changed files. Edit and auto mode write as before.
@@ -38,6 +39,15 @@ not text shown in a chat.
read-only where the computer allows plan mode only. A write is checked against what you last
saw, so a file changed meanwhile is not overwritten; a delete goes to the system's trash, or is
refused until you confirm it cannot be undone.
Changes run one at a time, and a path is looked at again after anything was waited for, so a
link moved in meanwhile cannot send a write somewhere else.
- **Files that run code are read-only from the web unless this computer says otherwise**
(`remote.files_that_run_code`, off by default; `lembas remote files-that-run-code on|off`).
Git's hooks and configuration, a project's agent configuration (its rules, MCP servers,
commands, agents and skills) and your shell's start-up files can be read from the file manager
of the web UI and the apps, and are changed there only once you turn the setting on here. Only
the global configuration can turn it on. The computer says which it is with its limits, so the
apps can show such a file as read-only beforehand.
- **The `show` tool also shows files that are not text** (capability `media`): a screenshot the
agent took, a chart, a recording, a PDF or a 3D model appears in the chat of a client that can
show one, whether or not the model can read that kind of file itself.
+4
View File
@@ -1091,6 +1091,10 @@
"description": "Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off.",
"type": "boolean"
},
"files_that_run_code": {
"description": "Let the file manager of the web UI and the apps change files that run code here (harness acp.md, spec 3.11.0): git's hooks and configuration, a project's agent configuration, your shell's start-up files. Default false: they can be read from there, and are changed only on this machine.",
"type": "boolean"
},
"terminal_integration": {
"description": "Shell integration in those terminals (bash, zsh, fish): after your own startup files, the shell marks each prompt, command and exit status (OSC 133) and its directory (OSC 7), so the web UI shows the directory, a mark beside each finished command, and can jump between commands. false: the shell starts as it is. Default true.",
"type": "boolean"
+63 -39
View File
@@ -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 { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs"
import { closeSync, existsSync, fstatSync, 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"
@@ -49,7 +49,7 @@ import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFi
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 { DeviceFiles, hashFd } 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"
@@ -58,6 +58,10 @@ 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"
/** The client's own id for a request (`_lembas/complete`, `_lembas/edit` and their cancels), read
* the same way wherever it is read. */
const requestId = (v: unknown): string | undefined => (typeof v === "string" && v ? v.slice(0, 100) : undefined)
export const ACP_VERSION = 1
/** The link's version (LLeMbas `services/device_link.py:PROTOCOL`, harness/acp.md *Versions*). 3:
* LLeMbas CLI 2.0 and LLeMbas 2.0, which speak it alone — a 1.x peer (1 and 2) and a 2.0 one refuse
@@ -83,6 +87,9 @@ export interface Limits {
enabled?: boolean
/** Accept scheduled work (`remote.scheduled`, spec 3.5.0), with remote work on. Absent: no. */
scheduled?: boolean
/** `remote.files_that_run_code` (spec 3.11.0): device files may change files that run code.
* Absent: no. */
filesThatRunCode?: boolean
/** The link a terminal holds for /remote on a machine whose remote work is off: only
* the sessions shared from that terminal can be reached; the web UI opens none of its own. */
sharedOnly?: boolean
@@ -499,7 +506,9 @@ export function historyTurns(messages: Message[], cwd = "") {
if (m.role === "user") {
reply = undefined
const texts = m.parts.map((p) => (p.type === "text" ? p.text : ""))
const text = texts.filter((t) => !ATTACHMENT.test(t)).join("\n").trim()
// The words typed are the first part; an attachment never is — so a message that happens to
// start like one is still shown.
const text = texts.filter((t, i) => i === 0 || !ATTACHMENT.test(t)).join("\n").trim()
const attachments = storedAttachments(texts, cwd)
// A turn the harness started (a note, with its mark) is in the history as what it is.
if (text || attachments.length) turns.push({ role: "user", text, ...(m.turnId ? { turnId: m.turnId } : {}), ...(attachments.length ? { attachments } : {}), ...(m.machine ? { machine: true as const } : {}) })
@@ -555,12 +564,14 @@ export class AcpAgent {
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<string, AbortController>()
/** Files handed to the client by the show tool, for `_lembas/show/read`, while their request is open. */
private handles = new Map<string, { abs: string; size: number; mtimeMs: number }>()
/** Every rewrite under way — stopped with the client — and those that carried an id, by it. */
private rewrites = new Set<AbortController>()
private rewriteIds = new Map<string, AbortController>()
/** Files handed to the client by the show tool, for `_lembas/show/read`, while their request is
* open: each an open descriptor, so what is read is the file the tool was allowed to show. */
private handles = new Map<string, { fd: number; size: number; mtimeMs: number }>()
/** `_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))
private files = new DeviceFiles(() => (this.limits ? { roots: this.limits.roots, maxMode: this.limits.maxMode, enabled: this.limits.enabled, sharedOnly: this.limits.sharedOnly, runsCode: this.limits.filesThatRunCode === true } : undefined))
constructor(
private peer: Peer,
@@ -605,7 +616,7 @@ export class AcpAgent {
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.on("_lembas/edit/cancel", (p) => this.rewriteIds.get(requestId(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))
@@ -638,7 +649,8 @@ export class AcpAgent {
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()
for (const a of this.rewrites) a.abort()
for (const h of this.handles.values()) closeSync(h.fd)
this.handles.clear()
this.files.close()
})
@@ -652,7 +664,9 @@ export class AcpAgent {
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 }
// Honoured on `serve --stdio` only: the link's client is a server, which holds no buffers of
// this machine's files — taking its word would have every file tool read from it and write to it.
this.clientFs = this.limits ? { read: false, write: false } : { 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.
@@ -678,7 +692,7 @@ export class AcpAgent {
lembas: {
protocol: this.protocol,
harness_spec: HARNESS_VERSION,
limits: this.limits ? { roots: this.limits.roots, max_mode: this.limits.maxMode, scheduled: this.limits.scheduled === true } : null,
limits: this.limits ? { roots: this.limits.roots, max_mode: this.limits.maxMode, scheduled: this.limits.scheduled === true, files_that_run_code: this.limits.filesThatRunCode === true } : null,
// The login's connection: a `model` event's ref `<connection>/<name>` is the
// instance's own model `<name>`; any other ref is one only this device has.
connection: this.instanceConnection ?? null,
@@ -981,18 +995,19 @@ export class AcpAgent {
* 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<ShowRequest, { file: string }>, callId?: string) {
const { file, ...said } = req
const st = statSync(file)
const fd = openSync(file, "r")
const st = fstatSync(fd)
const handle = `h_${crypto.randomUUID()}`
this.handles.set(handle, { abs: file, size: st.size, mtimeMs: st.mtimeMs })
this.handles.set(handle, { fd, size: st.size, mtimeMs: st.mtimeMs })
try {
const hash = await hashFile(file)
const hash = await hashFd(fd)
return (await this.peer.request(
"_lembas/show",
{ sessionId: s.id, toolCallId: callId ?? "", ...said, hash, handle, ...(this.limits ? {} : { uri: `file://${file.split("/").map(encodeURIComponent).join("/")}` }) },
{ sessionId: s.id, toolCallId: callId ?? "", ...said, size: st.size, 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)
if (this.handles.delete(handle)) closeSync(fd)
}
}
@@ -1001,24 +1016,13 @@ export class AcpAgent {
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<typeof statSync>
try {
st = statSync(h.abs)
} catch {
throw new RpcError(INVALID_PARAMS, "the file is gone from this computer", { reason: "changed" })
}
const st = fstatSync(h.fd)
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)
}
const n = buf.length ? readSync(h.fd, buf, 0, buf.length, offset) : 0
return { data: buf.subarray(0, n).toString("base64"), offset, eof: offset + n >= h.size }
}
@@ -1051,9 +1055,11 @@ export class AcpAgent {
? {
write: async (abs: string, content: string) => {
if (!live()) return false
// Taken, refused (the client answered with an error), or unknown: no answer came —
// the client may still apply it, so the disk is not written as well.
return this.peer.request("fs/write_text_file", { sessionId: s.id, path: abs, content }, wait).then(
() => true,
() => false,
() => true as const,
(e) => (e instanceof RpcError && !e.noAnswer ? false : ("unknown" as const)),
)
},
}
@@ -1068,7 +1074,8 @@ export class AcpAgent {
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() }
const id = requestId(p?.id)
const mine = { ...(id ? { id } : {}), abort: new AbortController() }
this.completion = mine
try {
return await completeOnServer(login, body, mine.abort.signal)
@@ -1083,7 +1090,7 @@ export class AcpAgent {
}
private completeCancel(p: any) {
const id = typeof p?.id === "string" ? p.id : ""
const id = requestId(p?.id)
const running = this.completion
if (id && running && running.id === id) running.abort.abort()
}
@@ -1102,7 +1109,26 @@ export class AcpAgent {
* 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 id = requestId(p?.id)
if (this.rewrites.size >= LOOP.editor.rewrite.concurrent_max)
throw new RpcError(INVALID_PARAMS, `${LOOP.editor.rewrite.concurrent_max} rewrites are already being written — wait for one, or cancel it`, { reason: "busy" })
// Tracked from here — before the model is even known — so a cancel that comes while it is
// being found, and the client going away, both reach it; with an id or without.
const abort = new AbortController()
this.rewrites.add(abort)
if (id) this.rewriteIds.get(id)?.abort(), this.rewriteIds.set(id, abort)
try {
return await this.rewrite(p, params, id, abort)
} catch (e) {
if (abort.signal.aborted) return CANCELLED
throw e
} finally {
this.rewrites.delete(abort)
if (id && this.rewriteIds.get(id) === abort) this.rewriteIds.delete(id)
}
}
private async rewrite(p: any, params: ReturnType<typeof rewriteParams>, id: string | undefined, abort: AbortController) {
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
@@ -1137,8 +1163,8 @@ export class AcpAgent {
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)
// Cancelled while the model was being found: nothing is sent to it.
if (abort.signal.aborted) return CANCELLED
try {
const text = await runRewrite({
client,
@@ -1153,8 +1179,6 @@ export class AcpAgent {
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)
}
}
+7 -3
View File
@@ -391,6 +391,10 @@ function saidPath(p: unknown, root: string): string | undefined {
return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel : clean
}
/** Text of a file's or a tool's own inside the block: it cannot close the block or the selection
* (`</editor>` is written `< /editor>`); nothing else of it is touched. */
const cannotClose = (s: string) => s.replace(/<\/(editor|selection)\s*>/gi, "< /$1>")
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"])
@@ -415,7 +419,7 @@ export function editorBlock(editor: unknown, root: string, limits: Partial<typeo
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(`<selection>\n${sel.text.replace(/\n$/, "")}\n</selection>`)
else lines.push(`<selection>\n${cannotClose(sel.text.replace(/\n$/, ""))}\n</selection>`)
}
}
const diagnostics = (Array.isArray(e.diagnostics) ? e.diagnostics : []).filter((d: any) => d && typeof d === "object" && typeof d.message === "string" && d.message.trim())
@@ -427,9 +431,9 @@ export function editorBlock(editor: unknown, root: string, limits: Partial<typeo
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()
let message = cannotClose((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)})` : ""
const source = typeof d.source === "string" && d.source.trim() ? ` (${oneLine(d.source).replace(/[<>]/g, "").trim().slice(0, 40)})` : ""
lines.push(`- ${head ? `${head}: ` : ""}${message}${source}`)
}
if (diagnostics.length > L.diagnostics_max) lines.push(`(${diagnostics.length - L.diagnostics_max} more)`)
+401 -130
View File
@@ -3,7 +3,8 @@
// 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 { closeSync, existsSync, fstatSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, renameSync, rmSync, statSync, writeFileSync, writeSync, chmodSync } from "node:fs"
import { cp, rm } from "node:fs/promises"
import { createHash } from "node:crypto"
import { homedir } from "node:os"
import { basename, dirname, isAbsolute, join, resolve } from "node:path"
@@ -12,12 +13,12 @@ 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 fuzzysort from "fuzzysort"
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"
export type FsReason = "off" | "invalid" | "outside" | "own" | "protected" | "runs_code" | "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. */
@@ -42,10 +43,12 @@ export interface Judging {
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 change at `p` would change what runs on the device (`runsCode`). Absent: not judged. */
runsCode?: (p: string) => 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. */
* applies of off, invalid, outside, own, protected, runs_code, 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()) : ""
@@ -61,10 +64,42 @@ export function judgePath(o: Judging): { ok: true; real: string } | { refused: F
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" }
// Reading a file that runs is reading; changing one is not the same act as changing a document.
if (o.op !== "read" && (o.runsCode?.(real) || o.runsCode?.(norm))) return { refused: "runs_code" }
if (o.op !== "read" && o.maxMode === "plan") return { refused: "read_only" }
return { ok: true, real }
}
/** Files that run code (acp.md, *Files that run code*; `loop.json` `files.runs_code`): git's own
* directory (hooks and config run programs), a project's agent configuration (its config,
* agents, commands, skills — and with them its MCP servers), and the start-up files of the
* device's user. `_lembas/fs/*` reads them and never changes them: a path that is one, is under
* one, or — for the project's and the home's — holds one. */
export function runsCode(p: string, home: string, R: typeof F.runs_code = F.runs_code): boolean {
const parts = p.split("/")
if (parts.some((x) => R.segments.includes(x))) return true
const at = parts.lastIndexOf(R.project_dir)
if (at >= 0) {
const rest = parts.slice(at + 1)
// The directory itself (moved or copied into place it brings all of them), or one of its names.
if (!rest.length || R.project.includes(rest[0]!)) return true
}
return R.home.some((h) => {
const g = join(home, h)
return inside(p, g) || (p !== home && inside(g, p) && inside(p, home))
})
}
/** After anything was waited for, a path is judged again: the method goes on only when it is
* still allowed and still the same place (`kind: again`). Otherwise something moved under it. */
export function sameAgain(first: string, again: { ok: true; real: string } | { refused: FsReason }): { act: true } | { refused: FsReason } {
if ("refused" in again) return { refused: again.refused }
return again.real === first ? { act: true } : { refused: "changed" }
}
/** A part file of an upload, beside its target: never listed, searched or named by a client. */
export const PART = /^\..*\.lembas-part$/
const HASH = /^sha256:[0-9a-f]{64}$/
/** Whether `_lembas/fs/write` writes (`kind: base`): the file must be as the client last saw it. */
@@ -81,6 +116,8 @@ export interface FsLimits {
maxMode: Mode
enabled?: boolean
sharedOnly?: boolean
/** `remote.files_that_run_code`: files that run code may be changed. Absent: no. */
runsCode?: boolean
}
const SENTENCES: Record<string, (p: string) => string> = {
@@ -94,6 +131,7 @@ const SENTENCES: Record<string, (p: string) => string> = {
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`,
runs_code: (p) => `${p} is a file that runs code on this computer (git's own files, a project's agent configuration, or a start-up file): it can be read from here, and is changed from here only once the computer allows it — lembas remote files-that-run-code on there (remote.files_that_run_code)`,
}
const refuse = (reason: FsReason, path: string, message?: string, extra: Record<string, unknown> = {}): never => {
@@ -107,15 +145,83 @@ export function ownDirs(): string[] {
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<string> {
const yieldNow = () => new Promise<void>((r) => setImmediate(r))
/** `sha256:` and the hex digest of an open file's content, read in pieces, letting other work in
* between. By descriptor: the file that was judged is the file that is read, whatever becomes
* of its name meanwhile. */
export async function hashFd(fd: number): Promise<string> {
const h = createHash("sha256")
for await (const chunk of createReadStream(abs)) h.update(chunk as Buffer)
const buf = Buffer.alloc(1024 * 1024)
for (let at = 0; ; ) {
const n = readSync(fd, buf, 0, buf.length, at)
if (n <= 0) break
h.update(buf.subarray(0, n))
at += n
await yieldNow()
}
return `sha256:${h.digest("hex")}`
}
/** The same for a path this process chose itself (the show tool's file). */
export async function hashFile(abs: string): Promise<string> {
const fd = openSync(abs, "r")
try {
return await hashFd(fd)
} finally {
closeSync(fd)
}
}
const hashBytes = (b: Uint8Array) => `sha256:${createHash("sha256").update(b).digest("hex")}`
/** The part files of uploads under way, kept in the state directory so that a process that died
* with one open can take it away at its next start. */
const journalFile = () => join(paths.state, "uploads.json")
function journal(change?: (list: string[]) => string[]): string[] {
let list: string[] = []
try {
const read = JSON.parse(readFileSync(journalFile(), "utf8"))
if (Array.isArray(read)) list = read.filter((x): x is string => typeof x === "string")
} catch {}
if (!change) return list
const next = change(list)
try {
mkdirSync(paths.state, { recursive: true, mode: 0o700 })
writeFileSync(journalFile(), JSON.stringify(next), { mode: 0o600 })
} catch {}
return next
}
/** Whether a part file's name still leads to where it was made: its directory, as recorded, is
* its own real path (nothing on the way became a link), and the name is a plain file. */
function partInPlace(part: string): boolean {
try {
return realPath(dirname(part)) === dirname(part) && lstatSync(part).isFile()
} catch {
return false
}
}
/** Part files a process left behind (it was killed with an upload open): removed, once, by the
* next one. Only what the journal names and what is named like a part file. */
export function sweepParts(live: ReadonlySet<string> = new Set()): string[] {
const gone: string[] = []
journal((list) =>
list.filter((part) => {
if (live.has(part)) return true
if (PART.test(basename(part)) && partInPlace(part)) {
try {
rmSync(part, { force: true })
gone.push(part)
} catch {}
}
return false
}),
)
return gone
}
interface Upload {
id: string
/** Where the file really goes, and the part file beside it. */
@@ -123,6 +229,8 @@ interface Upload {
part: string
fd: number
received: number
/** What was said of it when it began (for the sentences). */
said: string
base: unknown
overwrite: unknown
timer: ReturnType<typeof setTimeout>
@@ -180,23 +288,62 @@ export function moveToTrash(abs: string, env: NodeJS.ProcessEnv = process.env, p
}
}
/** One change at a time, for every link of this process: a path that was judged stays what it
* was judged to be until the method that judged it has acted, because nothing else that changes
* files through these methods runs in between. */
let changes: Promise<unknown> = Promise.resolve()
function oneAtATime<T>(fn: () => T | Promise<T>): Promise<T> {
const run = changes.then(fn, fn)
changes = run.catch(() => {})
return run
}
let swept = false
/** The names under a folder, for a search by name: kept for the few folders searched last. */
interface Names {
at: number
all: string[]
}
/** `_lembas/fs/*` for one link. */
export class DeviceFiles {
private uploads = new Map<string, Upload>()
private indexes = new Map<string, FileIndex>()
private names = new Map<string, Names>()
constructor(private limits: () => FsLimits | undefined) {}
constructor(private limits: () => FsLimits | undefined) {
if (!swept) {
swept = true
sweepParts()
}
}
/** Where `path` really is for `op`, or the refusal. */
private judge(op: FsOp, path: unknown, deep = false): string {
private judging(op: FsOp, path: unknown, deep = false) {
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)
if (!L) return { refused: "off" as FsReason }
if (PART.test(basename(said))) return { refused: "invalid" as FsReason }
const home = realPath(homedir())
return 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, ...(L.runsCode === true ? {} : { runsCode: (p: string) => runsCode(p, home) }) })
}
/** Where `path` really is for `op`, or the refusal. Nothing is waited for between this and
* the act it allows — see `again`. */
private judge(op: FsOp, path: unknown, deep = false): string {
const r = this.judging(op, path, deep)
if ("refused" in r) return refuse(r.refused, typeof path === "string" ? path : "")
return r.real
}
/** After something was waited for: the path judged once more, and still the same place. */
private again(op: FsOp, path: unknown, first: string, deep = false): void {
const r = sameAgain(first, this.judging(op, path, deep))
if ("act" in r) return
const said = typeof path === "string" ? path : ""
if (r.refused === "changed") return refuse("changed", said, `${said} is not where it was a moment ago — something moved under it while this was being done. Nothing was written; look at the folder again`)
return refuse(r.refused, said)
}
/** 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)
@@ -214,18 +361,21 @@ export class DeviceFiles {
const l = lstatSync(abs)
let link: string | undefined
let st = l
let outside = false
if (l.isSymbolicLink()) {
link = readlinkSync(abs)
try {
st = statSync(abs)
} catch {}
outside = !this.isInside(abs)
// What a link that leads out points to is not looked at: its name and target are all that is said.
if (!outside)
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,
kind: outside ? "other" : st.isDirectory() ? "dir" : st.isFile() ? "file" : "other",
size: !outside && st.isFile() ? st.size : 0,
mtime: Math.round(st.mtimeMs),
...(link !== undefined ? { link } : {}),
...(outside ? { outside: true as const } : {}),
@@ -233,6 +383,15 @@ export class DeviceFiles {
}
}
/** 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
}
}
list(p: any) {
const L = this.limits()
const wanted = typeof p?.path === "string" ? p.path.trim() : ""
@@ -242,70 +401,62 @@ export class DeviceFiles {
return { path: "", entries: roots.sort().map((d) => this.entry(d)) }
}
const dir = this.judge("read", wanted)
let st: ReturnType<typeof statSync>
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 there = this.kindOf(dir)
if (!there) return refuse("missing", wanted)
if (there !== "dir") return refuse("not_a_directory", wanted)
// Folders first, then by name — decided from the directory's own record, so that only the
// entries that are answered are looked at one by one.
const all = readdirSync(dir, { withFileTypes: true }).filter((d) => (p?.hidden === true || !d.name.startsWith(".")) && !PART.test(d.name))
const isDir = (d: (typeof all)[number]) => d.isDirectory() || (d.isSymbolicLink() && this.isInside(join(dir, d.name)) && this.kindOf(join(dir, d.name)) === "dir")
const ranked = all.map((d) => ({ name: d.name, dir: isDir(d) })).sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name))
const entries: Entry[] = []
for (const n of names) {
for (const d of ranked.slice(0, F.list_max)) {
try {
entries.push(this.entry(join(dir, n)))
entries.push(this.entry(join(dir, d.name)))
} 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 } : {}) }
return { path: dir, parent, entries, ...(ranked.length > F.list_max ? { truncated: true } : {}) }
}
async stat(p: any) {
const said = String(p?.path ?? "")
const abs = this.judge("read", p?.path)
if (!existsSync(abs)) return refuse("missing", String(p?.path))
if (!existsSync(abs)) return refuse("missing", said)
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 {
if (p?.hash !== true || e.kind !== "file") return e
// Opened in the same breath as it was judged: the hash is of that file.
const fd = openSync(abs, "r")
try {
return statSync(abs).isDirectory() ? "dir" : "other"
} catch {
return undefined
return { ...e, hash: await hashFd(fd) }
} finally {
closeSync(fd)
}
}
private file(abs: string, said: string) {
let st: ReturnType<typeof statSync>
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
let fd: number
try {
if (buf.length) n = readSync(fd, buf, 0, buf.length, offset)
fd = openSync(abs, "r")
} catch {
return refuse("missing", said)
}
try {
const st = fstatSync(fd)
if (!st.isFile()) return refuse("not_a_file", 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 n = buf.length ? readSync(fd, buf, 0, buf.length, offset) : 0
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) } : {}) }
} 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 {
@@ -315,13 +466,19 @@ export class DeviceFiles {
return b
}
/** The hash of the file at `abs` now, or null when there is none. */
private async current(abs: string): Promise<string | null> {
let fd: number
try {
if (!statSync(abs).isFile()) return null
fd = openSync(abs, "r")
} catch {
return null
}
return hashFile(abs)
try {
return fstatSync(fd).isFile() ? await hashFd(fd) : null
} finally {
closeSync(fd)
}
}
private async checkBase(u: { target: string; base: unknown; overwrite: unknown }, said: string) {
@@ -342,10 +499,18 @@ export class DeviceFiles {
private drop(u: Upload) {
clearTimeout(u.timer)
this.uploads.delete(u.id)
// The part file is removed by its name only while that name is still in the target's own
// directory. Where the folder was moved from under it, the name may lead anywhere: the file
// is emptied through its descriptor instead, and left where it lies.
const inPlace = partInPlace(u.part)
try {
if (!inPlace) ftruncateSync(u.fd, 0)
} catch {}
try {
closeSync(u.fd)
} catch {}
rmSync(u.part, { force: true })
if (inPlace) rmSync(u.part, { force: true })
journal((list) => list.filter((x) => x !== u.part))
}
private idle(u: Upload) {
@@ -354,52 +519,84 @@ export class DeviceFiles {
;(u.timer as { unref?: () => void }).unref?.()
}
async write(p: any) {
/** One part into an upload's part file — by its descriptor, never by name — within the cap. */
private take(u: Upload, data: Buffer) {
if (u.received + data.length > F.upload_max_bytes) {
this.drop(u)
return refuse("too_large", u.said, `${u.said} is larger than the ${Math.round(F.upload_max_bytes / 1024 / 1024)} MB one file may be from here — nothing was written`)
}
writeSync(u.fd, data)
u.received += data.length
}
write(p: any) {
return oneAtATime(() => this.writing(p))
}
private async writing(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
try {
// Judged again with every part: the limits, and the place, may have changed since the first.
this.again("write", u.target, u.target)
this.take(u, data)
} catch (e) {
if (this.uploads.has(u.id)) this.drop(u)
throw e
}
if (p.more === true) {
this.idle(u)
return { upload: u.id, received: u.received }
}
return this.commit(u, u.target)
return this.commit(u)
}
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`)
// Hashing what is there is waited for — so the path is judged again after it, and the part
// file is opened in the same breath as that second look.
await this.checkBase({ target, base: p?.base, overwrite: p?.overwrite }, said)
this.again("write", p?.path, target)
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) }
journal((list) => [...list, part])
let fd: number
try {
fd = openSync(part, "wx", 0o600)
} catch (e) {
journal((list) => list.filter((x) => x !== part))
throw e
}
const u: Upload = { id, target, part, fd, received: 0, said, base: p?.base, overwrite: p?.overwrite, timer: setTimeout(() => {}, 0) }
this.uploads.set(id, u)
try {
writeSync(u.fd, data)
u.received = data.length
this.take(u, data)
} catch (e) {
this.drop(u)
if (this.uploads.has(id)) this.drop(u)
throw e
}
if (p?.more === true) {
this.idle(u)
return { upload: id, received: u.received }
}
return this.commit(u, said)
return this.commit(u)
}
/** The last part is in: the base checked once more, then the file put in place whole. */
private async commit(u: Upload, said: string) {
/** The last part is in: the base checked once more, the path judged once more, the part file
* proved to be where the target is — and then, with nothing waited for in between, the file
* put in place whole. */
private async commit(u: Upload) {
try {
closeSync(u.fd)
await this.checkBase(u, said)
await this.checkBase(u, u.said)
this.again("write", u.target, u.target)
if (!partInPlace(u.part)) refuse("changed", u.said, `${u.said} is not where it was a moment ago — something moved under it while this was being done. Nothing was written; look at the folder again`)
// The file keeps its mode; a new one gets the usual.
let mode = 0o644
try {
@@ -408,24 +605,32 @@ export class DeviceFiles {
chmodSync(u.part, mode)
renameSync(u.part, u.target)
} catch (e) {
rmSync(u.part, { force: true })
if (partInPlace(u.part)) rmSync(u.part, { force: true })
throw e
} finally {
clearTimeout(u.timer)
this.uploads.delete(u.id)
journal((list) => list.filter((x) => x !== u.part))
}
const fd = openSync(u.target, "r")
try {
const st = fstatSync(fd)
return { path: u.target, size: st.size, mtime: Math.round(st.mtimeMs), hash: await hashFd(fd) }
} finally {
closeSync(fd)
}
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 }
return oneAtATime(() => {
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
@@ -442,50 +647,114 @@ export class DeviceFiles {
return abs
}
/** A whole tree copied, off the main thread: a link is copied as a link, never followed. */
private tree(from: string, to: string) {
return cp(from, to, { recursive: true, verbatimSymlinks: true, force: true })
}
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 }
return oneAtATime(async () => {
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. Nothing else changes
// files from here meanwhile (oneAtATime).
await this.tree(from, to)
await rm(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 }
return oneAtATime(async () => {
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")
await this.tree(from, to)
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)
return oneAtATime(async () => {
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`)
}
await rm(abs, { recursive: true, force: true })
return { deleted: true, trash: false }
})
}
/** The names under `root`, listed off the main thread and kept a few seconds; the folders
* searched longest ago are forgotten beyond `files.indexes_max`. */
private async namesOf(root: string): Promise<string[]> {
const kept = this.names.get(root)
if (kept && Date.now() - kept.at < 5000) {
this.names.delete(root)
this.names.set(root, kept)
return kept.all
}
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`)
const MAX = 50_000
const files: string[] = []
if (Bun.which("rg") !== null) {
// Gitignored files are left out (ripgrep's own rule); hidden ones are named.
const proc = Bun.spawn(["rg", "--files", "--hidden", "--glob", "!.git"], { cwd: root, stdout: "pipe", stderr: "ignore", stdin: "ignore" })
const timer = setTimeout(() => proc.kill(), 20_000)
let buf = ""
const decoder = new TextDecoder()
try {
outer: for await (const chunk of proc.stdout as unknown as AsyncIterable<Uint8Array>) {
buf += decoder.decode(chunk, { stream: true })
let nl: number
while ((nl = buf.indexOf("\n")) >= 0) {
const f = buf.slice(0, nl)
buf = buf.slice(nl + 1)
if (f) files.push(f)
if (files.length >= MAX) break outer
}
}
} finally {
clearTimeout(timer)
proc.kill()
}
} else {
let n = 0
for await (const f of new Bun.Glob("**/*").scan({ cwd: root, dot: true, onlyFiles: true, followSymlinks: false })) {
if (f.split("/").some((x) => x === ".git" || x === "node_modules")) continue
files.push(f)
if (files.length >= MAX) break
if (++n % 500 === 0) await yieldNow()
}
}
rmSync(abs, { recursive: true, force: true })
return { deleted: true, trash: false }
const dirs = new Set<string>()
for (const f of files) {
const parts = f.split("/")
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join("/") + "/")
}
const all = [...dirs, ...files].filter((f) => !PART.test(basename(f))).sort()
this.names.delete(root)
this.names.set(root, { at: Date.now(), all })
while (this.names.size > F.indexes_max) this.names.delete(this.names.keys().next().value!)
return all
}
async search(p: any) {
@@ -495,22 +764,23 @@ export class DeviceFiles {
if (!there) return refuse("missing", said)
if (there !== "dir") return refuse("not_a_directory", said)
const query = typeof p?.query === "string" ? p.query : ""
// Judged as each is answered, not when the search began: what is named can still be opened.
const open = (rel: string) => {
const abs = join(root, rel)
return !this.closed(abs) && this.isInside(abs)
return !PART.test(basename(rel)) && !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(/\/$/, "")))
const all = await this.namesOf(root)
const hits = query ? fuzzysort.go(query, all, { limit: 200, threshold: -10000 }).map((h) => h.target) : all
const found = hits.filter((f) => open(f.replace(/\/$/, ""))).slice(0, limit)
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 args = ["rg", "--line-number", "--no-heading", "--color", "never", "--hidden", "--glob", "!.git", "--glob", "!*.lembas-part", "--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 }[] = []
@@ -547,5 +817,6 @@ export class DeviceFiles {
/** The link is gone: unfinished uploads go with it. */
close() {
for (const u of [...this.uploads.values()]) this.drop(u)
this.names.clear()
}
}
+5 -2
View File
@@ -59,6 +59,9 @@ export function limitsFromConfig(o: { sharedOnly?: boolean } = {}): Limits & { e
get scheduled() {
return r().enabled === true && r().scheduled === true
},
get filesThatRunCode() {
return r().files_that_run_code === true
},
get terminalIntegration() {
return r().terminal_integration !== false
},
@@ -68,7 +71,7 @@ export function limitsFromConfig(o: { sharedOnly?: boolean } = {}): Limits & { e
/** What the instance is told when the link opens (the hello, initialize's limits and
* capabilities): when it changes, the link is dialled again so the instance hears the new one. */
function announced(L: Limits & { enabled: boolean }): string {
return JSON.stringify([L.enabled, L.sharedOnly, L.roots, L.maxMode, L.requireTrust, L.terminal, L.scheduled === true])
return JSON.stringify([L.enabled, L.sharedOnly, L.roots, L.maxMode, L.requireTrust, L.terminal, L.scheduled === true, L.filesThatRunCode === true])
}
export function pickInstance(name?: string): Instance {
@@ -202,7 +205,7 @@ export async function runLink(o: LinkOptions = {}): Promise<LinkStatus> {
version: VERSION,
harness_spec: HARNESS_VERSION,
device: { host: hostname(), platform: `${process.platform}-${process.arch}` },
limits: { roots: limits.roots, max_mode: limits.maxMode, require_trust: limits.requireTrust, scheduled: limits.scheduled === true },
limits: { roots: limits.roots, max_mode: limits.maxMode, require_trust: limits.requireTrust, scheduled: limits.scheduled === true, files_that_run_code: limits.filesThatRunCode === true },
})
status("linked")
// The limits apply at once, each time they are looked at. What the instance was told at
+5 -2
View File
@@ -15,6 +15,9 @@ export class RpcError extends Error {
public code: number,
message: string,
public data?: unknown,
/** Made here because no answer came (the wait ran out, the connection closed) — not an
* answer of the other side's: what was asked may or may not have been done. */
public noAnswer = false,
) {
super(message)
}
@@ -39,7 +42,7 @@ export class Peer {
t.onMessage((text) => void this.receive(text))
t.onClose(() => {
this.closed = true
for (const w of this.waiting.values()) w.reject(new RpcError(INTERNAL_ERROR, "the connection closed"))
for (const w of this.waiting.values()) w.reject(new RpcError(INTERNAL_ERROR, "the connection closed", undefined, true))
this.waiting.clear()
for (const fn of this.closers) fn()
})
@@ -71,7 +74,7 @@ export class Peer {
if (timeoutMs)
timer = setTimeout(() => {
this.waiting.delete(id)
reject(new RpcError(INTERNAL_ERROR, `${method}: no answer in ${Math.round(timeoutMs / 1000)}s`))
reject(new RpcError(INTERNAL_ERROR, `${method}: no answer in ${Math.round(timeoutMs / 1000)}s`, undefined, true))
}, timeoutMs)
this.waiting.set(id, {
resolve: (v) => (clearTimeout(timer), resolve(v)),
+2 -1
View File
@@ -50,7 +50,8 @@ Usage:
Accept scheduled work: your schedules may run here as agent
turns (remote.scheduled, off by default)
lembas remote list | add <dir>… | remove <dir>… | enable | disable
| mode <manual|edit|auto|plan> | terminal <on|off> | scheduled <on|off> [--json]
| mode <manual|edit|auto|plan> | terminal <on|off> | scheduled <on|off>
| files-that-run-code <on|off> [--json]
what the instance may do here (remote:): the directories it may
work in (add turns remote work on), the most permissive mode,
terminals; a running service applies a change within seconds
+3
View File
@@ -64,6 +64,8 @@ export interface RemoteState {
terminal: boolean
/** Accept scheduled work (spec 3.5.0). */
scheduled: boolean
/** Device files may change files that run code (spec 3.11.0). */
files_that_run_code: boolean
}
export function remoteState(b: RemoteBlock = remoteBlock()): RemoteState {
@@ -73,6 +75,7 @@ export function remoteState(b: RemoteBlock = remoteBlock()): RemoteState {
max_mode: b.max_mode ?? "edit",
terminal: b.terminal === true,
scheduled: b.scheduled === true,
files_that_run_code: b.files_that_run_code === true,
}
}
+1
View File
@@ -322,6 +322,7 @@ export const Config = z.strictObject({
require_trust: z.boolean().optional().describe("Only projects trusted on this machine (default true)."),
terminal: z.boolean().optional().describe("Let the web UI open a terminal here (LLeMbas's terminal panel on a chat on this device): a login shell as this user, in a directory remote sessions may use. Default false."),
scheduled: z.boolean().optional().describe("Accept scheduled work (harness acp.md, spec 3.5.0): let your schedules on the LLeMbas instance run here as agent turns, in the folders remote work may use, in the schedule's mode (Edit unless it says Auto) lowered to max_mode. Default false. lembas service scheduled on|off."),
files_that_run_code: z.boolean().optional().describe("Let the file manager of the web UI and the apps change files that run code here (harness acp.md, spec 3.11.0): git's hooks and configuration, a project's agent configuration, your shell's start-up files. Default false: they can be read from there, and are changed only on this machine."),
terminal_integration: z.boolean().optional().describe("Shell integration in those terminals (bash, zsh, fish): after your own startup files, the shell marks each prompt, command and exit status (OSC 133) and its directory (OSC 7), so the web UI shows the directory, a mark beside each finished command, and can jump between commands. false: the shell starts as it is. Default true."),
})
.optional()
+4 -1
View File
@@ -298,7 +298,7 @@ export const LOOP: {
* 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 }
rewrite: { selection_max_bytes: number; context_max_lines: number; context_max_bytes: number; instruction_max_chars: number; concurrent_max: number }
context: { selection_max_chars: number; diagnostics_max: number; diagnostic_max_chars: number; open_max: number }
diff: { max_bytes: number }
buffers: { timeout_seconds: number }
@@ -310,6 +310,9 @@ export const LOOP: {
uploads_max: number
upload_idle_seconds: number
search_max: number
upload_max_bytes: number
indexes_max: number
runs_code: { segments: string[]; project_dir: string; project: string[]; home: string[] }
show: { text_max_bytes: number; media_max_bytes: number; media_wait_seconds: number }
}
} = LOOP_JSON
+13 -2
View File
@@ -8,10 +8,11 @@
// lembas remote mode <manual|edit|auto|plan> remote.max_mode
// lembas remote terminal <on|off> remote.terminal
// lembas remote scheduled <on|off> remote.scheduled: Accept scheduled work (spec 3.5.0)
// lembas remote files-that-run-code <on|off> remote.files_that_run_code (spec 3.11.0), off by default
//
// Every change goes through the global config writer, which keeps the file's comments. A running
// `lembas service` reads the block again whenever it uses it, so a change applies to it within a few
// seconds, no restart (acp/link.ts). --json prints one object: {enabled, roots, max_mode, terminal, scheduled}.
// seconds, no restart (acp/link.ts). --json prints one object: {enabled, roots, max_mode, terminal, scheduled, files_that_run_code}.
import { resolve } from "node:path"
import { ConfigError } from "./config/load.ts"
import { expandHome } from "./config/paths.ts"
@@ -19,7 +20,7 @@ import { coveredBy, realOrResolved, remoteBlock, remoteState, rootFor, type Remo
import { MODES, type Mode } from "./config/schema.ts"
import { updateGlobalConfig } from "./config/write.ts"
export const REMOTE_USAGE = `usage: lembas remote list | add <dir>… | remove <dir>… | enable | disable | mode <${MODES.join("|")}> | terminal <on|off> | scheduled <on|off> [--json]`
export const REMOTE_USAGE = `usage: lembas remote list | add <dir>… | remove <dir>… | enable | disable | mode <${MODES.join("|")}> | terminal <on|off> | scheduled <on|off> | files-that-run-code <on|off> [--json]`
export interface Io {
out: (line: string) => void
@@ -36,6 +37,7 @@ function describe(s: RemoteState): string[] {
`max mode: ${s.max_mode}`,
`terminal: ${s.terminal ? "on" : "off"}`,
`accept scheduled work: ${s.scheduled ? "on" : "off"}`,
`files that run code may be changed from the web: ${s.files_that_run_code ? "on" : "off"}`,
]
}
@@ -156,6 +158,15 @@ export function remoteCommand(argv: string[], io: Io = stdio): number {
return show()
}
// remote.files_that_run_code (spec 3.11.0): whether the file manager of the web UI and the apps
// may change git's own files, a project's agent configuration and the shell's start-up files.
if (sub === "files-that-run-code") {
const v = rest[0]
if (rest.length !== 1 || (v !== "on" && v !== "off")) return io.err("usage: lembas remote files-that-run-code <on|off>"), 2
write([[["files_that_run_code"], v === "on"]])
return show()
}
io.err(REMOTE_USAGE)
return 2
}
+67 -17
View File
@@ -1,22 +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.
// tools start from its buffer and write through it; anywhere else they use the disk, as before.
// Nothing here decides whether a call may run: permissions were judged before a tool reads or
// writes anything.
//
// One rule above the rest: **text the session read from the editor is never replaced from the
// disk.** Once a file was read through the client, a later read there that fails, or a write the
// client did not confirm, refuses the call and asks for a new read — the buffer may hold what
// the person has not saved.
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"
import { readText, ToolError, type FileChange, type ToolContext } from "./tool.ts"
type Ctx = Pick<ToolContext, "editor" | "editorSeen">
/** What `editorSeen` holds for a file whose text in the editor is not known any more (a write the
* client never confirmed): no text has this hash, so every change is refused until a new read. */
const UNKNOWN = "unknown"
const readAgain = (abs: string) => new ToolError(`${abs} is open in the editor, and the editor did not give its text just now. Read it again before changing it.`)
/** Where a tool that changes a file takes its text from (conformance `editor`, `kind: buffer`):
* the editor's answer; the disk when the client gave none and the session never read the file
* there; a refusal when it did — its buffer may hold what is not saved. */
export function textFrom(o: { tracked: boolean; read: "text" | "fails" | "none" }): "editor" | "disk" | "refuse" {
if (o.read === "text") return "editor"
return o.tracked && o.read === "fails" ? "refuse" : "disk"
}
/** What becomes of a write (`kind: buffer`): `taken` by the client; `refused` by it — the disk,
* unless the session read the file in the editor; `unknown` — no answer: never the disk as well. */
export function writeTo(o: { tracked: boolean; write: "taken" | "refused" | "unknown" | "none" }): "editor" | "disk" | "refuse" {
if (o.write === "taken") return "editor"
if (o.write === "unknown") return "refuse"
return o.tracked && o.write === "refused" ? "refuse" : "disk"
}
/** Note what a call that ran changed, where a client wants to draw it (ToolContext.changed). */
export function noteChanges(ctx: Pick<ToolContext, "changed" | "callId">, 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. */
/** The read tool's: the text of `abs` as the client has it, or undefined when it is the disk's to
* give. What the model is shown here is what "read" means from now on. */
export async function editorText(abs: string, ctx: Ctx): Promise<string | undefined> {
const text = await ctx.editor?.read?.(abs).catch(() => undefined)
if (text === undefined) return undefined
@@ -24,26 +51,49 @@ export async function editorText(abs: string, ctx: Ctx): Promise<string | undefi
return text
}
/** A file's text: the client's buffer where it has one, else the disk — byte-order mark kept. */
/** Whether the session read `abs` through the client's editor (and has not been told since that
* the editor let go of it). */
const tracked = (abs: string, ctx: Ctx) => ctx.editorSeen?.has(abs) === true
/** A file's text for a tool that changes it or previews a change: the client's buffer where it
* gives one, else the disk — byte-order mark kept. Records nothing: looking at a file to work
* out a change is not the model reading it. For a file the session read through the editor, a
* client that does not answer is a refusal, never the disk. */
export async function fileText(abs: string, ctx: Ctx): Promise<string> {
return (await editorText(abs, ctx)) ?? (await readText(abs))
const text = ctx.editor?.read ? await ctx.editor.read(abs).catch(() => undefined) : undefined
const from = textFrom({ tracked: tracked(abs, ctx), read: !ctx.editor?.read ? "none" : text !== undefined ? "text" : "fails" })
if (from === "refuse") throw readAgain(abs)
return from === "editor" ? text! : 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. */
* there. False where the session never read it through the client; a client that cannot say is
* a refusal. */
export async function changedInEditor(abs: string, ctx: Ctx): Promise<boolean> {
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
if (now === undefined) throw readAgain(abs)
return 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<void> {
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)
/** Write a file's text: through the client where it takes it, else to the disk. True: the client
* took it (the disk may follow a moment later — the file's change time proves nothing then).
* A write the client neither took nor refused (no answer in time) is not repeated on the disk:
* the client may still apply it, and two writers would cross. */
export async function putText(abs: string, content: string, ctx: Ctx): Promise<boolean> {
const outcome = ctx.editor?.write ? await ctx.editor.write(abs, content).catch(() => false as const) : false
if (outcome === "unknown") {
ctx.editorSeen?.set(abs, UNKNOWN)
throw new ToolError(`The editor did not confirm writing ${abs}; it may or may not have been written. Read it again to see what is there before going on.`)
}
if (ctx.editor?.read) ctx.editorSeen?.set(abs, sha256(content))
if (outcome === true) {
ctx.editorSeen?.set(abs, sha256(content))
return true
}
// The client would not take it. Text it holds unsaved is not written over behind its back.
if (tracked(abs, ctx)) throw new ToolError(`${abs} is open in the editor, which refused the write. Nothing was written; tell the user, or read it again.`)
await mkdir(dirname(abs), { recursive: true })
await Bun.write(abs, content)
return false
}
+4 -3
View File
@@ -78,9 +78,10 @@ export interface ToolContext {
* 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<string | undefined>; write?(abs: string, content: string): Promise<boolean> }
* buffer when open there — and a write through it. `read` answers undefined when the
* client did not give it; `write` true when it took the text, false when it refused, "unknown"
* when it never answered (tool/buffers.ts says what each means for the disk). Absent: the disk alone. */
editor?: { read?(abs: string): Promise<string | undefined>; write?(abs: string, content: string): Promise<boolean | "unknown"> }
/** 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<string, string>
+3 -1
View File
@@ -16,7 +16,9 @@ export async function guardExisting(abs: string, ctx: ToolContext): Promise<bool
if (!st.isFile()) throw new ToolError(`${abs} is not a regular file`)
if (!ctx.readFiles.has(abs)) throw new ToolError(`${abs} exists and has not been read in this session. Read it first.`)
const seen = ctx.fileStamps.get(abs)
if (seen !== undefined && st.mtimeMs > seen + 1) throw new ToolError(`${abs} changed since you last read it. Read it again before changing it.`)
// A file the session reads through the client's editor is judged by its text there (below): its
// change time on disk moves whenever the editor saves, which is no change the model missed.
if (!ctx.editorSeen?.has(abs) && seen !== undefined && st.mtimeMs > 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
+1 -1
View File
@@ -537,7 +537,7 @@ export function createView(bus: Bus) {
items.push({ kind: "user", id: nextId(), text: stripMark(m.parts[0].text).body.trim(), mid: true, machine: true })
else if (m.role === "user")
// What was typed; attachments (@files, ! output) went to the model but are not shown again.
items.push({ kind: "user", id: nextId(), text: m.parts.filter((p) => p.type === "text" && !ATTACHMENT.test(p.text)).map((p) => (p.type === "text" ? p.text : "")).join("\n") })
items.push({ kind: "user", id: nextId(), text: m.parts.filter((p, i) => p.type === "text" && (i === 0 || !ATTACHMENT.test(p.text))).map((p) => (p.type === "text" ? p.text : "")).join("\n") })
else if (m.role === "assistant") {
for (const p of m.parts) {
if (p.type === "text" && p.text.trim()) {
+209 -1
View File
@@ -10,6 +10,7 @@ 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 { LOOP } from "../src/harness.ts"
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
let fake: Fake | undefined
@@ -69,7 +70,7 @@ const err = (message: string, status: number) => Response.json({ error: { messag
/** 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<Response>; editor?: boolean; allowed?: string[] | null } = {}) {
function server(o: { complete?: (body: any, req: Request) => Response | Promise<Response>; editor?: boolean; allowed?: string[] | null; slowEditorMs?: number } = {}) {
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({
@@ -82,6 +83,7 @@ function server(o: { complete?: (body: any, req: Request) => Response | Promise<
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 (o.slowEditorMs) await Bun.sleep(o.slowEditorMs)
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")
@@ -580,3 +582,209 @@ test("show: a client without media is not handed a picture; a table is named for
expect(sent[0]).toMatchObject({ path: "loaves.csv", kind: "table", text: "kind,count\nrye,3\n" })
expect(sent[0].handle).toBeUndefined()
})
// ── after the review ────────────────────────────────────────────────────────────────────────
test("unsaved text is never replaced from the disk: a client that stops answering at edit time refuses the edit", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] },
{ chunks: [toolCall(0, "e1", "edit", JSON.stringify({ path: "a.txt", old: "saved", new: "clobbered" }))] },
{ chunks: [toolCall(0, "w1", "write", JSON.stringify({ path: "a.txt", content: "clobbered\n" }))] },
{ chunks: [delta({ content: "done" })] },
])
config(fake.url)
const root = project({ "a.txt": "saved text\n" })
const file = join(root, "a.txt")
let reads = 0
const writes: string[] = []
const { c } = await editor({
fs: { readTextFile: true, writeTextFile: true },
handlers: {
// The first read gives the buffer; after that the editor is busy and fails.
"fs/read_text_file": () => {
if (reads++ === 0) return { content: "saved text\nand a line not saved yet\n" }
throw new Error("the editor is busy")
},
"fs/write_text_file": (p) => (writes.push(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: "go" }] })
const tools = fake.requests.at(-1).messages.filter((m: any) => m.role === "tool").map((m: any) => m.content)
expect(tools[0]).toContain("2: and a line not saved yet")
// Neither the edit nor the overwrite fell back to the disk's text.
expect(tools[1]).toContain("Read it again before changing it")
expect(tools[2]).toContain("Read it again before changing it")
expect(writes).toEqual([])
expect(readFileSync(file, "utf8")).toBe("saved text\n")
})
test("only the read tool and a write that ran count as reading: a patch that was shown and refused does not", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] },
{ chunks: [toolCall(0, "p1", "apply_patch", JSON.stringify({ patch: "--- a/a.txt\n+++ b/a.txt\n@@ -1 +1 @@\n-two\n+three\n" }))] },
{ chunks: [toolCall(0, "w1", "write", JSON.stringify({ path: "a.txt", content: "mine\n" }))] },
{ chunks: [delta({ content: "done" })] },
])
config(fake.url)
const root = project({ "a.txt": "one\n" })
let buffer = "one\n"
let reads = 0
const { c } = await editor({
fs: { readTextFile: true, writeTextFile: true },
// The patch is the one card refused; the write would be allowed.
ask: (p) => ({ outcome: { outcome: "selected", optionId: String(p.toolCall.rawInput?.patch ?? "") ? "deny" : "once" } }),
handlers: {
"fs/read_text_file": () => {
// After the model's read the person types: the buffer is "two" from then on.
const now = buffer
if (reads++ === 0) buffer = "two\n"
return { content: now }
},
"fs/write_text_file": (p) => ((buffer = p.content), null),
},
})
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 tools = fake.requests.at(-1).messages.filter((m: any) => m.role === "tool").map((m: any) => m.content)
expect(tools[0]).toContain("1: one")
// The preview of the refused patch looked at "two" — the model never did. The overwrite is refused.
expect(tools[2]).toContain("changed since you last read it")
expect(buffer).toBe("two\n")
})
test("the link's client is never asked for a file's text, whatever it says of fs", async () => {
fake = fakeProvider([
{ chunks: [toolCall(0, "r1", "read", JSON.stringify({ path: "a.txt" }))] },
{ chunks: [toolCall(0, "e1", "edit", JSON.stringify({ path: "a.txt", old: "disk", new: "changed" }))] },
{ chunks: [delta({ content: "done" })] },
])
config(fake.url)
const root = project({ "a.txt": "on disk\n" })
const calls: string[] = []
const { c } = await editor({
limits: { roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true },
fs: { readTextFile: true, writeTextFile: true },
handlers: { "fs/read_text_file": (p) => (calls.push(p.path), { content: "the server's own text\n" }), "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(calls).toEqual([])
expect(fake.requests[1].messages.find((m: any) => m.role === "tool").content).toContain("1: on disk")
expect(readFileSync(join(root, "a.txt"), "utf8")).toBe("on changed\n")
})
test("a write the editor never confirms is not written to the disk as well; one it took is not refused later for the disk's change time", async () => {
const old = LOOP.editor.buffers.timeout_seconds
LOOP.editor.buffers.timeout_seconds = 0.3
try {
fake = fakeProvider([
{ chunks: [toolCall(0, "w1", "write", JSON.stringify({ path: "slow.txt", content: "one\n" }))] },
{ chunks: [toolCall(0, "w2", "write", JSON.stringify({ path: "new.txt", content: "first\n" }))] },
{ chunks: [toolCall(0, "w3", "write", JSON.stringify({ path: "new.txt", content: "second\n" }))] },
{ chunks: [delta({ content: "done" })] },
])
config(fake.url)
const root = project()
const buffers: Record<string, string> = {}
const { c } = await editor({
fs: { readTextFile: true, writeTextFile: true },
handlers: {
"fs/read_text_file": (p) => {
if (!(p.path in buffers)) throw new Error("not open")
return { content: buffers[p.path] }
},
"fs/write_text_file": async (p) => {
// slow.txt: the editor never answers in time.
if (p.path.endsWith("slow.txt")) return new Promise(() => {})
buffers[p.path] = p.content
// The editor's save reaches the disk a moment after it answered.
setTimeout(() => writeFileSync(p.path, p.content), 40)
return 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" }] })
const tools = fake.requests.at(-1).messages.filter((m: any) => m.role === "tool").map((m: any) => m.content)
expect(tools[0]).toContain("did not confirm writing")
// Not written by the device as well: two writers would cross.
expect(await Bun.file(join(root, "slow.txt")).exists()).toBe(false)
expect(tools[1]).toContain("Created")
// The second write is judged by the text in the editor, not by the save that landed in between.
expect(tools[2]).not.toContain("changed since")
expect(tools[2]).not.toContain("Read it")
expect(buffers[join(root, "new.txt")]).toBe("second\n")
} finally {
LOOP.editor.buffers.timeout_seconds = old
}
})
/** A model's server that never answers, and says when a request to it is closed. */
function hangingProvider() {
const state = { open: 0, closed: 0 }
const s = Bun.serve({
port: 0,
async fetch(req) {
if (req.method !== "POST") return Response.json({ data: [] })
state.open++
await new Promise<void>((resolve) => req.signal.addEventListener("abort", () => (state.closed++, resolve())))
return new Response("gone", { status: 499 })
},
})
return { url: `http://127.0.0.1:${s.port}/v1`, state, stop: () => s.stop(true) }
}
test("rewrites: at most four at once; every one stops when its client goes, with an id or without", async () => {
const hang = hangingProvider()
try {
config(hang.url)
const { c, close } = await editor()
const running = [0, 1, 2, 3].map((i) => refusal(c.request("_lembas/edit", { text: "y", instruction: "i", ...(i % 2 ? { id: `e${i}` } : {}) })))
await until(() => hang.state.open === 4, "four rewrites to reach the model")
const fifth = await refusal(c.request("_lembas/edit", { text: "y", instruction: "i" }))
expect(fifth.data).toEqual({ reason: "busy" })
expect(hang.state.open).toBe(4)
// An id longer than 100 characters is cut the same way where it is given and where it is cancelled.
c.notify("_lembas/edit/cancel", { id: "e1" })
await until(() => hang.state.closed === 1, "the cancelled rewrite's request to close")
const long = "x".repeat(150)
const sixth = c.request("_lembas/edit", { id: long, text: "y", instruction: "i" })
await until(() => hang.state.open === 5, "the long-id rewrite to reach the model")
c.notify("_lembas/edit/cancel", { id: long })
expect(await sixth).toEqual({ text: "", cancelled: true })
// The client goes: the three still running — two of them without an id — are stopped.
close()
await until(() => hang.state.closed === 5, "every rewrite's request to close")
void running
} finally {
hang.stop()
}
})
test("a rewrite cancelled while its model is still being chosen never reaches the model", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "never" })] }])
config(fake.url)
// The person's main model is asked of the server first, and the server is slow about it.
server({ slowEditorMs: 300 })
const { c } = await editor()
const edit = c.request("_lembas/edit", { id: "early", text: "y", instruction: "i" })
await until(() => seen.some((s) => s.path === "/v1/lembas/editor"), "the settings to be asked for")
c.notify("_lembas/edit/cancel", { id: "early" })
expect(await edit).toEqual({ text: "", cancelled: true })
await Bun.sleep(350)
expect(fake.requests.length).toBe(0)
})
test("a typed message that begins like the editor's block is shown as typed", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "ok" })] }])
config(fake.url)
const root = project()
const { c } = await editor()
const s: any = await c.request("session/new", { cwd: root })
const typed = "<editor>\nis this tag valid XML?"
await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: typed }], _meta: { lembas: { editor: { path: "a.xml" } } } })
const h: any = await c.request("_lembas/session/history", { sessionId: s.sessionId })
// What was typed is there; the block the client added is not.
expect(h.turns[0].text).toBe(typed)
})
+190 -2
View File
@@ -7,7 +7,8 @@ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSyn
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 { DeviceFiles, moveToTrash, PART, sweepParts } from "../src/acp/files.ts"
import { LOOP } from "../src/harness.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { paths } from "../src/config/paths.ts"
@@ -273,7 +274,7 @@ test("outside the roots: every method refuses, and a link that points out is out
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 })
expect(l.entries.find((e: any) => e.name === "way-out")).toMatchObject({ kind: "other", size: 0, 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 () => {
@@ -344,3 +345,190 @@ test("a device that allows plan mode only is read-only; off, shared-only, no roo
}
expect(readFileSync(file, "utf8")).toBe("alpha\n")
})
// ── one change at a time; judged again after every wait (review finding 1) ──────────────────
test("a write racing two moves that swap a link into its path never lands outside the roots", async () => {
const { c } = await link()
mkdirSync(join(root, "a"))
// Large enough that hashing it for the base check is waited for.
writeFileSync(join(root, "a/keys.txt"), Buffer.alloc(24 * 1024 * 1024, 1))
symlinkSync(outside, join(root, "way-out"))
// All three at once, as a client may send them: the write, then the folder moved aside and the
// link moved into its place.
const write = refusal(c.request("_lembas/fs/write", { path: join(root, "a/keys.txt"), data: b64("planted\n"), overwrite: true }))
const aside = refusal(c.request("_lembas/fs/move", { from: join(root, "a"), to: join(root, "b") }))
const swap = refusal(c.request("_lembas/fs/move", { from: join(root, "way-out"), to: join(root, "a") }))
const [w] = await Promise.all([write, aside, swap])
// Changes run one after another: the write finished where it was judged, before either move.
expect(w.reason).toBeUndefined()
expect(readdirSync(outside).sort()).toEqual(["secret.txt"])
expect(readFileSync(join(root, "b/keys.txt"), "utf8")).toBe("planted\n")
expect(lstatSync(join(root, "a")).isSymbolicLink()).toBe(true)
})
test("a path that changes under a write while its base is hashed is judged again: refused, nothing written outside", async () => {
const { c } = await link()
mkdirSync(join(root, "a"))
writeFileSync(join(root, "a/keys.txt"), Buffer.alloc(48 * 1024 * 1024, 1))
const write = refusal(c.request("_lembas/fs/write", { path: join(root, "a/keys.txt"), data: b64("planted\n"), overwrite: true }))
// Not through these methods (which wait their turn): something else on the computer swaps the
// folder for a link that leads out, while the hash is under way.
await Bun.sleep(5)
const { renameSync } = await import("node:fs")
renameSync(join(root, "a"), join(root, "b"))
symlinkSync(outside, join(root, "a"))
const w = await write
expect(w.reason).toBe("outside")
expect(readdirSync(outside).sort()).toEqual(["secret.txt"])
expect(readdirSync(join(root, "b"))).toEqual(["keys.txt"])
// The same for the parts of an upload: the path is judged with each.
rmSync(join(root, "a"))
mkdirSync(join(root, "a"))
const up: any = await c.request("_lembas/fs/write", { path: join(root, "a/big.bin"), data: b64("one"), base: null, more: true })
renameSync(join(root, "a"), join(root, "c"))
symlinkSync(outside, join(root, "a"))
expect((await refusal(c.request("_lembas/fs/write", { upload: up.upload, data: b64("two") }))).reason).toBe("outside")
expect(readdirSync(outside).sort()).toEqual(["secret.txt"])
// The upload is dropped. Its part file's name now leads out, so nothing is removed by that name:
// the file is emptied where it lies.
const left = readdirSync(join(root, "c"))
expect(left.every((n) => PART.test(n))).toBe(true)
expect(left.map((n) => statSync(join(root, "c", n)).size)).toEqual([0])
})
test("a hash is of the file that was judged, whatever becomes of its name meanwhile", async () => {
const { c } = await link()
const big = Buffer.alloc(24 * 1024 * 1024, 3)
writeFileSync(join(root, "big.bin"), big)
const st = c.request<any>("_lembas/fs/stat", { path: join(root, "big.bin"), hash: true })
await Bun.sleep(5)
rmSync(join(root, "big.bin"))
symlinkSync(join(outside, "secret.txt"), join(root, "big.bin"))
expect((await st).hash).toBe(hash(big))
})
// ── files that run code (review finding 2; the owner's decision: a device setting, off) ─────
test("files that run code: read from here, changed only where remote.files_that_run_code is on", async () => {
mkdirSync(join(root, "app/.git/hooks"), { recursive: true })
mkdirSync(join(root, "app/.agent/commands"), { recursive: true })
writeFileSync(join(root, "app/.git/config"), "[core]\n")
writeFileSync(join(root, "app/.agent/config.yaml"), "mode: manual\n")
writeFileSync(join(root, "app/readme.md"), "r\n")
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limitsFor())
const c = new Peer(tb)
const init: any = await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
// Said with the limits, so a client knows beforehand.
expect(init._meta.lembas.limits.files_that_run_code).toBe(false)
const hook = join(root, "app/.git/hooks/pre-commit")
const w = await refusal(c.request("_lembas/fs/write", { path: hook, data: b64("#!/bin/sh\n"), base: null }))
expect(w.reason).toBe("runs_code")
expect(w.message).toContain("remote.files_that_run_code")
for (const [m, p] of [
["write", { path: join(root, "app/.git/config"), data: b64("x"), overwrite: true }],
["write", { path: join(root, "app/.agent/config.yaml"), data: b64("x"), overwrite: true }],
["write", { path: join(root, "app/.agent/commands/go.md"), data: b64("x"), base: null }],
["mkdir", { path: join(root, "app/.git/hooks/sub") }],
["delete", { path: join(root, "app/.git/config"), permanent: true }],
["move", { from: join(root, "app/readme.md"), to: hook }],
["move", { from: join(root, "app/.git/hooks"), to: join(root, "app/hooks") }],
["copy", { from: join(root, "app/readme.md"), to: hook }],
["move", { from: join(root, "docs"), to: join(root, "app/docs/.git") }],
["copy", { from: join(root, "docs"), to: join(root, "docs/.agent") }],
] as const)
expect([m, JSON.stringify(p).slice(0, 0), (await refusal(c.request(`_lembas/fs/${m}`, p))).reason]).toEqual([m, "", "runs_code"])
expect(existsSync(hook)).toBe(false)
expect(readFileSync(join(root, "app/.git/config"), "utf8")).toBe("[core]\n")
// Reading, listing and searching them stay allowed; so do a project's other files and the repository as a whole.
expect(Buffer.from((await c.request<any>("_lembas/fs/read", { path: join(root, "app/.git/config") })).data, "base64").toString()).toBe("[core]\n")
expect((await c.request<any>("_lembas/fs/list", { path: join(root, "app/.git") })).entries.map((e: any) => e.name)).toEqual(["hooks", "config"])
mkdirSync(join(root, "app/.agent/plans"))
await c.request("_lembas/fs/write", { path: join(root, "app/.agent/plans/next.md"), data: b64("# Plan\n"), base: null })
await c.request("_lembas/fs/copy", { from: join(root, "app"), to: join(root, "app2") })
expect(readFileSync(join(root, "app2/.git/config"), "utf8")).toBe("[core]\n")
// The device's own setting on: a file like any other.
const on = await link(limitsFor({ filesThatRunCode: true }))
await on.c.request("_lembas/fs/write", { path: hook, data: b64("#!/bin/sh\n"), base: null })
expect(readFileSync(hook, "utf8")).toBe("#!/bin/sh\n")
})
test("a start-up file of the device's user is refused where the home is shared (nothing is written there)", async () => {
const { c } = await link(limitsFor({ roots: [homedir()] }))
const rc = join(homedir(), ".bashrc")
const before = existsSync(rc) ? readFileSync(rc, "utf8") : undefined
expect((await refusal(c.request("_lembas/fs/write", { path: rc, data: b64("echo hi\n"), overwrite: true }))).reason).toBe("runs_code")
expect((await refusal(c.request("_lembas/fs/delete", { path: join(homedir(), ".config"), permanent: true }))).reason).not.toBeUndefined()
expect(existsSync(rc) ? readFileSync(rc, "utf8") : undefined).toBe(before)
})
// ── bounds (review findings 7 and 8) ────────────────────────────────────────────────────────
test("an upload is capped in all; a listing is cut before its entries are looked at; few folders' names are kept", async () => {
const { c } = await link()
const F = LOOP.files
const old = { upload: F.upload_max_bytes, list: F.list_max }
try {
F.upload_max_bytes = 10
const up: any = await c.request("_lembas/fs/write", { path: join(root, "cap.bin"), data: b64("12345678"), base: null, more: true })
const over = await refusal(c.request("_lembas/fs/write", { upload: up.upload, data: b64("abc"), more: true }))
expect(over.reason).toBe("too_large")
// Dropped: its part file is gone and it takes no more.
expect(readdirSync(root).filter((n) => PART.test(n))).toEqual([])
expect((await refusal(c.request("_lembas/fs/write", { upload: up.upload, data: b64("a") }))).reason).toBe("invalid")
expect(existsSync(join(root, "cap.bin"))).toBe(false)
F.list_max = 1
const l: any = await c.request("_lembas/fs/list", { path: root })
expect(l.entries.map((e: any) => e.name)).toEqual(["docs"])
expect(l.truncated).toBe(true)
} finally {
F.upload_max_bytes = old.upload
F.list_max = old.list
}
const files = new DeviceFiles(() => ({ roots: [root], maxMode: "auto", enabled: true }))
for (const d of ["d1", "d2", "d3", "d4", "d5", "d6"]) {
mkdirSync(join(root, d))
writeFileSync(join(root, d, "f.txt"), "x")
await files.search({ path: join(root, d), query: "f" })
}
expect((files as unknown as { names: Map<string, unknown> }).names.size).toBe(LOOP.files.indexes_max)
})
test("part files: never listed or found, not named by a client, and swept when a process left one behind", async () => {
const { c } = await link()
const up: any = await c.request("_lembas/fs/write", { path: join(root, "slow.bin"), data: b64("needle one"), base: null, more: true })
const part = readdirSync(root).find((n) => PART.test(n))!
expect(part).toBeDefined()
expect((await c.request<any>("_lembas/fs/list", { path: root, hidden: true })).entries.map((e: any) => e.name)).not.toContain(part)
expect((await c.request<any>("_lembas/fs/search", { path: root, query: "slow" })).files).toEqual([])
if (Bun.which("rg") !== null) expect((await c.request<any>("_lembas/fs/search", { path: root, query: "needle", content: true })).matches).toEqual([])
expect((await refusal(c.request("_lembas/fs/read", { path: join(root, part) }))).reason).toBe("invalid")
expect((await refusal(c.request("_lembas/fs/delete", { path: join(root, part), permanent: true }))).reason).toBe("invalid")
// The journal names it while it is open; a process that died would leave both behind.
const journal = join(paths.state, "uploads.json")
expect(JSON.parse(readFileSync(journal, "utf8"))).toContain(join(root, part))
// The next process sweeps what the journal names — and only what is named like a part file.
writeFileSync(join(root, "keep.txt"), "k")
writeFileSync(journal, JSON.stringify([join(root, part), join(root, "keep.txt")]))
expect(sweepParts()).toEqual([join(root, part)])
expect(existsSync(join(root, part))).toBe(false)
expect(existsSync(join(root, "keep.txt"))).toBe(true)
expect(JSON.parse(readFileSync(journal, "utf8"))).toEqual([])
void up
})
test("copying a whole tree does not stop the device answering", async () => {
const { c } = await link()
mkdirSync(join(root, "tree"))
for (let i = 0; i < 40; i++) {
mkdirSync(join(root, "tree", `d${i}`))
for (let j = 0; j < 60; j++) writeFileSync(join(root, "tree", `d${i}`, `f${j}.txt`), "x".repeat(2000))
}
const order: string[] = []
const copy = c.request("_lembas/fs/copy", { from: join(root, "tree"), to: join(root, "tree2") }).then(() => order.push("copy"))
const read = c.request("_lembas/fs/read", { path: join(root, "a.txt") }).then(() => order.push("read"))
await Promise.all([copy, read])
expect(order).toEqual(["read", "copy"])
expect(readdirSync(join(root, "tree2")).length).toBe(40)
})
+1 -1
View File
@@ -144,7 +144,7 @@ test("the device's limits: outside the roots, untrusted, a higher mode", async (
const root = project()
const limits: Limits = { roots: [root], maxMode: "edit", approvalTimeoutMs: 50, requireTrust: true }
const { c, init } = await client(limits)
expect(init._meta.lembas.limits).toEqual({ roots: [root], max_mode: "edit", scheduled: false })
expect(init._meta.lembas.limits).toEqual({ roots: [root], max_mode: "edit", scheduled: false, files_that_run_code: false })
await expect(c.request("session/new", { cwd: tmpdir() })).rejects.toThrow("outside the directories")
const untrusted = join(root, "..", `ph-untrusted-${Date.now()}`)
mkdirSync(untrusted)
+6 -1
View File
@@ -44,7 +44,8 @@ import { outstanding, type OutstandingInput } from "../src/session/outstanding.t
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 { baseCheck, judgePath, runsCode, sameAgain, type FsOp } from "../src/acp/files.ts"
import { textFrom, writeTo } from "../src/tool/buffers.ts"
import { showPlan } from "../src/tool/show.ts"
type Case = Record<string, unknown>
@@ -87,13 +88,16 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
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 === "buffer") return "read" in c ? { text: textFrom({ tracked: c.tracked === true, read: c.read as "text" | "fails" | "none" }) } : { write: writeTo({ tracked: c.tracked === true, write: c.write as "taken" | "refused" | "unknown" | "none" }) }
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 })
if (c.kind === "again") return sameAgain(c.first as string, c.again as Parameters<typeof sameAgain>[1])
const guardedRoots = c.protected as string[]
const home = c.home as string | undefined
const links = (c.links ?? {}) as Record<string, string>
return judgePath({
op: c.op as FsOp,
@@ -107,6 +111,7 @@ export const AREAS: Record<string, (c: Case) => unknown> = {
maxMode: c.max_mode as Mode,
real: (p) => followLinks(links, p),
deep: c.deep === true,
...(home && c.files_that_run_code !== true ? { runsCode: (p: string) => runsCode(p, home) } : {}),
})
},
// Spec 3.11.0: what the show tool sends for a file (src/tool/show.ts).
+12 -3
View File
@@ -37,7 +37,7 @@ test("list --json: one object, the defaults applied", () => {
const r = run("list", "--json")
expect(r.code).toBe(0)
expect(r.out).toHaveLength(1)
expect(r.json()).toEqual({ enabled: false, roots: [], max_mode: "edit", terminal: false, scheduled: false })
expect(r.json()).toEqual({ enabled: false, roots: [], max_mode: "edit", terminal: false, scheduled: false, files_that_run_code: false })
// Without --json, lines a person reads.
const plain = run("list")
expect(plain.out.join("\n")).toContain("remote work: off")
@@ -54,7 +54,7 @@ test("add: absolute real paths, turns remote work on, skips duplicates and cover
const r = run("add", a, link, "--json")
expect(r.code).toBe(0)
// The link is stored as where it leads.
expect(r.json()).toEqual({ enabled: true, roots: [a, b], max_mode: "edit", terminal: false, scheduled: false })
expect(r.json()).toEqual({ enabled: true, roots: [a, b], max_mode: "edit", terminal: false, scheduled: false, files_that_run_code: false })
// Again, and a directory inside one: nothing more.
const again = run("add", a, join(a, "sub"))
expect(again.code).toBe(0)
@@ -212,7 +212,7 @@ test("the service links with remote work off, says no roots and refuses everythi
// Turned on from outside, as Desktop does: it links again, saying the new roots, and serves.
run("add", a)
await until(() => hellos.length === 2, "a second hello")
expect(hellos[1].limits).toEqual({ roots: [a], max_mode: "edit", require_trust: true, scheduled: false })
expect(hellos[1].limits).toEqual({ roots: [a], max_mode: "edit", require_trust: true, scheduled: false, files_that_run_code: false })
expect(states.some((s) => s.detail === "the remote settings changed; linking again")).toBe(true)
await ask("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 2 } } } })
expect((await ask("_lembas/directories", {})).result.places.map((p: any) => [p.path, p.accepted])).toEqual([[a, true]])
@@ -226,3 +226,12 @@ test("the service links with remote work off, says no roots and refuses everythi
stop.abort()
expect((await done).state).toBe("stopped")
})
test("files-that-run-code: off by default, switched on and off", () => {
fresh()
expect(run("files-that-run-code", "on", "--json").json().files_that_run_code).toBe(true)
expect(run("list").out.join("\n")).toContain("files that run code may be changed from the web: on")
expect(run("files-that-run-code", "off", "--json").json().files_that_run_code).toBe(false)
expect(run("files-that-run-code").code).toBe(2)
expect(run("files-that-run-code", "maybe").code).toBe(2)
})