Files
LLeMbas-CLI/src/tool/tool.ts
T
HomerandClaude Opus 5.5 a302f22957 Texts and duplicates: one word for the server, one containment, one mode order (T6-T9, duplicates 1 and 4)
- User texts: "LLeMbas server" (the word used most) instead of "LLeMbas
  instance"; "sign-in" instead of 1.x's "connection"/"webui connection";
  "forge" out of SECURITY.md, the config schema, get.sh's help (earlier
  commit) and the workspace prompt block. --help: lembas logout [name],
  service run [name], files_that_run_code in remote --json.
- within.ts relativeWithin(): the four relative()-and-".." copies (showPath,
  the editor's and autocomplete's paths, the prompt's paths) and read.ts's
  root+"/" use the one containment. paths.json: a ..cache env case.
- permission/modes.ts: the mode order from modes.json, stricterMode and
  clampMode — the seven tables in app, config/load, tool/settings,
  session/commands, acp/agent, acp/scheduled and team/delegation go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:32:44 +00:00

301 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { relativeWithin } from "../within.ts"
import { within } from "../within.ts"
import { existsSync } from "node:fs"
import { isAbsolute, relative, resolve } from "node:path"
import { z } from "zod"
import type { PermissionRequest } from "../permission/evaluate.ts"
import { expandHome } from "../config/paths.ts"
import type { ToolSpec } from "../provider/types.ts"
import { fillParameters, PURPOSE_DEF, TOOL_SPECS } from "../harness.ts"
export interface ToolContext {
/** Absolute project root. */
root: string
/** Where the session was started (absolute): it ends the instruction chain and is told to the
* model relative to the root. Relative paths and the shell are the root's (context.md §11). */
cwd: string
signal: AbortSignal
/** Absolute paths read in this session — `edit`/`write` of an existing file requires one. */
readFiles: Set<string>
/** mtime (ms) of each file when it was last read or written by a tool, to detect outside edits. */
fileStamps: Map<string, number>
bashTimeoutMs: number
/** Whether `read` of this file would run without asking, by the rules and the mode as they are
* now (set by the engine per step). A tool that reads many files on the model's behalf (grep)
* returns nothing of a file this refuses (filesystem.md, *A search does not read what `read`
* would ask about*). Absent: nothing is filtered (a caller with no permissions of its own). */
mayRead?: (abs: string) => boolean
/** Instruction files (AGENTS.md / CLAUDE.md) the model has already been given. */
instructionsSeen?: Set<string>
/** Ask the user questions (the ask_user tool). Absent where nobody can answer. */
question?: (req: import("./ask_user.ts").QuestionRequest, callId?: string) => Promise<import("./ask_user.ts").QuestionReply>
/** Start a subagent (the task tool): a handle on its job, whose `done` is its report. `signal`:
* the parent's turn, which stops a synchronous subagent with it — never wired for a background
* one. Absent inside a subagent: no recursion. */
spawn?: (agent: string, prompt: string, opts: SpawnOptions) => Promise<SubagentHandleInfo>
/** Background jobs (jobs/registry.ts): the registry, and whose jobs these tools see — the
* session's, or a subagent's own (`job`: the subagent's job, which `report` speaks for). */
jobs?: { registry: import("../jobs/registry.ts").JobRegistry; owner(): { sessionId: string; job?: import("../jobs/registry.ts").Job } }
/** false: a foreground command is killed at its timeout rather than moved to the background —
* the TUI's own `!` commands, which no model owns. Default true. */
bashTimeline?: boolean
/** Aborted when the person wants the foreground command of this step in the background now
* (the TUI's ctrl+b): bash hands it to the registry as it would at its timeout. Set by the
* engine for the step's calls. */
backgroundNow?: AbortSignal
/** The team this agent is on (spec 3.2.0, team/runtime.ts) and its name there (`lead`, or a
* member's). Absent where no team is offered. */
team?: { runtime: import("../team/runtime.ts").TeamRuntime; as: string }
/** The id of the call being run (set by the engine per call). */
callId?: string
/** The project directory (.agent), when the project has one. */
projectDir?: string
/** The plans directory (plan mode writes only there). */
planDir?: string
/** The session's plan (plan_write, plan_update, plan_submit): read it, replace it (null clears),
* and present it for approval — `ask` is absent where nobody can answer. */
plan?: {
get(): import("../plan/plan.ts").Plan | undefined
set(plan: import("../plan/plan.ts").Plan | null): void
ask?: (req: import("./plan_submit.ts").PlanRequest, callId?: string) => Promise<import("./plan_submit.ts").PlanReply>
}
/** Change the permission mode (plan_submit, on approval). */
setMode?: (mode: import("../config/schema.ts").Mode) => void
/** Web search and fetch settings (config `search:`). */
search?: import("../search/index.ts").SearchConfig
/** Persistent memory (the memory tool); the default store when absent. */
memory?: import("../memory/store.ts").MemoryStore
/** This project's own memory (.agent/local/MEMORY.md), in a trusted project with a .agent. */
projectMemory?: import("../memory/store.ts").MemoryStore
/** Skills as they are on disk now, and where a new one may go. */
skills?: { list(): import("../skill/index.ts").Skill[]; projectDir?: string; changed?(): void }
/** Past sessions (session_search). */
sessions?: { store: import("../session/store.ts").Store; current(): string | undefined }
/** Settings (the settings tool): read and change them; the configured models. */
settings?: {
get(key: string): import("../config/settings.ts").Entry
list(): import("../config/settings.ts").Entry[]
set(key: string, value: unknown, scope?: import("../config/settings.ts").Scope): import("../settings.ts").SetResult
models(): string[]
}
/** Open a file in the user's viewer (the show tool): set only where a client over the link said
* it can show files (harness/acp.md, capability `show`). Absent: no display, and show is not offered. */
show?: (req: import("./show.ts").ShowRequest, callId?: string) => Promise<import("./show.ts").ShowReply>
/** The client also shows files that are not text (spec 3.11.0, capability `media`): a picture,
* sound, video, a PDF — handed over by a handle it fetches. Absent: text files only, as before. */
showsMedia?: boolean
/** The client's editor (acp.md *Unsaved text*): the text of a file as the client has it — its
* buffer when open there — and a write through it. `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>
/** What each edit that ran changed, by call id — each file's text before and after — for a
* client that draws its own diffs (acp.md *Edits as diffs*). Absent: nobody wants them, and
* none are kept. */
changed?: Map<string, FileChange[]>
/** A scheduled run's report (harness reports.md): set only in a session a schedule opened for
* its run that notifies at all. `active`: the turn running now is the schedule's (not a person
* writing into the run's session); `file` keeps the report — the last one written is the
* run's — and says how many this run has written. Absent: report_write is not offered. */
report?: { active(): boolean; file(report: { title: string; body: string; summary: string; importance: "normal" | "high" }): number }
/** A LLeMbas terminal's own session (harness acp.md, *A terminal as the client*): the terminal's
* command-line program and the pane the person showed last — undefined until they sent a
* context naming one. Absent: not such a session, and terminal_run and terminal_read are not offered. */
terminal?: {
executable?: string
pane(): { pane: number; cwd?: string } | undefined
/** The pane's status record now (acp.md, *A command typed, and how it ended*). */
status?(): import("../terminal/status.ts").StatusRecord | undefined
/** A command was typed and the pane's text for it answered. */
typed?(command: string): void
/** A command was typed and is being waited for; `done` once the call has its answer. */
pending?(command: string, pane: number, done: boolean): void
/** The terminal's display in manual mode (acp.md, *A command placed at the prompt*): a
* command is placed at the person's prompt, not entered. */
places?(): boolean
/** The terminal's input mark for the pane, where the terminal writes one. */
input?(): import("../terminal/place.ts").InputMark | undefined
/** The command the agent placed that has not been seen run or dismissed. `waiting`: a call
* is waiting for the person now. `set(undefined)`: it is settled. */
placement?: {
get(): import("../terminal/place.ts").Placement | undefined
set(p: import("../terminal/place.ts").Placement | undefined, waiting?: boolean): void
/** Said in the display (the wait was stopped, the line stays). */
say(text: string): void
}
}
/** The scope sent on every call to the server's memory (`_meta.lembas.scope`, harness/acp.md
* *Memory*): the id of a session the client opened; none for a session of this device's own. */
libraryScope?: string
/** The library: notes, and the knowledge bases this project searches (all, when
* `bases` is undefined); `project` is the scope of this project's notes. */
library?: {
lib: import("../library/store.ts").Library
project?: string
bases?: string[]
embedder?: import("../library/store.ts").Embedder
}
}
/** One file an edit changes: its text before (null: the call creates it) and after (null: the
* call deletes it). `path` is absolute. */
export interface FileChange {
path: string
oldText: string | null
newText: string | null
}
/** A call's change, before it is made. */
export interface Preview {
diff: string
files?: FileChange[]
}
export interface SpawnOptions {
signal?: AbortSignal
callId?: string
worktree?: boolean
description?: string
model?: string
background?: boolean
/** Spec 3.2.0: a team member (team.md §4) — run as one, not as a task helper. */
member?: import("../team/team.ts").TeamAgent
}
/** What the task tool gets back from spawn: the job's id and the report when it ends. */
export interface SubagentHandleInfo {
id: string
done: Promise<import("./task.ts").SubagentResult>
/** A team member's engine, for the team's runtime to drive. */
member?: import("../team/runtime.ts").MemberHandle
}
export interface ToolResult {
output: string
/** One-line summary for the UI: `src/app.ts +12 −3`, `exit 0 · 0.4s`. */
title?: string
isError?: boolean
/** UI-only extras (a unified diff, exit code…). Never sent to the model. */
meta?: Record<string, unknown>
/** Images for the model (view_image): sent in a user turn after the tool results. */
images?: import("../provider/types.ts").ImagePart[]
/** What the result is, for its insertion into the conversation (session/results.ts, harness
* context.md): a read's lines and hash, an edit's diff. Absent: an ordinary output. */
context?: import("../session/results.ts").ToolInsert
}
export interface Tool<S extends z.ZodType = z.ZodType> {
name: string
/** The permission key the tool is checked under; several tools can share one (edit, write). */
access: string
/** Runs alone, never alongside other calls of the same step (it waits on the user). */
exclusive?: boolean
/** What the tool needs: a model with vision, plan mode, a project directory, knowledge bases with
* documents, or a display (a client over the link that shows files: the spec's `requires:
* display`). The tool list is the session's (harness context.md §10): one the session could
* never meet leaves the tool out; one that comes and goes (plan mode, a display) keeps it in, and
* a call while it is unmet answers the spec's `unavailable` text. */
requires?: "vision" | "plan" | "project" | "knowledge" | "display" | "team" | "scheduled" | "terminal"
description: string
schema: S
/** The JSON Schema sent to the model, when it does not come from `schema` (MCP tools). */
jsonSchema?: Record<string, unknown>
/** The values of the spec's `{{variables}}` for this tool: its description is filled with them
* already (described), its parameters' descriptions when it is sent (toSpec). */
vars?: Record<string, string>
/** Where the model says what a call is for, shown when the user is asked to allow it: the
* `purpose` argument added to every tool (the default), a field of the tool's own (bash's
* `description`), or false for a tool that never asks. */
purpose?: string | false
/** What a call answers when its arguments do not parse, where the spec has its own words for it
* (team_add's name); undefined: the generic answer. */
invalid?(raw: unknown, ctx: ToolContext): string | undefined
permission(args: z.infer<S>, ctx: ToolContext): PermissionRequest
/** What the call would change, shown when the user is asked: a unified diff, and — for a client
* that draws its own (acp.md *Edits as diffs*) — each file's text before and after. Writes nothing. */
preview?(args: z.infer<S>, ctx: ToolContext): Promise<Preview>
run(args: z.infer<S>, ctx: ToolContext): Promise<ToolResult>
}
export function defineTool<S extends z.ZodType>(t: Tool<S>): Tool<S> {
return t
}
export const PURPOSE = PURPOSE_DEF.name
// The argument's schema is the harness spec's (harness/purpose.json), as LLeMbas sends it too.
const PURPOSE_SPEC = PURPOSE_DEF.schema
/** The argument that carries a call's purpose for this tool, or undefined when it has none. A
* tool (an MCP server's) that already takes an argument named `purpose` keeps it as its own. */
export function purposeKey(t: Tool): string | undefined {
if (t.purpose === false) return undefined
if (typeof t.purpose === "string") return t.purpose
const props = t.jsonSchema?.properties as Record<string, unknown> | undefined
return props && PURPOSE in props ? undefined : PURPOSE
}
/** Take the injected `purpose` out of a call's arguments: the tool itself never sees it. */
export function splitPurpose(t: Tool, raw: unknown): { args: unknown; purpose?: string } {
const key = purposeKey(t)
if (!key || !raw || typeof raw !== "object" || Array.isArray(raw)) return { args: raw }
const v = (raw as Record<string, unknown>)[key]
const purpose = typeof v === "string" && v.trim() ? v.trim() : undefined
if (key !== PURPOSE) return { args: raw, purpose }
const { [PURPOSE]: _, ...rest } = raw as Record<string, unknown>
return { args: rest, purpose }
}
export function toSpec(t: Tool): ToolSpec {
let schema: Record<string, unknown>
if (t.jsonSchema) schema = t.jsonSchema
// A built-in tool's parameters are the harness spec's, as LLeMbas sends them too; its zod schema
// validates the call, and tests/harness.test.ts keeps the two the same shape.
else if (TOOL_SPECS[t.name]) schema = t.vars ? fillParameters(TOOL_SPECS[t.name]!.parameters, t.vars) : structuredClone(TOOL_SPECS[t.name]!.parameters)
else {
schema = z.toJSONSchema(t.schema, { target: "draft-7", io: "input" }) as Record<string, unknown>
delete schema.$schema
}
if (purposeKey(t) === PURPOSE) schema = { ...schema, properties: { ...((schema.properties as Record<string, unknown>) ?? {}), [PURPOSE]: PURPOSE_SPEC } }
return { name: t.name, description: t.description, parameters: schema }
}
/** A file's text exactly as it is, byte-order mark included. Bun's `.text()` drops a BOM, so a tool
* that read with it and wrote the result back took the mark off every file it changed. */
export async function readText(abs: string): Promise<string> {
return new TextDecoder("utf-8", { ignoreBOM: true }).decode(await Bun.file(abs).bytes())
}
/** A tool's path argument, absolute. Models send both absolute and relative paths; a relative one
* is read against the project root, wherever the session was started (harness context.md §11). */
export function absPath(p: string, ctx: ToolContext): string {
// A model writes ~/x as a shell would; without this it becomes a directory named "~".
if (p === "~" || p.startsWith("~/")) return resolve(expandHome(p))
if (isAbsolute(p)) return resolve(p)
const rel = resolve(ctx.root, p)
// Small models often drop the leading "/" of an absolute path ("home/me/proj/a.py"). When the
// relative reading does not exist and the absolute one does, inside the project, take that.
if (!existsSync(rel)) {
const abs = resolve("/", p)
if (within(abs, ctx.root) && existsSync(abs)) return abs
}
return rel
}
/** For display and rule matching: relative to the root when inside it. */
export function showPath(abs: string, ctx: ToolContext): string {
return relativeWithin(resolve(abs), resolve(ctx.root)) || abs
}
export class ToolError extends Error {}
/** Cap tool output sent to the model; the head and tail are what matter. */
export function truncate(text: string, max = 30_000): string {
if (text.length <= max) return text
const head = Math.floor(max * 0.7)
const tail = max - head
return `${text.slice(0, head)}\n\n[… ${text.length - max} characters omitted …]\n\n${text.slice(-tail)}`
}