Files
LLeMbas-CLI/tests/conformance.ts
T
HomerandClaude Fable 5.2 97eadde13b An editor as the client, device files, and files that are not text shown (spec 3.11.0)
The CLI's side of harness spec 3.11.0, on serve --stdio and on the link.

- acp/editor.ts: _lembas/complete (one HTTP request with the login the
  agent holds, the window trimmed, a newer request closes the older one's
  connection and that one is answered as cancelled), _lembas/edit (one
  model request with no tools; the stream cleaned of a fence around the
  whole answer and given the selection's ending; deltas; cancel),
  _lembas/models, _lembas/editor/settings, the editor block of a prompt,
  and ACP diff items.
- acp/files.ts: _lembas/fs/list, stat, read, write, mkdir, move, copy,
  delete, search. A path is judged where it really is, symlinks followed
  first; outside remote.roots, the CLI's own directories and protected
  paths are refused, and so is a folder that holds them; read-only where
  the device allows plan mode only. A write is checked against the hash
  the client last saw, twice for an upload in parts, and put in place
  whole. A delete goes to the system's trash or is refused until the
  client says permanent.
- tool/buffers.ts: read, write, edit, multiedit and apply_patch take a
  file's text from the client's editor and write through it where the
  client offers ACP's fs methods; any failure there is the disk. The call
  is judged before any of it, as before. An overwrite of text that changed
  in the editor since it was read is refused.
- A tool's preview gives each file's text before and after beside the
  unified diff; a client that said editor: true gets them as diff items on
  the approval card and on every finished edit. The texts are kept only
  for such a client.
- tool/show.ts: to a client that said media: true a file that is not text
  is handed over by a handle (_lembas/show/read), good while the request
  is open and for that file as it was; a table, an SVG and a notebook are
  named. On stdio the request also says where the file is.
- The hardline, the modes and the rules are untouched; tool/replace.ts is
  untouched.

Tests: tests/acp-editor.test.ts (19), tests/acp-files.test.ts (13), and
the conformance areas editor, device_files and show.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 11:42:03 +00:00

582 lines
33 KiB
TypeScript

// What the CLI does with each conformance case (harness/conformance/*.json). The cases are the
// harness spec's: LLeMbas runs the same files through its own implementation. The test compares
// this with each case's `expect`; `bun run harness record` fills in an `expect` a new case lacks.
import { alwaysPatterns, toRules, evaluate, judgeNewRule, ruleAction, DEFAULT_RULES, type PermissionRequest, type Rule } from "../src/permission/evaluate.ts"
import { BUILTIN_HARDLINE, hardlineCommand, plainCommands } from "../src/permission/hardline.ts"
import { splitCommand, words } from "../src/permission/bash.ts"
import { prefix } from "../src/permission/arity.ts"
import { split } from "../src/library/chunks.ts"
import { ThinkSplitter } from "../src/provider/think.ts"
import { advertisedEfforts, effortRefused, levelFields, levelsOf, type LevelMeta } from "../src/provider/effort.ts"
import { replace } from "../src/tool/replace.ts"
import { applyUnified, parseUnified } from "../src/tool/unidiff.ts"
import { derive, joinBom, parse } from "../src/tool/patch.ts"
import type { Mode, PermissionConfig } from "../src/config/schema.ts"
import { apply, fromTodos, normalise, type Plan } from "../src/plan/plan.ts"
import { ToolCallAccumulator, toOpenAIMessages } from "../src/provider/openai-chat.ts"
import type { Message } from "../src/provider/types.ts"
import { pageNote, pagesOf, pagesOffered, textProjection } from "../src/pages/fence.ts"
import { staticFaults } from "../src/pages/static.ts"
import { resolveBase } from "../src/library/store.ts"
import { NarrowError, narrowParameters, type Narrow } from "../src/harness.ts"
import { fillPrompt } from "../src/prompt/fill.ts"
import { instructionChain } from "../src/prompt/assemble.ts"
import { CONTEXT, hunks, lineCount, memoryResults, presentIds, ResultContext, sha256 } from "../src/session/results.ts"
import { readBody } from "../src/tool/read.ts"
import { applyOps, type Op, type Target } from "../src/memory/store.ts"
import { jobNote, type NoteCase } from "../src/jobs/note.ts"
import { compactAsk, noteFor, offeredFor, toldAt, unavailable, type Now, type Requirement, type Told } from "../src/session/prefix.ts"
import { envLines, promptText } from "../src/prompt/assemble.ts"
import { absPath, type ToolContext } from "../src/tool/tool.ts"
import { LOOP, TOOL_SPECS } from "../src/harness.ts"
import { LEAD_TOOLS, memberTools, Team, TEAM_TOOLS, type Capacity } from "../src/team/team.ts"
import { noteBlock } from "../src/session/prefix.ts"
import { offer, subagentModel, type ModelInfo } from "../src/team/subagents.ts"
import { endLine, progressLine, progressText, type Progress } from "../src/session/progress.ts"
import { callDuration, callFacts, callTitle, changeText, diffCounts, drawnBlock, type CallState } from "../src/session/display.ts"
import { checkMode, requestRefusal, tighten, whoDecides, type Grant } from "../src/team/delegation.ts"
import { fillPrompt as fillText } from "../src/prompt/fill.ts"
import { isSilent, judgeCase, monitorHash, notifyInstruction, reportResult, reportTool, runLeaves, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts"
import { clientModel, records, startModel, type SessionKind } from "../src/session/lastmodel.ts"
import { cancelOf, reattach } from "../src/acp/turns.ts"
import { outstanding, type OutstandingInput } from "../src/session/outstanding.ts"
import { background, scheduledRefusal, twin, type BackgroundCall, type Listed } from "../src/provider/interactive.ts"
import { diffContent, editorBlock, rewriteMessage, rewriteModel, RewriteOutput, trimWindow } from "../src/acp/editor.ts"
import { baseCheck, judgePath, type FsOp } from "../src/acp/files.ts"
import { showPlan } from "../src/tool/show.ts"
type Case = Record<string, unknown>
/** A path with the symlinks of a case followed (`links`: path → target), as realPath would. */
function followLinks(links: Record<string, string>, path: string, depth = 0): string {
if (depth > 40) return path
const hit = Object.keys(links)
.filter((l) => path === l || path.startsWith(l + "/"))
.sort((a, b) => b.length - a.length)[0]
return hit === undefined ? path : followLinks(links, links[hit]! + path.slice(hit.length), depth + 1)
}
/** Whether a path is at `ro` or above under `grants` (fs_access's rule: the most specific grant on
* the path or above it wins; none where nothing is granted). No grants at all: everything readable. */
function readableUnder(grants: Record<string, string> | undefined, path: string): boolean {
if (!grants) return true
let best: string | undefined
for (const g of Object.keys(grants)) {
const covers = g === "/" || path === g || path.startsWith(g + "/")
if (covers && (best === undefined || g.length > best.length)) best = g
}
return best !== undefined && grants[best] !== "none"
}
export const AREAS: Record<string, (c: Case) => unknown> = {
// Spec 3.11.0: an editor as the client (src/acp/editor.ts).
editor: (c) => {
if (c.kind === "trim") return trimWindow(c.prefix as string, c.suffix as string, c.max as number)
if (c.kind === "context") return { block: editorBlock(c.editor, c.root as string, (c.limits ?? {}) as Record<string, number>) ?? null }
if (c.kind === "message") return { message: rewriteMessage(c as unknown as Parameters<typeof rewriteMessage>[0], (c.limits ?? {}) as Record<string, number>) }
if (c.kind === "output") {
const out = new RewriteOutput(c.selection as string)
const pieces = [...(c.chunks as string[]).map((x) => out.feed(x)), out.end()]
// The pieces sent as deltas, joined, are the result's text.
if (pieces.join("") !== out.text) throw new Error(`editor output: the pieces ${JSON.stringify(pieces)} are not the text ${JSON.stringify(out.text)}`)
return { text: out.text }
}
if (c.kind === "model") {
const r = rewriteModel({ asked: c.asked as string | undefined, session: c.session as string | undefined, main: c.main as string | undefined, served: c.served as string[], start: c.start as string | undefined })
return { model: r.model, from: r.from }
}
if (c.kind === "diff") return { content: diffContent({ editor: c.editor === true, when: c.when as "ask" | "done", bytes: c.bytes as number, max: c.max as number }) }
throw new Error(`editor: unknown kind ${String(c.kind)}`)
},
// Spec 3.11.0: device files (src/acp/files.ts).
device_files: (c) => {
if (c.kind === "base") return baseCheck({ ...("base" in c ? { base: c.base } : {}), overwrite: c.overwrite, current: (c.current ?? null) as string | null })
const guardedRoots = c.protected as string[]
const links = (c.links ?? {}) as Record<string, string>
return judgePath({
op: c.op as FsOp,
path: c.path as string,
roots: c.roots as string[],
own: c.own as string[],
guarded: (p) => guardedRoots.some((g) => p === g || p.startsWith(g + "/")),
guardedRoots,
enabled: c.enabled === true,
sharedOnly: c.shared_only === true,
maxMode: c.max_mode as Mode,
real: (p) => followLinks(links, p),
deep: c.deep === true,
})
},
// Spec 3.11.0: what the show tool sends for a file (src/tool/show.ts).
show: (c) => showPlan({ name: c.name as string, media: c.media === true, text: c.text === true, size: c.size as number }),
// Spec 3.10.0: which turn a `session/cancel` touches (src/acp/turns.ts).
cancel: (c) => cancelOf({ turn: c.turn as string | undefined, running: c.running as string | undefined, queued: c.queued as string[] | undefined }),
// Spec 3.10.0: what a session still has out when no turn of it runs (src/session/outstanding.ts).
outstanding: (c) => outstanding(c as unknown as OutstandingInput),
// Spec 3.10.0: a row reattached after a restart or a dropped link — the client's rule (src/acp/turns.ts).
reattach: (c) => reattach({ turn: c.turn as string, machine: c.machine === true, status: c.status as { turnId?: string; queued?: string[]; lastTurnId?: string } }),
// Spec 3.9.0: the model last used in a directory (src/session/lastmodel.ts).
last_model: (c) => {
const str = (k: string) => (typeof c[k] === "string" ? (c[k] as string) : undefined)
if (c.kind === "start") return startModel({ asked: str("asked"), project: str("project"), directory: str("directory"), global: str("global"), served: c.served as string[], default: str("default") })
if (c.kind === "record") return records({ session: c.session as SessionKind, agent: c.agent as "main" | "subagent", what: c.what as "turn" | "change" | "command", machine: c.machine === true })
if (c.kind === "client") return clientModel({ named: str("named"), directory: str("directory"), has: c.has as string[], default: str("default"), scheduled: c.scheduled === true, interactive_only: c.interactive_only as string[] | undefined })
throw new Error(`last_model: unknown kind ${String(c.kind)}`)
},
// Spec 3.9.0: interactive-only models (src/provider/interactive.ts).
interactive: (c) => {
const models = c.models as Listed[]
if (c.kind === "twin") return twin(c.model as string, models) ?? null
if (c.kind === "background") return background({ model: c.model as string, models, defaults: c.defaults as string[], call: c.call as BackgroundCall, unfit: c.unfit as string[] | undefined })
if (c.kind === "scheduled") {
const refused = scheduledRefusal(c.model as string, models)
return refused ? { refused } : { run: true }
}
throw new Error(`interactive: unknown kind ${String(c.kind)}`)
},
// Spec 3.5.0: scheduled work on a linked computer (src/acp/scheduled.ts).
scheduled: (c) => scheduledMode({ accept: c.accept === true, mode: c.mode, max_mode: c.max_mode as Mode, approval_wait_s: c.approval_wait_s }),
silent: (c) => ({ silent: isSilent(c.text as string), stripped: stripSentinel(c.text as string) }),
monitor: (c) => {
if (c.kind === "hash") return monitorHash(c.exit as number, c.output as string)
const r = judgeCase(c.line as string, c.mode as Mode, c.rules as PermissionConfig | undefined)
return "run" in r ? "run" : { refused: r.refused }
},
hardline: (c) => hardlineCommand(c.line as string, BUILTIN_HARDLINE)?.id ?? null,
split: (c) => splitCommand(c.line as string),
plain: (c) => plainCommands(c.line as string),
arity: (c) => prefix(words(c.command as string)).join(" "),
always: (c) => {
const line = c.line as string
const split = splitCommand(line)
// What an approval card offers to remember: nothing when the split cannot be trusted.
if (split.unsafe.length) return []
return alwaysPatterns({ permission: "bash", class: "execute", patterns: [line], command: line }, split.commands.length ? split.commands : [line])
},
permission: (c) => {
const line = c.line as string
const req: PermissionRequest = { permission: "bash", class: "execute", patterns: [line], command: line, paths: ["/project"] }
const rules = [...toRules(DEFAULT_RULES, "default"), ...toRules((c.rules ?? {}) as PermissionConfig, "global")]
return evaluate(req, { mode: c.mode as Mode, rules, hardline: BUILTIN_HARDLINE, root: "/project", planDir: "/project/.agent/plans", projectDir: "/project/.agent" }).action
},
chunk: (c) => split(c.text as string, c.size as number, c.overlap as number),
think: (c) => {
const s = new ThinkSplitter()
const pieces = [...(c.chunks as string[]).flatMap((x) => s.feed(x)), ...s.flush()]
const out = { reasoning: "", text: "" }
for (const p of pieces) out[p.kind] += p.text
return out
},
effort: (c) => ({ refused: effortRefused(c.message as string), advertised: advertisedEfforts(c.message as string) }),
// Effort levels (models/schema.json `levels`): what a model offers, how it is shown, where it
// starts, and what a request carries for a level.
levels: (c) => {
const meta = c.model as LevelMeta
if (c.op === "levels") return levelsOf(meta)
if (c.op === "request") return levelFields(meta, c.level as string)
throw new Error(`levels: unknown op ${String(c.op)}`)
},
edit: (c) => {
try {
return { content: replace(c.content as string, c.old as string, c.new as string, c.all === true) }
} catch (e) {
return { error: (e as Error).message }
}
},
unidiff: (c) => {
try {
const files = parseUnified(c.patch as string)
return { content: applyUnified(c.content as string, files.flatMap((f) => f.hunks)) }
} catch (e) {
return { error: (e as Error).message }
}
},
plan: (c) => {
if (c.op === "normalise") return normalise(c.plan)
if (c.op === "update") return apply(c.plan as Plan, c.changes)
if (c.op === "todos") return fromTodos(c.todos)
throw new Error(`plan: unknown op ${String(c.op)}`)
},
// HTML pages in answers (pages.md, spec 3.8.0): the fence, the note, the text projection, where
// pages are offered, the session note for a switch changed mid-chat.
pages: (c) => {
switch (c.show) {
case "fence":
return { pages: pagesOf(c.text as string), projection: textProjection(c.text as string) }
case "note":
return { note: pageNote(c.title as string) }
case "offered":
return { offered: pagesOffered(c as { instance?: boolean; model?: boolean; chat?: boolean; where?: string }) }
case "static": {
const why = staticFaults(c.html as string)
return why.length ? { static: false, why } : { static: true }
}
case "note_line":
return { line: c.change === "on" ? fillText(CONTEXT.note.pages_on, { pages_text: c.pages_text as string }) : CONTEXT.note.pages_off }
default:
throw new Error(`pages: unknown show ${String(c.show)}`)
}
},
// Reports (reports.md, spec 3.8.0): where report_write is offered, the instruction in the run's
// prompt, the tool's answer, and what a run leaves.
reports: (c) => {
switch (c.show) {
case "offered": {
const tool = reportTool(c as { session: string; notify?: unknown; turn: string; subagent?: boolean })
return tool === "unavailable" ? { tool, text: TOOL_SPECS.report_write!.unavailable } : { tool }
}
case "instruction":
return { text: notifyInstruction(c.notify, c.condition) }
case "result":
return { text: reportResult(c.calls as number) }
case "run":
return runLeaves(c as never)
default:
throw new Error(`reports: unknown show ${String(c.show)}`)
}
},
// Which permission rule decides, and what making one does (permission/rules.md, spec 3.8.0).
rules: (c) => {
const written: Rule[] = [...(c.defaults ? toRules(DEFAULT_RULES, "default") : []), ...toRules((c.user ?? {}) as PermissionConfig, "global"), ...toRules((c.project ?? {}) as PermissionConfig, "project")]
// An "always" answer is a learned rule; one set in a menu is a project's rule, in the session as in the file.
const made: Rule[] = ((c.made ?? []) as { permission: string; pattern: string; action: Rule["action"]; by: string }[]).map((m) => ({ permission: m.permission, pattern: m.pattern, action: m.action, ...(m.by === "always" ? { learned: true } : { source: "project" as const }) }))
const bare = (r: Rule) => ({ permission: r.permission, pattern: r.pattern, action: r.action })
if (c.set) {
const j = judgeNewRule(c.set as Rule, written, [...written, ...made])
return j.result === "made" ? { result: "made", still: j.still.map(bare) } : j.result === "refused" ? { result: "refused", by: bare(j.by) } : { result: "unchanged" }
}
const q = c.request as { permission: string; pattern: string }
return ruleAction(q.permission, q.pattern, [...written, ...made]) ?? null
},
fill: (c) => {
try {
return { text: fillPrompt(c.text as string, c.vars as Record<string, string>) }
} catch (e) {
// "prompt: no value for {{a}}, {{c}}": the names, sorted.
return { missing: [...(e as Error).message.matchAll(/\{\{(\w+)\}\}/g)].map((m) => m[1]!).sort() }
}
},
narrow: (c) => {
try {
return { parameters: narrowParameters(c.parameters as Record<string, unknown>, c.narrow as Narrow) }
} catch (e) {
if (e instanceof NarrowError) return { error: e.code }
throw e
}
},
memory: (c) => {
const r = applyOps(c.target as Target, c.entries as string[], c.ops as Op[], c.limit as number)
return { ok: r.ok, entries: r.ok ? r.after : c.entries, message: r.message, usage: r.usage, shown: Boolean(r.entries) }
},
jobs: (c) => jobNote(c as unknown as NoteCase),
// The instruction chain (filesystem.md): the CLI's own walk, with the case's files and grants as
// what it may read.
instructions: (c) => {
const files = new Set(c.files as string[])
return instructionChain(c.boundary as string, c.start as string, (p) => files.has(p) && readableUnder(c.grants as Record<string, string> | undefined, p))
},
// Context hygiene: one session's insertions, step by step. `messages` is the request being built
// (what a stub may point at); `history` the results since the last compaction, which its table
// is drawn from. `reply` starts a request that carries none of them, as a chat's next reply does.
context: (c) => {
const messages: { role: string; content: string }[] = []
const history = new Set<string>()
const store = memoryResults()
const rc = new ResultContext(store, () => presentIds(messages), { ...CONTEXT.cap, ...((c.limits ?? {}) as object) })
return (c.steps as Record<string, any>[]).map((st) => {
if (st.op === "reply") {
messages.length = 0
return ""
}
if (st.op === "compact") {
const table = rc.compactionTable(store.all().filter((r) => history.has(r.id)))
messages.length = 0
history.clear()
return table
}
let text: string
if (st.op === "read") {
const { body, from, to, of } = readBody(st.content, st.offset, st.limit)
text = rc.insert({ kind: "read", path: st.path, key: st.path, sha: sha256(st.content), from, to, of, body }, st.id)
} else if (st.op === "edit" || st.op === "write") {
const sha = sha256(st.after)
text = rc.insert({ kind: "edit", files: [st.before === undefined ? { path: st.path, sha, created: lineCount(st.after) } : { path: st.path, sha, hunks: hunks(st.before, st.after) }] }, st.id)
} else if (st.op === "recall") text = rc.insert({ kind: "recall", target: st.target, offset: st.offset, limit: st.limit }, st.id)
else text = rc.insert({ kind: "output", tool: st.tool, args: st.args, text: st.text }, st.id)
messages.push({ role: "tool", content: text })
history.add(st.id)
return text
})
},
// The prefix (context.md §10): one session's requests, step by step — which prompt each sends (a
// new number each time one is made), which tools it offers, and the note on a user message.
prefix: (c) => {
const start = c.start as Partial<Now> & { could?: Requirement[]; met?: Requirement[] }
const could = new Set<Requirement>(start.could ?? [])
let met = new Set<Requirement>(start.met ?? could)
const now: Now = { date: start.date!, mode: start.mode ?? "manual", plan: start.plan ?? "", memory: start.memory ?? "", personality: start.personality ?? "", files: start.files ?? {}, mcp: start.mcp ?? {} }
const modeText = (m: Mode) => fillPrompt(promptText(`modes/${m}.md`), { plan_dir: (c.plan_dir as string | undefined) ?? ".agent/plans" })
const requires = (t: string) => TOOL_SPECS[t]?.requires as Requirement[] | undefined
let made: { system: number; tools: string[]; told: Told } | undefined
let prompts = 0
let carried: string | undefined
const make = () => {
if (made) return made
made = { system: ++prompts, tools: (c.tools as string[]).filter((t) => offeredFor(requires(t), could)), told: { ...toldAt(now), ...(carried ? { date: carried } : {}) } }
carried = undefined
return made
}
const fields = ["date", "mode", "plan", "memory", "personality", "files", "mcp"] as const
return (c.steps as Record<string, any>[]).map((st) => {
if (st.op === "set") {
for (const f of fields) if (f in st) (now as unknown as Record<string, unknown>)[f] = structuredClone(st[f])
if (st.met) met = new Set(st.met)
// The model's own tool changed it: its result told the model.
if (st.by === "model" && made) for (const f of fields) if (f in st && f !== "date") (made.told as unknown as Record<string, unknown>)[f] = structuredClone(st[f])
return null
}
if (st.op === "call") {
const here = new Set(met)
if (now.mode === "plan") here.add("plan")
else here.delete("plan")
return unavailable(st.tool, requires(st.tool), here) ?? null
}
if (st.op === "model") {
carried = made?.told.date
made = undefined
return null
}
const k = make()
if (st.op === "user") {
const { note, told } = noteFor(k.told, now, modeText)
if (note) k.told = told
return { system: k.system, tools: k.tools, note: note || null }
}
if (st.op === "tool" || st.op === "wrapup") return { system: k.system, tools: k.tools, note: null }
if (st.op === "compact") {
made = undefined
return { system: k.system, tools: k.tools, ask: compactAsk() }
}
throw new Error(`prefix: unknown op ${String(st.op)}`)
})
},
// Reasoning sent back during its turn (context.md §8): the history as the OpenAI chat dialect
// sends it — role, content and reasoning_content (tool calls and ids left out, as the cases do).
reasoning: (c) => {
const history: Message[] = (c.messages as Record<string, any>[]).map((m, i): Message => {
if (m.role === "user") return { role: "user", parts: [{ type: "text", text: m.content }], ...(m.turn === false ? { turn: false as const } : {}) }
if (m.role === "assistant") return { role: "assistant", parts: [...(m.reasoning !== undefined ? [{ type: "reasoning" as const, text: m.reasoning }] : []), ...(m.content ? [{ type: "text" as const, text: m.content }] : [])] }
return { role: "tool", callId: `c${i}`, name: "read", content: m.content }
})
return (toOpenAIMessages("", history, false) as Record<string, any>[]).map((m) => ({ role: m.role, content: m.content ?? "", ...(m.reasoning_content !== undefined ? { reasoning_content: m.reasoning_content } : {}) }))
},
// No absolute paths (context.md §11): the environment block's lines, and how a tool reads a path.
paths: (c) => {
if (c.op === "env") return envLines(c.root as string, c.started as string)
if (c.op === "resolve") return absPath(c.path as string, { root: (c.root as string).replace(/\/+$/, ""), cwd: c.started as string } as ToolContext)
throw new Error(`paths: unknown op ${String(c.op)}`)
},
// Subagents (subagents.md, spec 3.3.0): the model a subagent runs on, through the rules spawn and
// team_add ask; the offer through the Team the app makes (its tools, setting and note).
subagents: (c) => {
const models = Object.entries(c.models as Record<string, Omit<ModelInfo, "ref">>).map(([ref, m]) => ({ ref, ...m }))
const byRef = (ref: string) => models.find((m) => m.ref === ref)!
const session = byRef(c.session as string)
if (c.op === "model") {
const r = subagentModel(session, c.model === undefined ? undefined : byRef(c.model as string), (c.said as string[] | undefined) ?? [])
return "refused" in r ? { refused: r.refused } : { model: r.model }
}
if (c.op === "offer") {
const subagents = c.subagents !== false
const pure = offer(session, models, subagents)
const team = new Team({ min: 1, max: 4, subagents, model: session.ref, capacity: (ref) => byRef(ref).capacity, models: () => models.map((m) => m.ref) })
if (team.offered !== pure.offered) throw new Error("subagents: the Team and the rule disagree on the offer")
const noted = team.offered && team.noteLines()[0]!.split("\n").includes(LOOP.context.note.team_own)
return { offered: team.offered, own: pure.own, note: noted ? LOOP.context.note.team_own : null }
}
throw new Error(`subagents: unknown op ${String(c.op)}`)
},
// Teams (team.md): one lead session's team, step by step, through the CLI's own rules
// (team/team.ts); the app drives the same class from real turns.
team: (c) => {
const start = c.start as { min: number; max: number; subagents?: boolean; capacity: Capacity; mode?: Mode }
let capacity = start.capacity
const team = new Team({ min: start.min, max: start.max, subagents: start.subagents, model: "m", capacity: () => capacity, mode: start.mode ?? "edit", steps: { main: 200, sub: 50 } })
// What each agent's turn was started with (a brief, or the messages that woke it).
const started: Record<string, string> = {}
team.effects = { start: (n, t) => void (started[n] = t), deliver: () => {}, stop: () => {} }
const delivered = () => {
const out: Record<string, string[]> = {}
for (const d of team.delivered.splice(0)) (out[d.name] ??= []).push(d.text)
return out
}
return (c.steps as Record<string, any>[]).map((st) => {
const by = (st.by as string | undefined) ?? "lead"
switch (st.op) {
case "offered": {
const a = team.get(by)!
const tools = !team.offered ? [] : by === "lead" ? [...LEAD_TOOLS] : memberTools(a)
return { tools: [...tools].sort(), setting: team.offered }
}
case "call": {
const args = st.args as Record<string, any>
let result: string | null
if (st.tool === "team_read") {
const no = team.offered ? team.unavailable() : "unavailable"
const room = no ? [] : team.readRoom(by, args.since ?? 0).messages.map((m) => ({ n: m.n, from: m.from, to: m.to.join(", ") }))
return { room, delivered: delivered() }
}
const first = (TEAM_TOOLS as readonly string[]).includes(st.tool) ? team.refusal(by, st.tool, args) : undefined
if (first) result = first
else if (st.tool === "team_add") result = team.add(by, args as any).text
else if (st.tool === "team_send") result = team.send(by, args as any)
else if (st.tool === "team_stop") result = team.stopCmd(by, args.name)
else if (st.tool === "team_assign") result = team.assign(by, args as any)
else if (st.tool === "team_replace") result = team.replace(by, args as any).text
else if (st.tool === "team_finish") result = team.finishTask(by, args.report)
else if (st.tool === "team_whoami") result = team.whoami(by)
else if (st.tool === "team_findings") result = args.action === "write" ? team.noteFinding(by, args.text ?? "") : team.readFindings(by, args.of)
else if (st.tool === "team_request") result = team.request(by, args as any, TOOL_SPECS[args.tool]?.risk as any)
else if (st.tool === "team_decide") result = team.decide(by, args as any)
else {
result = team.refusal(by, st.tool, args) ?? null
if (st.tool === "task" && result === null && team.offered) team.taskStart(by)
}
return { result, delivered: delivered() }
}
case "finish":
team.finish(by, st.reply ?? "", st.reason ?? "stop")
return { delivered: delivered() }
case "task_done":
team.taskDoneBy(by)
return null
case "set":
if (st.capacity) capacity = st.capacity
if (st.min !== undefined || st.max !== undefined) team.setSetting(st.min ?? team.min, st.max ?? team.max)
return null
case "person_stop":
team.personStop(st.name)
return null
case "user": {
const lines = team.noteLines()
team.leadWants()
return { note: lines.length ? noteBlock(lines) : null }
}
case "state":
return team.state()
// Spec 3.4.0.
case "context":
team.setContext(by, st.used, st.window)
return null
case "context_full":
team.pause(by)
return { delivered: delivered() }
case "started":
return { text: started[by] ?? null }
case "tree": {
const t = team.info()
const row = (a: (typeof t.agents)[number]) => ({ id: a.id, name: a.name, parent: a.parent, state: a.state, mode: a.mode, request: a.request })
return { size: t.size, open_slots: t.open_slots, agents: t.agents.map(row), ended: t.ended.map((a) => ({ id: a.id, name: a.name, state: a.state })) }
}
case "main_mode":
team.setMainMode(st.mode)
return null
}
throw new Error(`team: unknown op ${String(st.op)}`)
})
},
// Display (display.md, spec 3.7.0): a call's title, duration and facts; the line that ends a reply.
display: (c) => {
switch (c.show) {
case "title":
return { title: callTitle(c.args) ?? null }
case "duration":
return { duration: callDuration(c.state as CallState, c.ms as number | undefined) ?? null }
case "change": {
const n = diffCounts(c.diff as string)
return { ...n, text: changeText(n) }
}
case "facts":
return { facts: callFacts(c as { block?: string; diff?: string; exit?: number; hits?: number }) }
case "end":
return { line: endLine(c.progress as Progress | null, c.now as number) ?? null }
case "drawn":
return { drawn: drawnBlock(c.block as string | undefined) }
default:
throw new Error(`display: unknown show ${String(c.show)}`)
}
},
// Progress (progress.md, spec 3.4.0): the text and the line a client draws.
progress: (c) => {
const p = c.progress as Progress
return { text: progressText(p, c.now as number), line: progressLine(p, c.now as number) }
},
// Delegation (subagents.md §7, spec 3.4.0): the mode check, who decides a call, team_request's
// check, and tightening down the tree.
delegation: (c) => {
if (c.op === "add") {
const r = checkMode(c.parent_mode as Mode, c.mode as Mode | undefined, c.request as string[] | undefined)
return "error" in r ? { result: r.error, mode: null } : { result: null, mode: r.mode }
}
if (c.op === "call") {
const call = c.call as { tool: string; line?: string; path?: string }
const req: PermissionRequest =
call.tool === "bash"
? { permission: "bash", class: "execute", patterns: [call.line!], command: call.line!, paths: ["/project"] }
: { permission: call.tool === "read" ? "read" : "edit", class: call.tool === "read" ? "read" : "write", patterns: [call.path!], paths: [`/project/${call.path}`] }
const v = whoDecides(req, {
ctx: { rules: toRules(DEFAULT_RULES, "default"), hardline: BUILTIN_HARDLINE, root: "/project", planDir: "/project/.agent/plans", projectDir: "/project/.agent" },
mode: c.mode as Mode,
main: c.main_mode as Mode,
request: (c.request as string[] | undefined) ?? [],
grants: (c.grants as Grant[] | undefined) ?? [],
unattended: c.unattended === true,
})
// The text is compared unless the case says the reason is each project's own.
return v.answer === "refused" && c.own_reason !== true ? { answer: v.answer, text: v.text } : { answer: v.answer }
}
if (c.op === "request") {
const cls = TOOL_SPECS[c.tool as string]?.risk as "read" | "write" | "execute" | undefined
return { result: requestRefusal(c.tool as string, cls, c.request as string[]) ?? fillText(LOOP.team.texts.requested, { id: `${LOOP.team.request.id_prefix}1` }) }
}
if (c.op === "switch") {
return tighten(c.main_to as Mode, c.agents as { name: string; parent: string; mode: Mode }[])
}
throw new Error(`delegation: unknown op ${String(c.op)}`)
},
library_scope: (c) => resolveBase(c.bases as { id: string; name: string }[], c.base as string | null),
toolcall_index: (c) => {
// The deltas as the OpenAI stream carries them: `function.name` and `function.arguments`.
const acc = new ToolCallAccumulator()
acc.feed((c.deltas as Record<string, unknown>[]).map(({ index, id, name, arguments: args }) => ({ index, id, function: { name, arguments: args } })))
return acc.result().map((p) => ({ id: p.id, name: p.name, arguments: p.args }))
},
envelope: (c) => {
// planPatch's logic without the filesystem: every file followed through the patch in memory.
const files = new Map<string, string | null>(Object.entries(c.files as Record<string, string>))
try {
for (const h of parse(c.patch as string)) {
const text = files.get(h.path) ?? null
if (h.type === "add") {
if (text !== null) throw new Error(`${h.path} already exists; use Update File to change it.`)
files.set(h.path, h.contents.endsWith("\n") ? h.contents : h.contents + "\n")
} else if (h.type === "delete") {
if (text === null) throw new Error(`${h.path} does not exist.`)
files.set(h.path, null)
} else {
if (text === null) throw new Error(`${h.path} does not exist.`)
const next = derive(h.path, h.chunks, text)
if (h.movePath) files.set(h.path, null)
files.set(h.movePath ?? h.path, joinBom(next.content, next.bom))
}
}
return { files: Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b))) }
} catch (e) {
return { error: (e as Error).message }
}
},
}