Commit Graph
8 Commits
Author SHA1 Message Date
Kaede AkinoandClaude Opus 5 99be1d6885 Change a remote file without sending it through the model
Editing a config on a host cost two full copies of it in tokens. `sftp_read`
returns the file inline, and `sftp_write` takes the replacement back as a
`content` string the model has to re-emit in full — so the ordinary "pull it,
change three lines, push it back" job paid for the whole file twice, and
anything over the 128 KB inline cap, or anything that was not UTF-8, was out
of reach entirely. There was also nowhere to keep a draft between turns: a
script the agent was composing lived only in the transcript, which the context
pipeline trims head-and-tail as the run grows.

`AgentScratchWorkspace` is a per-conversation staging directory under
Application Support, inside the sandbox container, deleted with the
conversation that owns it. Application Support rather than Caches because the
system may evict a Caches directory mid-run, and a staging area that can vanish
between two tool calls is worse than none. Paths are relative; `..` is refused
rather than resolved, which is the inverse of `normalizeRemotePath` and the
right inversion — a relative path with `..` in it is never something the agent
needed. Symlinks are refused even when they point back inside, because an alias
within the workspace makes two paths the same file and quietly breaks both the
quota arithmetic and the atomicity `apply(_:to:)` claims. Every resolved path
is then proven to still be under the scope. Writes are bounded per file, per
conversation, and by entry count, and hidden files are counted — a quota you
can evade by naming a file `.big` is not a quota.

It is an actor, and that is load-bearing rather than incidental. Pi serializes
file mutations through an explicit per-path queue; here the actor already
serializes every operation against every other, so a read-modify-write is
atomic for free. That is what lets every local scratch tool stay `.parallel`:
a batch containing one does not have to drag its whole turn serial to be safe.

`scratch_edit` follows Pi's `edit` and is what makes the rest pay off. Every
`old_text` is matched against the file as it was before the call, not against
the result of the preceding edit, so the model never simulates its own changes
to write the second one. Matches must be unique and non-overlapping; anything
ambiguous fails the whole call rather than applying part of it, because a
half-applied edit is the one outcome nobody can reason about. Matching is exact
first, then one line-aligned retry that ignores smart quotes, unicode dashes
and trailing whitespace — without it an edit fails whenever the model retypes a
block with tidied punctuation, which is often. And it returns a unified diff
rather than the new file, which is the entire point: an 8 MB file can now be
changed for the price of the lines that changed.

`scratch_pull` and `scratch_push` move the bytes, and are separate tools rather
than options on `sftp_read` / `sftp_write`. A tool that means two different
things depending on which optional argument is present is harder for a model to
choose correctly and harder to audit, and it would have put two safety levels
inside one descriptor. The SFTP tools are untouched.

`Safety` gains `locallyContained`. The existing two cases state *why* a call may
skip the gate, and "read-only" is the wrong reason for a scratch write — it
changes something, it just cannot change anything outside storage the app owns.
It is auto-allowed in every mode including Ask for approval, because a staging
area you must approve into is not a staging area, and six dialogs for one edit
loop teach the reader to click through the seventh, which is the one that
reaches a host. `isAutoAllowed` is a property of the case rather than an
`== .requiresAuthorization` at the call site, so a fourth case has to make a
decision here instead of defaulting to allowed. Nothing switches exhaustively
over `Safety` and it is not persisted, so there is no migration.

`scratch_push` is the only gated tool here, and it has a problem the SFTP tools
do not: the approval card would show a filename where it used to show the bytes,
leaving the reviewer — human or model — agreeing to something neither had seen.
Its preflight therefore reads the staged file and puts the size, digest and a
redacted twenty-line head into `localReasons`, which both the card and Security
Review's `Local signals:` line already render. It also carries the digest in
`executionMetadata` and rechecks it at execute time: approval suspends the turn,
and what comes back from the workspace afterwards is only the same file if
nothing rewrote it in between.

