SLOPSHOPPER

awsh

awsh for Claude Code: an `aw` subagent type whose model steps are answered by a session on the local awsh harness daemon, so any harness and any backend the…

guardtoolprocessnetworkagents
★ 11v0.2.2MITupdated 2026-10-21Aitherium/awdk/adk/harnesses/claude_mod
A shopper browsing a rack in a slop shop
README

Aither ADK — Build AI Agent Fleets

<!-- aither-header:start GENERATED from the ecosystem registry. Edits here are overwritten; change the registry instead. -->

Docs · Source · pip install awdk · The Aither World

The Aither World is an operating system for agents — a Linux you can hand to one, the runtimes it works in, and the tools it works with. awnix is the Linux underneath it; awdk is one of its 69 bricks — each installs on its own, runs offline, and needs no account.

Start here: Point it at a backend you already pay for and run one agent loop.

<!-- aither-header:end -->

<!-- mcp-name: io.github.Aitherium/awdk -->

PyPI License: BSL 1.1 Docs

3 lines of code. Any backend. Local or cloud. Zero lock-in.

Aither ADK is a Python SDK + CLI for building AI agents that run on your hardware — a single helpful agent or a coordinated fleet that delegates work to each other. Agents get tools, persistent knowledge-graph memory, safety filtering, and effort-based model routing out of the box. Swap the LLM backend at runtime — your GPU, llama.cpp, or any cloud API — same code, same agents.

pip install awdk
adk quickstart                                    # auto-detect hardware, set up inference
adk init my-agent && cd my-agent && python agent.py

The package is awdk; the command is adk (awdk is the same command, and python -m adk always works). Windows, "adk is not recognized"? pip put the command in a Scripts folder that is not on PATH — its warning names the folder. Add it once, then open a new terminal:

$s = python -c "import sysconfig; print(sysconfig.get_path('scripts'))"
[Environment]::SetEnvironmentVariable('Path', "$([Environment]::GetEnvironmentVariable('Path','User'));$s", 'User')

Get running in 60 seconds — pick your path

You have…Run thisYou get
Nothing — not even Pythonone-line installer (below)isolated env + first-run wizard
No GPU, no API keyadk bonsai-localBonsai running free, offline, on CPU or GPU — native, no container; picks the size that fits, serves on :8090
A GPU (6 GB+)adk quickstartauto-detected vLLM/llama.cpp, models pulled, ready to chat
Just an API keyadk quickstart --cloudcloud inference (Anthropic / OpenAI / DeepSeek)
A whole LAN of machinesadk deploy gridmulti-machine effort-routed inference

The no-Python one-liner — sets up an isolated environment (via uv) and launches the wizard:

# macOS / Linux
curl -fsSL https://aitherium.com/install.sh | sh
# Windows
powershell -ExecutionPolicy ByPass -c "irm https://aitherium.com/install.ps1 | iex"

Then, whichever path you took:

adk start          # chat with your agent (zero config)
adk doctor         # something wrong? this names it

Using an AI coding agent (Claude Code, Cursor, Copilot)? Paste the Agent Setup Prompt into your session — it walks the agent through install, auth, inference, and the path from zero to fleet. There's also llms.txt / llms-full.txt for tools that ingest those.


Contents


New here? The five concepts

Everything in the ADK hangs off five ideas:

  1. Agent — AitherAgent("aither"). One object: await agent.chat("...") is the whole API. It has a persona, tools, and memory.
  2. Backend — where inference runs. Local (vLLM / llama.cpp / Bonsai) or cloud (Anthropic / OpenAI / DeepSeek / Aitherium gateway). Switchable at runtime, mid-session.
  3. Effort routing — every call carries a 1–10 effort level; cheap calls go to small fast models, hard calls go to the big reasoning model. Automatically. You never pick a model per call again.
  4. Memory — a local SQLite knowledge graph that auto-ingests entities and relations from every conversation. Hybrid keyword + semantic search. No external services.
  5. Fleet — multiple agents that can call each other via the built-in ask_agent tool. One YAML file, one adk-serve command, and you have an orchestrator delegating to specialists.

If you only remember one thing: agent.chat() is the agent. Everything else is configuration.

Documentation map

I want to…Read this
Drive Claude Code / Codex / OpenCode / Aider from one shellAWSH-OMNISHELL-PLAYBOOK.md — install → detect → daemon → UI, verified end to end
Build a real agent or publish a packdocs/AGENT_DEV_GUIDE.md — the golden path + gotcha checklist
Self-host the full managed-agent experienceQUICKSTART_SELF_HOSTED.md — adk onboard --quick
Operate a self-hosted node long-termdocs/SELF_HOSTING_RUNBOOK.md
Run inference across several machinesGRID_SETUP.md
Wire up a specific LLM providerdocs/providers/ — DeepSeek, Kimi, OpenAI-compatible, local AitherOS
Give my agent a persistent identity/personadocs/PERSONA.md · `adk soul importexport`
Understand the world-model layerdocs/WORLD_MODEL.md
Connect agents across machines (relay)docs/AITHERRELAY_GUIDE.md
Run a private, local-only companionPRIVATE_COMPANION.md
Reach my own agent from my phone (Aither Hearth)docs/agent-home.md — adk home serve, channels, approvals, receipts
See working codeexamples/ — five runnable scripts
See what changedCHANGELOG.md
Browse rendered docsaitherium.github.io/awdk

Interoperability

Aither agents speak three protocols for seamless integration with external systems:

1. ACP (Agent Client Protocol) — IDE Integration

Connect your agent to JetBrains, Zed, VS Code, or any ACP-compatible editor over JSON-RPC 2.0 stdio.

adk acp serve                          # Serve your agent to an editor
  • Harness ID: acp (registered in adk.harnesses.registry)
  • Transport: STRUCTURED_BIDI (JSON-RPC 2.0)
  • Usage: Agents appear as room participants in AitherShell, driven by editors that speak ACP v2

2. A2A (Agent-to-Agent) — Remote Agent Integration

Map remote A2A agents (Google A2A v0.3.0 compatible) as room participants with full task lifecycle visibility.

from adk.a2a_adapter import A2AAdapter

adapter = A2AAdapter(room_id="main", remote_agent_id="foo")
adapter.on_task_submitted("task_001", "what is AI?")
adapter.on_task_working("task_001", "thinking...")
adapter.on_task_completed("task_001", "AI is...")
  • Module: adk.a2a_adapter.A2AAdapter
  • Events: Task lifecycle maps to AitherEvents (orchestration + cognition pillars)
  • Flux codes: a2a.s (submit), a2a.u (update), a2a.d (done)
  • Actor kind: a2a — remote agents appear with their own identity in rooms

