diff --git a/CHANGELOG.md b/CHANGELOG.md index af460db..de0fabf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,15 @@ All notable changes to LLeMbas CLI. The format follows directory was judged for the directory only, so the lines of a `.env` in it came back unasked — in plan mode too. Such files are now left out of the result, which says how many and which, so the model can ask to `read` one. Names are not content: `glob` and `list` still show them. +- **A custom command's `` !`…` `` is a `bash` call of the session, and its arguments are data.** + The shell line in a command file ran with only the floor checked, with the arguments pasted + into it — also for a prompt that arrived over the link from the web, whatever the remote + limits said. It now runs only when the session would run that line as a `bash` call without + asking (its mode, its rules, the remote limits); otherwise the model is told it was not run. + The arguments reach the line as `$1…` and `$ARGUMENTS` of the shell, never as part of it, and + a `$` typed in the arguments is no longer rewritten. A substitution is stopped after ten + seconds. **A command of yours whose `` !`…` `` is not on the allowed list no longer runs by + itself in manual mode** — allow it with a rule, or let the model run it. - **The force-push floor reads the push.** It refused any forced push with "main" somewhere in it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`, `--delete main`), a forced `--all`/`--mirror`, and a bare `git push -f` while on main. The diff --git a/harness/README.md b/harness/README.md index 0c57186..7e1d9c9 100644 --- a/harness/README.md +++ b/harness/README.md @@ -117,6 +117,8 @@ page *Harness-parity* in LLeMbas CLI's wiki. - **A search does not read what `read` would ask about** (`filesystem.md`): `grep` returns no line of a file whose `read` is not allowed at that moment, and names the files left out; `glob` and `list` are names, not content, and unchanged. **Both implementations.** +- **A custom command's `` !`…` `` is a `bash` call of the session** (`permission/rules.md` §6; + the CLI's alone): judged in the session's mode, run only on `allow`, the arguments positional. - Conformance: every case of `conformance/terminal.json` is in the new names; cases of `env`, `status`, `status_dir` and `prompt` in the old ones; `errors.json` for the product `term`. diff --git a/harness/permission/rules.md b/harness/permission/rules.md index 7d42d95..79892d0 100644 --- a/harness/permission/rules.md +++ b/harness/permission/rules.md @@ -210,3 +210,29 @@ not given (`grep -r x .` reads every file under `.`; the search *tools* leave pr out — `filesystem.md`), what a script does once it runs, and in auto mode an unresolved word (a variable holding a protected path is not known to be one). +## 6. A custom command's shell substitution (spec 3.15.0; the CLI's alone) + +A custom command (a markdown file of the person's, or of a trusted project — an untrusted +project's commands do not exist) may hold `` !`line` ``, replaced by the line's output before +the prompt is sent. That line is the command file's code run with the person's rights, and the +prompt that triggers it may come from anywhere a prompt comes from — the keyboard, `lembas run`, +the link. So: + +1. **It is judged as a `bash` call of that line, in the session's mode, by the session's rules** + — the floor, the rules (§2), what the line touches (§5), the mode, and with them the device's + remote limits, which clamp a remote session's mode (`acp.md`). **Only `allow` runs it.** A + `deny` puts `[not run — {reason}]` in its place; an `ask` puts + ``[not run — `{line}` needs the person's approval here; run it with bash if its output is needed]`` + — nothing is asked while a prompt is being put together; the model may make the call itself, + which is then asked about as any call is. +2. **The arguments are never part of the line.** `$ARGUMENTS` and `$1`…`$9` are filled in the + command's *text* (in one pass: a `$` inside the arguments is text). Inside a `` !`…` `` nothing + is filled in: the line runs as written, with the arguments as the shell's positional + parameters (`$1`…, `"$@"`) and `ARGUMENTS` in its environment — data the shell expands, not + text it parses. By §5 a line with `$1` in it is unresolved, so outside auto mode it is not + run. +3. **The floor is checked twice**: on the line as written and on the line with the arguments + filled in as text. +4. It runs in the project root with the environment `bash` calls get, and is stopped after ten + seconds. + diff --git a/src/project/commands.ts b/src/project/commands.ts index b79653c..12e9431 100644 --- a/src/project/commands.ts +++ b/src/project/commands.ts @@ -2,7 +2,8 @@ // project) .agent/commands/. The file name is the command; YAML frontmatter may give a // description, a model and a mode; the body is the prompt. In the body: // $ARGUMENTS everything after the command $1 … $9 the arguments one by one -// !`command` replaced by that command's output (run in the project, the hardline applies) +// !`command` replaced by that command's output — run in the project only when the session +// would run it as a bash call without asking; the arguments are its $1 … $9 // @path attached like any @reference import { existsSync, readdirSync, readFileSync } from "node:fs" import { basename, join } from "node:path" @@ -10,6 +11,7 @@ import { parse } from "yaml" import { paths } from "../config/paths.ts" import { hardlineCommand, type HardlineRule } from "../permission/hardline.ts" import { words } from "../permission/bash.ts" +import { ENV } from "../tool/bash.ts" export interface CustomCommand { name: string @@ -55,15 +57,37 @@ export function customCommands(projectDir: string | undefined): CustomCommand[] return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)) } -/** The prompt a command sends. */ -export function expandCommand(cmd: CustomCommand, args: string, root: string, hardline: HardlineRule[]): string { +/** What is decided for one `` !`…` `` before it runs: the session's own answer for a `bash` call + * of that line (harness permission/rules.md §6). */ +export type SubstitutionJudge = (command: string) => { action: "allow" | "ask" | "deny"; reason: string } + +/** How long a substitution may take: it is a quick look, read before the prompt is sent. */ +export const SUBSTITUTION_TIMEOUT_MS = 10_000 + +/** The prompt a command sends (rules.md §6). `$ARGUMENTS` and `$1…$9` are filled in the text — + * in one pass, so nothing in the arguments is read as a placeholder again. Inside a + * `` !`…` `` nothing is filled in: the line is run as written, with the arguments as the + * shell's own positional parameters and `$ARGUMENTS` in its environment — data, never part of + * the command line — and only when `judge` allows a `bash` call of it without asking. */ +export function expandCommand(cmd: CustomCommand, args: string, root: string, hardline: HardlineRule[], judge: SubstitutionJudge): string { const list = words(args) - let text = cmd.body.replaceAll("$ARGUMENTS", args).replace(/\$(\d)/g, (_, n: string) => list[Number(n) - 1] ?? "") - text = text.replace(/!`([^`]+)`/g, (_, command: string) => { - const hit = hardlineCommand(command, hardline) + const fill = (text: string) => text.replace(/\$(ARGUMENTS|\d)/g, (_, n: string) => (n === "ARGUMENTS" ? args : (list[Number(n) - 1] ?? ""))) + const run = (command: string): string => { + // The floor, on the line as written and as it reads with the arguments in place. + const hit = hardlineCommand(command, hardline) ?? hardlineCommand(fill(command), hardline) if (hit) return `[not run — ${hit.description}]` - const r = Bun.spawnSync(["bash", "-c", command], { cwd: root, stdout: "pipe", stderr: "pipe" }) - return (r.stdout.toString() + r.stderr.toString()).trim() - }) - return text.trim() + const d = judge(command) + if (d.action === "deny") return `[not run — ${d.reason}]` + if (d.action === "ask") return `[not run — \`${command}\` needs the person's approval here; run it with bash if its output is needed]` + const r = Bun.spawnSync(["bash", "-c", command, "lembas", ...list], { cwd: root, stdout: "pipe", stderr: "pipe", stdin: "ignore", timeout: SUBSTITUTION_TIMEOUT_MS, env: { ...ENV, ARGUMENTS: args } }) + const out = (r.stdout.toString() + r.stderr.toString()).trim() + return r.exitedDueToTimeout ? `${out}\n[stopped after ${SUBSTITUTION_TIMEOUT_MS / 1000} s]`.trim() : out + } + let out = "" + let at = 0 + for (const m of cmd.body.matchAll(/!`([^`]+)`/g)) { + out += fill(cmd.body.slice(at, m.index)) + run(m[1]!) + at = m.index + m[0].length + } + return (out + fill(cmd.body.slice(at))).trim() } diff --git a/src/session/commands.ts b/src/session/commands.ts index 3956f68..0f54a16 100644 --- a/src/session/commands.ts +++ b/src/session/commands.ts @@ -317,7 +317,7 @@ export function expandSlash(app: App, text: string, o: { plain?: boolean } = {}) // A project's command may make the mode stricter for its prompt, never looser; your own may. const own = cc.mode && (MODES as readonly string[]).includes(cc.mode) ? (cc.mode as Mode) : undefined const mode = own && cc.source === "project" ? stricter(own, app.engine.mode) : own - return { kind: "prompt", name, prompt: expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline), shown: t, attachFrom: arg, model: cc.model, ...(mode ? { mode } : {}) } + return { kind: "prompt", name, prompt: expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline, (line) => app.engine.judgeCommand(line, app.project.root)), shown: t, attachFrom: arg, model: cc.model, ...(mode ? { mode } : {}) } } const sk = src.skills().find((s) => slug(s.name) === wanted) if (sk) return { kind: "prompt", name, prompt: skillMessage(sk, words), shown: t, attachFrom: words } diff --git a/src/session/engine.ts b/src/session/engine.ts index 2dfeb2b..702f355 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -364,6 +364,12 @@ export class Engine { } /** What is met now, for a call: the mode for plan, the display as it is; the rest are fixed. */ + /** What a `bash` call of this line would be answered right now, by the rules and the mode. */ + judgeCommand(line: string, cwd?: string): { action: "allow" | "ask" | "deny"; reason: string } { + const ctx: PermContext = { ...this.o.perm, mode: this.mode, rules: [...this.o.perm.rules, ...this.sessionRules] } + return evaluate({ permission: "bash", class: "execute", patterns: [line], command: line, paths: [cwd ?? ctx.root] }, ctx) + } + /** Whether the read tool would read this file unasked right now (ToolContext.mayRead). */ mayRead(abs: string): boolean { const ctx: PermContext = { ...this.o.perm, mode: this.mode, rules: [...this.o.perm.rules, ...this.sessionRules] } diff --git a/src/tui/app.tsx b/src/tui/app.tsx index b748381..feee5dd 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -633,7 +633,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () => /** A custom command: its expanded body is the prompt; its frontmatter's model and mode hold for * this one prompt. */ const runCustom = (cc: CustomCommand, arg: string, typed: string) => - sendAs(expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline), typed, { + sendAs(expandCommand(cc, arg, app.project.root, app.engine.o.perm.hardline, (line) => app.engine.judgeCommand(line, app.project.root)), typed, { // @files come from what was typed, not from the command's own text. attachFrom: arg, model: cc.model, diff --git a/tests/project.test.ts b/tests/project.test.ts index 890f3d2..92d8d0f 100644 --- a/tests/project.test.ts +++ b/tests/project.test.ts @@ -1,8 +1,9 @@ import { afterAll, describe, expect, test } from "bun:test" -import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs" +import { existsSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { paths } from "../src/config/paths.ts" +import { DEFAULT_RULES, evaluate, toRules } from "../src/permission/evaluate.ts" import { hardlineRules } from "../src/permission/hardline.ts" import { attachmentsFor } from "../src/project/attach.ts" import { customCommands, expandCommand } from "../src/project/commands.ts" @@ -35,6 +36,54 @@ describe("@ attachments", () => { }) }) +describe("a custom command's !`…` is a bash call of the session (rules.md §6)", () => { + const cmd = (body: string) => ({ name: "x", description: "", body, source: "project" as const, file: "/x.md" }) + const judgeIn = (mode: "manual" | "plan" | "auto", root: string) => (line: string) => + evaluate({ permission: "bash", class: "execute", patterns: [line], command: line, paths: [root] }, { mode, rules: toRules(DEFAULT_RULES, "default"), hardline: hardlineRules(), root, branch: () => undefined }) + + test("the arguments are never part of the command line", () => { + const root = tree() + const marker = join(root, "ran") + const body = "Log: !`printf '%s|' $ARGUMENTS \"$1\" \"$2\"`" + const out = expandCommand(cmd(body), `a; touch ${marker}`, root, hardlineRules(), judgeIn("auto", root)) + expect(existsSync(marker)).toBe(false) + expect(out).toBe(`Log: a;|touch|${marker}|a;|touch|`) + }) + + test("manual mode: what bash would ask about is not run, and the model is told", () => { + const root = tree() + const marker = join(root, "ran") + const out = expandCommand(cmd(`A: !\`touch ${marker}\` B: !\`pwd\``), "", root, hardlineRules(), judgeIn("manual", root)) + expect(existsSync(marker)).toBe(false) + expect(out).toContain("needs the person's approval here") + expect(out).toContain(`B: ${root}`) + }) + + test("an allowed command with an argument in it is not known safe: not run in manual mode", () => { + const root = tree() + const out = expandCommand(cmd("!`cat $1`"), ".env", root, hardlineRules(), judgeIn("manual", root)) + expect(out).toContain("needs the person's approval here") + }) + + test("plan mode (a remote session limited to it) runs nothing but what the rules allow", () => { + const root = tree() + const marker = join(root, "ran") + const out = expandCommand(cmd(`!\`touch ${marker}\``), "", root, hardlineRules(), judgeIn("plan", root)) + expect(existsSync(marker)).toBe(false) + expect(out).toContain("[not run — plan mode") + }) + + test("the floor is checked with the arguments in place too", () => { + const root = tree() + expect(expandCommand(cmd("!`rm -rf $1`"), "/", root, hardlineRules(), judgeIn("auto", root))).toContain("[not run — recursive delete of the root filesystem]") + }) + + test("a $ in the arguments is text: one pass", () => { + const root = tree() + expect(expandCommand(cmd("Say: $ARGUMENTS (first: $1)"), "costs $$5 and $& and $1", root, hardlineRules(), judgeIn("manual", root))).toBe("Say: costs $$5 and $& and $1 (first: costs)") + }) +}) + describe("custom commands", () => { test("global and project, the project overriding; $ARGUMENTS, $1, !`cmd`, and the hardline", () => { const root = tree() @@ -48,9 +97,9 @@ describe("custom commands", () => { const review = cmds.find((c) => c.name === "review")! expect(review.description).toBe("review a file") expect(cmds.find((c) => c.name === "danger")!.source).toBe("project") - expect(expandCommand(review, "src/app.ts quickly", root, hardlineRules())).toBe("Review src/app.ts carefully. All: src/app.ts quickly\nBranch: main") + expect(expandCommand(review, "src/app.ts quickly", root, hardlineRules(), () => ({ action: "allow", reason: "" }))).toBe("Review src/app.ts carefully. All: src/app.ts quickly\nBranch: main") const globalDanger = customCommands(undefined).find((c) => c.name === "danger")! - expect(expandCommand(globalDanger, "", root, hardlineRules())).toContain("[not run — recursive delete of the root filesystem]") + expect(expandCommand(globalDanger, "", root, hardlineRules(), () => ({ action: "allow", reason: "" }))).toContain("[not run — recursive delete of the root filesystem]") }) })