The schema helpers move to an `AgentToolSchemaBuilding` protocol with defaults
rather than a namespace enum, so a conforming type still calls `descriptor(…)`
and `string(max:)` unqualified and a second tool file costs a conformance
instead of a copy of forty lines.

`UnifiedDiff` is a formatter over `CollectionDifference` — Swift's
`difference(from:)` is already a Myers diff, so no dependency. It trims the
common prefix and suffix before running, because Myers is fast on similar
inputs and quadratic on unrelated ones, and refuses anything past a line limit
in what is left.

Its output was checked against the real tool before any expectation was written
down: for eight cases it is byte-identical to GNU `diff -u`, and `patch -p1`
applies each one and reproduces the target file. That found three bugs reading
the code had not. `firstChangedLine` was nil for every replacement, because the
first changed row of one is the removal and a removal has no line number on the
new side. A trailing-newline-only difference produced an empty diff with
`identical: false` — true and useless. And `LineEnding.detected` reported `.lf`
for every CRLF file, because Swift treats "\r\n" as a single Character and
`firstIndex(of: "\n")` finds nothing in a Windows file; editing one line would
have rewritten every line ending in it. A fourth came from the BOM test:
`String(data:encoding:.utf8)` strips a UTF-8 BOM while decoding, so checking the
decoded String never fired and writing it back dropped those three bytes. It
now reads the raw Data, and the test asserts on bytes for the same reason —
decoding would have reported a pass either way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 10:56:13 +08:00
Kaede AkinoandClaude Opus 5 bfbebc7b80 Answer tool calls that a killed process left hanging
Force quitting during a tool batch produced a conversation that could not
be continued at all, only deleted: `failed to stream request: error: No
tool output found for function call call_…`. The assistant turn is
persisted as soon as it arrives, its results only when the run next saves
a snapshot, so a process that dies in between restores a turn whose calls
nothing answers — and every provider rejects that outright rather than
degrading. It is the exact mirror of the orphaned result this codebase
already repaired, and the same class of fatal.

Recorded results come back first. `toolFinished` is durable and lands as
each tool finishes, so in the common case the output is sitting in the
database while the transcript claims to know nothing about it;
`loadConversations` now materializes any result whose transcript row was
never written. In a batch of three killed during the third, the first two
come back with the output they actually produced.

`AgentUnansweredToolCallRepair` answers whatever storage cannot, at the
model boundary and at the snapshot seed — the same two places the orphan
repair runs, and for the same reason: repairing at the seed writes the
fix forward instead of re-deriving it on every future turn. What it says
matters as much as that it says something. It does not claim the tool did
not run. The process died after the command was dispatched, so whether
the remote side executed it is genuinely unknown, and a model told "this
never ran" will cheerfully run it again — which is a data-loss bug the
first time the call was `rm`. It says the outcome is unknown and to check
before repeating.

A card caught mid-flight also came back spinning. Every unfinished run is
marked interrupted at launch, so `running` is not a state a restored card
can legitimately be in, and nothing was ever going to stop that spinner.

Worth noting against the previous commit: batching the snapshot save to
once per turn rather than once per tool widened this window, and the
recovery above is what closes it — results are still recorded one at a
time, so nothing a tool produced is lost, only deferred.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 09:36:53 +08:00
Kaede AkinoandClaude Opus 5 22258e3f2f Run a turn's tools at once, not one after another
`AgentRuntime` was one actor doing four jobs: holding the run's state,
driving the loop, executing tools, and publishing events. Adding an
audit, a rewrite, or a new tool source meant editing it. The loop now
keeps only the state and the control flow, and each phase is a value it
drives — `AgentContextPipeline` at the model boundary, `AgentTurnDriver`
for one assistant turn, `AgentToolScheduler` for the batch,
`AgentToolExecutor` for a single call, `AgentToolRegistry` for where
tools come from. Each is testable without a run around it. Four seams are
protocols with real conformers: `AgentToolProviding`, `AgentLoopHook`,
`AgentContextTransforming`, `AgentModelStreaming`. Authorization is
deliberately not among them — `AgentApprovalHandling` stays a structural
stage of the executor, because a permission gate you can remove by
leaving an element out of an array is not a gate.