3. MCP-UI — Render Blocks as Resources

Serve agent-generated RenderBlocks (server-driven UI: tables, forms, charts, approval gates) via the MCP resource protocol using ui:// URIs.

from adk.mcp_ui_resources import RenderBlocksMCPServer, create_table_block, create_scores_block

server = RenderBlocksMCPServer()
blocks = [
    create_table_block(columns=["Issue", "Severity"], rows=[[...], [...]]),
    create_scores_block({"security": 0.92, "style": 0.78}),
]
uri = server.from_agent_response("reviewer", "task_123", blocks)
# uri -> "ui://agent/reviewer/task_123"
  • Module: adk.mcp_ui_resources.RenderBlocksMCPServer
  • Block types: 24 primitives (markdown, header, table, code, form, approve, slider, file_upload, etc.)
  • Schema validation: Block schemas are kept at parity with the AitherOS RenderBlocks protocol, so a block emitted here renders identically in any AitherOS surface
  • MIME type: application/vnd.aitheros.renderblocks+json
  • Integration: Mount into FastAPI, use in MCP clients that understand ui://

The aw packages — three questions adk can ask about a repository

adk is the agent runtime; three small, independent packages give it the facts it would otherwise have to guess at. Each answers a different question, each installs on its own, and none of the three requires the others:

PackageKnowsThe question it answers
awgraphwhat the code is, and what depends on whatWhere is this symptom coming from?
awgitwhat changed, and who is editing itIs this an in-flight edit someone else owns?
awrelaywho found what, and who still needs to hear itWho do I tell?
pip install awgraph awgit awrelay   # or any one of them, alone

Used together, an agent can find a symptom with awgraph, check whether it is an in-flight edit with awgit, and tell the agent already working that file with awrelay — three questions a solo grep-and-guess loop cannot ask at all. The failure they remove is not "the agent was wrong"; it is two agents editing the same file without knowing, and a finding that died in a transcript nobody read.

Each publishes an aither-manifest.json beside its page, and each page renders the others live from those manifests — a project whose manifest is missing shows as unknown rather than silently disappearing: awgraph · awgit · awrelay.


Subagents — drive Claude Code, Codex, and eight more

Just want it working? → AWSH-OMNISHELL-PLAYBOOK.md. Install → detect → start the daemon → use it, with verified output at each step. The step people miss is that the harness daemon has to be running: without it the desktop app reports "No harnesses reported by the daemon yet", which reads as a missing feature rather than a stopped process.

Your agent can delegate a task to another coding agent's real product — not a reimplementation of it against the raw API.

That distinction is the whole design. Rebuilding Claude Code's behaviour yourself means inheriting none of its skills, hooks or account handling, and then chasing a product that ships faster than you can track it. So the ADK resolves the real binary on PATH (honouring PATHEXT, so the Windows .cmd shim works), runs it headless with an explicit tool scope, feeds the prompt over stdin — never argv, which is visible in the process table — gives each run its own config dir so concurrent subagents can't corrupt one another's state, and tears down the process tree on timeout.

adk shell harnesses          # what can this machine drive, and how to get the rest
adk shell new --harness claude
adk shell send  <id> "refactor the retry logic in billing/"
adk shell attach <id>        # watch it work
adk shell kill  <id>         # teardown

adk shell harnesses on a typical box:

ID           INSTALLED  TRANSPORT         DESCRIPTION
claude       yes        structured-bidi   Anthropic Claude Code — bidirectional stream-json, full tool use
gemini       yes        oneshot-per-turn  Google Gemini CLI — one process per turn, stream-json output
terminal     yes        pty-stream        A real shell on this host behind a pseudo-terminal (pwsh/bash)
sandbox      NO         pty-stream        A real Linux TTY inside a dev-workspace container
                                          -> Install Docker Desktop
acp          yes        structured-bidi   JSON-RPC 2.0 stdio harness for JetBrains/Zed/VS Code editors
codex        NO         oneshot-per-turn  OpenAI Codex CLI — one process per turn (codex exec --json)
                                          -> npm i -g @openai/codex
aider        NO         oneshot-per-turn  Aider — pair-programming CLI (one process per turn)
                                          -> pip install aider-install && aider-install
opencode     NO         oneshot-per-turn  OpenCode — open-source coding agent (one process per turn)
                                          -> npm i -g opencode-ai

Ten harnesses are declared; the ones you haven't installed say so and tell you the command. It never silently pretends the world is Claude-only — a harness you don't have is a missing install, not a missing feature, and the difference is printed rather than guessed at.

Harnesses are data, not drivers

A per-agent runner does not scale — you end up with claude_runner.py, codex_runner.py, gemini_runner.py, each drifting. So a harness is a row:

HarnessSpec(
    id            = "codex",
    label         = "OpenAI Codex CLI",
    transport     = Transport.ONESHOT_PER_TURN,
    binary        = "codex",
    version_argv  = ["--version"],
    install_hint  = "npm i -g @openai/codex",
    json_lines    = True,
    build_argv    = lambda spec, launch: [spec.binary, "exec", "--json", launch.prompt],
)

Four transports cover every agent CLI shipping today: structured-bidi (a persistent bidirectional stream-json session), oneshot-per-turn (a fresh process per turn), pty-stream (a real TTY behind a pseudo-terminal), and http-stream (a remote agent over SSE). Adding an eleventh harness is a table entry, not a new module.

Scoped by construction

A subagent is launched with an explicit allow-list, and the runner re-validates it fail-closed rather than trusting the caller:

from adk.claude_runner import ClaudeRunner, RunScope

runner = ClaudeRunner()
scope  = RunScope(allowed_tools=["Read", "Grep", "Glob"])      # read-only
rec    = runner.submit(task="audit error handling in ./api", scope=scope)

rec = runner.get(rec.run_id)          # queued | running | completed | failed | cancelled
print(rec.result_text)                # one task out, one answer back
runner.kill(rec.run_id)               # teardown, whole process tree

The scope becomes --allowedTools on the real CLI, so a subagent asked to audit code cannot write to your disk — enforced by the product you delegated to, not by a prompt asking it nicely.


Quick Start

1. Set up inference (one command)

adk quickstart detects your hardware, pulls the right models, configures backends, and gets you chatting:

pip install awdk
adk quickstart                 # local GPU: detect → pull models → serve
adk quickstart --cloud         # no GPU: enter an API key (Anthropic / OpenAI / DeepSeek)
adk start                      # start chatting

