Harness spec 2.0.0: background work is a job — commands and subagents alike, seen and steered
One registry per process, every job owned by a session: bash's background commands (and a command still running at its timeout, which now goes to the background instead of being killed) and subagents started with task background: true. job_list, job_output, job_stop (the former bash_list, bash_output, bash_kill) and the new job_send and report; a finished job wakes the owning session in every front end with its marked note. The TUI counts jobs, lists them (/jobs), opens a command's output, enters a subagent and messages it, moves a command to the background (ctrl+b) and asks before quitting with jobs running. The link gains the jobs capability. Subagents get a session row of their own, the spec's preamble and agent texts, and their errors reach the report. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
75 files changed
+3614
-437
No files matched your search
+66
-7
@@ -25,6 +25,7 @@ import { NOBODY_TO_ASK, type Answer, type QuestionReply, type QuestionRequest }
|
||||
import { nobodyToApprove, type PlanReply, type PlanRequest } from "../tool/plan_submit.ts"
|
||||
import { realPath } from "../permission/evaluate.ts"
|
||||
import type { Plan } from "../plan/plan.ts"
|
||||
import type { JobInfo } from "../jobs/registry.ts"
|
||||
import { PLAN_META } from "../session/engine.ts"
|
||||
import { ToolError } from "../tool/tool.ts"
|
||||
import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts"
|
||||
@@ -40,6 +41,7 @@ import { CWD_META, REMOTE_META, Store } from "../session/store.ts"
|
||||
import type { Message } from "../provider/types.ts"
|
||||
import type { Hub } from "./hub.ts"
|
||||
import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts"
|
||||
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs } from "./jobs.ts"
|
||||
|
||||
export const ACP_VERSION = 1
|
||||
/** The `_lembas/*` extension's version (LLeMbas `api/devices.py:PROTOCOL`). 2: every
|
||||
@@ -154,8 +156,10 @@ export function toolKind(name: string): string {
|
||||
if (["read", "list", "view_image"].includes(name)) return "read"
|
||||
if (["write", "edit", "multiedit", "apply_patch"].includes(name)) return "edit"
|
||||
if (["glob", "grep", "session_search", "knowledge_search", "notes_search"].includes(name)) return "search"
|
||||
if (["bash", "bash_output", "bash_kill"].includes(name)) return "execute"
|
||||
if (["bash", "job_stop"].includes(name)) return "execute"
|
||||
if (["job_output", "job_list"].includes(name)) return "read"
|
||||
if (["web_fetch", "web_search"].includes(name)) return "fetch"
|
||||
// A message between agents (job_send, report) is nothing the kinds name.
|
||||
return "other"
|
||||
}
|
||||
|
||||
@@ -266,6 +270,10 @@ export const CAPABILITIES = [
|
||||
"prototypes",
|
||||
"plan_state",
|
||||
"rewind",
|
||||
// Harness spec 2.0.0: the session's background jobs — the `job` and `job_note` events, the
|
||||
// `_lembas/jobs` and `_lembas/job/*` methods, `jobs` in `status`, `job` on an approval, and a
|
||||
// note's turn marked `machine`.
|
||||
"jobs",
|
||||
] as const
|
||||
export const STOP: Record<string, string> = { stop: "end_turn", steps: "max_turn_requests", budget: "max_tokens", cancelled: "cancelled", error: "end_turn" }
|
||||
|
||||
@@ -291,7 +299,16 @@ export function permissionParams(sessionId: string, req: AskRequest, o: { patien
|
||||
...(offerAlways ? [{ optionId: "session", kind: "allow_always", name: "Always, this session" }] : []),
|
||||
{ optionId: "deny", kind: "reject_once", name: "Deny" },
|
||||
],
|
||||
_meta: { lembas: { reason: req.decision.reason, purpose: req.purpose, always: req.decision.always ?? req.request.always, ...(o.patient ? { patient: true } : {}) } },
|
||||
_meta: {
|
||||
lembas: {
|
||||
reason: req.decision.reason,
|
||||
purpose: req.purpose,
|
||||
always: req.decision.always ?? req.request.always,
|
||||
...(o.patient ? { patient: true } : {}),
|
||||
// Which subagent asks (capability jobs), so the card can say — it may ask while the session itself is idle.
|
||||
...(req.source ? { job: { id: req.source.jobId, agent: req.source.agent, description: req.source.description } } : {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,6 +459,11 @@ export class AcpAgent {
|
||||
peer.handle("_lembas/terminal/open", (p) => this.terminalOpen(p))
|
||||
peer.handle("_lembas/files/search", (p) => this.filesSearch(p))
|
||||
peer.handle("_lembas/commands", (p) => this.commands(p))
|
||||
peer.handle("_lembas/jobs", (p) => this.jobs(p))
|
||||
peer.handle("_lembas/job/output", (p) => this.job("output", p))
|
||||
peer.handle("_lembas/job/stop", (p) => this.job("stop", p))
|
||||
peer.handle("_lembas/job/send", (p) => this.job("send", p))
|
||||
peer.handle("_lembas/job/transcript", (p) => this.job("transcript", p))
|
||||
peer.on("_lembas/terminal/input", (p) => this.terminalInput(p))
|
||||
peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p))
|
||||
peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? "")))
|
||||
@@ -963,9 +985,9 @@ export class AcpAgent {
|
||||
if (t) {
|
||||
// The terminal knows its turns; what the hub saw of them, when it cannot be asked.
|
||||
const turns = await t.client
|
||||
.request<{ turnId?: string; queued?: string[]; lastTurnId?: string; plan?: Plan | null }>("hub/status", { sessionId: t.sessionId }, 3000)
|
||||
.catch(() => ({ ...(t.turnId ? { turnId: t.turnId } : {}), queued: [], ...(t.lastTurnId ? { lastTurnId: t.lastTurnId } : {}), plan: this.storedPlan(id) }))
|
||||
return { sessionId: id, exists: true, held: "terminal", busy: t.busy, title: t.title, ...turns, queued: turns.queued ?? [], plan: turns.plan ?? null }
|
||||
.request<{ turnId?: string; queued?: string[]; lastTurnId?: string; plan?: Plan | null; jobs?: JobInfo[] }>("hub/status", { sessionId: t.sessionId }, 3000)
|
||||
.catch(() => ({ ...(t.turnId ? { turnId: t.turnId } : {}), queued: [], ...(t.lastTurnId ? { lastTurnId: t.lastTurnId } : {}), plan: this.storedPlan(id), jobs: this.storedJobsOf(id) }))
|
||||
return { sessionId: id, exists: true, held: "terminal", busy: t.busy, title: t.title, ...turns, queued: turns.queued ?? [], plan: turns.plan ?? null, jobs: turns.jobs ?? [] }
|
||||
}
|
||||
const s = this.sessions.get(id)
|
||||
if (s)
|
||||
@@ -979,11 +1001,46 @@ export class AcpAgent {
|
||||
queued: s.turns.queued(),
|
||||
...(s.turns.last ? { lastTurnId: s.turns.last } : {}),
|
||||
plan: s.app.engine.plan ?? null,
|
||||
jobs: jobList(s.app),
|
||||
}
|
||||
const row = (this.store ??= new Store()).session(id)
|
||||
// Not open: the last turn it finished, as kept across a restart, and its plan as stored.
|
||||
// Not open: the last turn it finished, as kept across a restart, its plan and its jobs as stored.
|
||||
const last = row ? turnStore(id).load().at(-1)?.[0] : undefined
|
||||
return { sessionId: id, exists: Boolean(row), held: "none", busy: false, title: row?.title ?? "", queued: [], ...(last ? { lastTurnId: last } : {}), plan: row ? this.storedPlan(id) : null }
|
||||
return { sessionId: id, exists: Boolean(row), held: "none", busy: false, title: row?.title ?? "", queued: [], ...(last ? { lastTurnId: last } : {}), plan: row ? this.storedPlan(id) : null, jobs: row ? this.storedJobsOf(id) : [] }
|
||||
}
|
||||
|
||||
/** A stored session's jobs (capability `jobs`), or none. */
|
||||
private storedJobsOf(id: string): JobInfo[] {
|
||||
try {
|
||||
return storedJobs((this.store ??= new Store()), id)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** `_lembas/jobs`: the session's background jobs, running first — the terminal's through the
|
||||
* hub when a terminal has it, as `status` goes. */
|
||||
private async jobs(p: any) {
|
||||
const t = this.terminalFor(p)
|
||||
if (t) return t.client.request("hub/job", { sessionId: t.sessionId, op: "list" }, 15_000)
|
||||
return { jobs: jobList(this.get(p).app) }
|
||||
}
|
||||
|
||||
/** `_lembas/job/output`, `/stop`, `/send`, `/transcript` (acp/jobs.ts): one job of the session. */
|
||||
private async job(op: "output" | "stop" | "send" | "transcript", p: any) {
|
||||
const t = this.terminalFor(p)
|
||||
if (t) return t.client.request("hub/job", { sessionId: t.sessionId, op, id: p?.id, since: p?.since, text: p?.text }, 15_000)
|
||||
const app = this.get(p).app
|
||||
switch (op) {
|
||||
case "output":
|
||||
return jobOutput(app, p?.id, p?.since)
|
||||
case "stop":
|
||||
return jobStop(app, p?.id)
|
||||
case "send":
|
||||
return jobSend(app, p?.id, p?.text)
|
||||
case "transcript":
|
||||
return jobTranscript(app, p?.id)
|
||||
}
|
||||
}
|
||||
|
||||
/** A stored session's plan (the engine keeps it under PLAN_META), or null. */
|
||||
@@ -1028,6 +1085,8 @@ export class AcpAgent {
|
||||
const s = this.sessions.get(id)
|
||||
if (s) {
|
||||
s.app.cancel()
|
||||
// Its jobs go with it: nothing is left running for a session that no longer exists.
|
||||
s.app.registry.stopAll(id)
|
||||
await s.queue?.catch(() => {})
|
||||
this.sessions.delete(id)
|
||||
await s.app.close().catch(() => {})
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// The `jobs` capability of the `_lembas/*` extension (harness/acp.md): a session's background jobs
|
||||
// shown and controlled from a client. The same answers whichever process holds the session — the
|
||||
// agent (acp/agent.ts) for one it runs or opens from the store, the terminal through the hub
|
||||
// (acp/share.ts `hub/job`) for one it has open — so both call here.
|
||||
import type { App } from "../app.ts"
|
||||
import { jobRegistry, type Job, type JobInfo } from "../jobs/registry.ts"
|
||||
import type { Store } from "../session/store.ts"
|
||||
import { historyTurns } from "./agent.ts"
|
||||
import { INVALID_PARAMS, RpcError } from "./rpc.ts"
|
||||
|
||||
/** How long `job/stop` waits for the stop to take before answering with the state as it is. */
|
||||
const STOP_WAIT_MS = 2500
|
||||
|
||||
/** `_lembas/jobs`: the session's jobs, running first (the registry's order). */
|
||||
export function jobList(app: App): JobInfo[] {
|
||||
return app.jobs().map((j) => app.registry.info(j))
|
||||
}
|
||||
|
||||
function find(app: App, id: unknown): Job {
|
||||
const job = typeof id === "string" ? app.registry.get(app.jobsSessionId(), id) : undefined
|
||||
if (!job) throw new RpcError(INVALID_PARAMS, `no job ${String(id ?? "")} in this session`)
|
||||
return job
|
||||
}
|
||||
|
||||
/** `_lembas/job/output`: the output from `since` (a command's output, a subagent's transcript
|
||||
* lines), how much there is now, and the state. The model's own read mark is not moved. */
|
||||
export function jobOutput(app: App, id: unknown, since: unknown): { text: string; length: number; state: string } {
|
||||
const job = find(app, id)
|
||||
const from = typeof since === "number" && Number.isFinite(since) ? Math.max(0, Math.floor(since)) : 0
|
||||
return { text: job.output.slice(from), length: job.output.length, state: job.state }
|
||||
}
|
||||
|
||||
/** `_lembas/job/stop`: stop it (TERM then KILL for a command, cancel for a subagent), and answer
|
||||
* once the stop has taken — or, after a moment, with the state as it is. The end note wakes the
|
||||
* owner as any end does. */
|
||||
export async function jobStop(app: App, id: unknown): Promise<{ state: string }> {
|
||||
const job = find(app, id)
|
||||
if (job.state !== "running") return { state: job.state }
|
||||
app.registry.stop(job)
|
||||
const until = Date.now() + STOP_WAIT_MS
|
||||
while (Date.now() < until && job.state === "running") await Bun.sleep(25)
|
||||
return { state: job.state }
|
||||
}
|
||||
|
||||
/** `_lembas/job/send`: a message to a subagent — its inbox while it runs, a new prompt under the
|
||||
* same id once it has finished (a new `job` start event follows). */
|
||||
export function jobSend(app: App, id: unknown, text: unknown): { state: string } {
|
||||
const job = find(app, id)
|
||||
if (job.kind !== "subagent") throw new RpcError(INVALID_PARAMS, `${job.id} is a command; only a subagent takes a message`)
|
||||
const t = typeof text === "string" ? text.trim() : ""
|
||||
if (!t) throw new RpcError(INVALID_PARAMS, "nothing to send")
|
||||
if (!job.subagent) throw new RpcError(INVALID_PARAMS, `${job.id} cannot be messaged any more — an earlier process ran it`)
|
||||
if (job.state === "running") job.subagent.send(t)
|
||||
else {
|
||||
app.registry.restartSubagent(job)
|
||||
void job.subagent.restart(t)
|
||||
}
|
||||
return { state: job.state }
|
||||
}
|
||||
|
||||
/** `_lembas/job/transcript`: a subagent's own conversation as `session/history` turns. */
|
||||
export function jobTranscript(app: App, id: unknown): { id: string; turns: ReturnType<typeof historyTurns> } {
|
||||
const job = find(app, id)
|
||||
if (job.kind !== "subagent") throw new RpcError(INVALID_PARAMS, `${job.id} is a command; its output is job/output`)
|
||||
const messages = job.subagent?.engine.messages ?? (job.childSessionId && app.store ? app.store.messages(job.childSessionId) : [])
|
||||
return { id: job.id, turns: historyTurns(messages, app.engine.o.toolCtx.cwd) }
|
||||
}
|
||||
|
||||
/** The jobs of a session nobody has open, as the store keeps them (for `status` of a session
|
||||
* `held: "none"`): one that was running when its process died reads `lost`. Running first. */
|
||||
export function storedJobs(store: Store, sessionId: string): JobInfo[] {
|
||||
const list: JobInfo[] = []
|
||||
for (const row of store.jobs(sessionId)) {
|
||||
try {
|
||||
const job = JSON.parse(row.json) as Job
|
||||
if (job.state === "running") job.state = "lost"
|
||||
list.push(jobRegistry().info(job))
|
||||
} catch {}
|
||||
}
|
||||
return [...list.filter((j) => j.state === "running"), ...list.filter((j) => j.state !== "running")]
|
||||
}
|
||||
+21
-1
@@ -15,6 +15,7 @@ import { commandSet, sourcesOf } from "../session/commands.ts"
|
||||
import type { PlanReply, PlanRequest } from "../tool/plan_submit.ts"
|
||||
import type { QuestionReply, QuestionRequest } from "../tool/ask_user.ts"
|
||||
import { clampMode, effortOf, markRemote, permissionParams, planParams, planReplyFrom, questionParams, questionReplyFrom, replyFrom, STOP, type PromptResult } from "./agent.ts"
|
||||
import { jobList, jobOutput, jobSend, jobStop, jobTranscript } from "./jobs.ts"
|
||||
import type { SessionContext } from "../app.ts"
|
||||
import { sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts"
|
||||
import { dropAttachments, preparePrompt } from "./prompt.ts"
|
||||
@@ -501,7 +502,26 @@ export class Share {
|
||||
// The terminal's turns: `_lembas/session/status` for a shared session asks here.
|
||||
peer.handle("hub/status", (p) => {
|
||||
this.mine(p)
|
||||
return { ...(this.turns.running ? { turnId: this.turns.running } : {}), queued: this.turns.queued(), ...(this.turns.last ? { lastTurnId: this.turns.last } : {}), plan: this.app.engine.plan ?? null }
|
||||
return { ...(this.turns.running ? { turnId: this.turns.running } : {}), queued: this.turns.queued(), ...(this.turns.last ? { lastTurnId: this.turns.last } : {}), plan: this.app.engine.plan ?? null, jobs: jobList(this.app) }
|
||||
})
|
||||
// The session's jobs (capability `jobs`): `_lembas/jobs` and `_lembas/job/*` for a session
|
||||
// this terminal has open are answered here, by the same code the agent uses for its own.
|
||||
peer.handle("hub/job", async (p) => {
|
||||
this.mine(p)
|
||||
switch (p?.op) {
|
||||
case "list":
|
||||
return { jobs: jobList(this.app) }
|
||||
case "output":
|
||||
return jobOutput(this.app, p?.id, p?.since)
|
||||
case "stop":
|
||||
return jobStop(this.app, p?.id)
|
||||
case "send":
|
||||
return jobSend(this.app, p?.id, p?.text)
|
||||
case "transcript":
|
||||
return jobTranscript(this.app, p?.id)
|
||||
default:
|
||||
throw new RpcError(INVALID_PARAMS, `no such job operation: ${String(p?.op ?? "")}`)
|
||||
}
|
||||
})
|
||||
// The web UI is editing or regenerating from a turn: that turn and the later ones go, as /undo
|
||||
// drops one — the files stay.
|
||||
|
||||
+135
-47
@@ -2,8 +2,10 @@
|
||||
// an Engine. The TUI and `run` both start here.
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs"
|
||||
import { join, relative } from "node:path"
|
||||
import { capacityRefusal } from "./session/capacity.ts"
|
||||
import { fillDescription, TOOL_SPECS } from "./harness.ts"
|
||||
import { capacityRefusal, capacityBeside } from "./session/capacity.ts"
|
||||
import { jobRegistry, type Job, type JobRegistry, type SubagentHandle } from "./jobs/registry.ts"
|
||||
import { MARKS, shownLine } from "./jobs/note.ts"
|
||||
import { fillDescription, LOOP, TOOL_SPECS } from "./harness.ts"
|
||||
import { duration } from "./duration.ts"
|
||||
import { createWorktree, finishWorktree, type Worktree } from "./git/worktree.ts"
|
||||
import { boardSummary } from "./project/board.ts"
|
||||
@@ -20,9 +22,10 @@ import { assembleSystem, instructionFiles, knowledgeScope } from "./prompt/assem
|
||||
import { describeRepo, repoState } from "./git/repo.ts"
|
||||
import { findProject, persistProjectRule, trustOf, type Project } from "./project/root.ts"
|
||||
import type { Message } from "./provider/types.ts"
|
||||
import { Engine, type EngineOptions } from "./session/engine.ts"
|
||||
import { Engine } from "./session/engine.ts"
|
||||
import { agents, NOT_FOR_SUBAGENTS } from "./project/agents.ts"
|
||||
import { ToolError, type Tool } from "./tool/tool.ts"
|
||||
import { ToolError, type SpawnOptions, type SubagentHandleInfo, type Tool } from "./tool/tool.ts"
|
||||
import type { SubagentResult } from "./tool/task.ts"
|
||||
import type { Client, ResolvedModel } from "./provider/types.ts"
|
||||
import { modelTitle, firstReply, promptTitle } from "./session/title.ts"
|
||||
import { Turns } from "./session/turns.ts"
|
||||
@@ -135,6 +138,16 @@ export interface App {
|
||||
embedder?: Embedder
|
||||
/** Stop whatever runs: the model's reply. */
|
||||
cancel(): void
|
||||
/** The process's job registry (jobs/registry.ts); this app is attached to it for its session. */
|
||||
registry: JobRegistry
|
||||
/** The id the registry knows the open session by (the store's, or a stand-in without a store). */
|
||||
jobsSessionId(): string
|
||||
/** The open session's jobs, running first. */
|
||||
jobs(): Job[]
|
||||
/** A note for the open session (a job's end, a subagent's message), beginning with its mark: to
|
||||
* the model's next step while a turn runs, else a turn of its own marked `machine`. `shown`:
|
||||
* the line a transcript shows for it. */
|
||||
wake(text: string, shown: string): void
|
||||
/** What the client holds for this session (the link): read into every prompt from now on. */
|
||||
context: SessionContext
|
||||
/** Replace it (`{}`: none), naming the instance it came from for the prompt's heading. */
|
||||
@@ -179,6 +192,9 @@ function openInBrowser(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/** Tools the spec offers to subagents only (`offered: subagent`): never a session's own model's. */
|
||||
export const SUBAGENT_ONLY = new Set(Object.values(TOOL_SPECS).filter((t) => t.offered === "subagent").map((t) => t.name))
|
||||
|
||||
const MODE_RANK: Record<Mode, number> = { auto: 0, edit: 1, manual: 2, plan: 3 }
|
||||
export function stricterMode(a: Mode | undefined, b: Mode): Mode {
|
||||
return a !== undefined && MODE_RANK[a] > MODE_RANK[b] ? a : b
|
||||
@@ -315,7 +331,7 @@ export function createApp(o: AppOptions): App {
|
||||
const prototypesBlock = () => (context.prototypes?.offered || (!context.prototypes && loaded.config.prototypes === true) ? { sources: context.prototypes?.sources ?? "" } : undefined)
|
||||
/** The three personal keys this session uses: the client's for it, else the config's. */
|
||||
const personal = () => (context.personalization ? personalConfig({ enabled: true, available: true, ...context.personalization }) : loaded.config)
|
||||
const system = (m: Mode, current: ResolvedModel, subagent?: { name: string; instructions: string }, at?: { cwd: string; root: string }, plan?: Plan) =>
|
||||
const system = (m: Mode, current: ResolvedModel, subagent?: { name: string; instructions: string; report: boolean; skills: boolean }, at?: { cwd: string; root: string }, plan?: Plan) =>
|
||||
assembleSystem({
|
||||
modelRef: current.ref,
|
||||
family: familyOf(current),
|
||||
@@ -333,7 +349,8 @@ export function createApp(o: AppOptions): App {
|
||||
files: at ? undefined : frozen.files,
|
||||
subagent,
|
||||
memory: frozen.memory,
|
||||
skills: frozen.skills,
|
||||
// The skills block tells of skill_view; a subagent without the tool gets no block.
|
||||
skills: subagent && !subagent.skills ? undefined : frozen.skills,
|
||||
manageSkills: true,
|
||||
// Read on every prompt: /personality and /settings change it without a restart.
|
||||
...personalityOf(personal()),
|
||||
@@ -357,9 +374,9 @@ export function createApp(o: AppOptions): App {
|
||||
// Subagents (the task tool): a child engine with its own bus and read-tracker, the agent's
|
||||
// tools and mode, the same asker (permission prompts still reach the user), no task tool of its
|
||||
// own. Only its final reply goes back; its tool lines are shown under the task line.
|
||||
const agentList = agents(trusted ? project.dir : undefined)
|
||||
const agentList = agents(trusted ? project.dir : undefined, loaded.warnings)
|
||||
const offered = BUILTIN_TOOLS.filter(
|
||||
(t) => (memoryOn || t.name !== "memory") && (settingsTool !== "off" || t.name !== "settings") && !(lembasLibrary && LOCAL_LIBRARY.has(t.name)),
|
||||
(t) => (memoryOn || t.name !== "memory") && (settingsTool !== "off" || t.name !== "settings") && !(lembasLibrary && LOCAL_LIBRARY.has(t.name)) && !SUBAGENT_ONLY.has(t.name),
|
||||
)
|
||||
// The spec's descriptions carry the facts LLeMbas CLI fills in itself (harness/README.md).
|
||||
const inWords = (sec: number) => (sec % 60 === 0 ? `${sec / 60} minute${sec === 60 ? "" : "s"}` : `${sec} seconds`)
|
||||
@@ -368,7 +385,7 @@ export function createApp(o: AppOptions): App {
|
||||
bash: {
|
||||
timeout: inWords(loaded.config.limits?.bash_timeout ?? 120),
|
||||
timeout_max: inWords(600),
|
||||
background: " For a server, a watcher or anything long, set `background: true`: it returns at once with a job id; read its output with bash_output, list jobs with bash_list, stop one with bash_kill.",
|
||||
background: " For a server, a watcher or anything long, set `background: true`: it returns at once with a job id. Read a job's output with job_output, list jobs with job_list, stop one with job_stop; you are told when one ends.",
|
||||
},
|
||||
}
|
||||
// A tool whose values are its own (the library's, set where it is defined) is filled already;
|
||||
@@ -379,13 +396,41 @@ export function createApp(o: AppOptions): App {
|
||||
const v = vars[t.name] ?? {}
|
||||
return { ...t, description: fillDescription(t.description, v), vars: { ...t.vars, ...v } }
|
||||
})
|
||||
const spawn: NonNullable<EngineOptions["spawn"]> = async (name, prompt, signal, callId, opts = {}) => {
|
||||
// Background jobs: one registry for the process, this app attached for whichever session it
|
||||
// holds. Without a store a session has no id of its own; the jobs get a stand-in.
|
||||
const registry = jobRegistry()
|
||||
let standIn = `local_${crypto.randomUUID().slice(0, 8)}`
|
||||
const jobsSessionId = () => engine.sessionId ?? standIn
|
||||
const wake = (text: string, shown: string) => {
|
||||
if (turns.current || engine.busy) return engine.note(text)
|
||||
void turns.prompt(text, [], shown, { machine: true }).catch((e) => bus.emit({ type: "notice", level: "warn", message: `a job's note could not start a turn: ${(e as Error).message}` }))
|
||||
}
|
||||
const detach = registry.attach({ sessionId: jobsSessionId, bus, wake, store, runningMax: () => loaded.config.limits?.jobs ?? registry.limits.runningMax })
|
||||
const childDetach: (() => void)[] = []
|
||||
// A note the turn ended before delivering (stopped, or a budget): a turn of its own now, or —
|
||||
// after Esc — with the next message, so it starts no work nobody asked for.
|
||||
bus.on((e) => {
|
||||
if (e.type !== "done") return
|
||||
const left = engine.takeNotes()
|
||||
if (!left.length) return
|
||||
if (e.reason === "cancelled") return void engine.pendingContext.push(...left)
|
||||
setTimeout(() => {
|
||||
for (const n of left) wake(n, shownLine(n))
|
||||
}, 0)
|
||||
})
|
||||
|
||||
// Subagents (the task tool): a child engine with its own bus, session row and read-tracker, the
|
||||
// agent's tools and mode, the same asker (permission prompts still reach the user, saying which
|
||||
// subagent asked), no task tool of its own. Every one runs as a job of the session: a synchronous
|
||||
// one's report goes back as the call's result, a background one's as a note when it ends.
|
||||
const spawn = async (name: string, prompt: string, opts: SpawnOptions): Promise<SubagentHandleInfo> => {
|
||||
const spec = agentList.find((a) => a.name === name)
|
||||
if (!spec) throw new ToolError(`There is no agent "${name}". The agents are: ${agentList.map((a) => a.name).join(", ")}.`)
|
||||
// The model asked for (task's `model`), else the agent's own, else the session's — and whether
|
||||
// its server can take it beside the session's (src/session/capacity.ts), before anything is made.
|
||||
// its server can take it beside the session's and beside every subagent already running
|
||||
// (src/session/capacity.ts), before anything is made.
|
||||
const m = opts.model ? resolveModel(loaded, opts.model) : spec.model ? resolveModel(loaded, spec.model) : engine.model
|
||||
const refused = capacityRefusal(engine.model, m)
|
||||
const refused = capacityRefusal(engine.model, m) || registry.running(jobsSessionId()).filter((j) => j.kind === "subagent" && j.subagent).map((j) => capacityBeside(j.subagent!.engine.model, m)).find(Boolean)
|
||||
if (refused) throw new ToolError(`${refused} Do this part yourself, or hand it to a model on another connection.`)
|
||||
// A checkout and branch of its own, when asked for (the task's worktree, the agent's isolation).
|
||||
let wt: Worktree | undefined
|
||||
@@ -401,46 +446,58 @@ export function createApp(o: AppOptions): App {
|
||||
// A directory not committed yet is not in the checkout; make it, so the tools have somewhere to be.
|
||||
if (at) for (const d of [at.root, at.cwd]) mkdirSync(d, { recursive: true })
|
||||
// Isolation is the point: the main checkout is refused to it outright, in every mode —
|
||||
// its prompt may well name files there by their absolute paths.
|
||||
// its prompt may well name files there by their absolute paths. Its project directory and plan
|
||||
// directory are the checkout's, so the edit-mode guard and plan mode judge the right place.
|
||||
const childProjectDir = at ? join(at.root, relative(project.root, project.dir)) : project.dir
|
||||
const childPerm = at
|
||||
? {
|
||||
...perm,
|
||||
root: at.root,
|
||||
projectDir: childProjectDir,
|
||||
planDir: join(childProjectDir, "plans"),
|
||||
rules: [...perm.rules, { permission: "external_directory", pattern: project.gitRoot!, action: "deny" as const }, { permission: "external_directory", pattern: `${project.gitRoot!}/*`, action: "deny" as const }],
|
||||
}
|
||||
: perm
|
||||
const childTools = tools.filter((t) => !NOT_FOR_SUBAGENTS.has(t.name) && (!spec.tools || spec.tools.includes(t.name)))
|
||||
// `report` is every subagent's: its way of speaking to the main agent before its final reply.
|
||||
const childTools = [...tools.filter((t) => !NOT_FOR_SUBAGENTS.has(t.name) && (!spec.tools || spec.tools.includes(t.name))), ...BUILTIN_TOOLS.filter((t) => SUBAGENT_ONLY.has(t.name))]
|
||||
const description = opts.description ?? prompt.split("\n")[0]!.slice(0, 60)
|
||||
const ownerSession = jobsSessionId()
|
||||
const childRow = store?.createSession(at?.root ?? project.root, m.ref, engine.sessionId)
|
||||
if (childRow) store!.setTitle(childRow.id, `${spec.name}: ${description}`)
|
||||
const childSessionId = childRow?.id ?? `${ownerSession}/${crypto.randomUUID().slice(0, 8)}`
|
||||
const childBus = new Bus()
|
||||
let steps = 0
|
||||
let calls = 0
|
||||
childBus.on((e) => {
|
||||
if (e.type === "step") steps++
|
||||
// What a subagent writes counts toward the task's tokens.
|
||||
if (e.type === "usage") bus.emit({ type: "usage", usage: e.usage, child: true })
|
||||
if ((e.type === "tool_end" || e.type === "tool_denied") && callId) {
|
||||
calls++
|
||||
bus.emit({
|
||||
type: "sub_tool",
|
||||
callId,
|
||||
name: e.name,
|
||||
title: e.type === "tool_end" ? (e.result.title ?? e.name) : `denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`,
|
||||
isError: e.type === "tool_denied" || e.result.isError,
|
||||
})
|
||||
}
|
||||
let job: Job
|
||||
// The asker is the session's; a child's ask says which subagent it comes from.
|
||||
const askerFor = (): Asker => ({
|
||||
ask: (req) => o.asker.ask({ ...req, source: { jobId: job.id, agent: spec.name, description } }),
|
||||
get question() {
|
||||
return o.asker.question
|
||||
},
|
||||
get plan() {
|
||||
return o.asker.plan
|
||||
},
|
||||
})
|
||||
const child = new Engine({
|
||||
bus: childBus,
|
||||
asker: o.asker,
|
||||
asker: askerFor(),
|
||||
client: m.ref === engine.model.ref ? engine.client : clientFor(m),
|
||||
model: m,
|
||||
tools: childTools,
|
||||
store,
|
||||
sessionId: childRow?.id,
|
||||
// An agent's own mode can make it stricter than its parent, never looser.
|
||||
mode: stricterMode(spec.mode, engine.mode),
|
||||
effort: m.ref === engine.model.ref ? engine.effort : startEffort(m),
|
||||
maxSteps: 50,
|
||||
maxSteps: loaded.config.limits?.subagent_steps ?? LOOP.jobs.subagent_steps.default,
|
||||
compaction,
|
||||
perm: childPerm,
|
||||
toolCtx: at ? { ...baseToolCtx(), root: at.root, cwd: at.cwd, projectDir: undefined } : baseToolCtx(),
|
||||
toolCtx: {
|
||||
...baseToolCtx(),
|
||||
...(at ? { root: at.root, cwd: at.cwd, projectDir: undefined } : {}),
|
||||
jobs: { registry, owner: () => ({ sessionId: childSessionId, job }) },
|
||||
},
|
||||
fallback: engine.o.fallback,
|
||||
steerMark: MARKS.to_subagent,
|
||||
system: (mode, current, plan) =>
|
||||
system(
|
||||
mode,
|
||||
@@ -450,26 +507,45 @@ export function createApp(o: AppOptions): App {
|
||||
instructions: wt
|
||||
? `${spec.instructions}\n\nYou are working in a separate checkout of the repository, at ${at!.root}, on the branch ${wt.branch} (made from the last commit — uncommitted work of the main agent is not here). Work only inside it. When you finish, your changes are committed on that branch for the main agent to merge: do not commit, merge or push yourself.`
|
||||
: spec.instructions,
|
||||
report: childTools.some((t) => t.name === "report"),
|
||||
skills: childTools.some((t) => t.name === "skill_view"),
|
||||
},
|
||||
at,
|
||||
plan,
|
||||
),
|
||||
})
|
||||
const onAbort = () => child.cancel()
|
||||
signal.addEventListener("abort", onAbort, { once: true })
|
||||
try {
|
||||
const reason = await child.prompt(prompt)
|
||||
// Its own background commands wake it at its next step while it runs; once it has ended they
|
||||
// are stopped with it, so nothing is left to wake.
|
||||
childDetach.push(registry.attach({ sessionId: () => childSessionId, bus: childBus, wake: (text) => void (child.busy && child.note(text)), store }))
|
||||
const finish = async (reason: string): Promise<SubagentResult> => {
|
||||
const last = [...child.messages].reverse().find((x) => x.role === "assistant")
|
||||
let text = last && last.role === "assistant" ? last.parts.map((p) => (p.type === "text" ? p.text : "")).join("") : ""
|
||||
if (wt) text += `\n\n[worktree] ${finishWorktree(project.gitRoot!, wt, `${spec.name}: ${opts.description ?? prompt.split("\n")[0]!.slice(0, 60)}`).summary}`
|
||||
const text = last && last.role === "assistant" ? last.parts.map((p) => (p.type === "text" ? p.text : "")).join("") : ""
|
||||
// Cancelled or failed too: what it did is kept the same way, and the branch named.
|
||||
const worktree = wt ? finishWorktree(project.gitRoot!, wt, `${spec.name}: ${description}${reason === "stop" ? "" : " (stopped)"}`).summary : undefined
|
||||
wt = undefined
|
||||
return { text, steps, tools: calls, reason }
|
||||
} finally {
|
||||
signal.removeEventListener("abort", onAbort)
|
||||
// Cancelled or failed: keep what it did, the same way.
|
||||
if (wt) finishWorktree(project.gitRoot!, wt, `${spec.name}: ${opts.description ?? "unfinished"} (stopped)`)
|
||||
const error = reason === "error" ? job.lastError : undefined
|
||||
const end = registry.finishSubagent(job, { reason, report: text, ...(error ? { error } : {}), ...(worktree ? { worktree } : {}) })
|
||||
return { text: worktree ? `${text}\n\n[worktree] ${worktree}` : text, steps: job.steps ?? 0, tools: job.tools ?? 0, reason, ...(error ? { error } : {}), ...(end.stopped ? { stopped: end.stopped } : {}) }
|
||||
}
|
||||
const run = (text: string) => child.prompt(text).then(finish, (e) => (job.lastError = (e as Error).message, finish("error")))
|
||||
const handle: SubagentHandle = {
|
||||
bus: childBus,
|
||||
engine: child,
|
||||
send: (text) => child.enqueue(text),
|
||||
restart: (text) => run(text).then(() => undefined),
|
||||
cancel: () => child.cancel(),
|
||||
}
|
||||
job = registry.startSubagent({ sessionId: ownerSession, ownerCallId: opts.callId, ownerJobId: baseOwner().job?.id, agent: spec.name, model: m.ref, description, handle, childSessionId, silent: !opts.background })
|
||||
// A synchronous subagent goes with its parent's turn (Esc stops both); a background one does not.
|
||||
const onAbort = () => child.cancel()
|
||||
opts.signal?.addEventListener("abort", onAbort, { once: true })
|
||||
const done = run(prompt).finally(() => opts.signal?.removeEventListener("abort", onAbort))
|
||||
// Nobody awaits a background one here; its end is its note.
|
||||
if (opts.background) done.catch(() => {})
|
||||
return { id: job.id, done }
|
||||
}
|
||||
/** Whose jobs the session's own tools see. */
|
||||
const baseOwner = () => ({ sessionId: jobsSessionId(), job: undefined as Job | undefined })
|
||||
|
||||
const engine = new Engine({
|
||||
bus,
|
||||
@@ -485,7 +561,7 @@ export function createApp(o: AppOptions): App {
|
||||
budget: { wall_seconds: loaded.config.limits?.wall_seconds, output_bytes: loaded.config.limits?.output_bytes, completion_tokens: loaded.config.limits?.completion_tokens },
|
||||
compaction,
|
||||
perm,
|
||||
toolCtx: baseToolCtx(),
|
||||
toolCtx: { ...baseToolCtx(), jobs: { registry, owner: baseOwner } },
|
||||
system: (m, current, plan) => system(m, current, undefined, undefined, plan),
|
||||
persistRule: trusted ? (rule) => persistProjectRule(project, rule) : undefined,
|
||||
spawn,
|
||||
@@ -675,13 +751,21 @@ export function createApp(o: AppOptions): App {
|
||||
mcp,
|
||||
mcpReady,
|
||||
small,
|
||||
close: () => mcp.close(),
|
||||
close: () => {
|
||||
detach()
|
||||
for (const d of childDetach.splice(0)) d()
|
||||
return mcp.close()
|
||||
},
|
||||
skills: skillList,
|
||||
library,
|
||||
embedder,
|
||||
cancel() {
|
||||
engine.cancel()
|
||||
},
|
||||
registry,
|
||||
jobsSessionId,
|
||||
jobs: () => registry.list(jobsSessionId()),
|
||||
wake,
|
||||
get context() {
|
||||
return context
|
||||
},
|
||||
@@ -704,6 +788,7 @@ export function createApp(o: AppOptions): App {
|
||||
firstShown = ""
|
||||
const s = store?.createSession(project.root, engine.model.ref)
|
||||
keepCwd(s?.id)
|
||||
standIn = `local_${crypto.randomUUID().slice(0, 8)}`
|
||||
engine.newSession(s?.id)
|
||||
turns.reset()
|
||||
if (s) bus.emit({ type: "session", id: s.id, model: engine.model.ref, mode: engine.mode })
|
||||
@@ -732,7 +817,10 @@ export function createApp(o: AppOptions): App {
|
||||
// makes, left behind by `-c` and /sessions as an empty, untitled row in /sessions and a chat
|
||||
// in the web UI that holds nothing. Only when it is empty: one with a word in it is kept.
|
||||
if (before && before !== id) discardEmpty(before)
|
||||
return store.messages(id)
|
||||
const messages = store.messages(id)
|
||||
// Notes its jobs left while nobody had it open: a turn of their own, now.
|
||||
setTimeout(() => registry.deliverPending(id), 0)
|
||||
return messages
|
||||
},
|
||||
}
|
||||
}
|
||||
+21
-4
@@ -17,7 +17,7 @@ export type Event =
|
||||
* `turnId`: the turn it starts, the web UI's message id or one made here, so a client
|
||||
* matches the turn to its own row by id rather than by timing. `attachments`: what went with it
|
||||
* (pasted images, @files, a web upload), for chips beside the text. */
|
||||
| { type: "prompt"; text: string; turnId?: string; attachments?: AttachmentInfo[] }
|
||||
| { type: "prompt"; text: string; turnId?: string; attachments?: AttachmentInfo[]; /** The harness started the turn, not the person: a job's note (jobs/note.ts), beginning with its mark. */ machine?: true }
|
||||
| { type: "step"; n: number }
|
||||
/** The session was named (or renamed). */
|
||||
| { type: "title"; id: string; title: string }
|
||||
@@ -54,8 +54,14 @@ export type Event =
|
||||
| { type: "plan"; plan: Plan | undefined }
|
||||
/** The conversation was replaced by a summary of it (/compact, or automatically). */
|
||||
| { type: "compacted"; summary: string }
|
||||
/** A subagent's tool call finished (shown under the task line). */
|
||||
| { type: "sub_tool"; callId: string; name: string; title: string; isError?: boolean }
|
||||
/** A subagent's tool call finished (shown under the task line); `jobId`: its job, when it runs as one. */
|
||||
| { type: "sub_tool"; callId: string; jobId?: string; name: string; title: string; isError?: boolean }
|
||||
/** A background job of the session began, has news (new output, a subagent's step — at most four
|
||||
* a second per job), or ended (jobs/registry.ts). */
|
||||
| { type: "job"; state: "start" | "update" | "end"; job: import("../jobs/registry.ts").JobInfo }
|
||||
/** The note about that job was given to the model: inside a turn at its next step, or as the
|
||||
* `machine` turn whose `prompt` follows. */
|
||||
| { type: "job_note"; jobId: string; text: string }
|
||||
/** The permission mode changed from inside a turn (plan approved). */
|
||||
| { type: "mode"; mode: Mode }
|
||||
/** The session's model or effort changed, for whatever reason — /model, /effort, the settings
|
||||
@@ -108,7 +114,18 @@ export type AskReply =
|
||||
/** Whoever answers permission questions: the TUI's dialog, a y/n prompt, or a policy in headless runs. */
|
||||
export interface Asker {
|
||||
/** `preview`: the change the call would make (a unified diff), or why it could not be worked out. */
|
||||
ask(req: { tool: string; args: unknown; request: PermissionRequest; decision: Decision; preview?: { diff?: string; error?: string }; /** What the model says the call is for. */ purpose?: string }): Promise<AskReply>
|
||||
ask(req: {
|
||||
tool: string
|
||||
args: unknown
|
||||
request: PermissionRequest
|
||||
decision: Decision
|
||||
preview?: { diff?: string; error?: string }
|
||||
/** What the model says the call is for. */
|
||||
purpose?: string
|
||||
/** Set when a subagent running as a background job asks, so the card can say which — it may
|
||||
* ask while the session itself is idle. */
|
||||
source?: { jobId: string; agent: string; description: string }
|
||||
}): Promise<AskReply>
|
||||
/** The ask_user tool. Absent: the tool reports that nobody can be asked. `callId`: the tool call's
|
||||
* id, which keys the card on another screen. */
|
||||
question?(req: QuestionRequest, callId?: string): Promise<QuestionReply>
|
||||
|
||||
+7
-2
@@ -8,7 +8,7 @@ import { ConfigError, loadConfig } from "./config/load.ts"
|
||||
import { asMode, EFFORTS, MODES, type Effort, type Mode } from "./config/schema.ts"
|
||||
import { isLocal, localRoot } from "./config/paths.ts"
|
||||
import { SettingError } from "./config/settings.ts"
|
||||
import { renderJson, renderPlain, terminalAsker } from "./headless.ts"
|
||||
import { renderJson, renderPlain, settleJobs, terminalAsker } from "./headless.ts"
|
||||
import { enterLocal, localFor, LocalError, localRefusal, localTmp, LOCAL_FLAGS } from "./project/local.ts"
|
||||
import { findProject, setTrust, trustOf } from "./project/root.ts"
|
||||
import { effortsFor } from "./provider/effort.ts"
|
||||
@@ -86,6 +86,7 @@ Options for run:
|
||||
--json events as JSON lines
|
||||
--reasoning show the model's reasoning
|
||||
--no-store do not record the session
|
||||
--no-wait do not wait for background jobs the prompt started; stop them
|
||||
`
|
||||
|
||||
function fail(msg: string, code = 1): never {
|
||||
@@ -264,6 +265,7 @@ async function main() {
|
||||
json: { type: "boolean" },
|
||||
reasoning: { type: "boolean" },
|
||||
"no-store": { type: "boolean" },
|
||||
"no-wait": { type: "boolean" },
|
||||
},
|
||||
})
|
||||
let prompt = positionals.join(" ").trim()
|
||||
@@ -291,7 +293,10 @@ async function main() {
|
||||
// connect timeout; a failure is a notice, not a stop).
|
||||
await app.mcpReady
|
||||
const atts = attachmentsFor(prompt, app.engine.o.toolCtx, app.engine.model.spec.vision === true)
|
||||
const reason = await app.engine.prompt(prompt, atts.flatMap((a) => (a.image ? [a.text, a.image] : [a.text])))
|
||||
// Through the turns, like every front end: a job's note wakes the session the same way.
|
||||
const reason = await app.turns.prompt(prompt, atts.flatMap((a) => (a.image ? [a.text, a.image] : [a.text])))
|
||||
// Jobs the prompt started: their notes come back as turns of their own, unless told not to wait.
|
||||
await settleJobs(app, !values["no-wait"])
|
||||
// Refused before the prompt was written (capacity, a cancel at once): no empty session is left
|
||||
// to crowd `lembas sessions`. Never shared, so nobody else is told.
|
||||
app.discardIfEmpty()
|
||||
|
||||
@@ -17,7 +17,7 @@ export type Action = (typeof ACTIONS)[number]
|
||||
|
||||
/** Permission keys the harness spec renamed (v1; 1.1.0 folded todo into the plan tools, whose key
|
||||
* is `plan`), read as the new ones in a config's `permission:` and in the spec's own defaults. */
|
||||
export const PERMISSION_ALIASES: Record<string, string> = { question: "ask_user", plan_exit: "plan_submit", websearch: "web_search", webfetch: "web_fetch", todo: "plan" }
|
||||
export const PERMISSION_ALIASES: Record<string, string> = { question: "ask_user", plan_exit: "plan_submit", websearch: "web_search", webfetch: "web_fetch", todo: "plan", bash_output: "job_output", bash_list: "job_list", bash_kill: "job_stop" }
|
||||
|
||||
export function renamePermissionKeys(p: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {}
|
||||
@@ -267,7 +267,9 @@ export const Config = z.strictObject({
|
||||
limits: z
|
||||
.strictObject({
|
||||
steps: z.number().int().positive().optional().describe("Most model steps in one prompt (default 200) — a runaway backstop, not a budget."),
|
||||
bash_timeout: z.number().positive().optional().describe("Seconds a bash command may run (default 120)."),
|
||||
bash_timeout: z.number().positive().optional().describe("Seconds a bash command may run in the foreground before it goes on in the background as a job (default 120)."),
|
||||
jobs: z.number().int().positive().optional().describe("Background commands one session may have running at once (default 8)."),
|
||||
subagent_steps: z.number().int().positive().optional().describe("Most model steps in one subagent run (default 50) — a runaway backstop, not a budget."),
|
||||
wall_seconds: z.number().positive().optional().describe("Budget for one prompt: seconds of work, not counting time spent waiting for you. Past it the model answers from what it has. Unset: none."),
|
||||
output_bytes: z.number().int().positive().optional().describe("Budget for one prompt: bytes of tool output read. Unset: none."),
|
||||
completion_tokens: z.number().int().positive().optional().describe("Budget for one prompt: tokens the model writes. Unset: none."),
|
||||
|
||||
@@ -59,6 +59,8 @@ export const SETTINGS: SettingDef[] = [
|
||||
{ key: "memory.enabled", kind: "boolean", agent: true, scopes: ALL, reload: true, fallback: "true" },
|
||||
{ key: "limits.steps", kind: "number", agent: true, scopes: ALL, fallback: "200" },
|
||||
{ key: "limits.bash_timeout", kind: "number", agent: true, scopes: ALL, fallback: "120" },
|
||||
{ key: "limits.jobs", kind: "number", agent: true, scopes: ALL, fallback: "8" },
|
||||
{ key: "limits.subagent_steps", kind: "number", agent: true, scopes: ALL, fallback: "50" },
|
||||
{ key: "limits.wall_seconds", kind: "number", agent: true, scopes: ALL, fallback: "none" },
|
||||
{ key: "limits.output_bytes", kind: "number", agent: true, scopes: ALL, fallback: "none" },
|
||||
{ key: "limits.completion_tokens", kind: "number", agent: true, scopes: ALL, fallback: "none" },
|
||||
|
||||
+21
-8
@@ -7,13 +7,14 @@ import LOOP_JSON from "../harness/loop.json"
|
||||
import t_apply_patch from "../harness/tools/apply_patch.json"
|
||||
import t_ask_user from "../harness/tools/ask_user.json"
|
||||
import t_bash from "../harness/tools/bash.json"
|
||||
import t_bash_kill from "../harness/tools/bash_kill.json"
|
||||
import t_bash_list from "../harness/tools/bash_list.json"
|
||||
import t_bash_output from "../harness/tools/bash_output.json"
|
||||
import t_decisions from "../harness/tools/decisions.json"
|
||||
import t_edit from "../harness/tools/edit.json"
|
||||
import t_glob from "../harness/tools/glob.json"
|
||||
import t_grep from "../harness/tools/grep.json"
|
||||
import t_job_list from "../harness/tools/job_list.json"
|
||||
import t_job_output from "../harness/tools/job_output.json"
|
||||
import t_job_send from "../harness/tools/job_send.json"
|
||||
import t_job_stop from "../harness/tools/job_stop.json"
|
||||
import t_knowledge_get from "../harness/tools/knowledge_get.json"
|
||||
import t_knowledge_search from "../harness/tools/knowledge_search.json"
|
||||
import t_list from "../harness/tools/list.json"
|
||||
@@ -26,6 +27,7 @@ import t_plan_submit from "../harness/tools/plan_submit.json"
|
||||
import t_plan_update from "../harness/tools/plan_update.json"
|
||||
import t_plan_write from "../harness/tools/plan_write.json"
|
||||
import t_read from "../harness/tools/read.json"
|
||||
import t_report from "../harness/tools/report.json"
|
||||
import t_session_search from "../harness/tools/session_search.json"
|
||||
import t_settings from "../harness/tools/settings.json"
|
||||
import t_skill_manage from "../harness/tools/skill_manage.json"
|
||||
@@ -55,6 +57,8 @@ export interface ToolSpecDef {
|
||||
purpose: string | false
|
||||
/** Names each project used before spec v1; a call under one is read as this tool. */
|
||||
aliases: { cli: string[]; llembas: string[] }
|
||||
/** `subagent`: offered only to a subagent (report), never to a session's own model. */
|
||||
offered?: "subagent"
|
||||
argument_aliases?: Record<string, string>
|
||||
/** `{{name}}` in the description: a fact the projects differ in, filled in by each (fillDescription). */
|
||||
variables?: Record<string, string>
|
||||
@@ -75,6 +79,14 @@ export const LOOP: {
|
||||
wrap_up: { message: string }
|
||||
nudges: { max: number }
|
||||
parallel: { max: number }
|
||||
/** Background work (spec 2.0.0): the marks every note begins with, and the caps. */
|
||||
jobs: {
|
||||
marks: { command: string; subagent: string; message: string; to_subagent: string }
|
||||
note_tail_chars: { default: number }
|
||||
finished_kept: { default: number }
|
||||
running_max: { default: number }
|
||||
subagent_steps: { default: number }
|
||||
}
|
||||
} = LOOP_JSON
|
||||
|
||||
/** The `purpose` argument (harness/purpose.json). */
|
||||
@@ -151,13 +163,14 @@ export function narrowParameters(parameters: Record<string, unknown>, narrow: Na
|
||||
}
|
||||
|
||||
export const TOOL_SPECS: Record<string, ToolSpecDef> = Object.fromEntries(
|
||||
([t_apply_patch, t_ask_user, t_bash, t_bash_kill, t_bash_list, t_bash_output, t_decisions, t_edit, t_glob, t_grep, t_knowledge_get, t_knowledge_search, t_list, t_memory, t_multiedit, t_note_manage, t_note_view, t_notes_search, t_plan_submit, t_plan_update, t_plan_write, t_read, t_session_search, t_settings, t_skill_manage, t_skill_view, t_skills_list, t_task, t_tasks, t_view_image, t_web_fetch, t_web_search, t_write] as ToolSpecDef[]).map((t) => [t.name, t]),
|
||||
([t_apply_patch, t_ask_user, t_bash, t_decisions, t_edit, t_glob, t_grep, t_job_list, t_job_output, t_job_send, t_job_stop, t_knowledge_get, t_knowledge_search, t_list, t_memory, t_multiedit, t_note_manage, t_note_view, t_notes_search, t_plan_submit, t_plan_update, t_plan_write, t_read, t_report, t_session_search, t_settings, t_skill_manage, t_skill_view, t_skills_list, t_task, t_tasks, t_view_image, t_web_fetch, t_web_search, t_write] as ToolSpecDef[]).map((t) => [t.name, t]),
|
||||
)
|
||||
|
||||
/** A tool's name and description as the spec has them, for its definition: `...described("read")`.
|
||||
* With `vars`, the description filled and the values kept for its parameters (toSpec). */
|
||||
export function described(name: string, vars?: Record<string, string>): { name: string; description: string; vars?: Record<string, string> } {
|
||||
/** A tool's name, description and `exclusive` flag as the spec has them, for its definition:
|
||||
* `...described("read")`. With `vars`, the description filled and the values kept for its
|
||||
* parameters (toSpec). */
|
||||
export function described(name: string, vars?: Record<string, string>): { name: string; description: string; exclusive: boolean; vars?: Record<string, string> } {
|
||||
const t = TOOL_SPECS[name]
|
||||
if (!t) throw new Error(`harness: no tool ${name} in the spec`)
|
||||
return vars ? { name: t.name, description: fillDescription(t.description, vars), vars } : { name: t.name, description: t.description }
|
||||
return vars ? { name: t.name, description: fillDescription(t.description, vars), exclusive: t.exclusive, vars } : { name: t.name, description: t.description, exclusive: t.exclusive }
|
||||
}
|
||||
+38
-3
@@ -63,6 +63,14 @@ export function renderPlain(bus: Bus, opts: { color: boolean; showReasoning: boo
|
||||
case "sub_tool":
|
||||
line(` ${c(C.dim, "┊")} ${icon(e.name)} ${c(C.dim, e.name.padEnd(6))} ${e.title}`)
|
||||
break
|
||||
case "prompt":
|
||||
// A turn the harness started: a job's note, shown as such before the reply it brings.
|
||||
if (e.machine) line(c(C.label, e.text))
|
||||
break
|
||||
case "job":
|
||||
if (e.state === "start") line(`${c(C.dim, "┊")} ${c(C.label, e.job.id)} ${e.job.kind} started · ${e.job.description}`)
|
||||
else if (e.state === "end") line(`${c(C.dim, "┊")} ${c(C.label, e.job.id)} ${e.job.state}${e.job.exit !== undefined ? ` (${e.job.exit === null ? "stopped" : `exit ${e.job.exit}`})` : ""} · ${e.job.description}`)
|
||||
break
|
||||
case "tool_denied":
|
||||
line(`${c(C.dim, "┊")} ${theme.icons.denied} ${c(C.warn, e.name.padEnd(6))} ${e.reason.split("\n")[0]!.slice(0, 140)}`)
|
||||
break
|
||||
@@ -88,9 +96,36 @@ export function renderJson(bus: Bus) {
|
||||
bus.on((e) => process.stdout.write(JSON.stringify(e) + "\n"))
|
||||
}
|
||||
|
||||
/** Asks on the terminal when there is one; otherwise follows --yes, or refuses. */
|
||||
/** After the prompt: wait for the jobs it started — their notes start turns of their own, which may
|
||||
* start more — then stop whatever still runs (the spec's lifecycle: nobody is there to ask).
|
||||
* `wait: false` (--no-wait) stops them at once. */
|
||||
export async function settleJobs(app: import("./app.ts").App, wait: boolean): Promise<void> {
|
||||
const sid = app.jobsSessionId()
|
||||
if (wait) while (app.turns.current || app.registry.running(sid).length) await Bun.sleep(200)
|
||||
// Quietly: a note about a job stopped on the way out would only start a turn nobody reads.
|
||||
const left = app.registry.stopAll(sid, true)
|
||||
if (left) await Bun.sleep(100)
|
||||
}
|
||||
|
||||
/** Asks on the terminal when there is one; otherwise follows --yes, or refuses. One question at a
|
||||
* time: parallel subagents can ask at once, and two readlines on one stdin answer each other. */
|
||||
export function terminalAsker(opts: { yes: boolean; unattended?: "recommended" | "first" | "fail"; theme?: string }): Asker {
|
||||
const C = escapes(loadTheme(opts.theme).theme)
|
||||
let queue: Promise<unknown> = Promise.resolve()
|
||||
const serial = <T,>(fn: () => Promise<T>): Promise<T> => {
|
||||
const p = queue.then(fn)
|
||||
queue = p.catch(() => {})
|
||||
return p
|
||||
}
|
||||
const asker = terminalAskerNow(opts, C)
|
||||
return {
|
||||
...(asker.plan ? { plan: (req: PlanRequest, callId?: string) => serial(() => asker.plan!(req, callId)) } : {}),
|
||||
question: (req: QuestionRequest, callId?: string) => serial(() => asker.question!(req, callId)),
|
||||
ask: (req) => serial(() => asker.ask(req)),
|
||||
}
|
||||
}
|
||||
|
||||
function terminalAskerNow(opts: { yes: boolean; unattended?: "recommended" | "first" | "fail" }, C: ReturnType<typeof escapes>): Asker {
|
||||
return {
|
||||
// With nobody at a terminal there is no plan method at all: plan_submit then saves and stops.
|
||||
...(process.stdin.isTTY && !opts.yes
|
||||
@@ -139,14 +174,14 @@ export function terminalAsker(opts: { yes: boolean; unattended?: "recommended" |
|
||||
rl.close()
|
||||
}
|
||||
},
|
||||
async ask({ tool, args, request, decision, preview, purpose }): Promise<AskReply> {
|
||||
async ask({ tool, args, request, decision, preview, purpose, source }): Promise<AskReply> {
|
||||
if (opts.yes) return { kind: "once" }
|
||||
if (!process.stdin.isTTY)
|
||||
return { kind: "deny", final: true, feedback: `nobody is present to approve ${tool} in this headless run.` }
|
||||
const what = request.command ?? request.patterns.join(", ")
|
||||
const rl = createInterface({ input: process.stdin, output: process.stderr })
|
||||
try {
|
||||
process.stderr.write(`\n${C.warn}? ${tool}${C.reset} ${what}\n`)
|
||||
process.stderr.write(`\n${C.warn}? ${source ? `${source.agent} (${source.jobId}): ` : ""}${tool}${C.reset} ${what}\n`)
|
||||
if (purpose) process.stderr.write(` ${C.label}${purpose}${C.reset}\n`)
|
||||
if (preview?.diff)
|
||||
for (const l of preview.diff.split("\n").filter((l) => !/^(Index:|={5,}|--- |\+\+\+ )/.test(l)))
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// What a session is told about its background work (harness spec loop.json `jobs.marks`,
|
||||
// conformance/jobs.json): a finished command, a finished subagent, a message from a subagent, or
|
||||
// one to a subagent. Every note begins with its mark, said rather than hidden — Hermes found that
|
||||
// a model refuses an unmarked mid-turn message as an injection. Pure: the registry composes the
|
||||
// case from a job's record and hands the text on; LLeMbas's services/jobs.py says the same words.
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
|
||||
export const MARKS = LOOP.jobs.marks
|
||||
|
||||
export type NoteCase =
|
||||
| { kind: "command"; id: string; command: string; exit: number | null; seconds: number; unread: string }
|
||||
| {
|
||||
kind: "subagent"
|
||||
id: string
|
||||
agent: string
|
||||
description: string
|
||||
report: string
|
||||
steps: number
|
||||
tools: number
|
||||
reason: string
|
||||
error?: string
|
||||
seconds: number
|
||||
worktree?: string
|
||||
}
|
||||
| { kind: "message"; id: string; agent: string; description: string; text: string }
|
||||
| { kind: "to_subagent"; text: string }
|
||||
|
||||
/** A command's first line, as the notes and lists name it. */
|
||||
export function commandLine(command: string, max = 120): string {
|
||||
return command.split("\n")[0]!.slice(0, max)
|
||||
}
|
||||
|
||||
/** How a finished command ended, in words: the exit code, or the signal that stopped it. */
|
||||
export function exitWords(exit: number | null | undefined): string {
|
||||
return exit === null ? "stopped (SIGTERM)" : `exited with ${exit ?? "?"}`
|
||||
}
|
||||
|
||||
const ENDED: Record<string, string> = {
|
||||
stop: "finished",
|
||||
stopped: "was stopped",
|
||||
steps: "stopped at its step limit",
|
||||
budget: "stopped at its budget",
|
||||
error: "failed",
|
||||
}
|
||||
|
||||
/** The tail line under a subagent's report: steps, tool calls, and how it ended when not of its
|
||||
* own accord. The task tool's result carries the same line. */
|
||||
export function subagentTail(agent: string, steps: number, tools: number, reason: string, error?: string): string {
|
||||
const ended = reason === "stop" ? "" : reason === "error" ? ` · ended: error${error ? ` — ${error}` : ""}` : ` · ended: ${reason}`
|
||||
return `[${agent} subagent · ${steps} step${steps === 1 ? "" : "s"} · ${tools} tool call${tools === 1 ? "" : "s"}${ended}]`
|
||||
}
|
||||
|
||||
export function jobNote(c: NoteCase): { text: string } {
|
||||
switch (c.kind) {
|
||||
case "command": {
|
||||
const how = `${c.id} (${commandLine(c.command)}) ${exitWords(c.exit)} after ${duration(c.seconds * 1000, true)}.`
|
||||
const unread = c.unread.trim() ? `\nOutput you had not read:\n${c.unread.replace(/\n$/, "")}` : " It printed nothing you had not read."
|
||||
return { text: `${MARKS.command}\n${how}${unread}` }
|
||||
}
|
||||
case "subagent": {
|
||||
const head = `${c.id} (${c.agent}: ${c.description}) ${ENDED[c.reason] ?? `ended: ${c.reason}`} after ${duration(c.seconds * 1000, true)}.`
|
||||
const report = c.report.trim() || "(the subagent returned no report)"
|
||||
const tail = subagentTail(c.agent, c.steps, c.tools, c.reason, c.error)
|
||||
return { text: `${MARKS.subagent}\n${head}\n${report}\n\n${tail}${c.worktree ? `\n[worktree] ${c.worktree}` : ""}` }
|
||||
}
|
||||
case "message":
|
||||
return { text: `${MARKS.message}\n${c.id} (${c.agent}: ${c.description}):\n${c.text}` }
|
||||
case "to_subagent":
|
||||
return { text: `${MARKS.to_subagent}\n${c.text}` }
|
||||
}
|
||||
}
|
||||
|
||||
/** A note's mark and what follows it, for a front end that shows the message without the mark;
|
||||
* `mark` undefined when the text begins with none. */
|
||||
export function stripMark(text: string): { mark?: string; body: string } {
|
||||
for (const mark of Object.values(MARKS)) if (text.startsWith(mark)) return { mark, body: text.slice(mark.length).replace(/^\n/, "") }
|
||||
return { body: text }
|
||||
}
|
||||
|
||||
/** How a machine turn is shown in a transcript: `⏎` and the note's first line after its mark. */
|
||||
export function shownLine(text: string): string {
|
||||
const { body } = stripMark(text)
|
||||
return `⏎ ${body.split("\n").find((l) => l.trim()) ?? ""}`.trimEnd()
|
||||
}
|
||||
@@ -0,0 +1,620 @@
|
||||
// Background work, one registry per process (harness spec loop.json `jobs`): a job is a command run
|
||||
// in the background — bash `background: true`, or a foreground command still running when its
|
||||
// timeout passed — or a subagent run in the background. Every job is owned by a session and every
|
||||
// lookup is scoped by it, so a subagent's tools see only what it started. A job that ends wakes the
|
||||
// session that owns it with a marked note (note.ts): the owning front end is attached here and
|
||||
// decides whether the note goes in mid-turn or starts a turn of its own; a session nobody has open
|
||||
// keeps the note on its row until it is resumed. Processes die with this one: on exit every group
|
||||
// gets SIGTERM, then SIGKILL, synchronously — an unref'd timer never fires at exit.
|
||||
import { spawn, type ChildProcess } from "node:child_process"
|
||||
import type { Bus } from "../bus/index.ts"
|
||||
import type { Engine } from "../session/engine.ts"
|
||||
import type { Store, StoredJob } from "../session/store.ts"
|
||||
import { LOOP } from "../harness.ts"
|
||||
import { commandLine, jobNote, shownLine, stripMark } from "./note.ts"
|
||||
|
||||
export type JobKind = "command" | "subagent"
|
||||
export type JobState = "running" | "done" | "stopped" | "error" | "lost"
|
||||
|
||||
/** The public shape of a job (harness/acp.md `JobInfo`): what a front end lists and shows. */
|
||||
export interface JobInfo {
|
||||
id: string
|
||||
kind: JobKind
|
||||
state: JobState
|
||||
/** What is shown for it: a command's `description` or its first line; a subagent's description. */
|
||||
description: string
|
||||
command?: string
|
||||
agent?: string
|
||||
model?: string
|
||||
started: number
|
||||
ended?: number
|
||||
/** A command's exit code; null when a signal stopped it. */
|
||||
exit?: number | null
|
||||
/** Characters of output the model has not read. */
|
||||
unread: number
|
||||
steps?: number
|
||||
tools?: number
|
||||
/** Set on a job a subagent started: the subagent's own job id. */
|
||||
ownerJobId?: string
|
||||
}
|
||||
|
||||
/** How the registry drives a subagent (app.ts spawn builds one): its bus, its engine, and the
|
||||
* three things done to it from outside. */
|
||||
export interface SubagentHandle {
|
||||
bus: Bus
|
||||
engine: Engine
|
||||
/** A message while it runs: its inbox, delivered at its next step under the to_subagent mark. */
|
||||
send(text: string): void
|
||||
/** Once finished: start it again with this text as a new prompt, its context intact. */
|
||||
restart(text: string): Promise<void>
|
||||
/** Stop it where it is; its partial report goes out as its end note. */
|
||||
cancel(): void
|
||||
}
|
||||
|
||||
export interface Job {
|
||||
id: string
|
||||
kind: JobKind
|
||||
/** The session that owns it: a subagent's own session for what the subagent started. */
|
||||
sessionId: string
|
||||
/** The tool call that started it. */
|
||||
ownerCallId?: string
|
||||
ownerJobId?: string
|
||||
description: string
|
||||
command?: string
|
||||
cwd?: string
|
||||
agent?: string
|
||||
model?: string
|
||||
state: JobState
|
||||
started: number
|
||||
ended?: number
|
||||
exit?: number | null
|
||||
/** A command's output, or a subagent's transcript lines: the tail, sliding at MAX_BUFFER. */
|
||||
output: string
|
||||
/** How much of `output` the model has already been given. */
|
||||
read: number
|
||||
/** A subagent's own session row (sessions.parent_id). */
|
||||
childSessionId?: string
|
||||
steps?: number
|
||||
tools?: number
|
||||
/** A note composed while nobody had the owning session open, kept until it is resumed. */
|
||||
note?: string
|
||||
/** The process, while a command runs. */
|
||||
child?: ChildProcess
|
||||
subagent?: SubagentHandle
|
||||
/** The last error the subagent's engine reported, for the tail of its report. */
|
||||
lastError?: string
|
||||
/** No end note: a subagent's own commands stopped because the subagent ended. */
|
||||
quiet?: boolean
|
||||
/** Set when the note's wake should not happen: a synchronous subagent whose result goes back
|
||||
* as the task call's output. */
|
||||
silent?: boolean
|
||||
}
|
||||
|
||||
/** A front end holding a session: where its jobs' events go, and how a note wakes it. The
|
||||
* session id is read when needed — it changes under one app on /new and on a resume. */
|
||||
export interface Attachment {
|
||||
sessionId(): string | undefined
|
||||
bus: Bus
|
||||
/** Deliver a note: mid-turn to the model's next step, or as a turn of its own (`machine`). */
|
||||
wake(text: string, shown: string): void
|
||||
store?: Store
|
||||
/** Background commands the session may have running at once (limits.jobs). */
|
||||
runningMax?(): number
|
||||
}
|
||||
|
||||
export interface StartCommand {
|
||||
sessionId: string
|
||||
command: string
|
||||
cwd: string
|
||||
env: Record<string, string | undefined>
|
||||
ownerCallId?: string
|
||||
ownerJobId?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface AdoptCommand {
|
||||
sessionId: string
|
||||
command: string
|
||||
cwd: string
|
||||
child: ChildProcess
|
||||
output: string
|
||||
read: number
|
||||
started: number
|
||||
ownerCallId?: string
|
||||
ownerJobId?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface SubagentStart {
|
||||
sessionId: string
|
||||
agent: string
|
||||
model: string
|
||||
description: string
|
||||
handle: SubagentHandle
|
||||
ownerCallId?: string
|
||||
ownerJobId?: string
|
||||
childSessionId?: string
|
||||
/** Its result goes back as the task call's output: no note when it ends. */
|
||||
silent?: boolean
|
||||
}
|
||||
|
||||
export interface SubagentEnd {
|
||||
reason: string
|
||||
report: string
|
||||
error?: string
|
||||
worktree?: string
|
||||
}
|
||||
|
||||
/** Characters of output kept per job; the model only ever reads what is new. */
|
||||
const MAX_BUFFER = 2_000_000
|
||||
/** Of that, what a job's row in the store keeps. */
|
||||
const STORED_TAIL = 64_000
|
||||
/** `update` events at most this often per job. */
|
||||
const UPDATE_MS = 250
|
||||
/** After `exit`, how long the pipes are drained before the job counts as ended: a daemon the
|
||||
* command left behind may hold stdout open for ever. */
|
||||
const DRAIN_MS = 300
|
||||
|
||||
const key = (sessionId: string, id: string) => `${sessionId}\u0000${id}`
|
||||
|
||||
export class JobRegistry {
|
||||
private jobs = new Map<string, Job>()
|
||||
private seq = new Map<string, number>()
|
||||
private loaded = new Set<string>()
|
||||
private attachments: Attachment[] = []
|
||||
private updates = new Map<string, { last: number; timer?: ReturnType<typeof setTimeout> }>()
|
||||
readonly limits = { runningMax: LOOP.jobs.running_max.default, finishedKept: LOOP.jobs.finished_kept.default, noteTailChars: LOOP.jobs.note_tail_chars.default }
|
||||
|
||||
constructor(private o: { store?: Store } = {}) {
|
||||
process.once("exit", () => this.killAllSync())
|
||||
}
|
||||
|
||||
/** A front end takes a session (and the next one it moves to): detach when it closes. */
|
||||
attach(a: Attachment): () => void {
|
||||
this.attachments.push(a)
|
||||
return () => {
|
||||
this.attachments = this.attachments.filter((x) => x !== a)
|
||||
}
|
||||
}
|
||||
|
||||
private attachmentFor(sessionId: string): Attachment | undefined {
|
||||
return this.attachments.find((a) => a.sessionId() === sessionId)
|
||||
}
|
||||
|
||||
private storeFor(sessionId: string): Store | undefined {
|
||||
return this.attachmentFor(sessionId)?.store ?? this.attachments.find((a) => a.store)?.store ?? this.o.store
|
||||
}
|
||||
|
||||
/** The store's jobs of a session, read once: one that was running when the process that ran it
|
||||
* died is `lost`, with the last tail it kept. */
|
||||
private ensureLoaded(sessionId: string) {
|
||||
if (this.loaded.has(sessionId)) return
|
||||
this.loaded.add(sessionId)
|
||||
const store = this.storeFor(sessionId)
|
||||
if (!store) return
|
||||
let max = this.seq.get(sessionId) ?? 0
|
||||
for (const row of store.jobs(sessionId)) {
|
||||
const n = Number(row.id.replace(/^job/, ""))
|
||||
if (Number.isFinite(n)) max = Math.max(max, n)
|
||||
if (this.jobs.has(key(sessionId, row.id))) continue
|
||||
const job = { ...(JSON.parse(row.json) as Omit<Job, "child" | "subagent">), state: row.state as JobState } as Job
|
||||
if (job.state === "running") {
|
||||
job.state = "lost"
|
||||
job.ended = Date.now()
|
||||
this.persist(job)
|
||||
}
|
||||
this.jobs.set(key(sessionId, job.id), job)
|
||||
}
|
||||
this.seq.set(sessionId, max)
|
||||
}
|
||||
|
||||
private persist(job: Job) {
|
||||
const store = this.storeFor(job.sessionId)
|
||||
if (!store) return
|
||||
const { child: _c, subagent: _s, output, read, ...rest } = job
|
||||
const cut = Math.max(0, output.length - STORED_TAIL)
|
||||
const row: StoredJob = { id: job.id, session_id: job.sessionId, kind: job.kind, state: job.state, started: job.started, ended: job.ended ?? null, json: JSON.stringify({ ...rest, output: output.slice(cut), read: Math.max(0, read - cut) }) }
|
||||
try {
|
||||
store.saveJob(row)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** The next id of a session: `job1, job2…`, continuing from what the store holds. */
|
||||
nextId(sessionId: string): string {
|
||||
this.ensureLoaded(sessionId)
|
||||
const n = (this.seq.get(sessionId) ?? 0) + 1
|
||||
this.seq.set(sessionId, n)
|
||||
return `job${n}`
|
||||
}
|
||||
|
||||
list(sessionId: string): Job[] {
|
||||
this.ensureLoaded(sessionId)
|
||||
const all = [...this.jobs.values()].filter((j) => j.sessionId === sessionId)
|
||||
// Running first, each group in the order they were started.
|
||||
return [...all.filter((j) => j.state === "running"), ...all.filter((j) => j.state !== "running")]
|
||||
}
|
||||
|
||||
running(sessionId: string): Job[] {
|
||||
return this.list(sessionId).filter((j) => j.state === "running")
|
||||
}
|
||||
|
||||
get(sessionId: string, id: string): Job | undefined {
|
||||
this.ensureLoaded(sessionId)
|
||||
return this.jobs.get(key(sessionId, id))
|
||||
}
|
||||
|
||||
info(job: Job): JobInfo {
|
||||
return {
|
||||
id: job.id,
|
||||
kind: job.kind,
|
||||
state: job.state,
|
||||
description: job.description,
|
||||
...(job.command !== undefined ? { command: job.command } : {}),
|
||||
...(job.agent !== undefined ? { agent: job.agent } : {}),
|
||||
...(job.model !== undefined ? { model: job.model } : {}),
|
||||
started: job.started,
|
||||
...(job.ended !== undefined ? { ended: job.ended } : {}),
|
||||
...(job.exit !== undefined ? { exit: job.exit } : {}),
|
||||
unread: Math.max(0, job.output.length - job.read),
|
||||
...(job.steps !== undefined ? { steps: job.steps } : {}),
|
||||
...(job.tools !== undefined ? { tools: job.tools } : {}),
|
||||
...(job.ownerJobId !== undefined ? { ownerJobId: job.ownerJobId } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** How many background commands a session may have at once. */
|
||||
runningMax(sessionId: string): number {
|
||||
return this.attachmentFor(sessionId)?.runningMax?.() ?? this.limits.runningMax
|
||||
}
|
||||
|
||||
/** Start a command in the background: its own process group, so stopping it takes the whole
|
||||
* tree down. Refused past the session's cap. */
|
||||
start(o: StartCommand): Job {
|
||||
const commands = this.running(o.sessionId).filter((j) => j.kind === "command")
|
||||
const max = this.runningMax(o.sessionId)
|
||||
if (commands.length >= max) throw new Error(`This session already has ${commands.length} background command${commands.length === 1 ? "" : "s"} running (limits.jobs: ${max}). Stop one with job_stop, or wait for one to end.`)
|
||||
const child = spawn("bash", ["-c", `exec 2>&1\n${o.command}`], { cwd: o.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], env: o.env })
|
||||
return this.adopt({ ...o, child, output: "", read: 0, started: Date.now() })
|
||||
}
|
||||
|
||||
/** Take over a command somebody else started — bash's foreground child at its timeout, with what
|
||||
* it had printed — and follow it from here. */
|
||||
adopt(o: AdoptCommand): Job {
|
||||
const job: Job = {
|
||||
id: this.nextId(o.sessionId),
|
||||
kind: "command",
|
||||
sessionId: o.sessionId,
|
||||
ownerCallId: o.ownerCallId,
|
||||
ownerJobId: o.ownerJobId,
|
||||
description: o.description ?? commandLine(o.command, 80),
|
||||
command: o.command,
|
||||
cwd: o.cwd,
|
||||
state: "running",
|
||||
started: o.started,
|
||||
output: o.output,
|
||||
read: o.read,
|
||||
child: o.child,
|
||||
}
|
||||
this.jobs.set(key(job.sessionId, job.id), job)
|
||||
this.follow(job, o.child)
|
||||
this.persist(job)
|
||||
this.emit(job, "start")
|
||||
return job
|
||||
}
|
||||
|
||||
private follow(job: Job, child: ChildProcess) {
|
||||
child.stdout?.on("data", (d: Buffer) => {
|
||||
this.append(job, d.toString())
|
||||
})
|
||||
let exited = false
|
||||
let closed = false
|
||||
let ended = false
|
||||
const end = () => {
|
||||
if (ended) return
|
||||
ended = true
|
||||
job.exit = child.exitCode ?? (child.signalCode ? null : (job.exit ?? null))
|
||||
this.finishCommand(job)
|
||||
}
|
||||
child.on("close", () => {
|
||||
closed = true
|
||||
if (exited) end()
|
||||
})
|
||||
child.on("exit", (code, signal) => {
|
||||
exited = true
|
||||
job.exit = signal ? null : code
|
||||
if (closed) return end()
|
||||
// The pipes may still hold output; a grandchild that keeps them open must not keep the job
|
||||
// "running" for ever.
|
||||
setTimeout(end, DRAIN_MS).unref()
|
||||
})
|
||||
child.on("error", () => end())
|
||||
// Adopted after it had already ended: nothing more will come.
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
job.exit = child.signalCode ? null : child.exitCode
|
||||
end()
|
||||
}
|
||||
}
|
||||
|
||||
/** Output (or a subagent's transcript line) arrived: kept to the tail, the model's read mark
|
||||
* moved with it. */
|
||||
append(job: Job, text: string) {
|
||||
if (!text) return
|
||||
job.output += text
|
||||
if (job.output.length > MAX_BUFFER) {
|
||||
const cut = job.output.length - MAX_BUFFER
|
||||
job.output = job.output.slice(cut)
|
||||
job.read = Math.max(0, job.read - cut)
|
||||
}
|
||||
this.scheduleUpdate(job)
|
||||
}
|
||||
|
||||
/** What the model has not read, and that it has now. */
|
||||
takeUnread(job: Job): string {
|
||||
const fresh = job.output.slice(job.read)
|
||||
job.read = job.output.length
|
||||
return fresh
|
||||
}
|
||||
|
||||
/** Stop a job: a command gets SIGTERM and, two seconds later, SIGKILL; a subagent is cancelled. */
|
||||
stop(job: Job) {
|
||||
if (job.state !== "running") return
|
||||
if (job.kind === "subagent") return void job.subagent?.cancel()
|
||||
const pid = job.child?.pid
|
||||
if (!pid) return
|
||||
try {
|
||||
process.kill(-pid, "SIGTERM")
|
||||
} catch {}
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.kill(-pid, "SIGKILL")
|
||||
} catch {}
|
||||
}, 2000).unref()
|
||||
}
|
||||
|
||||
/** Every running job of a session: on its deletion, or a subagent's end for its own commands
|
||||
* (`quiet`: those end without a note — nobody is left to read it). */
|
||||
stopAll(sessionId: string, quiet = false): number {
|
||||
const running = this.running(sessionId)
|
||||
for (const j of running) {
|
||||
if (quiet) j.quiet = true
|
||||
this.stop(j)
|
||||
}
|
||||
return running.length
|
||||
}
|
||||
|
||||
/** On process exit: TERM every command's group, a moment for it to take, then KILL — done
|
||||
* synchronously, since nothing runs after this. */
|
||||
killAllSync() {
|
||||
const alive = [...this.jobs.values()].filter((j) => j.kind === "command" && j.state === "running" && j.child?.pid)
|
||||
if (!alive.length) return
|
||||
for (const j of alive)
|
||||
try {
|
||||
process.kill(-j.child!.pid!, "SIGTERM")
|
||||
} catch {}
|
||||
Bun.sleepSync(100)
|
||||
for (const j of alive)
|
||||
try {
|
||||
process.kill(-j.child!.pid!, "SIGKILL")
|
||||
} catch {}
|
||||
}
|
||||
|
||||
private finishCommand(job: Job) {
|
||||
if (job.state !== "running") return
|
||||
job.ended = Date.now()
|
||||
job.state = job.exit === null ? "stopped" : job.exit === 0 ? "done" : "error"
|
||||
job.child = undefined
|
||||
this.flushUpdate(job)
|
||||
const note = job.quiet ? undefined : this.commandNote(job)
|
||||
this.persist(job)
|
||||
this.forget(job.sessionId)
|
||||
this.emit(job, "end")
|
||||
if (note) this.deliver(job, note)
|
||||
}
|
||||
|
||||
/** The note about a finished command; what it carries counts as read, so job_output does not
|
||||
* repeat it. */
|
||||
private commandNote(job: Job): string {
|
||||
const unread = this.takeUnread(job)
|
||||
const max = this.limits.noteTailChars
|
||||
const tail = unread.length > max ? `…${unread.slice(-max)}` : unread
|
||||
return jobNote({ kind: "command", id: job.id, command: job.command ?? "", exit: job.exit ?? null, seconds: Math.round(((job.ended ?? Date.now()) - job.started) / 1000), unread: tail }).text
|
||||
}
|
||||
|
||||
/** A subagent starts as a job: its bus is followed from here — its text and tool lines become the
|
||||
* job's transcript (job_output), its tool calls are announced under the task line (`sub_tool`),
|
||||
* and its tokens count toward the owner's task. */
|
||||
startSubagent(o: SubagentStart): Job {
|
||||
const job: Job = {
|
||||
id: this.nextId(o.sessionId),
|
||||
kind: "subagent",
|
||||
sessionId: o.sessionId,
|
||||
ownerCallId: o.ownerCallId,
|
||||
ownerJobId: o.ownerJobId,
|
||||
description: o.description,
|
||||
agent: o.agent,
|
||||
model: o.model,
|
||||
state: "running",
|
||||
started: Date.now(),
|
||||
output: "",
|
||||
read: 0,
|
||||
childSessionId: o.childSessionId,
|
||||
steps: 0,
|
||||
tools: 0,
|
||||
subagent: o.handle,
|
||||
silent: o.silent,
|
||||
}
|
||||
this.jobs.set(key(job.sessionId, job.id), job)
|
||||
o.handle.bus.on((e) => {
|
||||
const owner = this.attachmentFor(job.sessionId)
|
||||
switch (e.type) {
|
||||
case "prompt":
|
||||
this.append(job, `${job.output ? "\n\n" : ""}> ${e.text}\n`)
|
||||
break
|
||||
case "step":
|
||||
job.steps = (job.steps ?? 0) + 1
|
||||
this.scheduleUpdate(job)
|
||||
break
|
||||
case "text":
|
||||
this.append(job, e.text)
|
||||
break
|
||||
case "steered":
|
||||
this.append(job, `\n${e.texts.map((t) => `> ${stripMark(t).body}`).join("\n")}\n`)
|
||||
break
|
||||
case "tool_end":
|
||||
case "tool_denied": {
|
||||
job.tools = (job.tools ?? 0) + 1
|
||||
const title = e.type === "tool_end" ? (e.result.title ?? e.name) : `denied — ${e.reason.split("\n")[0]!.slice(0, 80)}`
|
||||
const isError = e.type === "tool_denied" || e.result.isError === true
|
||||
this.append(job, `\n[${e.name}] ${title}${isError && e.type === "tool_end" ? " (error)" : ""}\n`)
|
||||
if (job.ownerCallId) owner?.bus.emit({ type: "sub_tool", callId: job.ownerCallId, jobId: job.id, name: e.name, title, ...(isError ? { isError } : {}) })
|
||||
break
|
||||
}
|
||||
case "notice":
|
||||
this.append(job, `\n(${e.message})\n`)
|
||||
break
|
||||
case "error":
|
||||
job.lastError = e.message
|
||||
this.append(job, `\n(error: ${e.message})\n`)
|
||||
break
|
||||
case "usage":
|
||||
owner?.bus.emit({ type: "usage", usage: e.usage, child: true })
|
||||
break
|
||||
}
|
||||
})
|
||||
this.persist(job)
|
||||
this.emit(job, "start")
|
||||
return job
|
||||
}
|
||||
|
||||
/** A finished subagent starts again (job_send to it): the same job, running once more. */
|
||||
restartSubagent(job: Job) {
|
||||
job.state = "running"
|
||||
job.started = Date.now()
|
||||
job.ended = undefined
|
||||
job.exit = undefined
|
||||
job.lastError = undefined
|
||||
this.persist(job)
|
||||
this.emit(job, "start")
|
||||
}
|
||||
|
||||
/** The subagent ended: its state from the reason; its own background commands are stopped, and
|
||||
* its end note goes to the owner (unless its result goes back as the task call's output). */
|
||||
finishSubagent(job: Job, r: SubagentEnd): { text: string; stopped: number } {
|
||||
if (job.state !== "running") return { text: "", stopped: 0 }
|
||||
job.ended = Date.now()
|
||||
job.state = r.reason === "stop" || r.reason === "steps" || r.reason === "budget" ? "done" : r.reason === "cancelled" ? "stopped" : "error"
|
||||
const stopped = job.childSessionId ? this.stopAll(job.childSessionId, true) : 0
|
||||
this.flushUpdate(job)
|
||||
const error = r.error ?? (r.reason === "error" ? job.lastError : undefined)
|
||||
const note = jobNote({
|
||||
kind: "subagent",
|
||||
id: job.id,
|
||||
agent: job.agent ?? "",
|
||||
description: job.description,
|
||||
report: r.report,
|
||||
steps: job.steps ?? 0,
|
||||
tools: job.tools ?? 0,
|
||||
reason: r.reason === "cancelled" ? "stopped" : r.reason,
|
||||
...(error ? { error } : {}),
|
||||
seconds: Math.round((job.ended - job.started) / 1000),
|
||||
...(r.worktree ? { worktree: r.worktree } : {}),
|
||||
}).text
|
||||
const text = stopped ? `${note}\n${stoppedLine(stopped)}` : note
|
||||
this.persist(job)
|
||||
this.forget(job.sessionId)
|
||||
this.emit(job, "end")
|
||||
if (!job.silent) this.deliver(job, text)
|
||||
return { text, stopped }
|
||||
}
|
||||
|
||||
/** A subagent's `report`: a message to its owner now, before its final reply. */
|
||||
message(job: Job, text: string) {
|
||||
const note = jobNote({ kind: "message", id: job.id, agent: job.agent ?? "", description: job.description, text }).text
|
||||
this.deliver(job, note)
|
||||
}
|
||||
|
||||
/** Hand a note to the owning session: the front end holding it decides how it goes in; with
|
||||
* nobody holding it, the note waits on the job's row for a resume. */
|
||||
private deliver(job: Job, text: string) {
|
||||
const a = this.attachmentFor(job.sessionId)
|
||||
if (!a) {
|
||||
job.note = text
|
||||
this.persist(job)
|
||||
return
|
||||
}
|
||||
a.bus.emit({ type: "job_note", jobId: job.id, text })
|
||||
try {
|
||||
a.wake(text, shownLine(text))
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** Notes kept for a session nobody had open: delivered now that it is. */
|
||||
deliverPending(sessionId: string) {
|
||||
for (const job of this.list(sessionId)) {
|
||||
if (!job.note) continue
|
||||
const text = job.note
|
||||
job.note = undefined
|
||||
this.persist(job)
|
||||
this.deliver(job, text)
|
||||
}
|
||||
}
|
||||
|
||||
/** Finished jobs beyond the cap are forgotten, oldest first. */
|
||||
private forget(sessionId: string) {
|
||||
const done = this.list(sessionId).filter((j) => j.state !== "running")
|
||||
const extra = done.slice(0, Math.max(0, done.length - this.limits.finishedKept))
|
||||
const store = this.storeFor(sessionId)
|
||||
for (const j of extra) {
|
||||
this.jobs.delete(key(sessionId, j.id))
|
||||
try {
|
||||
store?.deleteJob(sessionId, j.id)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
private emit(job: Job, state: "start" | "update" | "end") {
|
||||
this.attachmentFor(job.sessionId)?.bus.emit({ type: "job", state, job: this.info(job) })
|
||||
}
|
||||
|
||||
private scheduleUpdate(job: Job) {
|
||||
const k = key(job.sessionId, job.id)
|
||||
const u = this.updates.get(k) ?? { last: 0 }
|
||||
this.updates.set(k, u)
|
||||
if (u.timer) return
|
||||
const wait = UPDATE_MS - (Date.now() - u.last)
|
||||
if (wait <= 0) {
|
||||
u.last = Date.now()
|
||||
return this.update(job)
|
||||
}
|
||||
u.timer = setTimeout(() => {
|
||||
u.timer = undefined
|
||||
u.last = Date.now()
|
||||
if (job.state === "running") this.update(job)
|
||||
}, wait)
|
||||
u.timer.unref()
|
||||
}
|
||||
|
||||
/** News of a running job: said, and its tail kept — so a job the process dies under is found
|
||||
* with what it had printed, not as it was at its start. */
|
||||
private update(job: Job) {
|
||||
this.persist(job)
|
||||
this.emit(job, "update")
|
||||
}
|
||||
|
||||
private flushUpdate(job: Job) {
|
||||
const u = this.updates.get(key(job.sessionId, job.id))
|
||||
if (u?.timer) clearTimeout(u.timer)
|
||||
this.updates.delete(key(job.sessionId, job.id))
|
||||
}
|
||||
}
|
||||
|
||||
/** The sentence under a subagent's note when its own background commands were stopped with it. */
|
||||
export function stoppedLine(n: number): string {
|
||||
return `Its ${n} background command${n === 1 ? " was" : "s were"} stopped with it.`
|
||||
}
|
||||
|
||||
let shared: JobRegistry | undefined
|
||||
/** The process's one registry (createApp attaches every front end to it). */
|
||||
export function jobRegistry(): JobRegistry {
|
||||
return (shared ??= new JobRegistry())
|
||||
}
|
||||
+17
-10
@@ -7,6 +7,7 @@ import { parse } from "yaml"
|
||||
import { paths } from "../config/paths.ts"
|
||||
import { asMode, type Mode } from "../config/schema.ts"
|
||||
import { canonicalToolNames } from "../tool/names.ts"
|
||||
import { promptText } from "../prompt/assemble.ts"
|
||||
|
||||
export interface AgentSpec {
|
||||
name: string
|
||||
@@ -22,28 +23,29 @@ export interface AgentSpec {
|
||||
source: "builtin" | "global" | "project"
|
||||
}
|
||||
|
||||
/** Never given to a subagent: it cannot spawn more, and it has no user of its own to ask. */
|
||||
export const NOT_FOR_SUBAGENTS = new Set(["task", "ask_user", "plan_submit", "plan_write", "plan_update", "tasks", "decisions", "memory", "skill_manage", "settings", "note_manage"])
|
||||
/** Never given to a subagent: it cannot spawn more (so nothing to send to), and it has no user of
|
||||
* its own to ask. */
|
||||
export const NOT_FOR_SUBAGENTS = new Set(["task", "job_send", "ask_user", "plan_submit", "plan_write", "plan_update", "tasks", "decisions", "memory", "skill_manage", "settings", "note_manage"])
|
||||
|
||||
export const BUILTIN_AGENTS: AgentSpec[] = [
|
||||
{
|
||||
name: "explore",
|
||||
description: "read-only research: find where things are, how they work, what a change would touch",
|
||||
instructions:
|
||||
"You can read, search and fetch, but not change anything. Look widely — several searches in one step when they are independent — then report what you found, not what you did: the answer first, then the evidence as file:line references.",
|
||||
// The texts are the spec's (harness/prompts/agents), so LLeMbas's helper says the same words.
|
||||
instructions: promptText("agents/explore.md"),
|
||||
mode: "plan",
|
||||
tools: ["read", "glob", "grep", "list", "bash", "web_search", "web_fetch", "view_image"],
|
||||
tools: ["read", "glob", "grep", "list", "bash", "job_output", "job_list", "job_stop", "web_search", "web_fetch", "view_image"],
|
||||
source: "builtin",
|
||||
},
|
||||
{
|
||||
name: "general",
|
||||
description: "a self-contained piece of work with the full toolset, under the same permission mode",
|
||||
instructions: "Do the task completely, check it, and report what you changed and how you verified it.",
|
||||
instructions: promptText("agents/general.md"),
|
||||
source: "builtin",
|
||||
},
|
||||
]
|
||||
|
||||
function load(dir: string, source: AgentSpec["source"]): AgentSpec[] {
|
||||
function load(dir: string, source: AgentSpec["source"], warnings?: string[]): AgentSpec[] {
|
||||
if (!existsSync(dir)) return []
|
||||
const out: AgentSpec[] = []
|
||||
for (const f of readdirSync(dir)) {
|
||||
@@ -53,7 +55,11 @@ function load(dir: string, source: AgentSpec["source"]): AgentSpec[] {
|
||||
let meta: Record<string, unknown> = {}
|
||||
try {
|
||||
meta = fm ? ((parse(fm[1]!) as Record<string, unknown>) ?? {}) : {}
|
||||
} catch {}
|
||||
} catch (e) {
|
||||
// The agent is still offered, with its body: said, so a broken frontmatter is not a silent
|
||||
// loss of its model, mode or tools.
|
||||
warnings?.push(`agent ${join(dir, f)}: frontmatter not read (${(e as Error).message.split("\n")[0]}); its description, model, mode and tools are ignored`)
|
||||
}
|
||||
const body = (fm ? raw.slice(fm[0].length) : raw).trim()
|
||||
out.push({
|
||||
name: basename(f, ".md").toLowerCase().replace(/[^a-z0-9_-]/g, "-"),
|
||||
@@ -69,8 +75,9 @@ function load(dir: string, source: AgentSpec["source"]): AgentSpec[] {
|
||||
return out
|
||||
}
|
||||
|
||||
export function agents(projectDir: string | undefined): AgentSpec[] {
|
||||
/** `warnings`: where a file that could not be read whole is said (a notice at start). */
|
||||
export function agents(projectDir: string | undefined, warnings?: string[]): AgentSpec[] {
|
||||
const byName = new Map<string, AgentSpec>()
|
||||
for (const a of [...BUILTIN_AGENTS, ...load(join(paths.config, "agents"), "global"), ...(projectDir ? load(join(projectDir, "agents"), "project") : [])]) byName.set(a.name, a)
|
||||
for (const a of [...BUILTIN_AGENTS, ...load(join(paths.config, "agents"), "global", warnings), ...(projectDir ? load(join(projectDir, "agents"), "project", warnings) : [])]) byName.set(a.name, a)
|
||||
return [...byName.values()]
|
||||
}
|
||||
+29
-4
@@ -15,6 +15,9 @@ import blockAgentsGit from "../../harness/prompts/blocks/agents-git.md" with { t
|
||||
import blockAgentsKeep from "../../harness/prompts/blocks/agents-keep.md" with { type: "text" }
|
||||
import blockLibrary from "../../harness/prompts/blocks/library.md" with { type: "text" }
|
||||
import blockPrototypes from "../../harness/prompts/blocks/prototypes.md" with { type: "text" }
|
||||
import blockSubagent from "../../harness/prompts/blocks/subagent.md" with { type: "text" }
|
||||
import agentExplore from "../../harness/prompts/agents/explore.md" with { type: "text" }
|
||||
import agentGeneral from "../../harness/prompts/agents/general.md" with { type: "text" }
|
||||
import modeManual from "../../harness/prompts/modes/manual.md" with { type: "text" }
|
||||
import modeEdit from "../../harness/prompts/modes/edit.md" with { type: "text" }
|
||||
import modeAuto from "../../harness/prompts/modes/auto.md" with { type: "text" }
|
||||
@@ -49,6 +52,9 @@ const BUILTIN: Record<string, string> = {
|
||||
"blocks/agents-keep.md": blockAgentsKeep,
|
||||
"blocks/library.md": blockLibrary,
|
||||
"blocks/prototypes.md": blockPrototypes,
|
||||
"blocks/subagent.md": blockSubagent,
|
||||
"agents/explore.md": agentExplore,
|
||||
"agents/general.md": agentGeneral,
|
||||
"modes/manual.md": modeManual,
|
||||
"modes/edit.md": modeEdit,
|
||||
"modes/auto.md": modeAuto,
|
||||
@@ -93,7 +99,17 @@ export function fill(text: string, vars: Record<string, string>): string {
|
||||
const INTRO = "Use the instructions below and the tools you have to help with software engineering and with running the project."
|
||||
const SURFACE = "Your output is shown in a terminal and rendered as GitHub-flavoured markdown in a monospace font."
|
||||
const FILE_TOOLS = "Use the dedicated tools for files: read (not cat), edit and write (not sed or heredocs), grep and glob (not find or grep in bash)."
|
||||
const BACKGROUND = "A long-running command (a server, a watcher) runs with bash `background: true`; check it with bash_output and stop it with bash_kill."
|
||||
const BACKGROUND = "A long-running command (a server, a watcher) runs with bash `background: true`; a foreground command still running at its timeout goes on in the background too. Read a job's output with job_output, list jobs with job_list, stop one with job_stop. A finished job or subagent announces itself to you: you are told when one ends, so do not poll."
|
||||
// The two bullets a subagent does not get: it has no plan tools and nobody to ask (the spec's
|
||||
// `plan_tools` and `ask_tool` variables of system/default.md).
|
||||
const PLAN_TOOLS =
|
||||
"For work with three or more steps, write a plan with plan_write from the start and keep it current with plan_update as you go rather than at the end: mark a task doing when you start it and done once you have checked it works, drop one that turns out to be unnecessary, and add work the plan did not anticipate when you find it. The plan is what somebody reads to see where you are, so a plan updated only at the end is a report rather than a plan. If what you find makes the plan wrong rather than merely incomplete, say so and ask with ask_user rather than quietly planning something else."
|
||||
const ASK_TOOL =
|
||||
"When a decision is genuinely the user's — a trade-off only they can weigh, a requirement the request leaves open — ask with ask_user: everything you need in one call, with the options you consider plausible and the one you would choose marked recommended. Do not ask what you can find out yourself."
|
||||
/** `{{report}}` of blocks/subagent.md, when the subagent has the report tool. */
|
||||
const SUBAGENT_REPORT = " Before that, the report tool sends the main agent a message — a finding it should act on at once, or a question you cannot settle yourself — and a message from it may reach you meanwhile."
|
||||
/** `{{read_only}}` of blocks/subagent.md, in plan mode. */
|
||||
const SUBAGENT_READ_ONLY = " You can read and search; you cannot change anything."
|
||||
const GIT_SECTION = [
|
||||
"# Git",
|
||||
"- How git is used in this project — whether you commit on your own, and on which branch — is in the \"## Git\" section of its AGENTS.md. Follow it. Where nothing says, only commit, amend, push, tag or create branches when the user asks.",
|
||||
@@ -182,8 +198,9 @@ export interface PromptContext {
|
||||
files?: { path: string; text: string }[]
|
||||
/** Open items on the project's task board. */
|
||||
tasks?: string
|
||||
/** Set for a subagent: who it is and what it is for; replaces the mode's own instructions. */
|
||||
subagent?: { name: string; instructions: string }
|
||||
/** Set for a subagent: who it is and what it is for; replaces the mode's own instructions.
|
||||
* `report`: it has the report tool. */
|
||||
subagent?: { name: string; instructions: string; report?: boolean }
|
||||
/** The memory snapshot taken when the session started ("" when both files are empty);
|
||||
* undefined when memory is off. */
|
||||
memory?: string
|
||||
@@ -225,6 +242,9 @@ export function assembleSystem(ctx: PromptContext): string {
|
||||
background: BACKGROUND,
|
||||
git: GIT_SECTION,
|
||||
plan_context: planContext(ctx.plan),
|
||||
// A subagent has neither: the bullets go with the empty values (fill.ts).
|
||||
plan_tools: ctx.subagent ? "" : PLAN_TOOLS,
|
||||
ask_tool: ctx.subagent ? "" : ASK_TOOL,
|
||||
}
|
||||
const sections: string[] = []
|
||||
// Who: the built-in line.
|
||||
@@ -290,7 +310,12 @@ export function assembleSystem(ctx: PromptContext): string {
|
||||
|
||||
if (ctx.subagent)
|
||||
sections.push(
|
||||
`You are the "${ctx.subagent.name}" subagent. You work for the main agent, not for the user directly, on one task it gave you; you cannot ask anyone anything. ${ctx.subagent.instructions}\n\nOnly your final reply reaches the main agent — make it complete on its own: the result, then the evidence (file:line), then anything you could not settle.${ctx.mode === "plan" ? " You can read and search; you cannot change anything." : ""}`,
|
||||
fillPrompt(promptText("blocks/subagent.md"), {
|
||||
name: ctx.subagent.name,
|
||||
instructions: ctx.subagent.instructions,
|
||||
report: ctx.subagent.report ? SUBAGENT_REPORT : "",
|
||||
read_only: ctx.mode === "plan" ? SUBAGENT_READ_ONLY : "",
|
||||
}),
|
||||
)
|
||||
else sections.push(fillPrompt(promptText(`modes/${ctx.mode}.md`), vars))
|
||||
if (ctx.unattended) sections.push(fillPrompt(promptText("modes/unattended.md"), { ...vars, refused: ctx.unattended }))
|
||||
|
||||
@@ -13,7 +13,7 @@ export type ToolCallPart = { type: "tool_call"; id: string; name: string; args:
|
||||
export type Message =
|
||||
/** `turnId`: the turn a prompt started, kept with it in the store for
|
||||
* `_lembas/session/history`; never sent to a model. */
|
||||
| { role: "user"; parts: (TextPart | ImagePart)[]; turnId?: string }
|
||||
| { role: "user"; parts: (TextPart | ImagePart)[]; turnId?: string; /** The harness wrote it (a job's note), not the person: shown as such. */ machine?: true }
|
||||
| { role: "assistant"; parts: (TextPart | ReasoningPart | ToolCallPart)[] }
|
||||
| { role: "tool"; callId: string; name: string; content: string; isError?: boolean }
|
||||
|
||||
|
||||
@@ -25,6 +25,22 @@ export function capacityRefusal(main: ResolvedModel, helper: ResolvedModel): str
|
||||
return ""
|
||||
}
|
||||
|
||||
/** The same rule between two subagents: a new one is not started where its model would unload, or
|
||||
* take the only slot of, a subagent already running (the spec's "beside the model of a subagent
|
||||
* already running"). */
|
||||
export function capacityBeside(running: ResolvedModel, helper: ResolvedModel): string {
|
||||
if (helper.ref === running.ref) {
|
||||
if (helper.spec.single_session) return `${helper.ref} serves one request at a time (single_session), and a subagent is already running on it; a second would wait for the first, or push it out.`
|
||||
return ""
|
||||
}
|
||||
const shared = groupOf(running)
|
||||
if (shared !== undefined && shared === groupOf(helper)) {
|
||||
const where = running.spec.group !== undefined ? `${running.ref}'s server (group ${running.spec.group})` : running.connectionName
|
||||
return `${where} holds one model at a time, and a subagent is already running on ${running.ref} there; one on ${helper.ref} would unload it.`
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
/** Which one-model-at-a-time server a model is on: its own `group`, else its connection when the
|
||||
* connection sets one_model_at_a_time, else none. The spec's capacity.group. */
|
||||
function groupOf(m: ResolvedModel): string | undefined {
|
||||
|
||||
+23
-1
@@ -32,7 +32,7 @@ export interface CommandInfo {
|
||||
* the built-in wins — so it is not one here either, even where the built-in is not offered. */
|
||||
export const TUI_COMMAND_NAMES = [
|
||||
"agents", "continue", "help", "model", "effort", "mode", "plan", "plans", "prototype", "review", "changelog", "init", "release", "tasks", "decisions", "decide",
|
||||
"sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context",
|
||||
"jobs", "sessions", "resume", "remote", "delete", "new", "clear", "copy", "undo", "redo", "diff", "checkpoint", "checkpoints", "branch", "commit", "context",
|
||||
"compact", "memory", "skills", "skill", "personality", "voice", "speak", "mcp", "login", "logout", "settings", "usage", "kb", "theme", "skin", "terminal",
|
||||
"icons", "trust", "reload", "restart", "quit", "exit", "q",
|
||||
] as const
|
||||
@@ -46,8 +46,26 @@ export const SHARED_BUILTINS: { name: string; description: string; hint?: string
|
||||
{ name: "changelog", description: "update CHANGELOG.md's Unreleased section from the commits since the last tag", hint: "since" },
|
||||
{ name: "init", description: "make or update the project's AGENTS.md from what the repository says", hint: "what to focus on" },
|
||||
{ name: "continue", description: "carry on — after esc stopped it, or when it should keep going (ctrl+g)" },
|
||||
{ name: "agents", description: "subagents: list them, make one, or hand one a task", hint: "name" },
|
||||
]
|
||||
|
||||
/** `/agents [name]`: the subagents the task tool offers, or one of them — the text both the TUI and
|
||||
* a client over ACP show. Making one (`new`) and handing one a task need a screen: the TUI's. */
|
||||
export function agentsText(app: App, arg: string): string {
|
||||
const list = app.agents
|
||||
const describe = (a: (typeof list)[number]) =>
|
||||
[
|
||||
`${a.name} (${a.source}) — ${a.description}`,
|
||||
` model ${a.model ?? "the session's"} · mode ${a.mode ?? "the session's"} · tools ${a.tools?.join(", ") ?? "all a subagent may have"}${a.isolation ? " · own worktree" : ""}`,
|
||||
].join("\n")
|
||||
const name = arg.trim().split(/\s+/)[0]
|
||||
if (name) {
|
||||
const one = list.find((a) => a.name === name)
|
||||
return one ? describe(one) : `no agent "${name}" — ${list.map((a) => a.name).join(", ")}`
|
||||
}
|
||||
return [...list.map(describe), "", 'The model hands work to one through its task tool when that helps; you can ask it to ("use the explore subagent to…").'].join("\n")
|
||||
}
|
||||
|
||||
const reserved = new Set<string>(TUI_COMMAND_NAMES)
|
||||
|
||||
/** Where the commands come from: a trusted project's `.agent` (or none), and the skills. */
|
||||
@@ -154,6 +172,10 @@ export function expandSlash(app: App, text: string): Expanded | undefined {
|
||||
return arg ? { kind: "prompt", name, prompt: arg, shown: arg, attachFrom: arg, mode: "plan" } : { kind: "action", name, arg }
|
||||
case "continue":
|
||||
return { kind: "prompt", name, prompt: CONTINUE_PROMPT, shown: "↻ continue", attachFrom: "" }
|
||||
case "agents":
|
||||
// List and describe anywhere; `new` and `<name> <task>` are the TUI's own.
|
||||
if (/^(new)\b/.test(arg) || arg.trim().split(/\s+/).length > 1) return { kind: "message", name, text: "/agents here lists and describes the subagents; making one or handing one a task is done at the terminal." }
|
||||
return { kind: "message", name, text: agentsText(app, arg) }
|
||||
case "init":
|
||||
// The prompt is ours; only what was typed after the name may attach files.
|
||||
return { kind: "prompt", name, prompt: initPrompt(app, arg), shown: t, attachFrom: arg }
|
||||
|
||||
+34
-12
@@ -45,12 +45,17 @@ export interface EngineOptions {
|
||||
/** The model to switch to when this one's server cannot be reached (its `fallback` list), or
|
||||
* undefined when there is none left to try. */
|
||||
fallback?: (current: ResolvedModel, tried: Set<string>) => { model: ResolvedModel; client: Client; effort: Effort | null } | undefined
|
||||
/** What a message sent mid-turn starts with: the user's words for a session, the main agent's for
|
||||
* a subagent (loop.json jobs.marks to_subagent). */
|
||||
steerMark?: string
|
||||
}
|
||||
|
||||
/** What a prompt carries besides its text. */
|
||||
export interface PromptMeta {
|
||||
turnId?: string
|
||||
attachments?: AttachmentInfo[]
|
||||
/** The harness started this turn — a job's note — not the person. */
|
||||
machine?: true
|
||||
}
|
||||
|
||||
const MAX_PARALLEL = LOOP.parallel.max
|
||||
@@ -62,7 +67,8 @@ const PRUNED = "[This output was removed to save context. Run the tool again if
|
||||
export const CONTINUE_PROMPT = continueText.replace(/<!--[\s\S]*?-->\n?/g, "").trim()
|
||||
|
||||
export const STEER_MARK = "[The user sent this while you were working — take it into account from here:]"
|
||||
export const JOB_MARK = "[A background job you started has finished:]"
|
||||
/** The mark on a finished command's note (the spec's text; jobs/note.ts composes the notes). */
|
||||
export const JOB_MARK = LOOP.jobs.marks.command
|
||||
|
||||
/** Neighbouring user messages as one: a message sent mid-turn after the image message, or after a
|
||||
* nudge, would otherwise be two user turns in a row, which strict chat templates (llama.cpp's
|
||||
@@ -110,9 +116,9 @@ export class Engine {
|
||||
private inbox: string[] = []
|
||||
/** Beside the inbox, entry for entry: the id the sender gave a message (the web UI's message id), so where it was taken in can be shown at that point of the reply. */
|
||||
private inboxIds: (string | undefined)[] = []
|
||||
/** What happened while the task ran that is not the user's word: background jobs that finished.
|
||||
* Given to the model at the next step, like a steer; left over at the end, `takeNotes` hands
|
||||
* them out to start a turn of their own. */
|
||||
/** What happened while the task ran that is not the user's word: background jobs that finished,
|
||||
* a subagent's message. Each begins with its mark (jobs/note.ts). Given to the model at the next
|
||||
* step, like a steer; left over at the end, `takeNotes` hands them out to start a turn of their own. */
|
||||
private notes: string[] = []
|
||||
/** Those given to the model in this turn: kept word for word through a compaction, like the prompt. */
|
||||
private turnSteers: string[] = []
|
||||
@@ -130,6 +136,8 @@ export class Engine {
|
||||
private turnOutputBytes = 0
|
||||
private turnCompletion = 0
|
||||
private abort: AbortController | undefined
|
||||
/** The step's "background now" signal (ToolContext.backgroundNow), while its tools run. */
|
||||
private bgNow: AbortController | undefined
|
||||
|
||||
constructor(readonly o: EngineOptions) {
|
||||
this.mode = o.mode
|
||||
@@ -357,6 +365,14 @@ export class Engine {
|
||||
this.abort?.abort()
|
||||
}
|
||||
|
||||
/** The person wants the foreground command running in this step in the background now (ctrl+b):
|
||||
* bash hands it to the job registry and the call returns. False when no tools run. */
|
||||
backgroundNow(): boolean {
|
||||
if (!this.bgNow || this.bgNow.signal.aborted) return false
|
||||
this.bgNow.abort()
|
||||
return true
|
||||
}
|
||||
|
||||
/** A message the user sent while a task runs. It goes to the model at the next step (steer), or
|
||||
* is held for the task's end (queue, or a turn that ends first): `takeInbox` gives it back. */
|
||||
enqueue(text: string, id?: string) {
|
||||
@@ -394,7 +410,8 @@ export class Engine {
|
||||
return texts
|
||||
}
|
||||
|
||||
/** A background job ended while a task runs: it goes to the model at the next step. */
|
||||
/** A background job ended while a task runs: it goes to the model at the next step. The text
|
||||
* carries its own mark. */
|
||||
note(text: string) {
|
||||
this.notes.push(text)
|
||||
}
|
||||
@@ -408,14 +425,15 @@ export class Engine {
|
||||
private deliverInbox(): boolean {
|
||||
const notes = this.notes.splice(0)
|
||||
if (notes.length) {
|
||||
this.push({ role: "user", parts: [{ type: "text", text: `${JOB_MARK}\n${notes.join("\n\n")}` }] })
|
||||
this.o.bus.emit({ type: "notice", message: notes.map((n) => n.split("\n")[0]!).join("; ") })
|
||||
this.push({ role: "user", parts: [{ type: "text", text: notes.join("\n\n") }] })
|
||||
// Said as what happened, not as its mark: the line after it.
|
||||
this.o.bus.emit({ type: "notice", message: notes.map((n) => n.split("\n").find((l, i) => i > 0 && l.trim()) ?? n.split("\n")[0]!).join("; ") })
|
||||
}
|
||||
if (this.busyInput !== "steer" || !this.inbox.length) return notes.length > 0
|
||||
const texts = this.inbox.splice(0)
|
||||
const ids = this.inboxIds.splice(0).filter((i): i is string => typeof i === "string")
|
||||
this.turnSteers.push(...texts)
|
||||
this.push({ role: "user", parts: [{ type: "text", text: `${STEER_MARK}\n${texts.join("\n\n")}` }] })
|
||||
this.push({ role: "user", parts: [{ type: "text", text: `${this.o.steerMark ?? STEER_MARK}\n${texts.join("\n\n")}` }] })
|
||||
this.o.bus.emit({ type: "steered", texts, ...(ids.length ? { ids } : {}) })
|
||||
this.o.bus.emit({ type: "inbox", texts: [], mode: this.busyInput })
|
||||
return true
|
||||
@@ -431,19 +449,19 @@ export class Engine {
|
||||
async prompt(text: string, extra: (string | ImagePart)[] = [], shown = text, meta: PromptMeta = {}): Promise<"stop" | "steps" | "budget" | "cancelled" | "error"> {
|
||||
if (this.busy) throw new Error("busy")
|
||||
this.busy = true
|
||||
this.o.bus.emit({ type: "prompt", text: shown, ...(meta.turnId ? { turnId: meta.turnId } : {}), ...(meta.attachments?.length ? { attachments: meta.attachments } : {}) })
|
||||
this.o.bus.emit({ type: "prompt", text: shown, ...(meta.turnId ? { turnId: meta.turnId } : {}), ...(meta.attachments?.length ? { attachments: meta.attachments } : {}), ...(meta.machine ? { machine: true as const } : {}) })
|
||||
try {
|
||||
return await this.run(text, [...this.pendingContext.splice(0), ...extra], meta.turnId)
|
||||
return await this.run(text, [...this.pendingContext.splice(0), ...extra], meta.turnId, meta.machine)
|
||||
} finally {
|
||||
this.busy = false
|
||||
}
|
||||
}
|
||||
|
||||
private async run(text: string, extra: (string | ImagePart)[], turnId?: string): Promise<"stop" | "steps" | "budget" | "cancelled" | "error"> {
|
||||
private async run(text: string, extra: (string | ImagePart)[], turnId?: string, machine?: true): Promise<"stop" | "steps" | "budget" | "cancelled" | "error"> {
|
||||
const { bus } = this.o
|
||||
this.abort = new AbortController()
|
||||
const signal = this.abort.signal
|
||||
this.push({ role: "user", parts: [{ type: "text", text }, ...extra.map((t) => (typeof t === "string" ? { type: "text" as const, text: t } : t))], ...(turnId ? { turnId } : {}) })
|
||||
this.push({ role: "user", parts: [{ type: "text", text }, ...extra.map((t) => (typeof t === "string" ? { type: "text" as const, text: t } : t))], ...(turnId ? { turnId } : {}), ...(machine ? { machine } : {}) })
|
||||
this.turnPrompt = this.messages[this.messages.length - 1]
|
||||
this.turnSteers = []
|
||||
this.autoCompactions = 0
|
||||
@@ -602,9 +620,12 @@ export class Engine {
|
||||
if (decided.denied) bus.emit({ type: "tool_denied", id: call.id, name: call.name, reason: decided.result.output })
|
||||
} else runnable.push({ call, ...decided })
|
||||
}
|
||||
const bgNow = new AbortController()
|
||||
this.bgNow = bgNow
|
||||
const toolCtx: ToolContext = {
|
||||
...this.o.toolCtx,
|
||||
signal,
|
||||
backgroundNow: bgNow.signal,
|
||||
question: this.o.asker.question ? (req, id) => this.waiting(this.o.asker.question!(req, id)) : undefined,
|
||||
plan: {
|
||||
get: () => this.plan,
|
||||
@@ -646,6 +667,7 @@ export class Engine {
|
||||
}),
|
||||
)
|
||||
}
|
||||
this.bgNow = undefined
|
||||
const images: ImagePart[] = []
|
||||
for (const call of calls) {
|
||||
const r = results.get(call.id) ?? { output: "Not run: the reply was cancelled.", isError: true }
|
||||
|
||||
+53
-7
@@ -14,6 +14,20 @@ export interface SessionRow {
|
||||
title: string
|
||||
root: string
|
||||
model: string
|
||||
/** A subagent's session: the session whose task started it. Null for a session of its own. */
|
||||
parent_id?: string | null
|
||||
}
|
||||
|
||||
/** A background job's row (jobs/registry.ts persists one per job): the record as JSON, with the
|
||||
* columns a list needs beside it. */
|
||||
export interface StoredJob {
|
||||
id: string
|
||||
session_id: string
|
||||
kind: string
|
||||
state: string
|
||||
started: number
|
||||
ended: number | null
|
||||
json: string
|
||||
}
|
||||
|
||||
const SCHEMA = `
|
||||
@@ -28,6 +42,11 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS messages_session_kind ON messages(session_id, kind, id);
|
||||
CREATE INDEX IF NOT EXISTS messages_session ON messages(session_id, id);
|
||||
CREATE TABLE IF NOT EXISTS jobs (
|
||||
id TEXT NOT NULL, session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, json TEXT NOT NULL, state TEXT NOT NULL, started INTEGER NOT NULL, ended INTEGER,
|
||||
PRIMARY KEY (session_id, id)
|
||||
);
|
||||
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(text, content='', contentless_delete=1);
|
||||
CREATE TABLE IF NOT EXISTS session_meta (
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, key TEXT NOT NULL, value TEXT NOT NULL,
|
||||
@@ -76,14 +95,39 @@ export class Store {
|
||||
this.db.exec(SCHEMA.split("CREATE INDEX IF NOT EXISTS messages_session_kind")[0]!)
|
||||
const cols = (this.db.query("PRAGMA table_info(messages)").all() as { name: string }[]).map((c) => c.name)
|
||||
if (!cols.includes("kind")) this.db.run("ALTER TABLE messages ADD COLUMN kind TEXT NOT NULL DEFAULT 'message'")
|
||||
// A subagent's session hangs off its parent's and goes with it (spec 2.0.0).
|
||||
const sessionCols = (this.db.query("PRAGMA table_info(sessions)").all() as { name: string }[]).map((c) => c.name)
|
||||
if (!sessionCols.includes("parent_id")) this.db.run("ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE")
|
||||
this.db.exec(SCHEMA)
|
||||
}
|
||||
|
||||
createSession(root: string, model: string): SessionRow {
|
||||
/** `parentId`: a subagent's session, which belongs to the one whose task started it — listed
|
||||
* nowhere on its own, deleted with it. */
|
||||
createSession(root: string, model: string, parentId?: string): SessionRow {
|
||||
const now = Date.now()
|
||||
const id = `ses_${now.toString(36)}${Math.random().toString(36).slice(2, 8)}`
|
||||
this.db.query("INSERT INTO sessions (id, created, updated, root, model) VALUES (?, ?, ?, ?, ?)").run(id, now, now, root, model)
|
||||
return { id, created: now, updated: now, title: "", root, model }
|
||||
this.db.query("INSERT INTO sessions (id, created, updated, root, model, parent_id) VALUES (?, ?, ?, ?, ?, ?)").run(id, now, now, root, model, parentId ?? null)
|
||||
return { id, created: now, updated: now, title: "", root, model, parent_id: parentId ?? null }
|
||||
}
|
||||
|
||||
/** A subagent's sessions under this one. */
|
||||
children(sessionId: string): string[] {
|
||||
return (this.db.query("SELECT id FROM sessions WHERE parent_id = ?").all(sessionId) as { id: string }[]).map((r) => r.id)
|
||||
}
|
||||
|
||||
saveJob(j: StoredJob) {
|
||||
this.db
|
||||
.query("INSERT INTO jobs (id, session_id, kind, json, state, started, ended) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (session_id, id) DO UPDATE SET json = excluded.json, state = excluded.state, started = excluded.started, ended = excluded.ended")
|
||||
.run(j.id, j.session_id, j.kind, j.json, j.state, j.started, j.ended)
|
||||
}
|
||||
|
||||
/** A session's jobs as the store has them, oldest first. */
|
||||
jobs(sessionId: string): StoredJob[] {
|
||||
return this.db.query("SELECT id, session_id, kind, json, state, started, ended FROM jobs WHERE session_id = ? ORDER BY started, id").all(sessionId) as StoredJob[]
|
||||
}
|
||||
|
||||
deleteJob(sessionId: string, id: string) {
|
||||
this.db.query("DELETE FROM jobs WHERE session_id = ? AND id = ?").run(sessionId, id)
|
||||
}
|
||||
|
||||
append(sessionId: string, m: Message): number {
|
||||
@@ -99,7 +143,8 @@ export class Store {
|
||||
* deleting the chat it is. The search index has no content of its own, so its rows go by id. */
|
||||
deleteSession(sessionId: string): boolean {
|
||||
const del = this.db.transaction(() => {
|
||||
this.db.query("DELETE FROM messages_fts WHERE rowid IN (SELECT id FROM messages WHERE session_id = ?)").run(sessionId)
|
||||
// Its subagents' sessions go with it (ON DELETE CASCADE), so their index rows go here too.
|
||||
this.db.query("DELETE FROM messages_fts WHERE rowid IN (SELECT id FROM messages WHERE session_id = ? OR session_id IN (SELECT id FROM sessions WHERE parent_id = ?))").run(sessionId, sessionId)
|
||||
return this.db.query("DELETE FROM sessions WHERE id = ?").run(sessionId).changes > 0
|
||||
})
|
||||
// IMMEDIATE: the write lock taken up front, so busy_timeout applies. A deferred
|
||||
@@ -179,9 +224,10 @@ export class Store {
|
||||
}
|
||||
|
||||
/** Newest first. `withMessages`: only sessions somebody said something in (every start and /new
|
||||
* makes one, so the empty ones would crowd out the rest). */
|
||||
* makes one, so the empty ones would crowd out the rest). A subagent's session is never listed:
|
||||
* it is reached through the job that ran it. */
|
||||
sessions(limit = 50, root?: string, withMessages = false): SessionRow[] {
|
||||
const where = [root ? "s.root = ?" : "", withMessages ? "EXISTS (SELECT 1 FROM messages m WHERE m.session_id = s.id AND m.kind = 'message')" : ""].filter(Boolean)
|
||||
const where = ["s.parent_id IS NULL", root ? "s.root = ?" : "", withMessages ? "EXISTS (SELECT 1 FROM messages m WHERE m.session_id = s.id AND m.kind = 'message')" : ""].filter(Boolean)
|
||||
return this.db
|
||||
.query(`SELECT s.* FROM sessions s ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY s.updated DESC LIMIT ?`)
|
||||
.all(...(root ? [root] : []), limit) as SessionRow[]
|
||||
@@ -195,7 +241,7 @@ export class Store {
|
||||
const ex = o.exclude ?? []
|
||||
const order = (t: string) => (o.sort === "newest" ? `${t}.created DESC, ${t}.id DESC` : o.sort === "oldest" ? `${t}.created ASC, ${t}.id ASC` : `${t}.r, ${t}.id`)
|
||||
const inner = `SELECT m.session_id, m.id, m.role, m.json, m.created, f.rank AS r FROM messages_fts f JOIN messages m ON m.id = f.rowid
|
||||
${o.root !== undefined ? "JOIN sessions s ON s.id = m.session_id AND s.root = ?" : ""}
|
||||
JOIN sessions s ON s.id = m.session_id AND s.parent_id IS NULL${o.root !== undefined ? " AND s.root = ?" : ""}
|
||||
WHERE messages_fts MATCH ? AND m.kind = 'message' AND m.role IN (${roles.map(() => "?").join(",")})
|
||||
${ex.length ? `AND m.session_id NOT IN (${ex.map(() => "?").join(",")})` : ""}`
|
||||
const sql = o.perSession
|
||||
|
||||
+86
-70
@@ -1,9 +1,9 @@
|
||||
import { spawn } from "node:child_process"
|
||||
import { z } from "zod"
|
||||
import { getJob, killJob, listJobs, startJob } from "./jobs.ts"
|
||||
import { absPath, defineTool, showPath, ToolError, truncate } from "./tool.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
import { described } from "../harness.ts"
|
||||
import { commandLine } from "../jobs/note.ts"
|
||||
|
||||
// git run by the model reads a repository's own config, which can name programs to run (an external
|
||||
// diff, an fsmonitor, a pager) — and "git diff", "git show", "git status" are allowed unasked. These
|
||||
@@ -21,7 +21,7 @@ if (outerTmp !== undefined) {
|
||||
if (outerTmp) startEnv.TMPDIR = outerTmp
|
||||
else delete startEnv.TMPDIR
|
||||
}
|
||||
const ENV = {
|
||||
export const ENV = {
|
||||
...startEnv,
|
||||
// A command can tell it runs under the agent.
|
||||
LEMBAS: "1",
|
||||
@@ -33,6 +33,11 @@ const ENV = {
|
||||
...Object.fromEntries(GIT_SAFE.flatMap(([k, v], i) => [[`GIT_CONFIG_KEY_${i}`, k], [`GIT_CONFIG_VALUE_${i}`, v]])),
|
||||
}
|
||||
|
||||
/** How long a background start waits for a first line before returning. */
|
||||
const FIRST_OUTPUT_MS = 100
|
||||
/** Output a foreground command keeps; past it the oldest goes, as a job's buffer does. */
|
||||
const MAX_BUFFER = 2_000_000
|
||||
|
||||
export const bashTool = defineTool({
|
||||
...described("bash"),
|
||||
purpose: "description",
|
||||
@@ -50,19 +55,31 @@ export const bashTool = defineTool({
|
||||
},
|
||||
async run(a, ctx) {
|
||||
const cwd = absPath(a.cwd ?? ".", ctx)
|
||||
const line = a.description ?? commandLine(a.command, 80)
|
||||
if (a.background) {
|
||||
const job = startJob(a.command, cwd, ENV)
|
||||
await Bun.sleep(300)
|
||||
const early = job.output
|
||||
job.read = early.length
|
||||
if (!ctx.jobs) throw new ToolError("Background commands are not available here.")
|
||||
const { sessionId, job: owner } = ctx.jobs.owner()
|
||||
let job
|
||||
try {
|
||||
job = ctx.jobs.registry.start({ sessionId, command: a.command, cwd, env: ENV, ownerCallId: ctx.callId, ownerJobId: owner?.id, description: a.description })
|
||||
} catch (e) {
|
||||
throw new ToolError((e as Error).message)
|
||||
}
|
||||
// Whatever it says in its first moment goes with the answer — a port in use, a missing
|
||||
// program — without waiting for a command that starts quietly.
|
||||
const until = Date.now() + FIRST_OUTPUT_MS
|
||||
while (Date.now() < until && job.state === "running" && !job.output) await Bun.sleep(10)
|
||||
const early = ctx.jobs.registry.takeUnread(job)
|
||||
const ended = job.state !== "running" ? ` It has already ${job.exit === null ? "stopped (SIGTERM)" : `exited with ${job.exit}`}.` : ""
|
||||
return {
|
||||
output: `Started in the background as ${job.id} (pid ${job.child.pid}).${job.exit !== undefined ? ` It has already exited with ${job.exit}.` : ""}${early ? `\nFirst output:\n${truncate(early, 4000)}` : ""}\nRead more with bash_output, stop it with bash_kill.`,
|
||||
title: `${a.description ?? a.command.split("\n")[0]!.slice(0, 80)} · background ${job.id}`,
|
||||
output: `Started in the background as ${job.id}.${ended}${early ? `\nFirst output:\n${truncate(early, 4000)}` : ""}\nRead more with job_output, stop it with job_stop.`,
|
||||
title: `${line} · background ${job.id}`,
|
||||
meta: { job: job.id },
|
||||
}
|
||||
}
|
||||
const timeout = a.timeout ?? ctx.bashTimeoutMs
|
||||
// Own process group, so a timeout or cancel takes the whole tree down.
|
||||
const started = Date.now()
|
||||
// Own process group, so a cancel takes the whole tree down.
|
||||
const child = spawn("bash", ["-c", `exec 2>&1\n${a.command}`], {
|
||||
cwd,
|
||||
detached: true,
|
||||
@@ -70,9 +87,11 @@ export const bashTool = defineTool({
|
||||
env: ENV,
|
||||
})
|
||||
let out = ""
|
||||
child.stdout!.on("data", (d: Buffer) => {
|
||||
if (out.length < 2_000_000) out += d.toString()
|
||||
})
|
||||
const onData = (d: Buffer) => {
|
||||
out += d.toString()
|
||||
if (out.length > MAX_BUFFER) out = out.slice(out.length - MAX_BUFFER)
|
||||
}
|
||||
child.stdout!.on("data", onData)
|
||||
let killed = ""
|
||||
const kill = (why: string) => {
|
||||
killed = why
|
||||
@@ -82,73 +101,70 @@ export const bashTool = defineTool({
|
||||
try {
|
||||
process.kill(-child.pid!, "SIGKILL")
|
||||
} catch {}
|
||||
}, 2000)
|
||||
}, 2000).unref()
|
||||
} catch {}
|
||||
}
|
||||
const timer = setTimeout(() => kill(`timed out after ${duration(timeout, true)}`), timeout)
|
||||
// At the timeout the command is not killed: it goes on as a background job, and the call
|
||||
// returns what it had printed with the job id (the timeline). Only when there is a session to
|
||||
// own the job; the TUI's own `!` commands (bashTimeline: false) are killed as before.
|
||||
const timeline = ctx.bashTimeline !== false && ctx.jobs !== undefined
|
||||
const onAbort = () => kill("cancelled")
|
||||
ctx.signal.addEventListener("abort", onAbort, { once: true })
|
||||
const code: number | null = await new Promise((res) => child.on("close", (c) => res(c)))
|
||||
clearTimeout(timer)
|
||||
// The person asked for it in the background now (ctrl+b): the same hand-over, before the timeout.
|
||||
let onBackground: (() => void) | undefined
|
||||
const outcome = await new Promise<{ kind: "exit"; code: number | null } | { kind: "timeout"; why: "timeout" | "user" }>((res) => {
|
||||
let exited = false
|
||||
let settled = false
|
||||
const settle = (v: { kind: "exit"; code: number | null } | { kind: "timeout"; why: "timeout" | "user" }) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
res(v)
|
||||
}
|
||||
if (timeline && ctx.backgroundNow) {
|
||||
onBackground = () => settle({ kind: "timeout", why: "user" })
|
||||
ctx.backgroundNow.addEventListener("abort", onBackground, { once: true })
|
||||
}
|
||||
// `close` means every pipe is drained; after `exit` a grandchild may hold them open for ever,
|
||||
// so a short drain is all it gets.
|
||||
child.on("close", (code) => exited && settle({ kind: "exit", code: child.signalCode ? null : code }))
|
||||
child.on("exit", (code, signal) => {
|
||||
exited = true
|
||||
setTimeout(() => settle({ kind: "exit", code: signal ? null : code }), 300).unref()
|
||||
})
|
||||
child.on("error", () => settle({ kind: "exit", code: null }))
|
||||
const timer = setTimeout(() => {
|
||||
if (timeline) settle({ kind: "timeout", why: "timeout" })
|
||||
else kill(`timed out after ${duration(timeout, true)}`)
|
||||
}, timeout)
|
||||
})
|
||||
// Whatever happens to the parent's turn from here is not this process's business: a cancel
|
||||
// after the hand-over must not kill a job the model was told about.
|
||||
ctx.signal.removeEventListener("abort", onAbort)
|
||||
const status = killed ? killed : `exit ${code ?? "?"}`
|
||||
if (onBackground) ctx.backgroundNow!.removeEventListener("abort", onBackground)
|
||||
if (outcome.kind === "timeout") {
|
||||
// From here the registry follows the process; this call stops listening.
|
||||
child.stdout!.off("data", onData)
|
||||
const { sessionId, job: owner } = ctx.jobs!.owner()
|
||||
const job = ctx.jobs!.registry.adopt({ sessionId, command: a.command, cwd, child, output: out, read: out.length, started, ownerCallId: ctx.callId, ownerJobId: owner?.id, description: a.description })
|
||||
const status =
|
||||
outcome.why === "user"
|
||||
? `the user moved it to the background after ${duration(Date.now() - started, true)}, as ${job.id} — job_output to read on`
|
||||
: `still running after ${duration(timeout, true)}; moved to the background as ${job.id} — job_output to read on`
|
||||
return {
|
||||
output: `${truncate(out.trimEnd()) || "(no output yet)"}\n\n[${status}]`,
|
||||
title: `${line} · background ${job.id}`,
|
||||
isError: false,
|
||||
meta: { job: job.id, cwd: showPath(cwd, ctx) },
|
||||
}
|
||||
}
|
||||
const code = outcome.code
|
||||
const status = killed ? killed : code === null ? "stopped (SIGTERM)" : `exit ${code}`
|
||||
return {
|
||||
output: `${truncate(out.trimEnd()) || "(no output)"}\n\n[${status}]`,
|
||||
title: `${a.description ?? a.command.split("\n")[0]!.slice(0, 80)} · ${status}`,
|
||||
title: `${line} · ${status}`,
|
||||
isError: killed !== "" || code !== 0,
|
||||
meta: { exit: code, cwd: showPath(cwd, ctx) },
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
export const bashOutputTool = defineTool({
|
||||
...described("bash_output"),
|
||||
purpose: false,
|
||||
access: "bash_output",
|
||||
schema: z.object({ id: z.string(), wait: z.number().min(0).max(60).optional() }),
|
||||
permission: () => ({ permission: "bash_output", class: "read", patterns: ["*"] }),
|
||||
async run(a, ctx) {
|
||||
const job = getJob(a.id)
|
||||
if (!job) throw new ToolError(`No background job ${a.id}.`)
|
||||
const until = Date.now() + (a.wait ?? 0) * 1000
|
||||
while (Date.now() < until && job.exit === undefined && job.output.length === job.read && !ctx.signal.aborted) await Bun.sleep(200)
|
||||
const fresh = job.output.slice(job.read)
|
||||
job.read = job.output.length
|
||||
const state = job.exit === undefined ? "still running" : `exited with ${job.exit}`
|
||||
return { output: `${truncate(fresh.trimEnd()) || "(no new output)"}\n\n[${job.id} ${state}]`, title: `${job.id} · ${state}` }
|
||||
},
|
||||
})
|
||||
|
||||
export const bashKillTool = defineTool({
|
||||
...described("bash_kill"),
|
||||
purpose: false,
|
||||
access: "bash_kill",
|
||||
schema: z.object({ id: z.string() }),
|
||||
permission: () => ({ permission: "bash_kill", class: "execute", patterns: ["*"] }),
|
||||
async run(a) {
|
||||
const job = getJob(a.id)
|
||||
if (!job) throw new ToolError(`No background job ${a.id}.`)
|
||||
if (job.exit !== undefined) return { output: `${job.id} had already exited with ${job.exit}.`, title: `${job.id} · already exited` }
|
||||
killJob(job)
|
||||
return { output: `Stopped ${job.id} (${job.command.split("\n")[0]}).`, title: `${job.id} · stopped` }
|
||||
},
|
||||
})
|
||||
|
||||
export const bashListTool = defineTool({
|
||||
...described("bash_list"),
|
||||
purpose: false,
|
||||
access: "bash_output",
|
||||
schema: z.object({}),
|
||||
permission: () => ({ permission: "bash_output", class: "read", patterns: ["*"] }),
|
||||
async run() {
|
||||
const jobs = listJobs()
|
||||
if (!jobs.length) return { output: "No background jobs.", title: "0 jobs" }
|
||||
const now = Date.now()
|
||||
const lines = jobs.map((j) => {
|
||||
const state = j.exit === undefined ? "running" : `exited with ${j.exit}`
|
||||
const unread = j.output.length > j.read ? " · new output" : ""
|
||||
return `${j.id} · ${state} · ${duration(now - j.started, true)}${unread} · ${j.command.split("\n")[0]!.slice(0, 120)}`
|
||||
})
|
||||
return { output: lines.join("\n"), title: `${jobs.length} jobs` }
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
// The model's side of background work (harness spec 2.0.0, jobs/registry.ts): list the session's
|
||||
// jobs, read one's new output, stop one, message a subagent; and `report`, a subagent's message to
|
||||
// the main agent before its final reply. Every lookup is the owner's: a subagent sees what it
|
||||
// started, nothing of its parent's.
|
||||
import { z } from "zod"
|
||||
import { defineTool, ToolError, truncate, type ToolContext } from "./tool.ts"
|
||||
import { described } from "../harness.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
import { commandLine, exitWords } from "../jobs/note.ts"
|
||||
import type { Job } from "../jobs/registry.ts"
|
||||
|
||||
function jobsOf(ctx: ToolContext) {
|
||||
if (!ctx.jobs) throw new ToolError("Background jobs are not available here.")
|
||||
return ctx.jobs
|
||||
}
|
||||
|
||||
function find(ctx: ToolContext, id: string): Job {
|
||||
const { registry, owner } = jobsOf(ctx)
|
||||
const job = registry.get(owner().sessionId, id.trim())
|
||||
if (!job) throw new ToolError(`No background job ${id}. job_list shows this session's jobs.`)
|
||||
return job
|
||||
}
|
||||
|
||||
/** A job's state in words: a command's exit, a subagent's end. */
|
||||
export function stateWords(job: Job): string {
|
||||
if (job.state === "running") return "still running"
|
||||
if (job.state === "lost") return "lost (the process that ran it ended)"
|
||||
if (job.kind === "command") return exitWords(job.exit)
|
||||
return job.state === "done" ? "finished" : job.state === "stopped" ? "stopped" : "ended with an error"
|
||||
}
|
||||
|
||||
/** What a job is, for a list: the command's first line, or the subagent and its description. */
|
||||
export function whatWords(job: Job): string {
|
||||
return job.kind === "command" ? commandLine(job.command ?? "", 120) : `${job.agent}: ${job.description}`
|
||||
}
|
||||
|
||||
export const jobListTool = defineTool({
|
||||
...described("job_list"),
|
||||
purpose: false,
|
||||
access: "job_list",
|
||||
schema: z.object({}),
|
||||
permission: () => ({ permission: "job_list", class: "read", patterns: ["*"] }),
|
||||
async run(_a, ctx) {
|
||||
const { registry, owner } = jobsOf(ctx)
|
||||
const jobs = registry.list(owner().sessionId)
|
||||
if (!jobs.length) return { output: "No background jobs.", title: "0 jobs" }
|
||||
const now = Date.now()
|
||||
const lines = jobs.map((j) => {
|
||||
const unread = j.output.length > j.read ? ` · ${j.output.length - j.read} chars unread` : ""
|
||||
return `${j.id} · ${j.kind} · ${stateWords(j)} · ${duration((j.ended ?? now) - j.started, true)}${unread} · ${whatWords(j)}`
|
||||
})
|
||||
const running = jobs.filter((j) => j.state === "running").length
|
||||
return { output: lines.join("\n"), title: `${jobs.length} job${jobs.length === 1 ? "" : "s"}${running ? ` · ${running} running` : ""}` }
|
||||
},
|
||||
})
|
||||
|
||||
export const jobOutputTool = defineTool({
|
||||
...described("job_output"),
|
||||
purpose: false,
|
||||
access: "job_output",
|
||||
schema: z.object({ id: z.string(), wait: z.number().min(0).max(60).optional() }),
|
||||
permission: () => ({ permission: "job_output", class: "read", patterns: ["*"] }),
|
||||
async run(a, ctx) {
|
||||
const { registry } = jobsOf(ctx)
|
||||
const job = find(ctx, a.id)
|
||||
const until = Date.now() + (a.wait ?? 0) * 1000
|
||||
while (Date.now() < until && job.state === "running" && job.output.length === job.read && !ctx.signal.aborted) await Bun.sleep(200)
|
||||
const fresh = registry.takeUnread(job)
|
||||
const state = stateWords(job)
|
||||
return { output: `${truncate(fresh.trimEnd()) || "(no new output)"}\n\n[${job.id} ${state}]`, title: `${job.id} · ${state}` }
|
||||
},
|
||||
})
|
||||
|
||||
export const jobStopTool = defineTool({
|
||||
...described("job_stop"),
|
||||
purpose: false,
|
||||
access: "job_stop",
|
||||
schema: z.object({ id: z.string() }),
|
||||
permission: () => ({ permission: "job_stop", class: "execute", patterns: ["*"] }),
|
||||
async run(a, ctx) {
|
||||
const { registry } = jobsOf(ctx)
|
||||
const job = find(ctx, a.id)
|
||||
if (job.state !== "running") return { output: `${job.id} had already ${stateWords(job)}.`, title: `${job.id} · already ended` }
|
||||
registry.stop(job)
|
||||
if (job.kind === "subagent") return { output: `Stopping ${job.id} (${whatWords(job)}). What it had worked out comes to you as its report when it has stopped.`, title: `${job.id} · stopping` }
|
||||
return { output: `Stopped ${job.id} (${whatWords(job)}).`, title: `${job.id} · stopped` }
|
||||
},
|
||||
})
|
||||
|
||||
export const jobSendTool = defineTool({
|
||||
...described("job_send"),
|
||||
purpose: false,
|
||||
access: "job_send",
|
||||
schema: z.object({ id: z.string(), text: z.string().min(1) }),
|
||||
permission: (a) => ({ permission: "job_send", class: "interact", patterns: [a.id] }),
|
||||
async run(a, ctx) {
|
||||
const { registry } = jobsOf(ctx)
|
||||
const job = find(ctx, a.id)
|
||||
if (job.kind !== "subagent" || !job.subagent) throw new ToolError(`${job.id} is a command, not a subagent; a message can only go to a subagent.`)
|
||||
if (job.state === "running") {
|
||||
job.subagent.send(a.text)
|
||||
return { output: `Sent to ${job.id} (${whatWords(job)}); it is given to it at its next step.`, title: `${job.id} · message sent` }
|
||||
}
|
||||
registry.restartSubagent(job)
|
||||
void job.subagent.restart(a.text)
|
||||
return { output: `${job.id} (${whatWords(job)}) is running again with your message as its new prompt, its context intact. Its report comes to you when it ends.`, title: `${job.id} · started again` }
|
||||
},
|
||||
})
|
||||
|
||||
export const reportTool = defineTool({
|
||||
...described("report"),
|
||||
purpose: false,
|
||||
access: "report",
|
||||
schema: z.object({ text: z.string().min(1) }),
|
||||
permission: () => ({ permission: "report", class: "interact", patterns: ["*"] }),
|
||||
async run(a, ctx) {
|
||||
const { registry, owner } = jobsOf(ctx)
|
||||
const job = owner().job
|
||||
if (!job) throw new ToolError("report is for a subagent: you are the main agent, so write to the user directly.")
|
||||
registry.message(job, a.text)
|
||||
return { output: "Sent to the main agent. An answer, if one comes, arrives as a message to you; carry on meanwhile.", title: "message to the main agent" }
|
||||
},
|
||||
})
|
||||
@@ -1,86 +0,0 @@
|
||||
// Background commands started by `bash` with background: true. Each runs in its own process group;
|
||||
// all of them are killed when LLeMbas CLI exits, however it exits.
|
||||
import { spawn, type ChildProcess } from "node:child_process"
|
||||
|
||||
export interface Job {
|
||||
id: string
|
||||
command: string
|
||||
child: ChildProcess
|
||||
output: string
|
||||
/** How much of `output` the model has already been given. */
|
||||
read: number
|
||||
exit?: number | null
|
||||
started: number
|
||||
}
|
||||
|
||||
const MAX_BUFFER = 2_000_000
|
||||
const exitListeners = new Set<(job: Job) => void>()
|
||||
|
||||
/** Be told when a background job ends — how a session is woken by one (after LLeMbas's
|
||||
* jobs). Returns the way to stop listening. */
|
||||
export function onJobExit(fn: (job: Job) => void): () => void {
|
||||
exitListeners.add(fn)
|
||||
return () => exitListeners.delete(fn)
|
||||
}
|
||||
|
||||
/** What the model is told when a job it started ends: which, how, and the output it has not read. */
|
||||
export function jobNote(job: Job, maxChars = 4000): string {
|
||||
const unread = job.output.slice(job.read)
|
||||
const tail = unread.length > maxChars ? `…${unread.slice(-maxChars)}` : unread
|
||||
const how = job.exit === null ? "was killed" : `exited with ${job.exit}`
|
||||
const secs = Math.round((Date.now() - job.started) / 1000)
|
||||
return `Background job ${job.id} (${job.command.split("\n")[0]!.slice(0, 120)}) ${how} after ${secs}s.${tail.trim() ? `\nOutput you had not read:\n${tail}` : " It printed nothing you had not read."}`
|
||||
}
|
||||
const jobs = new Map<string, Job>()
|
||||
let seq = 0
|
||||
|
||||
export function startJob(command: string, cwd: string, env: Record<string, string | undefined>): Job {
|
||||
const child = spawn("bash", ["-c", `exec 2>&1\n${command}`], { cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], env })
|
||||
const job: Job = { id: `job${++seq}`, command, child, output: "", read: 0, started: Date.now() }
|
||||
child.stdout!.on("data", (d: Buffer) => {
|
||||
job.output += d.toString()
|
||||
// Keep the tail when a long-running job talks a lot; the model only ever reads what is new.
|
||||
if (job.output.length > MAX_BUFFER) {
|
||||
const cut = job.output.length - MAX_BUFFER
|
||||
job.output = job.output.slice(cut)
|
||||
job.read = Math.max(0, job.read - cut)
|
||||
}
|
||||
})
|
||||
child.on("close", (code) => {
|
||||
job.exit = code
|
||||
for (const fn of exitListeners) {
|
||||
try {
|
||||
fn(job)
|
||||
} catch {}
|
||||
}
|
||||
})
|
||||
jobs.set(job.id, job)
|
||||
// Finished jobs beyond the last 50 are forgotten (each keeps up to MAX_BUFFER of output).
|
||||
const done = [...jobs.values()].filter((j) => j.exit !== undefined)
|
||||
for (const j of done.slice(0, Math.max(0, done.length - 50))) jobs.delete(j.id)
|
||||
return job
|
||||
}
|
||||
|
||||
export function getJob(id: string): Job | undefined {
|
||||
return jobs.get(id)
|
||||
}
|
||||
|
||||
export function killJob(job: Job) {
|
||||
try {
|
||||
process.kill(-job.child.pid!, "SIGTERM")
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.kill(-job.child.pid!, "SIGKILL")
|
||||
} catch {}
|
||||
}, 2000).unref()
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function listJobs(): Job[] {
|
||||
return [...jobs.values()]
|
||||
}
|
||||
|
||||
function killAll() {
|
||||
for (const j of jobs.values()) if (j.exit === undefined) killJob(j)
|
||||
}
|
||||
process.once("exit", killAll)
|
||||
@@ -1,5 +1,6 @@
|
||||
import { applyPatchTool } from "./apply_patch.ts"
|
||||
import { bashKillTool, bashListTool, bashOutputTool, bashTool } from "./bash.ts"
|
||||
import { bashTool } from "./bash.ts"
|
||||
import { jobListTool, jobOutputTool, jobSendTool, jobStopTool, reportTool } from "./job_tools.ts"
|
||||
import { editTool } from "./edit.ts"
|
||||
import { multieditTool } from "./multiedit.ts"
|
||||
import { askUserTool } from "./ask_user.ts"
|
||||
@@ -30,9 +31,10 @@ export const BUILTIN_TOOLS: Tool[] = [
|
||||
grepTool,
|
||||
listTool,
|
||||
bashTool,
|
||||
bashOutputTool,
|
||||
bashListTool,
|
||||
bashKillTool,
|
||||
jobOutputTool,
|
||||
jobListTool,
|
||||
jobStopTool,
|
||||
jobSendTool,
|
||||
webSearchTool,
|
||||
webFetchTool,
|
||||
taskTool,
|
||||
@@ -54,6 +56,8 @@ export const BUILTIN_TOOLS: Tool[] = [
|
||||
skillManageTool,
|
||||
settingsTool,
|
||||
viewImageTool,
|
||||
// Offered to subagents only (the spec's `offered: subagent`; app.ts SUBAGENT_ONLY).
|
||||
reportTool,
|
||||
] as Tool[]
|
||||
|
||||
export function toolMap(tools: Tool[] = BUILTIN_TOOLS): Map<string, Tool> {
|
||||
|
||||
+21
-4
@@ -1,12 +1,18 @@
|
||||
import { z } from "zod"
|
||||
import { defineTool, ToolError } from "./tool.ts"
|
||||
import { described } from "../harness.ts"
|
||||
import { stoppedLine } from "../jobs/registry.ts"
|
||||
import { subagentTail } from "../jobs/note.ts"
|
||||
|
||||
export interface SubagentResult {
|
||||
text: string
|
||||
steps: number
|
||||
tools: number
|
||||
reason: string
|
||||
/** The last error its engine reported, when `reason` is error. */
|
||||
error?: string
|
||||
/** How many of its own background commands were stopped with it. */
|
||||
stopped?: number
|
||||
}
|
||||
|
||||
export const taskTool = defineTool({
|
||||
@@ -17,20 +23,31 @@ export const taskTool = defineTool({
|
||||
prompt: z.string().min(1),
|
||||
agent: z.string().optional(),
|
||||
worktree: z.boolean().optional(),
|
||||
background: z.boolean().optional(),
|
||||
model: z.string().optional(),
|
||||
}),
|
||||
permission: (a) => ({ permission: "task", class: "interact", patterns: [a.model ? `${a.agent ?? "explore"} on ${a.model}` : (a.agent ?? "explore")] }),
|
||||
async run(a, ctx) {
|
||||
if (!ctx.spawn) throw new ToolError("Subagents cannot start subagents.")
|
||||
const agent = a.agent ?? "explore"
|
||||
let r: Awaited<ReturnType<NonNullable<typeof ctx.spawn>>>
|
||||
let handle: Awaited<ReturnType<NonNullable<typeof ctx.spawn>>>
|
||||
try {
|
||||
r = await ctx.spawn(agent, a.prompt, ctx.signal, ctx.callId, { worktree: a.worktree, description: a.description, model: a.model })
|
||||
// A background subagent is not tied to this turn: Esc stops the reply, not the job.
|
||||
handle = await ctx.spawn(agent, a.prompt, { signal: a.background ? undefined : ctx.signal, callId: ctx.callId, worktree: a.worktree, description: a.description, model: a.model, background: a.background })
|
||||
} catch (e) {
|
||||
if (e instanceof ToolError) throw e
|
||||
throw new ToolError((e as Error).message)
|
||||
}
|
||||
const tail = `\n\n[${agent} subagent · ${r.steps} step${r.steps === 1 ? "" : "s"} · ${r.tools} tool call${r.tools === 1 ? "" : "s"}${r.reason !== "stop" ? ` · ended: ${r.reason}` : ""}]`
|
||||
return { output: (r.text.trim() || "(the subagent returned no report)") + tail, title: `${agent}${a.model ? ` on ${a.model}` : ""}: ${a.description} · ${r.steps} steps`, isError: r.reason === "error" }
|
||||
const who = `${agent}${a.model ? ` on ${a.model}` : ""}`
|
||||
if (a.background) {
|
||||
return {
|
||||
output: `Started subagent ${agent} as ${handle.id} (${a.description}). Its report comes to you as a message when it ends; meanwhile job_output shows its progress, job_send gives it a message, job_stop stops it.`,
|
||||
title: `${who}: ${a.description} · background ${handle.id}`,
|
||||
meta: { job: handle.id },
|
||||
}
|
||||
}
|
||||
const r = await handle.done
|
||||
const tail = `\n\n${subagentTail(agent, r.steps, r.tools, r.reason, r.error)}${r.stopped ? `\n${stoppedLine(r.stopped)}` : ""}`
|
||||
return { output: (r.text.trim() || "(the subagent returned no report)") + tail, title: `${who}: ${a.description} · ${r.steps} steps`, isError: r.reason === "error" }
|
||||
},
|
||||
})
|
||||
+29
-2
@@ -21,8 +21,20 @@ export interface ToolContext {
|
||||
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>
|
||||
/** Run a subagent (the task tool). Absent inside a subagent: no recursion. */
|
||||
spawn?: (agent: string, prompt: string, signal: AbortSignal, callId?: string, opts?: { worktree?: boolean; description?: string; model?: string }) => Promise<import("./task.ts").SubagentResult>
|
||||
/** 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 id of the call being run (set by the engine per call). */
|
||||
callId?: string
|
||||
/** The project directory (.agent), when the project has one. */
|
||||
@@ -68,6 +80,21 @@ export interface ToolContext {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SpawnOptions {
|
||||
signal?: AbortSignal
|
||||
callId?: string
|
||||
worktree?: boolean
|
||||
description?: string
|
||||
model?: string
|
||||
background?: boolean
|
||||
}
|
||||
|
||||
/** 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>
|
||||
}
|
||||
|
||||
export interface ToolResult {
|
||||
output: string
|
||||
/** One-line summary for the UI: `src/app.ts +12 −3`, `exit 0 · 0.4s`. */
|
||||
|
||||
+135
-45
@@ -1,7 +1,6 @@
|
||||
import type { ScrollBoxRenderable, TextareaRenderable } from "@opentui/core"
|
||||
import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/solid"
|
||||
import { createEffect, createMemo, createSignal, onCleanup, Show } from "solid-js"
|
||||
import { jobNote, onJobExit } from "../tool/jobs.ts"
|
||||
import { stricterMode, type App as Runtime } from "../app.ts"
|
||||
import { isLocal } from "../config/paths.ts"
|
||||
import type { Effort, Mode } from "../config/schema.ts"
|
||||
@@ -13,6 +12,9 @@ import { copiedMessage, copyText } from "./clipboard.ts"
|
||||
import { QuestionCard } from "./components/question.tsx"
|
||||
import { PlanCard } from "./components/plancard.tsx"
|
||||
import { PlanPanel } from "./components/plan.tsx"
|
||||
import { JobView } from "./components/jobview.tsx"
|
||||
import { SubagentView } from "./components/subagent.tsx"
|
||||
import { Bus } from "../bus/index.ts"
|
||||
import { Prompt, type PaletteEntry } from "./components/prompt.tsx"
|
||||
import { FileIndex } from "../project/files.ts"
|
||||
import { attachmentsFor } from "../project/attach.ts"
|
||||
@@ -30,7 +32,7 @@ import { Welcome } from "./components/welcome.tsx"
|
||||
import { Share, type SharedPrompt } from "../acp/share.ts"
|
||||
import { mentionInfo } from "../acp/prompt.ts"
|
||||
import { TuiContext, type Ctx } from "./context.ts"
|
||||
import type { View } from "./state.ts"
|
||||
import { createView, type View } from "./state.ts"
|
||||
import { loadTheme, markdownStyle, paintBackground, reasoningStyle, themeNames, type IconSet, type Theme } from "./theme.ts"
|
||||
|
||||
const CYCLE: Mode[] = ["manual", "edit", "plan"]
|
||||
@@ -94,6 +96,78 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
const dims = useTerminalDimensions()
|
||||
const ctx: Ctx = { app, view, theme, md, thought, dims }
|
||||
|
||||
// Background jobs: the view's list is the registry's at the start and on every session change
|
||||
// (resume, /new), then follows the `job` events.
|
||||
const seedJobs = () => view.setJobs(app.jobs().map((j) => app.registry.info(j)))
|
||||
seedJobs()
|
||||
app.bus.on((e) => e.type === "session" && seedJobs())
|
||||
const running = () => app.registry.running(app.jobsSessionId()).length
|
||||
// A command job opened from /jobs (its live output), and a subagent entered (its transcript in
|
||||
// place of the session's, the prompt box sending to it). One View per entered job, kept: its bus
|
||||
// feeds it from the moment it is first entered, its history loaded from the child's messages.
|
||||
const [jobPanel, setJobPanel] = createSignal<string>()
|
||||
const [entered, setEntered] = createSignal<string>()
|
||||
const childViews = new Map<string, View>()
|
||||
const enterJob = (id: string) => {
|
||||
const job = app.registry.get(app.jobsSessionId(), id)
|
||||
if (!job || job.kind !== "subagent") return view.info(`${id} is not a subagent — /jobs lists them`, "warn")
|
||||
if (!childViews.has(id)) {
|
||||
const v = createView(job.subagent?.bus ?? new Bus())
|
||||
v.load(job.subagent?.engine.messages ?? (job.childSessionId && app.store ? app.store.messages(job.childSessionId) : []))
|
||||
childViews.set(id, v)
|
||||
}
|
||||
view.seenJobs(id)
|
||||
setEntered(id)
|
||||
}
|
||||
const leaveJob = () => setEntered(undefined)
|
||||
/** What is typed while a subagent is entered goes to it: its inbox while it runs, a new prompt
|
||||
* under the same job once it has finished. */
|
||||
const sendToJob = (text: string) => {
|
||||
const id = entered()!
|
||||
const job = app.registry.get(app.jobsSessionId(), id)
|
||||
if (!job?.subagent) return view.info(`${id} cannot be messaged any more — an earlier process ran it`, "warn")
|
||||
if (job.state === "running") {
|
||||
job.subagent.send(text)
|
||||
flash(`sent to ${id} — it reads it at its next step`)
|
||||
} else {
|
||||
app.registry.restartSubagent(job)
|
||||
childViews.get(id)?.user(text)
|
||||
void job.subagent.restart(text)
|
||||
flash(`${id} is running again with your message`)
|
||||
}
|
||||
}
|
||||
/** Leaving with jobs running is asked about: `N jobs running — stop them and quit?`. `what`:
|
||||
* quit or reload; `then`: what happens once they are stopped (or when none run). */
|
||||
const confirmStop = (what: string, then: () => void) => {
|
||||
const n = running()
|
||||
if (!n) return then()
|
||||
const go = () => {
|
||||
app.registry.stopAll(app.jobsSessionId())
|
||||
then()
|
||||
}
|
||||
setDialog({
|
||||
title: `${n} job${n === 1 ? "" : "s"} running — stop ${n === 1 ? "it" : "them"} and ${what}?`,
|
||||
options: [
|
||||
{ label: `Stop and ${what}`, value: "yes", description: "a command gets SIGTERM, a subagent is cancelled" },
|
||||
{ label: "Cancel", value: "no" },
|
||||
],
|
||||
hint: `y stop and ${what} · n / esc cancel`,
|
||||
keys: [
|
||||
{ when: (k) => k.name === "y" && !k.ctrl, run: () => go() },
|
||||
{ when: (k) => k.name === "n" && !k.ctrl, run: () => {} },
|
||||
],
|
||||
onSelect: (v) => v === "yes" && go(),
|
||||
})
|
||||
}
|
||||
const quit = () => confirmStop("quit", () => p.onQuit())
|
||||
/** ctrl+b: the foreground command of this step goes to the background now, as it would at its
|
||||
* timeout — the call returns with the output so far and the job's id. */
|
||||
const backgroundNow = () => {
|
||||
const bashRunning = view.state.items.some((it) => it.kind === "tool" && it.name === "bash" && it.status === "running" && !String(it.title ?? "").startsWith("! "))
|
||||
if (bashRunning && app.engine.backgroundNow()) flash("moving the command to the background…")
|
||||
else flash("no command is running in the foreground")
|
||||
}
|
||||
|
||||
// Voice: the record key, what was heard, replies read aloud.
|
||||
const voiceCfg = app.loaded.config.voice
|
||||
const recordKey = keyMatcher(voiceCfg?.record_key)
|
||||
@@ -121,16 +195,6 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
if (meter) clearInterval(meter)
|
||||
void voice.close()
|
||||
})
|
||||
// A background job that ends wakes the session (after LLeMbas): mid-task the model is
|
||||
// told at its next step; idle, the note starts a turn of its own, as if the user had said it —
|
||||
// shown as what it is. What the note hands over counts as read, so bash_output does not repeat it.
|
||||
const stopJobs = onJobExit((job) => {
|
||||
const text = jobNote(job)
|
||||
job.read = job.output.length
|
||||
if (app.turns.current || busy()) app.engine.note(text)
|
||||
else void send(text, `⏎ ${job.id} finished${job.exit === null ? " (killed)" : ` (exit ${job.exit})`}`, "")
|
||||
})
|
||||
onCleanup(stopJobs)
|
||||
// A finished reply is read out when replies are spoken.
|
||||
app.bus.on((e) => {
|
||||
if (e.type !== "done" || e.reason !== "stop" || !voice.speakReplies) return
|
||||
@@ -174,20 +238,26 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
},
|
||||
flash,
|
||||
refresh,
|
||||
quit: () => p.onQuit(),
|
||||
quit,
|
||||
reload() {
|
||||
if (!p.onReload) return view.info("/reload is not available here", "warn")
|
||||
// Back on this session, with what it was using; everything else comes from the files again.
|
||||
const e = app.engine
|
||||
const args = [...(isLocal() ? ["-l"] : []), ...(e.sessionId ? ["-s", e.sessionId] : []), "-m", e.model.ref, "--mode", e.mode, "-e", e.effort ?? "off"]
|
||||
void app
|
||||
.close()
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
app.store?.db.close()
|
||||
p.onReload!(args)
|
||||
})
|
||||
// The new process would not know the jobs; they would run on, orphaned, and their notes be
|
||||
// lost — so they are stopped first, after asking.
|
||||
confirmStop("reload", () => {
|
||||
// Back on this session, with what it was using; everything else comes from the files again.
|
||||
const e = app.engine
|
||||
const args = [...(isLocal() ? ["-l"] : []), ...(e.sessionId ? ["-s", e.sessionId] : []), "-m", e.model.ref, "--mode", e.mode, "-e", e.effort ?? "off"]
|
||||
void app
|
||||
.close()
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
app.store?.db.close()
|
||||
p.onReload!(args)
|
||||
})
|
||||
})
|
||||
},
|
||||
openJob: (id) => setJobPanel(id),
|
||||
enterJob,
|
||||
copy: (text: string) => copy(text),
|
||||
renderer,
|
||||
send: (text: string) => void send(text),
|
||||
@@ -235,12 +305,8 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
.then((reason) => {
|
||||
// What was sent during the task and never reached the model: stopped — back into the box,
|
||||
// to edit or send; otherwise (queue mode, or a turn that ended first) — sent now. After a
|
||||
// tick, so a command's own model and mode (sendAs) are put back first.
|
||||
// A job that ended as the task did: its own turn now.
|
||||
const notes = app.engine.takeNotes()
|
||||
// Stopped: they go with the next message instead of starting work nobody asked for now.
|
||||
if (notes.length && reason === "cancelled") app.engine.pendingContext.push(...notes)
|
||||
else if (notes.length) setTimeout(() => void send(notes.join("\n\n"), `⏎ ${notes.length} background job${notes.length === 1 ? "" : "s"} finished`, ""), 0)
|
||||
// tick, so a command's own model and mode (sendAs) are put back first. (A job's note left
|
||||
// over the same way is the app's business: app.ts wakes the session with it.)
|
||||
const left = app.turns.takeInbox()
|
||||
if (!left.length) return reason
|
||||
const joined = left.join("\n\n")
|
||||
@@ -336,7 +402,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
const id = view.shellStart(command)
|
||||
const t0 = performance.now()
|
||||
bashTool
|
||||
.run({ command }, { ...app.engine.o.toolCtx, signal: new AbortController().signal })
|
||||
.run({ command }, { ...app.engine.o.toolCtx, signal: new AbortController().signal, bashTimeline: false })
|
||||
.then((r) => {
|
||||
view.shellEnd(id, r, performance.now() - t0)
|
||||
app.engine.pendingContext.push(`<shell command="${command.replaceAll('"', "'")}">\n${r.output}\n</shell>`)
|
||||
@@ -348,6 +414,8 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
/** false: refused — the text stays in the box. */
|
||||
const submit = (text: string): boolean | void => {
|
||||
const t = text.trim()
|
||||
// Inside a subagent, what is typed is for it; commands are still the session's.
|
||||
if (entered() && !t.startsWith("/")) return void sendToJob(t)
|
||||
if (t.startsWith("!") && t.length > 1) return shell(t.slice(1).trim())
|
||||
if (t.startsWith("/")) {
|
||||
const [name, ...rest] = t.slice(1).split(/\s+/)
|
||||
@@ -437,7 +505,7 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
return
|
||||
}
|
||||
// A card or dialog owns the keyboard: esc there means that card's own thing.
|
||||
const overlay = dialog() || view.state.pending || view.state.question || view.state.plan
|
||||
const overlay = dialog() || jobPanel() || view.state.pending || view.state.question || view.state.plan
|
||||
if (!overlay && recordKey.matches(key) && (voice.canListen || voiceCfg)) {
|
||||
key.preventDefault()
|
||||
// Held down, a key repeats: in hold mode (or any repeat) only the first press counts.
|
||||
@@ -462,8 +530,12 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
)
|
||||
|
||||
const keys = (key: Parameters<Parameters<typeof useKeyboard>[0]>[0]) => {
|
||||
if (dialog() || view.state.pending || view.state.question || view.state.plan) return
|
||||
if (key.name === "escape" && busy()) {
|
||||
if (dialog() || jobPanel() || view.state.pending || view.state.question || view.state.plan) return
|
||||
if (key.name === "escape" && entered()) {
|
||||
// Back to the session; the model is not stopped by leaving a subagent.
|
||||
leaveJob()
|
||||
key.preventDefault()
|
||||
} else if (key.name === "escape" && busy()) {
|
||||
app.cancel()
|
||||
key.preventDefault()
|
||||
} else if (key.ctrl && key.name === "c" && (key.shift || renderer.hasSelection)) {
|
||||
@@ -473,9 +545,16 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
else flash("nothing selected — drag over text, or /copy the last reply")
|
||||
renderer.clearSelection()
|
||||
key.preventDefault()
|
||||
} else if (key.ctrl && key.name === "d" && !(input?.plainText ?? "").trim()) {
|
||||
// An empty box and ctrl+d: leave, as a shell does.
|
||||
quit()
|
||||
key.preventDefault()
|
||||
} else if (key.ctrl && key.name === "b") {
|
||||
backgroundNow()
|
||||
key.preventDefault()
|
||||
} else if (key.ctrl && key.name === "c") {
|
||||
// The first press stops the model (if busy); a second within 1.5 s always quits.
|
||||
if (Date.now() - quitArmed < 1500) p.onQuit()
|
||||
if (Date.now() - quitArmed < 1500) quit()
|
||||
else {
|
||||
if (busy()) app.cancel()
|
||||
quitArmed = Date.now()
|
||||
@@ -527,17 +606,25 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
return (
|
||||
<TuiContext.Provider value={ctx}>
|
||||
<box flexDirection="column" width="100%" height="100%">
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => (scroll = r)}
|
||||
flexGrow={1}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
viewportOptions={{ paddingRight: 1 }}
|
||||
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
|
||||
<Show
|
||||
when={entered()}
|
||||
keyed
|
||||
fallback={
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => (scroll = r)}
|
||||
flexGrow={1}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
viewportOptions={{ paddingRight: 1 }}
|
||||
verticalScrollbarOptions={{ trackOptions: { backgroundColor: theme().colors.panel, foregroundColor: theme().colors.dim } }}
|
||||
>
|
||||
<Welcome />
|
||||
<Messages />
|
||||
</scrollbox>
|
||||
}
|
||||
>
|
||||
<Welcome />
|
||||
<Messages />
|
||||
</scrollbox>
|
||||
{(id: string) => <SubagentView id={id} view={childViews.get(id)!} scrollRef={(r) => (scroll = r)} />}
|
||||
</Show>
|
||||
<box flexShrink={0} flexDirection="column">
|
||||
<PlanPanel />
|
||||
<Show when={view.state.pending}>
|
||||
@@ -553,12 +640,15 @@ export function Root(p: { app: Runtime; view: View; theme: Theme; onQuit: () =>
|
||||
<Spinner />
|
||||
</Show>
|
||||
<Queued />
|
||||
<Prompt focused={() => !dialog() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} />
|
||||
<Prompt focused={() => !dialog() && !jobPanel() && !view.state.pending && !view.state.question && !view.state.plan} busy={busy} commands={palette} files={files} onSubmit={submit} ref={(r) => (input = r)} queue={queueAccess} onWheel={(dir, lines) => scroll?.scrollBy(dir * lines)} onBackground={backgroundNow} />
|
||||
<StatusBar mode={mode} model={model} effort={effort} branch={branch()} voice={voiceStatus} flash={flashText} remote={() => (rev(), share.label())} credits={credits} />
|
||||
</box>
|
||||
<Show when={dialog()}>
|
||||
<Dialog spec={dialog()!} close={() => setDialog(undefined)} />
|
||||
</Show>
|
||||
<Show when={jobPanel()} keyed>
|
||||
{(id: string) => <JobView id={id} close={() => setJobPanel(undefined)} />}
|
||||
</Show>
|
||||
</box>
|
||||
</TuiContext.Provider>
|
||||
)
|
||||
|
||||
+124
-1
@@ -27,6 +27,8 @@ import { PERSONALITIES, personalityText } from "../prompt/personality.ts"
|
||||
import { listPrototypes } from "../prototype/store.ts"
|
||||
import { keyMatcher } from "../voice/index.ts"
|
||||
import { PLAYER_NAMES, playerFor, recorderFor } from "../voice/audio.ts"
|
||||
import { duration } from "../duration.ts"
|
||||
import type { Job, JobInfo } from "../jobs/registry.ts"
|
||||
|
||||
export interface CommandCtx extends Ctx {
|
||||
voice: import("../voice/index.ts").VoiceController
|
||||
@@ -56,6 +58,10 @@ export interface CommandCtx extends Ctx {
|
||||
reload(): void
|
||||
/** The status bar's balance, as /usage just read it. */
|
||||
setCredits?(text: string): void
|
||||
/** Open a command job's live output (components/jobview.tsx). */
|
||||
openJob(id: string): void
|
||||
/** Enter a subagent job: its transcript in place of the session's, the prompt box sends to it. */
|
||||
enterJob(id: string): void
|
||||
}
|
||||
|
||||
export interface Command {
|
||||
@@ -68,7 +74,8 @@ export interface Command {
|
||||
|
||||
const HELP_KEYS = [
|
||||
"enter send · shift+enter / ctrl+j new line · ↑↓ history",
|
||||
"esc stop the model · ctrl+g continue (after a stop, or to keep going) · ctrl+c clear, twice to quit",
|
||||
"esc stop the model · ctrl+g continue (after a stop, or to keep going) · ctrl+c clear, twice to quit · ctrl+d (empty box) quit",
|
||||
"/jobs background jobs: enter opens one (a subagent: esc back, type to message it), k stops it · ctrl+b moves the running command to the background",
|
||||
"shift+tab cycle mode (manual → edit → plan) · ctrl+r show reasoning · ctrl+o expand tool output",
|
||||
"pgup/pgdn scroll half a screen · ctrl+↑/↓ three lines · the mouse wheel · ↑ in an empty box takes back a message waiting to go in",
|
||||
]
|
||||
@@ -366,6 +373,17 @@ export const COMMANDS: Command[] = [
|
||||
c.view.info(`recorded: ${d.date} · ${d.title}`)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "jobs",
|
||||
args: "[<id> | stop <id>]",
|
||||
description: "background jobs: the list (enter opens one, k stops it); /jobs <id> opens one, /jobs stop <id> stops it",
|
||||
run(c, arg) {
|
||||
const [first, second] = arg.trim().split(/\s+/).filter(Boolean)
|
||||
if (!first) return openJobs(c)
|
||||
if (first === "stop") return second ? stopJob(c, second) : c.view.info("/jobs stop <id> — /jobs lists them", "warn")
|
||||
openJob(c, first)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sessions",
|
||||
aliases: ["resume"],
|
||||
@@ -1055,6 +1073,109 @@ export const COMMANDS: Command[] = [
|
||||
{ name: "quit", aliases: ["exit", "q"], description: "leave", run: (c) => c.quit() },
|
||||
]
|
||||
|
||||
/** `text` cut to `width` columns (wide characters counted as the terminal draws them), an ellipsis
|
||||
* where it was cut — at the end, not the middle: a description is a sentence, not a path. */
|
||||
export function fitColumns(text: string, width: number): string {
|
||||
if (Bun.stringWidth(text) <= width) return text
|
||||
let out = ""
|
||||
for (const ch of text) {
|
||||
if (Bun.stringWidth(out + ch) > width - 1) break
|
||||
out += ch
|
||||
}
|
||||
return `${out}…`
|
||||
}
|
||||
|
||||
/** One row of the Jobs picker, exactly `width` columns: icon, id (6), what it is (the column that
|
||||
* gives), state (7), how long (6), and `!` for one that ended unseen or holds unread output. The
|
||||
* icon's width is the set's — every emoji here is two columns, every plain icon one — so the
|
||||
* columns line up by construction. */
|
||||
export function jobRow(j: JobInfo, width: number, icon: string, unseen = false): string {
|
||||
const fixed = Bun.stringWidth(icon) + 1 + 6 + 1 + 1 + 7 + 1 + 6 + 1 + 1
|
||||
const descW = Math.max(4, width - fixed)
|
||||
const what = `${j.kind === "subagent" && j.agent ? `${j.agent}: ` : ""}${j.description.replace(/\s+/g, " ")}`
|
||||
const desc = fitColumns(what, descW)
|
||||
const pad = " ".repeat(Math.max(0, descW - Bun.stringWidth(desc)))
|
||||
const took = duration((j.ended ?? Date.now()) - j.started, true).padStart(6)
|
||||
const mark = unseen || j.unread > 0 ? "!" : " "
|
||||
return `${icon} ${j.id.padEnd(6)} ${desc}${pad} ${j.state.padEnd(7)} ${took} ${mark}`
|
||||
}
|
||||
|
||||
/** The Jobs picker: one row per job of the session, running first. Enter opens one (a command's
|
||||
* output, or the subagent itself), k stops it, esc closes. The list is a snapshot, so while it is
|
||||
* shown it redraws itself on the session's job events — at most four times a second — and the
|
||||
* cursor stays where it was (the dialog is the same one; only its rows change). */
|
||||
function openJobs(c: CommandCtx) {
|
||||
if (!c.app.jobs().length) return c.view.info("no jobs in this session — the model starts one with bash background: true or task background: true, and a long command moves there at its timeout (or ctrl+b)")
|
||||
c.view.seenJobs()
|
||||
const width = () => Math.min(100, c.dims().width - 4)
|
||||
const icon = (j: Job) => c.theme().toolEmoji[j.kind === "command" ? "bash" : "task"] ?? c.theme().icons.other
|
||||
// The dialog draws two columns before the label (the current marker), and its border and padding.
|
||||
const rows = () => c.app.jobs().map((j) => ({ label: jobRow(c.app.registry.info(j), width() - 6, icon(j), c.view.state.jobs.find((x) => x.id === j.id)?.unseen), value: j.id }))
|
||||
let open = true
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const onClose = () => {
|
||||
open = false
|
||||
off()
|
||||
clearTimeout(timer)
|
||||
}
|
||||
const spec = (): DialogSpec => ({
|
||||
title: "Jobs",
|
||||
width: width(),
|
||||
filter: true,
|
||||
options: rows(),
|
||||
hint: "↑↓ move · enter open · k stop · esc close · type to filter",
|
||||
keys: [{ when: (k) => k.name === "k" && !k.ctrl && !k.meta, run: (id) => stopJob(c, id, () => openJobs(c)) }],
|
||||
onSelect: (id) => openJob(c, id),
|
||||
onClose,
|
||||
})
|
||||
const off = c.app.bus.on((e) => {
|
||||
if (e.type !== "job" || !open || timer) return
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined
|
||||
if (open) c.openDialog(spec())
|
||||
}, 250)
|
||||
})
|
||||
c.openDialog(spec())
|
||||
}
|
||||
|
||||
/** Open one job: a command's live output, or the subagent itself. */
|
||||
function openJob(c: CommandCtx, id: string) {
|
||||
const job = c.app.registry.get(c.app.jobsSessionId(), id)
|
||||
if (!job) return c.view.info(`no job ${id} in this session — /jobs lists them`, "warn")
|
||||
if (job.kind === "command") c.openJob(id)
|
||||
else c.enterJob(id)
|
||||
}
|
||||
|
||||
/** Stop one job. A running subagent is asked about first (its report so far becomes its end note);
|
||||
* a command is stopped at once. `then`: what follows either way — the picker comes back. */
|
||||
function stopJob(c: CommandCtx, id: string, then?: () => void) {
|
||||
const job = c.app.registry.get(c.app.jobsSessionId(), id)
|
||||
if (!job) return c.view.info(`no job ${id} in this session — /jobs lists them`, "warn")
|
||||
if (job.state !== "running") {
|
||||
c.view.info(`${id} is not running (${job.state})`)
|
||||
return then?.()
|
||||
}
|
||||
const stop = () => {
|
||||
c.app.registry.stop(job)
|
||||
c.flash(`stopping ${id}`)
|
||||
}
|
||||
if (job.kind !== "subagent") {
|
||||
stop()
|
||||
return then?.()
|
||||
}
|
||||
c.openDialog({
|
||||
title: `Stop ${id} (${job.agent}: ${fitColumns(job.description, 40)})?`,
|
||||
options: [
|
||||
{ label: "Stop", value: "yes", description: "what it has so far goes to the model as its end note" },
|
||||
{ label: "Cancel", value: "no" },
|
||||
],
|
||||
onSelect: (v) => {
|
||||
if (v === "yes") stop()
|
||||
then?.()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function firstUserLine(c: CommandCtx, id: string): string {
|
||||
const m = c.app.store?.messages(id).find((x) => x.role === "user")
|
||||
if (!m || m.role !== "user") return ""
|
||||
@@ -1113,6 +1234,8 @@ function confirmDelete(c: CommandCtx, id: string, current = false, then?: () =>
|
||||
],
|
||||
onSelect: async (v) => {
|
||||
if (v !== "yes") return then?.()
|
||||
// A deleted session's jobs go with it.
|
||||
c.app.registry.stopAll(id)
|
||||
if (current) {
|
||||
c.app.cancel()
|
||||
c.app.newSession()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { RGBA, TextAttributes } from "@opentui/core"
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
import { createMemo, createSignal, For, Show } from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, For, onCleanup, Show } from "solid-js"
|
||||
import { useTui } from "../context.ts"
|
||||
|
||||
export interface Option {
|
||||
@@ -24,6 +24,12 @@ export interface DialogSpec {
|
||||
/** The footer in place of `↑↓ move · enter choose · esc close`, to name those keys: a
|
||||
* binding nobody is told about is one nobody finds, which is how delete went unseen in /sessions. */
|
||||
hint?: string
|
||||
/** Columns the box may take (72 by default; the terminal less four is the ceiling either way):
|
||||
* a list whose rows are columns of their own (/jobs) asks for more. */
|
||||
width?: number
|
||||
/** The dialog is gone, however it went (chosen, esc, replaced): a list that follows events
|
||||
* while it is shown stops following here. */
|
||||
onClose?: () => void
|
||||
}
|
||||
|
||||
const CUSTOM = "\u0000custom"
|
||||
@@ -41,6 +47,14 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
})
|
||||
const start = Math.max(0, p.spec.options.findIndex((o) => o.current))
|
||||
const [sel, setSel] = createSignal(start)
|
||||
// The spec is live: a list that redraws itself with fewer rows keeps the cursor on a row.
|
||||
createEffect(() => {
|
||||
const n = shown().length
|
||||
if (n && sel() >= n) setSel(n - 1)
|
||||
})
|
||||
// Taken once: the spec that opened the dialog says what to do when it goes.
|
||||
const onClose = p.spec.onClose
|
||||
onCleanup(() => onClose?.())
|
||||
const visible = () => Math.max(3, Math.min(14, dims().height - 10))
|
||||
const offset = () => Math.max(0, Math.min(sel() - Math.floor(visible() / 2), shown().length - visible()))
|
||||
|
||||
@@ -80,7 +94,7 @@ export function Dialog(p: { spec: DialogSpec; close: () => void }) {
|
||||
key.stopPropagation()
|
||||
})
|
||||
|
||||
const width = () => Math.min(72, dims().width - 4)
|
||||
const width = () => Math.min(p.spec.width ?? 72, dims().width - 4)
|
||||
return (
|
||||
<box position="absolute" zIndex={100} left={0} top={0} width={dims().width} height={dims().height} alignItems="center" paddingTop={Math.max(1, Math.floor(dims().height / 6))} backgroundColor={RGBA.fromInts(0, 0, 0, 140)}>
|
||||
<box width={width()} border borderStyle="rounded" borderColor={c().border} backgroundColor={c().menu} flexDirection="column" paddingLeft={1} paddingRight={1} title={` ${p.spec.title} `} titleColor={c().title}>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { RGBA, type ScrollBoxRenderable } from "@opentui/core"
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
import { createSignal, onCleanup } from "solid-js"
|
||||
import { duration } from "../../duration.ts"
|
||||
import { useTui } from "../context.ts"
|
||||
import { jobWords } from "./messages.tsx"
|
||||
|
||||
/** Of a command's output, how much the view draws: the end of it (the whole buffer is 2 MB). */
|
||||
const SHOWN = 32_000
|
||||
|
||||
/** A command job, live: `job3 · running 1m 12s · k stop · pgup/pgdn scroll · esc back` over a box
|
||||
* that follows the tail of its output. Redrawn on the job's events and once a second for the
|
||||
* clock. Lines longer than the box wrap by character, so nothing is wider than the terminal. */
|
||||
export function JobView(p: { id: string; close: () => void }) {
|
||||
const { theme, dims, app, view } = useTui()
|
||||
const c = () => theme().colors
|
||||
const [rev, setRev] = createSignal(0)
|
||||
const bump = () => setRev((n) => n + 1)
|
||||
const job = () => (rev(), app.registry.get(app.jobsSessionId(), p.id))
|
||||
const off = app.bus.on((e) => e.type === "job" && e.job.id === p.id && bump())
|
||||
const clock = setInterval(bump, 1000)
|
||||
onCleanup(() => {
|
||||
off()
|
||||
clearInterval(clock)
|
||||
})
|
||||
// Looked at: not news any more.
|
||||
view.seenJobs(p.id)
|
||||
const [stopping, setStopping] = createSignal(false)
|
||||
let box: ScrollBoxRenderable | undefined
|
||||
|
||||
useKeyboard((key) => {
|
||||
if (key.name === "escape") p.close()
|
||||
else if (key.name === "k" && !key.ctrl && !key.meta) {
|
||||
const j = job()
|
||||
if (j && j.state === "running") {
|
||||
app.registry.stop(j)
|
||||
setStopping(true)
|
||||
}
|
||||
} else if (key.name === "pageup") box?.scrollBy(-Math.max(1, Math.floor((box.height || 2) / 2)))
|
||||
else if (key.name === "pagedown") box?.scrollBy(Math.max(1, Math.floor((box.height || 2) / 2)))
|
||||
else return
|
||||
key.preventDefault()
|
||||
key.stopPropagation()
|
||||
})
|
||||
|
||||
const head = () => {
|
||||
const j = job()
|
||||
if (!j) return `${p.id} · gone · esc back`
|
||||
const state = j.state === "running" ? `running ${duration(Date.now() - j.started, true)}${stopping() ? " · stopping…" : ""}` : jobWords(j)
|
||||
return [j.id, state, ...(j.state === "running" ? ["k stop"] : []), "pgup/pgdn scroll", "esc back"].join(" · ")
|
||||
}
|
||||
// What it is: the model's description, and the command itself where that says more.
|
||||
const what = () => {
|
||||
const j = job()
|
||||
if (!j) return ""
|
||||
if (j.kind === "subagent") return `${j.agent ?? "subagent"}: ${j.description}`
|
||||
const line = (j.command ?? "").split("\n")[0]!
|
||||
return line && line !== j.description ? `${j.description} · $ ${line}` : j.description
|
||||
}
|
||||
const tail = () => {
|
||||
const out = job()?.output ?? ""
|
||||
return (out.length > SHOWN ? `…${out.slice(-SHOWN)}` : out) || "(no output yet)"
|
||||
}
|
||||
const width = () => Math.max(20, dims().width - 4)
|
||||
const height = () => Math.max(6, dims().height - 4)
|
||||
return (
|
||||
<box position="absolute" zIndex={100} left={0} top={0} width={dims().width} height={dims().height} alignItems="center" paddingTop={1} backgroundColor={RGBA.fromInts(0, 0, 0, 140)}>
|
||||
<box width={width()} height={height()} border borderStyle="rounded" borderColor={c().border} backgroundColor={c().menu} flexDirection="column" paddingLeft={1} paddingRight={1} title={` ${p.id} `} titleColor={c().title}>
|
||||
<box flexDirection="column" flexShrink={0} height={2}>
|
||||
<text fg={c().info} wrapMode="none" truncate height={1}>
|
||||
{head()}
|
||||
</text>
|
||||
<text fg={c().muted} wrapMode="none" truncate height={1}>
|
||||
{what()}
|
||||
</text>
|
||||
</box>
|
||||
<scrollbox ref={(r: ScrollBoxRenderable) => (box = r)} flexGrow={1} stickyScroll stickyStart="bottom" scrollX={false} viewportOptions={{ paddingRight: 1 }} verticalScrollbarOptions={{ trackOptions: { backgroundColor: c().panel, foregroundColor: c().dim } }}>
|
||||
<text fg={c().text} wrapMode="char">
|
||||
{tail()}
|
||||
</text>
|
||||
</scrollbox>
|
||||
</box>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
@@ -113,6 +113,13 @@ function Reasoning(p: { item: Extract<Item, { kind: "reasoning" }> }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** How a job is doing, in a word or two: `running…`, `done · 1m 12s`, `stopped · 4s`. */
|
||||
export function jobWords(j: { state: string; started: number; ended?: number; exit?: number | null }): string {
|
||||
if (j.state === "running") return "running…"
|
||||
const took = duration((j.ended ?? Date.now()) - j.started, true)
|
||||
return `${j.state}${j.state !== "lost" && j.exit !== undefined && j.exit !== null && j.exit !== 0 ? ` (exit ${j.exit})` : ""} · ${took}`
|
||||
}
|
||||
|
||||
function ToolLine(p: { item: Extract<Item, { kind: "tool" }> }) {
|
||||
const { theme, view } = useTui()
|
||||
const c = () => theme().colors
|
||||
@@ -134,6 +141,14 @@ function ToolLine(p: { item: Extract<Item, { kind: "tool" }> }) {
|
||||
<span style={{ fg: c().error }}> ✗</span>
|
||||
</Show>
|
||||
</text>
|
||||
<Show when={p.item.job}>
|
||||
<text wrapMode="none" truncate>
|
||||
<span style={{ fg: c().dim }}>{" → "}</span>
|
||||
<span style={{ fg: c().label }}>{p.item.job!.id}</span>
|
||||
<span style={{ fg: c().muted }}>{` (${p.item.job!.agent ? `${p.item.job!.agent}: ` : ""}${p.item.job!.description})`}</span>
|
||||
<span style={{ fg: p.item.job!.state === "running" ? c().accent : p.item.job!.state === "error" || p.item.job!.state === "lost" ? c().error : c().dim }}>{` ${jobWords(p.item.job!)}`}</span>
|
||||
</text>
|
||||
</Show>
|
||||
<For each={p.item.children ?? []}>
|
||||
{(ch) => (
|
||||
<text wrapMode="none" truncate>
|
||||
|
||||
@@ -92,6 +92,8 @@ export function PermissionPrompt(p: { pending: Pending }) {
|
||||
})
|
||||
|
||||
const what = () => p.pending.request.command ?? p.pending.request.patterns.join(", ")
|
||||
// A subagent's ask says which one: `explore (job7): bash`.
|
||||
const title = () => (p.pending.source ? `${p.pending.source.agent} (${p.pending.source.jobId}): ${p.pending.tool}` : p.pending.tool)
|
||||
// Inside the border, the padding and the scrollbar.
|
||||
const width = () => Math.max(10, dims().width - 5)
|
||||
const purpose = () => (p.pending.purpose ? rowsOf(p.pending.purpose, width()).slice(0, 3) : [])
|
||||
@@ -116,7 +118,7 @@ export function PermissionPrompt(p: { pending: Pending }) {
|
||||
.filter(Boolean)
|
||||
.join(" · ")
|
||||
return (
|
||||
<box border borderStyle="rounded" borderColor={c().warn} paddingLeft={1} paddingRight={1} flexDirection="column" flexShrink={0} title={` ${p.pending.tool} `} titleColor={c().warn}>
|
||||
<box border borderStyle="rounded" borderColor={c().warn} paddingLeft={1} paddingRight={1} flexDirection="column" flexShrink={0} title={` ${title()} `} titleColor={c().warn}>
|
||||
<Show when={purpose().length}>
|
||||
<text fg={c().accent} wrapMode="none">
|
||||
{purpose().join("\n")}
|
||||
|
||||
@@ -40,6 +40,9 @@ export function Prompt(p: {
|
||||
queue?: { count(): number; take(index: number): string | undefined; putBack(index: number, text: string): void }
|
||||
/** A burst of ↑/↓ that was a mouse wheel: scroll the transcript `lines` up (-1) or down (1). */
|
||||
onWheel?: (dir: -1 | 1, lines: number) => void
|
||||
/** ctrl+b: the foreground command goes to the background now. Taken here because the textarea
|
||||
* itself binds ctrl+b (move left) and would keep the key. */
|
||||
onBackground?: () => void
|
||||
}) {
|
||||
const { theme } = useTui()
|
||||
const c = () => theme().colors
|
||||
@@ -233,6 +236,10 @@ export function Prompt(p: {
|
||||
onKeyDown={(e) => {
|
||||
if (!area) return
|
||||
if (e.ctrl && e.name === "v" && pasteClipboardImage()) return e.preventDefault()
|
||||
if (e.ctrl && e.name === "b" && p.onBackground) {
|
||||
p.onBackground()
|
||||
return e.preventDefault()
|
||||
}
|
||||
const pop = popup()
|
||||
if (pop) {
|
||||
const n = pop.items.length
|
||||
|
||||
@@ -9,8 +9,19 @@ export function fmtTokens(n: number): string {
|
||||
return n >= 10_000 ? `${Math.round(n / 1000)}k` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
|
||||
}
|
||||
|
||||
/** One line: mode · model · effort on the left; context use and where on the right — or, for a
|
||||
* moment, a flash (a copy) in their place. */
|
||||
/** The status bar's word for the session's jobs: the running count, `!` when one ended unseen or
|
||||
* holds output the model has not read; nothing while there is nothing to say. */
|
||||
export function jobsWord(jobs: { state: string; unread: number; unseen?: boolean }[]): string {
|
||||
const running = jobs.filter((j) => j.state === "running").length
|
||||
const news = jobs.some((j) => j.unseen || j.unread > 0)
|
||||
if (!running && !news) return ""
|
||||
return `${running} job${running === 1 ? "" : "s"}${news ? "!" : ""}`
|
||||
}
|
||||
|
||||
/** One line: mode · model · effort on the left; the jobs, context use and where on the right — or,
|
||||
* for a moment, a flash (a copy) in their place. The jobs word sits on the right, which is never
|
||||
* truncated: at 80 columns a long project name cuts the left short, and a running job is the one
|
||||
* thing that must stay visible. */
|
||||
export function StatusBar(p: { mode: () => string; model: () => string; effort: () => string; branch?: string; voice?: () => string; flash?: () => string | undefined; remote?: () => string; credits?: () => string }) {
|
||||
const { theme, view, app } = useTui()
|
||||
const c = () => theme().colors
|
||||
@@ -39,6 +50,7 @@ export function StatusBar(p: { mode: () => string; model: () => string; effort:
|
||||
when={p.flash?.()}
|
||||
fallback={
|
||||
<text wrapMode="none">
|
||||
<span style={{ fg: jobsWord(view.state.jobs).endsWith("!") ? c().statusWarn : c().statusText }}>{jobsWord(view.state.jobs) ? `${jobsWord(view.state.jobs)} · ` : ""}</span>
|
||||
<span style={{ fg: c().statusDim }}>{view.state.rate ? `${Math.round(view.state.rate)} tok/s · ` : ""}</span>
|
||||
<span style={{ fg: c().statusText }}>{p.credits?.() ? `${p.credits()} · ` : ""}</span>
|
||||
<span style={{ fg: ctx().color }}>{ctx().text}</span>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { ScrollBoxRenderable } from "@opentui/core"
|
||||
import { createSignal, onCleanup } from "solid-js"
|
||||
import { duration } from "../../duration.ts"
|
||||
import { TuiContext, useTui } from "../context.ts"
|
||||
import type { View } from "../state.ts"
|
||||
import { jobWords } from "./messages.tsx"
|
||||
import { Messages } from "./messages.tsx"
|
||||
|
||||
/** A subagent entered from /jobs: its transcript in place of the session's, under a header line
|
||||
* `subagent explore · job7 · running 1m 12s · esc back · type to message`. The items are the
|
||||
* child's own View (fed by its bus; Root keeps one per job), read-only here; what is typed goes to
|
||||
* the job through Root. The clock ticks while it runs. */
|
||||
export function SubagentView(p: { id: string; view: View; scrollRef?: (r: ScrollBoxRenderable) => void }) {
|
||||
const ctx = useTui()
|
||||
const { theme, app } = ctx
|
||||
const c = () => theme().colors
|
||||
const [rev, setRev] = createSignal(0)
|
||||
const bump = () => setRev((n) => n + 1)
|
||||
const job = () => (rev(), app.registry.get(app.jobsSessionId(), p.id))
|
||||
const off = app.bus.on((e) => e.type === "job" && e.job.id === p.id && bump())
|
||||
const clock = setInterval(bump, 1000)
|
||||
onCleanup(() => {
|
||||
off()
|
||||
clearInterval(clock)
|
||||
})
|
||||
const head = () => {
|
||||
const j = job()
|
||||
if (!j) return `subagent · ${p.id} · gone · esc back`
|
||||
const state = j.state === "running" ? `running ${duration(Date.now() - j.started, true)}` : jobWords(j)
|
||||
const message = j.subagent ? "type to message" : "cannot be messaged (an earlier process ran it)"
|
||||
return [`subagent ${j.agent ?? ""}`.trimEnd(), j.id, state, "esc back", message].join(" · ")
|
||||
}
|
||||
const what = () => job()?.description ?? ""
|
||||
return (
|
||||
<box flexDirection="column" flexGrow={1}>
|
||||
<box flexDirection="column" paddingLeft={1} flexShrink={0} height={2} backgroundColor={c().panel}>
|
||||
<text fg={c().info} wrapMode="none" truncate height={1}>
|
||||
{head()}
|
||||
</text>
|
||||
<text fg={c().muted} wrapMode="none" truncate height={1}>
|
||||
{what()}
|
||||
</text>
|
||||
</box>
|
||||
<TuiContext.Provider value={{ ...ctx, view: p.view }}>
|
||||
<scrollbox
|
||||
ref={(r: ScrollBoxRenderable) => p.scrollRef?.(r)}
|
||||
flexGrow={1}
|
||||
stickyScroll
|
||||
stickyStart="bottom"
|
||||
viewportOptions={{ paddingRight: 1 }}
|
||||
verticalScrollbarOptions={{ trackOptions: { backgroundColor: c().panel, foregroundColor: c().dim } }}
|
||||
>
|
||||
<Messages />
|
||||
</scrollbox>
|
||||
</TuiContext.Provider>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
+5
-3
@@ -14,9 +14,11 @@ export const PLAIN: { toolEmoji: Record<string, string>; icons: { mcp: string; o
|
||||
grep: "/",
|
||||
list: "▤",
|
||||
bash: "$",
|
||||
bash_output: "›",
|
||||
bash_list: "›",
|
||||
bash_kill: "×",
|
||||
job_output: "›",
|
||||
job_list: "›",
|
||||
job_stop: "×",
|
||||
job_send: "→",
|
||||
report: "←",
|
||||
plan_write: "▣",
|
||||
plan_update: "▣",
|
||||
ask_user: "?",
|
||||
|
||||
+5
-3
@@ -128,9 +128,11 @@ export const HERMES: Theme = {
|
||||
grep: "🔎",
|
||||
list: "📂",
|
||||
bash: "💻",
|
||||
bash_output: "📜",
|
||||
bash_list: "📜",
|
||||
bash_kill: "🛑",
|
||||
job_output: "📜",
|
||||
job_list: "📜",
|
||||
job_stop: "🛑",
|
||||
job_send: "📨",
|
||||
report: "📨",
|
||||
plan_write: "📋",
|
||||
plan_update: "📋",
|
||||
ask_user: "❓",
|
||||
|
||||
+62
-5
@@ -11,13 +11,16 @@ import type { Plan } from "../plan/plan.ts"
|
||||
import type { PlanReply, PlanRequest } from "../tool/plan_submit.ts"
|
||||
import type { QuestionReply, QuestionRequest } from "../tool/ask_user.ts"
|
||||
import { CONTINUE_PROMPT, STEER_MARK } from "../session/engine.ts"
|
||||
import { shownLine, stripMark } from "../jobs/note.ts"
|
||||
import type { JobInfo } from "../jobs/registry.ts"
|
||||
import { splitPrototypes, titleFor, type PrototypeKind } from "../prototype/fence.ts"
|
||||
import { savePrototype } from "../prototype/store.ts"
|
||||
import { CHARS_PER_TOKEN } from "../provider/tokens.ts"
|
||||
|
||||
export type Item =
|
||||
/** `mid`: sent while the agent worked, and given to it at a step boundary. */
|
||||
| { kind: "user"; id: string; text: string; mid?: boolean }
|
||||
/** `mid`: sent while the agent worked, and given to it at a step boundary. `machine`: the harness
|
||||
* said it (a job's note), not the person. */
|
||||
| { kind: "user"; id: string; text: string; mid?: boolean; machine?: boolean }
|
||||
/** `prototypes`: the prototype fences in the text that have been saved, by where each starts. */
|
||||
| { kind: "assistant"; id: string; text: string; streaming: boolean; prototypes?: Record<number, SavedPrototype> }
|
||||
| { kind: "reasoning"; id: string; text: string; streaming: boolean; started: number; ms?: number; tokens?: number }
|
||||
@@ -33,6 +36,10 @@ export type Item =
|
||||
diff?: string
|
||||
/** A subagent's tool lines (the task tool), newest last. */
|
||||
children?: { name: string; title: string; isError?: boolean }[]
|
||||
/** The background job this call started (bash background, a background task), and how it is
|
||||
* doing — from the `job` events, for the line under the call. */
|
||||
jobId?: string
|
||||
job?: JobInfo
|
||||
}
|
||||
| { kind: "notice"; id: string; text: string; level: "info" | "warn" }
|
||||
| { kind: "diff"; id: string; title: string; patch: string }
|
||||
@@ -73,9 +80,14 @@ export interface Pending {
|
||||
preview?: { diff?: string; error?: string }
|
||||
/** What the model says the call is for. */
|
||||
purpose?: string
|
||||
/** The subagent (running as a job) that asks, when one does. */
|
||||
source?: { jobId: string; agent: string; description: string }
|
||||
resolve: (r: AskReply) => void
|
||||
}
|
||||
|
||||
/** A job as the TUI keeps it: the registry's record, and whether the person has seen it end. */
|
||||
export type TrackedJob = JobInfo & { unseen?: boolean }
|
||||
|
||||
export interface PendingQuestion {
|
||||
req: QuestionRequest
|
||||
resolve: (r: QuestionReply) => void
|
||||
@@ -105,14 +117,18 @@ export interface ViewState {
|
||||
queued: { texts: string[]; mode: "steer" | "queue" }
|
||||
/** The server reading the prompt (llama.cpp): set while it reads, gone once the reply starts. */
|
||||
progress?: { total: number; done: number; processed: number; ms: number }
|
||||
/** The session's background jobs (the registry's list, kept from `job` events), running first. */
|
||||
jobs: TrackedJob[]
|
||||
}
|
||||
|
||||
const ATTACHMENT = /^<(file|directory|shell|image) /
|
||||
/** Running first, then by start — the registry's order. */
|
||||
const byRunning = (a: JobInfo, b: JobInfo) => Number(b.state === "running") - Number(a.state === "running") || a.started - b.started
|
||||
let seq = 0
|
||||
const nextId = () => `i${++seq}`
|
||||
|
||||
export function createView(bus: Bus) {
|
||||
const [state, set] = createStore<ViewState>({ items: [], phase: "idle", busySince: 0, showReasoning: false, expandTools: false, queued: { texts: [], mode: "steer" } })
|
||||
const [state, set] = createStore<ViewState>({ items: [], phase: "idle", busySince: 0, showReasoning: false, expandTools: false, queued: { texts: [], mode: "steer" }, jobs: [] })
|
||||
let stepStart = 0
|
||||
// The task's output tokens (every step, subagents included), and the reply
|
||||
// streaming now, counted as it arrives so the number moves before the step's usage comes in.
|
||||
@@ -187,6 +203,11 @@ export function createView(bus: Bus) {
|
||||
case "session":
|
||||
set("sessionId", e.id)
|
||||
break
|
||||
case "prompt":
|
||||
// A turn the harness started (a job's note): shown as such. A typed prompt is shown by
|
||||
// whoever sent it (view.user), as it was typed.
|
||||
if (e.machine) set(produce((s) => void s.items.push({ kind: "user", id: nextId(), text: e.text, machine: true })))
|
||||
break
|
||||
case "step":
|
||||
set(produce((s) => settle(s)))
|
||||
stepStart = state.items.length
|
||||
@@ -222,6 +243,10 @@ export function createView(bus: Bus) {
|
||||
it.ms = e.ms
|
||||
it.output = e.result.output
|
||||
it.diff = typeof e.result.meta?.diff === "string" ? (e.result.meta.diff as string) : undefined
|
||||
if (typeof e.result.meta?.job === "string") {
|
||||
it.jobId = e.result.meta.job
|
||||
it.job = state.jobs.find((j) => j.id === it.jobId)
|
||||
}
|
||||
}),
|
||||
)
|
||||
break
|
||||
@@ -263,7 +288,23 @@ export function createView(bus: Bus) {
|
||||
(it) => it.kind === "tool" && it.id === e.callId,
|
||||
produce((it) => {
|
||||
if (it.kind !== "tool") return
|
||||
it.children = [...(it.children ?? []), { name: e.name, title: e.title, isError: e.isError }].slice(-8)
|
||||
// Every line while it runs; a stored session shows none (they are not kept).
|
||||
it.children = [...(it.children ?? []), { name: e.name, title: e.title, isError: e.isError }]
|
||||
}),
|
||||
)
|
||||
break
|
||||
case "job":
|
||||
set(
|
||||
produce((s) => {
|
||||
const i = s.jobs.findIndex((j) => j.id === e.job.id)
|
||||
const was = i >= 0 ? s.jobs[i] : undefined
|
||||
// Ended: news until the person looks at the list or at the job.
|
||||
const unseen = e.state === "end" ? true : was?.unseen
|
||||
const next: TrackedJob = { ...e.job, ...(unseen ? { unseen } : {}) }
|
||||
if (i >= 0) s.jobs[i] = next
|
||||
else s.jobs.push(next)
|
||||
s.jobs.sort(byRunning)
|
||||
for (const it of s.items) if (it.kind === "tool" && it.jobId === e.job.id) it.job = e.job
|
||||
}),
|
||||
)
|
||||
break
|
||||
@@ -403,7 +444,19 @@ export function createView(bus: Bus) {
|
||||
set(produce((s) => void s.items.push({ kind: "diff", id: nextId(), title, patch })))
|
||||
},
|
||||
clear() {
|
||||
set({ items: [], usage: undefined, used: undefined })
|
||||
set({ items: [], usage: undefined, used: undefined, jobs: [] })
|
||||
},
|
||||
/** The session's jobs as the registry has them now (at a start or a resume, before any event). */
|
||||
setJobs(list: JobInfo[]) {
|
||||
set("jobs", [...list].sort(byRunning))
|
||||
},
|
||||
/** The person looked at the list (or at one job): nothing is unseen any more. */
|
||||
seenJobs(id?: string) {
|
||||
set(
|
||||
produce((s) => {
|
||||
for (const j of s.jobs) if (id === undefined || j.id === id) delete j.unseen
|
||||
}),
|
||||
)
|
||||
},
|
||||
toggleReasoning() {
|
||||
set("showReasoning", (v) => !v)
|
||||
@@ -420,6 +473,10 @@ export function createView(bus: Bus) {
|
||||
items.push({ kind: "user", id: nextId(), text: "↻ continue" })
|
||||
else if (m.role === "user" && m.parts[0]?.type === "text" && m.parts[0].text.startsWith(STEER_MARK))
|
||||
items.push({ kind: "user", id: nextId(), text: m.parts[0].text.slice(STEER_MARK.length).trim(), mid: true })
|
||||
else if (m.role === "user" && m.machine && m.parts[0]?.type === "text") items.push({ kind: "user", id: nextId(), text: shownLine(m.parts[0].text), machine: true })
|
||||
else if (m.role === "user" && m.parts[0]?.type === "text" && stripMark(m.parts[0].text).mark)
|
||||
// A job's note given mid-turn: without its mark, as a steer is shown.
|
||||
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") })
|
||||
|
||||
Reference in new issue
Block a user