A turn's calls run concurrently only when every one of them is marked
parallel; a single sequential call takes the whole turn serial rather
than being fenced into its own segment. Segmenting would buy back only
the cross-host case and cost semantics nobody can hold in their head
while reading an incident transcript. Concurrency is declared per tool
and may be overridden per call by preflight, which is how `ssh_exec`
decides: parallel exactly when `CommandRiskClassifier` proves the command
safe, the same locally-proven evidence that already decides its safety.
MCP tools are parallel by default, and a server's destructive hint or Ask
First makes them sequential — the hints can only tighten concurrency,
never grant it, so remote annotations remain risk hints rather than proof
of safety. The ceiling is worth stating plainly: `SSHExecSession` and
`SFTPClient` are actors, so calls aimed at one host still queue inside
their session. The win is several hosts at once, and host work
overlapping `fetch`, `web_search`, and MCP.

Whatever order they finish in, results reach the transcript in the order
the model asked. `toolFinished` still follows completion, because that is
when a card should stop spinning, so the two orders now disagree by
design — and `AgentToolResultOrdering` repairs it at the model boundary,
where both the run's snapshot and the conversation's own copy pass
through one implementation.

Three defects that serial execution was hiding, in rising order of harm.
A denied call was relabelled `Failed` the instant it was refused, because
the denial is an error to the model and the card followed the result;
`Denied` therefore never reached the screen. A run that gave up halfway —
cancelled, out of tool budget, or handed a response truncated
mid-arguments — left an assistant turn whose tool calls nothing answered,
and every provider rejects that outright on the *next* request, so an
interrupted run became a permanently unusable conversation. Every call
now gets a card and a result on every path, refusals included. And
`pendingApproval` was a single slot: two calls needing approval in one
turn overwrote each other, the first continuation was never resumed, and
the run stopped with no error and nothing on screen to answer. Approvals
and agent questions are queues now, presented one at a time with a
`1 of N` count, and run state is derived from what is outstanding rather
than asserted by whichever call moved last.

Events travel one ordered path. The runtime and the approval broker used
to publish independently, each wrapping its durable write in its own
unstructured `Task`, so a review's events had no defined order against
the tool events they belong between. `AgentEventChannel` fans out to the
UI and to a single serial recorder. `messageStarted` now carries its
message rather than just an id, so the visible turn is stamped with the
run's clock instead of whenever the UI got around to the event — a card
proposed later could otherwise carry an earlier timestamp than the turn
that asked for it, and sort above it.

`AgentContextPipeline` is also where trimming finally has somewhere to
live. `ssh_exec` returns up to 256 KB and `sftp_read` up to 128 KB, and
each is replayed on every later turn; two log reads were enough to crowd
out the conversation they were meant to explain. At most one turn's tool
output is now replayed in full, and older results keep their head and
their tail, because a truncated command output missing its ending has
lost the error message. It shapes only the request: snapshots and stored
history keep everything.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 09:28:07 +08:00
Kaede Akino b58e599127 Allow fetch headers and approved private networks 2026-08-25 23:53:25 +08:00
Kaede Akino 59c29957c5 Remove inline suggestions 2026-08-25 20:25:27 +08:00
Kaede Akino 8c858d246b feat: add Termind agent runtime and inline suggestions 2026-08-25 20:06:06 +08:00
Kaede Akino 3c5951fedc Merge context panel into sidebar 2026-08-24 21:58:00 +08:00
Kaede Akino 3f4f382ac4 Initial commit 2026-08-24 18:20:20 +08:00