Either way you get the full harness: tools, skills, memory, and multi-agent coordination.

Want the full self-hosted, managed-agent experience (local LLM → customize a pack → enroll your machine → manage it from the portal)? See QUICKSTART_SELF_HOSTED.md — adk onboard --quick does it in one command.

2. Your first agent

import asyncio
from adk import AitherAgent

async def main():
    agent = AitherAgent("aither")              # auto-detects vLLM/llama.cpp on localhost
    response = await agent.chat("Hello! What can you help me with?")
    print(response.content)

asyncio.run(main())

3. Grow into a fleet

The package ships one ready agent — aither, the orchestrator. Add specialists by installing a ready-made pack, or by defining your own. Any agent can then call any other through the built-in ask_agent tool.

# install a ready-made specialist (web research)
adk install pack:openclaw

# define a fleet — the shipped orchestrator + an installed pack + your own agent — and serve it
cat > fleet.yaml <<'YAML'
orchestrator: aither
agents:
  - identity: aither                  # ships with the package
  - identity: openclaw                # installed above
  - name: reviewer                    # your own — just give it a prompt
    system_prompt: "You review code for bugs and security issues."
YAML
adk-serve --fleet fleet.yaml --port 8080

4. Earn tokens by volunteering

Earn Aitherium tokens by contributing compute to the community embedding pool:

adk volunteer enroll                   # register as a volunteer (tenant from adk login)
adk volunteer serve                    # download the embedding model & start llama-server
adk volunteer start                    # loop: claim batches → embed → submit → earn tokens

Reputation, verified batches and earnings show in the Volunteer Compute panel of the tenant workspace (dgg.aitherium.com) and in adk volunteer status.

Why Aither?

Locked appliancesAither ADK
Their hardware, their cloudYour hardware, your rules
1 AI assistantBuild a fleet — start with aither, add ready-made packs or your own; they delegate to each other
Their model picksAny model — route by effort level automatically
Data on their serversData stays on your machine
Closed system, monthly feeOpen-core (BSL-1.1) — free, runs entirely on your box
Locked to one providerRuntime backend switching — swap LLM mid-session
Cloud-only reasoningHybrid reasoning — local orchestration + cloud deep thinking

Aither Hearth: your agent, on your phone

adk home runs one personal agent on your machine that answers only you, on the chat apps you already use. The same CLI is installed as aither-hearth.

adk home init --name pip                  # ~/.aither/agent-home: persona, model, memory
adk home model --byo anthropic            # or --local llamacpp | bonsai
adk home model --check
adk home signin                           # Sign in with Aitherium
export HEARTH_TELEGRAM_TOKEN=...          # a Telegram bot token from @BotFather
adk home serve --channels telegram --pair # prints a 6-digit code: DM it to the bot
  • Serve and channels. adk home serve answers you on the relay, Telegram, Discord, Slack, email, WhatsApp and SMS: every channel whose credentials are in the environment (adk home channels shows which), or exactly the ones in --channels. Pair another channel by sending pair <channel> from one that is already paired.
  • It messages you first. Reminders and follow-ups you ask for arrive on the channel you last used.
  • Approvals. Anything that sends, books or adds (an email, a calendar event, a to-do, a recurring follow-up) waits for your yes <code> on the channel the request arrived on.
  • Receipts. Every action is appended to a signed, hash-chained log: adk home receipts --verify exits 0 intact, 1 tampered, 2 cannot judge. adk home trust status shows what is enforced.
  • Connectors (optional). After adk home signin, a workspace admin connects a Google account at api.aitherium.com/admin?tab=connections (admin-only); the agent can then read your agenda and mail, and add to them only after an approval. Microsoft 365 is not available yet.
  • Local window. adk home say "...", adk home events and /hearth in adk-shell talk to the running serve over 127.0.0.1 instead of starting a second agent.

Everything above is free. The paid agent-home pack adds learning that carries across game sessions and more than one agent at a time. Full guide: docs/agent-home.md.


Bonsai: an agent on literally anything

No GPU. No API key. No account. Nothing leaves your machine.

Bonsai is Aitherium's family of ultra-compact models built to make agents sovereign by default — they run on hardware everyone already owns. The 1-bit Bonsai-27B runs on a plain CPU with 4 GB of RAM; Bonsai-4B runs in 2 GB (Android via Termux, Raspberry Pi Zero). Agents on Bonsai get the full harness — tool calling, memory, safety, fleets — not a demo mode.

adk bonsai-local --status       # what fits this machine (1.7B, 4B, 8B, 27B, Bonsai 2 27B)
adk bonsai-local                # native, no Docker: the largest size that fits, served on :8090
adk bonsai-local --model bonsai-8b   # or pick one; --container keeps the Docker image path

Why this matters, concretely:

  • Free forever, offline after setup — one network pull for the model/image, then a fully working agent with zero external dependencies. Air-gapped targets work too: fetch the artifacts on a connected machine and sideload them.
  • Tool calling works — Bonsai drives the same @tool functions, ask_agent delegation, and pack skills as the big models.
  • Private by construction — no key means no telemetry decision to trust; there is simply no wire out.
  • A floor, not a ceiling — start on Bonsai today, add a GPU tier or a cloud reasoning backend later; your agent code does not change.

When you outgrow it, effort routing lets you keep Bonsai for the cheap calls and send only the hard ones somewhere bigger — see hybrid profiles.


Reasoning capture & code intelligence

Three packs added in 3.2.0. Each exists because of something the platform's chat models structurally cannot do.

External thinking — get the chain of thought back

Providers stopped returning raw reasoning. The recovery, from Oh My Pi's externalThinking (MIT), needs no jailbreak: turn the model's native reasoning channel off, then give it a tool whose only parameter is a string described as a private scratchpad. It keeps reasoning — into the tool call, which the API returns in plaintext. What comes back is the model's own shorthand, not a written-for-an-audience summary.

from adk.packs.omp_thinking import reconcile, deep_think_directive

model = {"api": "anthropic-messages", "reasoning": True,
         "thinking_requires_effort": True, "thinking_suppress_when_off": True}

reconcile(agent._tools, model)          # arms `deep_think` only if the model can take it
print(deep_think_directive(8)["directive"])   # the effort number, aimed at the scratchpad

Two things this pack refuses to do, both deliberate:

  • It refuses unknown and incapable models. A model that cannot suppress its native channel gets both channels or a rejected request, so it is refused and counted, never probed hopefully.
  • It disarms on model swap. Whether the scratchpad is legal is a property of the model
Source 1 files
hooks/register.ts 756 lines
1import type { EngineInterface, On, TurnStepChunk, TurnStepResult, TurnUsage } from 'claude-code'
2
3/*
4 * awsh for Claude Code: the `aw` subagent type.
5 *
6 * The step-replacement shape (a real subagent loop whose model request is
7 * answered from elsewhere, chained through a no-op tool across the engine's
8 * hook budget, signed with the model that actually answered) is adapted from
9 * pi-agent-for-claude by Fazal Ali, MIT. This module talks HTTP to the awsh
10 * harness daemon instead of shelling out to a CLI, so it needs no sh, no /tmp
11 * and no tmux, and runs wherever the daemon does.
12 */
13
14/** How often a running session's events are read for new ones. */
15const STREAM_POLL_MS = 150
16
17/**
18 * How long one step streams before handing off to the next. The engine gives a
19 * hook call 10 s and, past it, finishes the step with the real model; the
20 * daemon's session runs on its own, so a longer turn spans several steps,
21 * chained through PROGRESS_TOOL.
22 */
23const STEP_BUDGET_MS = 7_000
24
25/**
26 * The no-op tool a step ends on while the harness is still working: its call
27 * makes the engine run another step, which carries on streaming the same turn.
28 */
29const PROGRESS_TOOL = 'aw_progress'
30
31/** How long a follow-up step waits for its message to reach the transcript. */
32const FOLLOW_UP_WAIT_MS = 5_000
33const POLL_MS = 200
34
35/** How long a new session may take to leave `starting` before it is a failure. */
36const START_WAIT_MS = 6_000
37
38/**
39 * The tool a subagent delivers its final report through, where the session
40 * runs the hand-back contract. A report left as plain text is bounced back
41 * with `[handback-send-enforce]`.
42 */
43const HANDBACK_TOOL = 'SubagentHandback'
44
45/**
46 * User messages the engine writes into a subagent's transcript itself. They
47 * are not the person's follow-ups, so the harness is never sent them.
48 */
49const ENGINE_PREFIXES = [
50  '<system-reminder>',
51  '[handback-send-enforce]',
52  '[Your previous response had no visible output',
53]
54
55/** The harness a spawn gets when neither its prompt nor mods.json names one. */
56const FALLBACK_HARNESS = 'opencode'
57
58/**
59 * How deep a chain of mod-started Claude Code sessions may get. The daemon's
60 * `adk/harnesses/mod.py` holds the same number.
61 */
62const MAX_DEPTH = 2
63
64/** How many notice/raw lines a run keeps to explain a failed turn with. */
65const NOISE_LINES = 6
66
67/** Session states in which the daemon's harness is still producing a turn. */
68const WORKING_STATES = ['starting', 'busy']
69
70/** Where the daemon is and how to talk to it. */
71export type Daemon = { base: string; token: string; home: string }
72
73/** What a spawn asked to be run on. Every field is optional. */
74export type Route = { harness?: string; backend?: string; model?: string; agent?: string }
75
76/** One turn on a daemon session, as it streams across the steps it spans. */
77export type Run = {
78  /** The daemon session answering this agent. */
79  session: string
80  /** The harness that session runs. */
81  harness: string
82  /** This run's number for the agent, which keeps tool call ids unique. */
83  id: number
84  /** The last event `seq` read. */
85  since: number
86  /** How many reads in a row came back empty with the session not working. */
87  quiet: number
88  /** Every piece of text shown so far, across steps. */
89  shown: string
90  /** The text of the turn's answer. */
91  report: string
92  /** Whether the turn has ended. */
93  ended: boolean
94  /** Whether it ended on a failure this module reports, not on an answer. */
95  failed: boolean
96  /** Whether the answer must be handed back through HANDBACK_TOOL. */
97  handback: boolean
98  /** How many steps have handed off to the next through PROGRESS_TOOL. */
99  steps: number
100  /** The model the daemon reported for this session. */
101  model: string
102  /** The last few notice/raw lines: a failed turn's only account of itself. */
103  noise: string[]
104  /** Tokens used since the last step reported them. */
105  usage: { i: number; o: number; cr: number; cw: number }
106}
107
108/**
109 * Claude Code's http hooks fail OPEN: when hookd (awdk's resident hook runner) is down,
110 * every hook routed through it is skipped without a word. A session whose settings route
111 * hooks through it starts it when it is not answering. Never throws.
112 *
113 * @param $ the engine interface
114 * @returns what it found or did, for the debug log
115 */
116export async function keepHookd($: EngineInterface): Promise<string> {
117  try {
118    const hooks = JSON.stringify(((await $.settings.read()) as { hooks?: unknown }).hooks ?? {})
119    const port = /127\.0\.0\.1:(\d+)\/run\?/.exec(hooks)?.[1]
120    if (!port) return 'hookd: not routed'
121    try {
122      if ((await $.http.fetch(`http://127.0.0.1:${port}/health`)).ok) return 'hookd: up'
123    } catch {
124      // not answering: start it below
125    }
126    const r = await $.process.run(
127      ['python', '-m', 'adk.harnesses.hookd', 'ensure', '--port', port],
128      { timeoutMs: 20000 },
129    )
130    return r.exitCode === 0 ? 'hookd: started' : `hookd: ensure exited ${r.exitCode}`
131  } catch (err) {
132    return `hookd: ${String(err).slice(0, 200)}`
133  }
134}
135
136/**
137 * Registers the `aw` subagent type.
138 *
139 * The spawn runs as it always does, so the engine starts a real subagent loop
140 * with its own id, transcript and entry in `$.agent.list()`; only the model
141 * request inside that loop is replaced, by a turn on an awsh daemon session.
142 * Each loop keeps one daemon session, so a follow-up continues the same
143 * conversation, and the session is visible and steerable from awsh the whole
144 * time (its owner is `claude-code:<agent id>`).
145 *
146 * @param on the engine's registrar
147 */
148export function register(on: On) {
149  const seeds = new Map<string, string>()
150  const consumed = new Map<string, number>()
151  // Loops whose last step delivered the answer through a tool call, with the
152  // text the step after it ends on.
153  const delivered = new Map<string, string>()
154  // PROGRESS_TOOL's full name as the engine registered it, `mcp__<plugin>__…`.
155  let progressTool = ''
156  const lastAnswers = new Map<string, string>()
157  const runs = new Map<string, Run>()
158  // The daemon session each loop talks to, and the route it was opened on.
159  const sessions = new Map<string, { id: string; harness: string }>()
160
161  on('session.start', async ($, e, next) => {
162    const started = await next(e)
163    void keepHookd($).then((said) => $.ui.log(said, { to: 'debug' }))
164    try {
165      ;({ tool: progressTool } = await $.tool.register({
166        name: PROGRESS_TOOL,
167        description: 'Internal to aw subagents: marks an awsh turn still in progress. Never call it.',
168      }))
169    } catch {
170      // The plugin shares its name with an `awsh` MCP server in the session's
171      // config, and the engine refuses to replace that server. Leave the
172      // session alone; aw subagents report the collision instead of chaining.
173      progressTool = ''
174    }
175    return started
176  })
177
178  on('tool.call', async ($, e, next) => {
179    if (e.tool !== progressTool) return next(e)
180    if (e.agentId === undefined || !runs.has(e.agentId)) {
181      return { deny: `${PROGRESS_TOOL} is internal to aw subagents.` }
182    }
183    return { result: 'the awsh harness is still working.' }
184  })
185
186  on('agent.spawn', async ($, e, next) => {
187    const started = await next(e)
188    if (isAw(e.subagentType) && started.agentId) {
189      seeds.set(started.agentId, e.prompt)
190    }
191    return started
192  })
193
194  on('session.end', async ($, e, next) => {
195    // A daemon session must not outlive the Claude Code session that opened it.
196    const daemon = await daemonOf($).catch(() => undefined)
197    if (daemon !== undefined) {
198      for (const { id } of sessions.values()) {
199        await call($, daemon, 'DELETE', `/sessions/${id}`).catch(() => undefined)
200      }
201    }
202    sessions.clear()
203    return next(e)
204  })
205
206  on('turn.step', async function* ($, e, next) {
207    // An aw subagent's loop, keyed by its id; any other loop is the model's.
208    const agentId = e.agentId
209    const seed = agentId === undefined ? undefined : seeds.get(agentId)
210    if (agentId === undefined || seed === undefined) {
211      return yield* next(e)
212    }
213    const deadline = (await $.clock.now()) + STEP_BUDGET_MS
214
215    // The step after a delivery is that tool's result coming back: the answer
216    // is delivered, so the loop ends here without asking the harness again.
217    const done = delivered.get(agentId)
218    if (done !== undefined) {
219      delivered.delete(agentId)
220      return yield* respond(e, [
221        { kind: 'text', index: 0, text: done },
222        { kind: 'stop', stopReason: 'end_turn', usage: null },
223      ], done, [])
224    }
225
226    let run = runs.get(agentId)
227    if (run === undefined) {
228      const already = consumed.get(agentId) ?? 0
229      const { prompt, count, handback, bounced } = await promptOf($, agentId, seed, already)
230      consumed.set(agentId, count)
231      if (bounced || prompt === undefined) {
232        // A bounce is the engine refusing a plain-text report: hand back the
233        // answer already given rather than asking again.
234        const text = bounced
235          ? lastAnswers.get(agentId) ?? ''
236          : "awsh: no new message reached this agent's transcript."
237        return yield* finish(e, agentId, text, text, 1, handback || bounced, [{ kind: 'text', index: 0, text }])
238      }
239      const started = await start($, agentId, prompt, count, handback, sessions.get(agentId))
240      if ('failure' in started) {
241        // Never throw: a throw hands the step to the model beneath, a Claude
242        // subagent with Claude's tools, and that answer would read as awsh's.
243        const text = started.failure
244        return yield* finish(e, agentId, text, text, 1, handback, [{ kind: 'text', index: 0, text }])
245      }
246      run = started.run
247      sessions.set(agentId, { id: run.session, harness: run.harness })
248      runs.set(agentId, run)
249    }
250
251    const { shown, blocks, lastKind } = yield* pump($, run, deadline, next.signal)
252    if (!run.ended && progressTool === '') {
253      runs.delete(agentId)
254      const text = shown + '\n\nawsh: turn outran one step and cannot chain: an MCP server named '
255        + '"awsh" in this session\'s config blocked registering aw_progress.'
256      return yield* finish(e, agentId, text, text, 1, run.handback, [{ kind: 'text', index: 0, text }])
257    }
258    if (!run.ended) {
259      const input = {}
260      return yield* respond(e, [
261        { kind: 'tool', index: blocks, id: `toolu_aw_${idOf(agentId)}_${run.id}_${run.steps++}`, name: progressTool },
262        { kind: 'input', index: blocks, json: JSON.stringify(input) },
263        { kind: 'stop', stopReason: 'tool_use', usage: takeUsage(run) },
264      ], shown, [{ name: progressTool, input }])
265    }
266
267    runs.delete(agentId)
268    // The hand-back reminder can reach the transcript after the run's first
269    // step read it; checking again now saves a bounce.
270    const handback = run.handback || (await transcriptOf($, agentId)).handback
271    const answer = run.report.trim() || run.shown
272    // Named from the daemon's own record of the session: a model asked what it
273    // is often answers wrongly, and the parent has nothing else to check it by.
274    // A failure is this module's account, not a model's answer: unsigned, so
275    // the parent's rule ("no signature, not awsh's work") holds for it too.
276    const report = run.failed
277      ? answer
278      : `${answer}\n\n— answered by awsh, ${run.harness}/${run.model || 'unreported'}`
279    // The parent reads the last text block, so it must hold the whole answer.
280    // A run spanning several steps streamed its answer across them and gets it
281    // again whole; one whose answer streamed whole here gets just the
282    // signature, onto that same block.
283    const whole = run.steps > 0 && !shown.includes(answer)
284    const extra = whole ? report : report.slice(answer.length)
285    const into = !whole && lastKind === 'text' ? blocks - 1 : blocks
286    const tail: TurnStepChunk[] = extra ? [{ kind: 'text', index: Math.max(into, 0), text: extra }] : []
287    return yield* finish(e, agentId, shown + extra, report, Math.max(into, 0) + (extra ? 1 : 0), handback, tail, takeUsage(run))
288  })
289
290  /**
291   * Ends a step on the answer: plain text, or text then the HANDBACK_TOOL call
292   * that delivers it where the session runs the hand-back contract.
293   */
294  async function* finish(
295    e: { turnId: string; index: number },
296    agentId: string,
297    shown: string,
298    report: string,
299    blocks: number,
300    handback: boolean,
301    chunks: TurnStepChunk[],
302    usage: TurnUsage | null = null,
303  ) {
304    lastAnswers.set(agentId, report)
305    if (!handback) {
306      return yield* respond(e, [...chunks, { kind: 'stop', stopReason: 'end_turn', usage }], shown, [])
307    }
308    delivered.set(agentId, 'Report delivered.')
309    const input = { message: report }
310    const id = `toolu_aw_${idOf(agentId)}_${HANDBACK_TOOL}_${consumed.get(agentId) ?? 0}`
311    return yield* respond(e, [
312      ...chunks,
313      { kind: 'tool', index: blocks, id, name: HANDBACK_TOOL },
314      { kind: 'input', index: blocks, json: JSON.stringify(input) },
315      { kind: 'stop', stopReason: 'tool_use', usage },
316    ], shown, [{ name: HANDBACK_TOOL, input }])
317  }
318}
319
320/** An agent id as a tool-call id may spell it. */
321export function idOf(agentId: string) {
322  return agentId.replace(/[^A-Za-z0-9_]/g, '_')
323}
324
325/**
326 * The tokens a run used since the last step reported them, as this step's
327 * usage under the model the daemon named; null before it named one.
328 */
329export function takeUsage(run: Run | undefined): TurnUsage | null {
330  if (!run?.model) return null
331  const { i, o, cr, cw } = run.usage
332  run.usage = { i: 0, o: 0, cr: 0, cw: 0 }
333  return {
334    model: run.model,
335    input_tokens: i,
336    output_tokens: o,
337    cache_read_input_tokens: cr,
338    cache_creation_input_tokens: cw,
339  }
340}
341
342/** Whether a spawn names this plugin's type, plain or plugin-qualified. */
343export function isAw(subagentType: string) {
344  return subagentType === 'aw' || subagentType.endsWith(':aw')
345}
346
347/**
348 * Takes the `aw-harness:` / `aw-backend:` / `aw-model:` / `aw-agent:` lines out
349 * of a prompt: the way a caller routes a spawn, since the Agent tool's own
350 * `model` names Claude models only. Only the first line of each kind counts.
351 */
352export function routeOf(text: string): { prompt: string; route: Route } {
353  const route: Route = {}
354  let prompt = text
355  const keys = [['harness', 'harness'], ['backend', 'backend'], ['model', 'model'], ['agent', 'agent']] as const
356  for (const [word, field] of keys) {
357    const line = prompt.match(new RegExp(`^[ \\t]*aw-${word}:[ \\t]*([A-Za-z0-9_.:\\/@+-]+)[ \\t]*$`, 'im'))
358    if (!line) continue
359    route[field] = line[1]
360    prompt = prompt.replace(line[0], '')
361  }
362  return { prompt: prompt.trim(), route }
363}
364
365/**
366 * Yields a step's chunks and returns the result the engine expects of it.
367 *
368 * @param e the step being answered
369 * @param chunks what the person watches stream, in order
370 * @param answer the step's visible text
371 * @param toolUses the tool calls the chunks made
372 */
373export async function* respond(
374  e: { turnId: string; index: number },
375  chunks: TurnStepChunk[],
376  answer: string,
377  toolUses: TurnStepResult['toolUses'],
378): AsyncGenerator<TurnStepChunk, TurnStepResult> {
379  for (const chunk of chunks) yield chunk
380  const stop = chunks.at(-1)
381  const stopReason = stop?.kind === 'stop' ? stop.stopReason : 'end_turn'
382  const usage = stop?.kind === 'stop' ? stop.usage : null
383  return { turnId: e.turnId, index: e.index, answer, toolUses, stopReason, usage }
384}
385
386/** Reads a text file, or '' when it is absent or unreadable. */
387export async function readText($: EngineInterface, path: string): Promise<string> {
388  try {
389    const got: unknown = await $.fs.read(path)
390    if (typeof got === 'string') return got
391    const text = (got as { text?: unknown } | undefined)?.text
392    return typeof text === 'string' ? text : ''
393  } catch {
394    return ''
395  }
396}
397
398/**
399 * Finds the daemon: `AITHER_HARNESS_HOST`/`PORT` and the bearer file
400 * `AITHER_HARNESS_TOKEN_FILE`, the same three names every other daemon client
401 * reads, defaulting to 127.0.0.1:8362 and ~/.aither/harness_token. The token is
402 * read on every call rather than cached, since the daemon rewrites it.
403 */
404export async function daemonOf($: EngineInterface): Promise<Daemon> {
405  const home = ((await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || '').replace(/\\/g, '/')
406  const host = (await $.env.get('AITHER_HARNESS_HOST')) || '127.0.0.1'
407  const port = (await $.env.get('AITHER_HARNESS_PORT')) || '8362'
408  const file = (await $.env.get('AITHER_HARNESS_TOKEN_FILE')) || `${home}/.aither/harness_token`
409  const token = (await readText($, file)).trim()
410  return { base: `http://${host}:${port}`, token, home }
411}
412
413/**
414 * One call to the daemon. Never throws: a failure comes back as status 0 with
415 * the reason, so the caller can end the step on it as text.
416 */
417export async function call(
418  $: EngineInterface,
419  daemon: Daemon,
420  method: string,
421  path: string,
422  body?: unknown,
423): Promise<{ status: number; json: any; detail: string }> {
424  try {
425    const got = await $.http.fetch(`${daemon.base}${path}`, {
426      method,
427      headers: {
428        Authorization: `Bearer ${daemon.token}`,
429        ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
430      },
431      ...(body === undefined ? {} : { body: JSON.stringify(body) }),
432    })
433    let json: any
434    try {
435      json = JSON.parse(got.text)
436    } catch {
437      json = undefined
438    }
439    const detail = typeof json?.detail === 'string' ? json.detail : got.ok ? '' : got.text.slice(0, 400)
440    return { status: got.status, json, detail }
441  } catch (err) {
442    return { status: 0, json: undefined, detail: String(err) }
443  }
444}
445
446/**
447 * The spawn defaults from `~/.aither/mods.json` (`{ "aw": { "harness": … } }`),
448 * the file `awsettings --domain mods` syncs. Absent or malformed, no defaults.
449 */
450export async function defaultsOf($: EngineInterface, daemon: Daemon): Promise<Route & { permission_mode?: string }> {
451  try {
452    const aw = JSON.parse(await readText($, `${daemon.home}/.aither/mods.json`))?.aw
453    return aw !== null && typeof aw === 'object' ? aw : {}
454  } catch {
455    return {}
456  }
457}
458
459/**
460 * Opens (or reuses) the agent's daemon session and submits one turn to it.
461 *
462 * @param prompt what to send the harness, routing lines still in it
463 * @param id this run's number for the agent
464 * @param handback whether the answer must be handed back
465 * @param open the session a previous turn of this agent opened, if any
466 */
467export async function start(
468  $: EngineInterface,
469  agentId: string,
470  prompt: string,
471  id: number,
472  handback: boolean,
473  open: { id: string; harness: string } | undefined,
474): Promise<{ run: Run } | { failure: string }> {
475  const daemon = await daemonOf($)
476  if (!daemon.token) {
477    return { failure: 'awsh: no harness token found, so the daemon cannot be reached. Start it once (`adk harness serve`) - it writes ~/.aither/harness_token.' }
478  }
479  // A Claude Code the mod started can start the mod again; the daemon tells
480  // each one how deep it is, and the chain stops here rather than at a bill.
481  const depth = Number((await $.env.get('AITHER_AW_DEPTH')) || 0)
482  if (depth >= MAX_DEPTH) {
483    return { failure: `awsh: refused - this Claude Code session is already ${depth} aw spawns deep (the limit is ${MAX_DEPTH}). Do the work here instead of delegating it again.` }
484  }
485  const asked = routeOf(prompt)
486  let session = open
487  // A follow-up that names another harness gets a new session; one that names
488  // none continues the conversation it is part of.
489  if (session !== undefined && asked.route.harness !== undefined && asked.route.harness !== session.harness) {
490    await call($, daemon, 'DELETE', `/sessions/${session.id}`)
491    session = undefined
492  }
493  if (session === undefined) {
494    const defaults = await defaultsOf($, daemon)
495    const harness = asked.route.harness ?? defaults.harness ?? FALLBACK_HARNESS
496    const made = await call($, daemon, 'POST', '/sessions', {
497      harness,
498      cwd: await $.session.cwd(),
499      model_profile: asked.route.backend ?? defaults.backend ?? '',
500      model: asked.route.model ?? defaults.model ?? '',
501      target: asked.route.agent ?? defaults.agent ?? '',
502      permission_mode: defaults.permission_mode ?? '',
503      title: `aw ${harness} (Claude Code subagent)`,
504      // The depth rides in the owner because that is the one free-text field a
505      // session create already carries to the child's environment.
506      owner: `claude-code:${agentId}@d${depth + 1}`,
507    })
508    if (made.status !== 200 || typeof made.json?.id !== 'string') {
509      const why = made.status === 0 ? `the daemon at ${daemon.base} did not answer (${made.detail})` : `${made.status} ${made.detail}`
510      return { failure: `awsh: could not open a ${harness} session: ${why}` }
511    }
512    session = { id: made.json.id, harness }
513    // A harness that cannot start says so within moments; submitting into a
514    // session still `starting` is refused with a 409 that names nothing.
515    for (let waited = 0; waited < START_WAIT_MS; waited += POLL_MS) {
516      const info = await call($, daemon, 'GET', `/sessions/${session.id}`)
517      if (info.json?.state !== 'starting') break
518      await $.clock.sleep(POLL_MS)
519    }
520  }
521  const before = await call($, daemon, 'GET', `/sessions/${session.id}/events?since=999999999`)
522  const sent = await call($, daemon, 'POST', `/sessions/${session.id}/submit`, { text: asked.prompt, submit: true })
523  if (sent.status !== 200) {
524    const events = await call($, daemon, 'GET', `/sessions/${session.id}/events?since=0`)
525    const errors = (events.json?.events ?? [])
526      .filter((ev: any) => ev.kind === 'error')
527      .map((ev: any) => ev.text)
528      .join('\n')
529    return { failure: `awsh: the ${session.harness} session refused the turn: ${sent.status} ${sent.detail}\n${errors}`.trim() }
530  }
531  return {
532    run: {
533      session: session.id,
534      harness: session.harness,
535      id,
536      since: Number(before.json?.last_seq ?? 0),
537      quiet: 0,
538      shown: '',
539      report: '',
540      ended: false,
541      failed: false,
542      handback,
543      steps: 0,
544      model: '',
545      noise: [],
546      usage: { i: 0, o: 0, cr: 0, cw: 0 },
547    },
548  }
549}
550
551/**
552 * Streams a run's new events as this step's chunks, until the turn ends or the
553 * step's `deadline` passes: text as text, thinking as thinking, and each tool
554 * the harness starts as a one-line `▸ tool: args` note in the text.
555 *
556 * Never throws: see `start`. An aborted step interrupts the harness, since the
557 * daemon's session would otherwise carry on with a turn nobody is reading.
558 *
559 * @param deadline when this step must stop streaming, in `$.clock` ms
560 * @param signal the step's abort signal
561 * @returns the text this step showed, how many content blocks it used, and
562 *   the kind of the last one
563 */
564export async function* pump(
565  $: EngineInterface,
566  run: Run,
567  deadline: number,
568  signal: AbortSignal,
569): AsyncGenerator<TurnStepChunk, { shown: string; blocks: number; lastKind?: 'text' | 'thinking' }> {
570  let shown = ''
571  let index = -1
572  let kind: 'text' | 'thinking' | undefined
573  let failure = ''
574  const daemon = await daemonOf($)
575
576  try {
577    while (!run.ended && !signal.aborted && (await $.clock.now()) < deadline) {
578      const got = await call($, daemon, 'GET', `/sessions/${run.session}/events?since=${run.since}`)
579      if (got.status !== 200) {
580        failure = `awsh: lost the ${run.harness} session: ${got.status} ${got.detail}`
581        break
582      }
583      const events: any[] = got.json?.events ?? []
584      for (const event of events) {
585        run.since = Math.max(run.since, Number(event.seq ?? 0))
586        let pieceKind: 'text' | 'thinking' = 'text'
587        let text = ''
588        if (event.kind === 'text.delta') {
589          text = event.text ?? ''
590          run.report += text
591        } else if (event.kind === 'thinking.delta') {
592          pieceKind = 'thinking'
593          text = event.text ?? ''
594        } else if (event.kind === 'tool.call') {
595          const args = JSON.stringify(event.data?.input ?? {})
596          text = `\n▸ ${event.tool}: ${args.length > 100 ? `${args.slice(0, 100)}…` : args}\n`
597        } else if (event.kind === 'error') {
598          text = `\n[${run.harness} error] ${event.text ?? ''}\n`
599          run.report += text
600        } else if (event.kind === 'usage') {
601          const u = event.data?.usage ?? {}
602          run.usage.i += Number(u.input_tokens ?? u.input ?? 0)
603          run.usage.o += Number(u.output_tokens ?? u.output ?? 0)
604          run.usage.cr += Number(u.cache_read_input_tokens ?? 0)
605          run.usage.cw += Number(u.cache_creation_input_tokens ?? 0)
606        } else if (event.kind === 'notice' || event.kind === 'raw') {
607          // Never shown as they arrive (a CLI's stderr is mostly noise), but a
608          // failed turn's reason is only ever here, and so is the model name
609          // of a harness the daemon cannot ask (`> build · provider/model`).
610          const line = String(event.text ?? '').replace(/\u001b\[[0-9;]*m/g, '').trim()
611          const named = line.match(/^>\s*\S+\s+·\s+(\S+)$/)
612          if (named) run.model = named[1]
613          else if (line) run.noise = [...run.noise, line].slice(-NOISE_LINES)
614        } else if (event.kind === 'turn.completed') {
615          // A harness that streams nothing still carries its answer here.
616          if (!run.report.trim() && event.text) {
617            text = event.text
618            run.report = text
619          } else if (event.data?.is_error && !run.report.trim()) {
620            failure = `awsh: the ${run.harness} turn failed (exit ${event.data?.exit_code ?? '?'}):\n${[...new Set(run.noise)].join('\n')}`
621          }
622          run.ended = true
623        } else if (event.kind === 'session.exited') {
624          run.ended = true
625        }
626        if (!text) continue
627        if (pieceKind !== kind) {
628          kind = pieceKind
629          index += 1
630        }
631        if (pieceKind === 'text') shown += text
632        yield { kind: pieceKind, index, text }
633      }
634      // A session that stopped working without a closing event still ended.
635      const working = WORKING_STATES.includes(got.json?.state)
636      run.quiet = events.length === 0 && !working ? run.quiet + 1 : 0
637      if (run.quiet >= 3) run.ended = true
638      if (!run.ended) await $.clock.sleep(STREAM_POLL_MS)
639    }
640  } catch (err) {
641    failure = `awsh: the ${run.harness} run failed: ${String(err)}`
642  }
643
644  if (signal.aborted && !run.ended) {
645    run.ended = true
646    await call($, daemon, 'POST', `/sessions/${run.session}/interrupt`)
647  }
648  if (run.ended && !failure && !(run.shown + shown).trim()) {
649    failure = `awsh: the ${run.harness} session ended with no answer.`
650  }
651  if (failure) {
652    run.ended = true
653    run.failed = true
654    shown += failure
655    run.report = failure
656    index += 1
657    kind = 'text'
658    yield { kind: 'text', index, text: failure }
659  }
660  if (run.ended) {
661    const info = await call($, daemon, 'GET', `/sessions/${run.session}`)
662    const binding = info.json?.model_binding
663    run.model = info.json?.reported_model || binding?.model || binding?.profile || run.model
664  }
665  run.shown += shown
666  return { shown, blocks: index + 1, lastKind: kind }
667}
668
669/**
670 * Decides what to send the harness this step, and whether its answer must be
671 * handed back through HANDBACK_TOOL.
672 *
673 * The first step sends the spawn's prompt. A later one waits for a person's
674 * message past the first `already` in `agentId`'s own transcript and sends the
675 * newest; the engine can start the step before it writes the message there,
676 * so this polls briefly.
677 *
678 * @param seed the prompt the spawn was given
679 * @param already how many of the person's messages the harness has been sent
680 */
681export async function promptOf($: EngineInterface, agentId: string, seed: string, already: number) {
682  for (let waited = 0; ; waited += POLL_MS) {
683    const { texts, handback, bounced } = await transcriptOf($, agentId)
684    if (already === 0) return { prompt: seed, count: Math.max(texts.length, 1), handback, bounced: false }
685    if (texts.length > already) return { prompt: texts.at(-1), count: texts.length, handback, bounced: false }
686    if (bounced) return { prompt: undefined, count: already, handback: true, bounced }
687    if (waited >= FOLLOW_UP_WAIT_MS) return { prompt: undefined, count: already, handback, bounced }
688    await $.clock.sleep(POLL_MS)
689  }
690}
691
692/**
693 * Where Claude Code keeps `agentId`'s transcript:
694 * `~/.claude/projects/<project>/<session id>/subagents/agent-<id>.jsonl`.
695 *
696 * Leans on Claude Code's on-disk layout, not an API: `$.session.messages()`
697 * reads the main loop's transcript only. The project directory is the launch
698 * directory with every non-alphanumeric turned into `-`; when that guess
699 * misses, every project directory is tried for this session's id.
700 */
701export async function transcriptPathOf($: EngineInterface, agentId: string): Promise<string | undefined> {
702  const { home } = await daemonOf($)
703  const projects = `${home}/.claude/projects`
704  const sessionId = await $.session.id()
705  const tail = `${sessionId}/subagents/agent-${agentId}.jsonl`
706  const guess = `${projects}/${(await $.session.cwd()).replace(/[^A-Za-z0-9]/g, '-')}/${tail}`
707  if (await $.fs.exists(guess).catch(() => false)) return guess
708  const listed: unknown = await $.fs.list(projects).catch(() => [])
709  for (const entry of Array.isArray(listed) ? listed : []) {
710    const name = typeof entry === 'string' ? entry : (entry as { name?: string })?.name
711    if (!name) continue
712    const path = `${projects}/${name}/${tail}`
713    if (await $.fs.exists(path).catch(() => false)) return path
714  }
715  return undefined
716}
717
718/**
719 * Reads `agentId`'s transcript: the text of every message the person (or the
720 * spawn) sent it, oldest first; whether the engine asked it to hand its
721 * report back through HANDBACK_TOOL; and whether the newest message is the
722 * engine bouncing a report that was not.
723 */
724export async function transcriptOf($: EngineInterface, agentId: string) {
725  const path = await transcriptPathOf($, agentId)
726  const raw = path === undefined ? '' : await readText($, path)
727  const all = raw
728    .split('\n')
729    .flatMap((line) => {
730      try {
731        return [JSON.parse(line)]
732      } catch {
733        return [] // the line Claude Code is still writing
734      }
735    })
736    .filter((entry) => entry.type === 'user')
737    .map((entry) => textOf(entry.message?.content))
738    .filter(Boolean)
739  return {
740    texts: all.filter((text) => !ENGINE_PREFIXES.some((prefix) => text.startsWith(prefix))),
741    handback: all.some((text) => text.includes(HANDBACK_TOOL)),
742    bounced: all.at(-1)?.startsWith('[handback-send-enforce]') ?? false,
743  }
744}
745
746/** Joins a message's text: a plain string, or the text blocks of a block list. */
747export function textOf(content: unknown): string {
748  if (typeof content === 'string') return content.trim()
749  if (!Array.isArray(content)) return ''
750  return content
751    .filter((block) => block?.type === 'text')
752    .map((block) => block.text)
753    .join('\n')
754    .trim()
755}
756