@dudko.dev/agent 0.0.57 → 0.0.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -140,7 +140,7 @@ Pass an event handler as the second argument to `createAgent`, or per run via `o
140
140
  | `user.question-asked` / `user.question-answered` | The model asked the person a question ([`askUser`](#asking-the-user-a-question-with-choices)) and `onQuestion` is being called (`id`, `question`, `options: { label, description? }[]`, `multiple`, `allowOther`, `step?`, `subagent?` - the model's text, cleaned) / how it ended (`id`, `action: 'choice' \| 'other' \| 'declined' \| 'timeout' \| 'stopped'`, `automatic`, `choice?` - the labels picked -, `reason?: 'handler-error' \| 'invalid-answer' \| 'cannot-park'`). Never the person's own words. With the journal the id is the id of the item a [park](#parking-a-run-a-persons-answer-or-a-result-from-outside) on it would have; a question the run parks on is answered in the attempt that resumes it. |
141
141
  | `mcp.elicitation-requested` / `mcp.elicitation-answered` | An MCP server asked the user for input during a tool call and `onElicitation` is being called (`id`, `server`, `tool`, `mode`, `message`, `requestedSchema?`, `url?`, `step?`, `subagent?` - the server's text, cleaned and capped) / the question was settled (`action`, `automatic`, `reason?`, `fields?` - field names, never a value). See [MCP elicitation](#mcp-elicitation-a-server-asks-the-user). |
142
142
  | `egress.request` | A `web_fetch` request (or `web_search`'s call to its [search API](#search-finding-the-page-to-fetch)), allowed or refused by the [egress policy](#egress-what-the-model-may-fetch) (`url` is origin and path only, `allowed`, `status?`, `reason?`). |
143
- | `media.generated` | A [media tool](#media-images-speech-and-transcription) wrote a file: `kind: 'image' \| 'speech'`, `path` (absolute), `mediaType`, `bytes`, `model`, `references?` (`{ used, count, paths }`: the reference pictures of a `generate_image` call, and whether they were sent), `step?`. The bytes are in the file, never in an event. |
143
+ | `media.generated` | A [media tool](#media-images-speech-and-transcription) wrote a file: `kind: 'image' \| 'speech'`, `path` (absolute), `mediaType`, `bytes`, `model`, `references?` (`{ used, count, paths, fitted? }`: the reference pictures of a `generate_image` call, whether they were sent), `step?`. The bytes are in the file, never in an event. |
144
144
  | `media.transcribed` | An audio file became text: `source: 'attachment' \| 'tool'`, `name`, `text` (what the model reads), `language?`, `durationInSeconds?`, `model`. |
145
145
  | `skill.learned` / `skill.forgotten` | The agent wrote, rewrote (`update`) or removed a lesson — see [Learning](#learning-lessons-that-outlive-the-task) (`name`, and for a lesson `description`, `chars`, `sources`). |
146
146
 
@@ -414,6 +414,50 @@ const history = [
414
414
  await agent.run({ input: 'Got a contact?', history })
415
415
  ```
416
416
 
417
+ #### What a turn did: the action record
418
+
419
+ An answer says what the agent SAID it did; a later turn that reads only answers takes a vague or
420
+ wrong one for the truth ("did you pass my photo?" - "no, in words", when it had). So the runner
421
+ keeps its own record of what the turn **did**, `result.actionRecord`, and you store it with the
422
+ answer:
423
+
424
+ ```ts
425
+ import { actionRecordOf, neutralizeActionRecords, withActionRecord } from '@dudko.dev/agent'
426
+
427
+ try {
428
+ const result = await agent.run({ input, history })
429
+ history.push({ role: 'user', content: neutralizeActionRecords(input) })
430
+ history.push({ role: 'assistant', content: withActionRecord(result.text, result.actionRecord) })
431
+ // "The picture is ready.\n[done: generate_image → /srv/media/image-1a2b3c4d5e6f.png (reference /srv/media/me.jpg used); lookup ×2]"
432
+ } catch (err) {
433
+ // A stopped or failed run throws: what it did before it ended is on the error (when a tool ran).
434
+ const record = actionRecordOf(err)
435
+ if (record) {
436
+ history.push({ role: 'user', content: neutralizeActionRecords(input) })
437
+ history.push({ role: 'assistant', content: withActionRecord('', record, 'stopped') })
438
+ }
439
+ }
440
+ ```
441
+
442
+ - **Written by the runner, never by a model**, from the run's own events: each tool by name, how its
443
+ calls ended (`×n`, `failed`, `denied`, `unfinished` - no result came before the stop), what
444
+ `generate_image` / `generate_speech` made and generate_image's reference pictures (`used` / `NOT
445
+ used`), which helper (`spawn_subagent`, by its role), whether a question was answered (`ask_user`:
446
+ `answered` / `declined` / `not answered` - never the words). `find_tools`, `load_skill` and
447
+ `read_skill_file` are left out; a helper's own calls are its run's. No tool call: no record.
448
+ - **Bounded and cleaned**: at most 300 characters (`ACTION_RECORD_MAX_CHARS`, then "; and n more"), a
449
+ path or a name at most 60, one line, no bracket, `;`, control or invisible character. A path the
450
+ model chose is data, never instructions.
451
+ - **Only the runner writes one**: `withActionRecord` stores a `[done:` in the answer as `(done:` (and
452
+ appends a record only when it is one); `neutralizeActionRecords` does the same to the user's own
453
+ message before you keep it (the CLI does both; so do the swarm examples).
454
+ - **What the stages read**: `renderHistory` keeps a turn's record when it clips a long one (1 500
455
+ characters), and while a record is shown one fixed sentence says what it is (`ACTION_RECORD_NOTE`,
456
+ in the user prompt of the planner, the executor and the synthesizer; the system prompts do not
457
+ change). A compaction summary keeps the records of the turns it folds in after the model's text.
458
+ - The REPL keeps it this way (a cancelled turn too, when a tool ran). The browser sibling writes it
459
+ into its session memory itself; the format is the same file in both packages.
460
+
417
461
  ### Reconnecting MCP
418
462
 
419
463
  Use `getHeaders` on a server config to inject fresh credentials at connect time, then call `agent.reconnect()` after a token rotation. Reconnect refuses while runs are in flight.
@@ -682,7 +726,7 @@ compaction: {
682
726
  }
683
727
  ```
684
728
 
685
- - **History, at run start.** When the history no longer fits (see below), all but the last `keepRecentTurns` turns become ONE assistant turn starting with `[Summary of earlier conversation]`. The run works on the compacted copy; your array is never mutated, and the result carries it as `result.compactedHistory` so you can store it instead.
729
+ - **History, at run start.** When the history no longer fits (see below), all but the last `keepRecentTurns` turns become ONE assistant turn starting with `[Summary of earlier conversation]`. The run works on the compacted copy; your array is never mutated, and the result carries it as `result.compactedHistory` so you can store it instead. The records of what the folded turns did (`[done: …]`, see [Conversation history](#what-a-turn-did-the-action-record)) are kept after the summary as they were.
686
730
  - **Trace, before each executor / replanner / synthesizer call.** When it no longer fits, every step but the last `keepRecentSteps` is folded into a running summary; prompts show `Summary of earlier steps: …` followed by the recent steps verbatim. The trace itself stays intact in the result, the events and persistence; the summary is saved in the snapshot (`traceSummary`, `traceSummaryUpTo`) so a resumed run keeps it.
687
731
  - **Tool results.** Every tool (MCP, native, built-in) gets a `toModelOutput` that clips what the model sees to `maxToolOutputChars` with a `… [truncated N chars]` marker. A tool's own `toModelOutput` runs first. The raw output still lands in the trace and in `step.tool-result`.
688
732
  - **Stale tool results inside a step** (context editing, like Anthropic's `clear_tool_uses` and Claude Code's micro-compaction). Once a step's tool loop grows past `clearToolResultsAfterTokens`, the oldest results are replaced with a one-line stub (`[<tool> result cleared to save context — call the tool again if you still need it]`), keeping the newest `keepToolResults`. The calls stay, so the model knows what it did. Clearing is sticky (the cached prefix doesn't flip back) and keyed by position, so servers that repeat tool-call ids are fine. `createToolResultClearer` is exported.
@@ -1446,6 +1490,9 @@ const { mediaCalls, imagesGenerated, transcriptionSeconds } = result.usage // 2,
1446
1490
  | --- | --- |
1447
1491
  | `imageModel` | Mounts `generate_image({ prompt, size?, aspectRatio?, images? })`: one image per call; `images` are reference pictures (below). |
1448
1492
  | `imageInputs` | Whether the image model takes reference pictures. Default: what the model object declares (`supportsFileInputs`; unknown counts as no). |
1493
+ | `fitReference` | Make a reference picture that is over the bounds small enough to send, instead of refusing it (below). This package ships no image codec: your function (e.g. on `sharp`), or `fitReferenceInWorker(module)` to run your module in a worker thread. It must not block the event loop. Default: none - refused. |
1494
+ | `fitTimeoutMs` | One call of `fitReference`. Default `30000` (`MEDIA_FIT_TIMEOUT_MS`). |
1495
+ | `viewGenerated` | Show the executor's model the picture `generate_image` made, **once**, in the request right after the call (below). Default: on where the step's model reads pictures; `true`: on for any model whose adapter carries a picture in a tool result; `false`: off - the path alone. |
1449
1496
  | `speechModel` | Mounts `generate_speech({ text, voice?, language? })`. |
1450
1497
  | `transcriptionModel` | Mounts `transcribe_audio({ path })` and lets a run take audio in `run({ files })`. |
1451
1498
  | `maxCalls` | Media calls **one run** may make, attachments included. Default `8` (`MEDIA_DEFAULT_MAX_CALLS`); `0` = no cap. |
@@ -1454,19 +1501,70 @@ const { mediaCalls, imagesGenerated, transcriptionSeconds } = result.usage // 2,
1454
1501
  | `voice` | The voice of `generate_speech` when the model names none (a provider-specific id). |
1455
1502
  | `speechFormat` | The format asked of the speech model (`'mp3'`, `'wav'`, ...). Default: the provider's. |
1456
1503
 
1457
- **Where the bytes go.** Never to the language model: a base64 image in a tool result would fill the context and be billed as tokens on every later call. `generate_image` and `generate_speech` write a file and return `{ path, mediaType, bytes }`; the `media.generated` event carries the same, so a UI shows the picture or plays the audio from the path. By default the file lands in the run's own directory (`<sandboxRoot>/<runId>/media/`, the same per-run directory binary MCP results are spilled to) and **is removed with it when the run ends** unless `keepSandbox` is set - copy it in the event handler, or set `media.dir` to a directory of yours, which the agent never cleans.
1504
+ **Where the bytes go.** Not into the context: a base64 image in a tool result would fill it and be billed as tokens on every later call (the one exception, a picture shown to the model once, is `viewGenerated`, below). `generate_image` and `generate_speech` write a file and return `{ path, mediaType, bytes }`; the `media.generated` event carries the same, so a UI shows the picture or plays the audio from the path. By default the file lands in the run's own directory (`<sandboxRoot>/<runId>/media/`, the same per-run directory binary MCP results are spilled to) and **is removed with it when the run ends** unless `keepSandbox` is set - copy it in the event handler, or set `media.dir` to a directory of yours, which the agent never cleans.
1458
1505
 
1459
1506
  - **What a file is, is read from its bytes.** The signature decides the type and the extension; what the provider declared is ignored. Only PNG, JPEG, GIF and WebP are written as images, and MP3, WAV, Ogg, FLAC, AAC, M4A and WebM as audio. Anything else - HTML, SVG (it can carry a script), raw PCM, an empty answer - is refused and nothing is written.
1460
1507
  - **Size caps**: an image or an audio file of at most 8 MiB is written (`MEDIA_MAX_IMAGE_BYTES`, `MEDIA_MAX_SPEECH_BYTES`); audio of at most 20 MiB is sent for transcription (`MEDIA_MAX_AUDIO_INPUT_BYTES`); a prompt or a text to speak is at most 4 000 characters.
1461
1508
  - **The tool names the file**: `image-<random>.png`, `speech-<random>.mp3`. The model has no argument that is a path or a name, an existing file is never replaced, and the final path is checked to be a direct child of the folder.
1462
1509
  - **`transcribe_audio` reads only inside the run's directory** (and `media.dir`): the path a tool returned for an audio file - an MCP tool's spilled audio, or a file `generate_speech` wrote. Both sides are resolved through symlinks before they are compared, so `../`, an absolute path elsewhere and a link that points out are all refused before a byte is read. The Node agent has no workspace of the user's files, which is why the tool reaches no further; the browser sibling's reads its virtual file system.
1463
1510
 
1511
+ **The model sees the picture it made** (`media.viewGenerated`). With only a path the model cannot check a picture against the request ("is the cat on the left?"), make a wrong one again, or say later what it drew. So after a successful `generate_image`, a model that reads pictures gets the picture itself - an image part of that call's tool result (the AI SDK's tool-result content, `{ type: 'file', mediaType, data }`) - in the executor's **next request only**: from the request after it, the picture is taken out again and a line says it was shown. Nothing else carries it: the tool's output (`{ path, mediaType, bytes }`), the `step.tool-result` and `media.generated` events, the trace and the result, snapshots, the call journal and the conversation you keep are exactly as without it; the picture waits in the run's memory until that request, and a step that ends first drops it.
1512
+
1513
+ - **Which models.** Only an executor model whose AI SDK adapter sends an image part of a tool result as an image - Gemini (`google.generative-ai`, `google.vertex.chat`), Claude (`anthropic.messages`), OpenAI's Responses API (`openai.responses`, `azure.responses`; the `openai(id)` default), xAI (`xai.responses`), DeepSeek (`deepseek.chat` / `deepseek.responses`) - read from the model object's `provider`. The others turn a tool result's content into JSON text: OpenAI's Chat Completions (`openai.chat(id)`) and every OpenAI-compatible endpoint would put megabytes of base64 into the prompt, so they **never** get one, whatever the setting says. Among those adapters the default is on for a model known to read pictures (not a text-only family - GPT-3.5, o1-mini / o3-mini, embeddings -, and only DeepSeek's Flash line); `viewGenerated: true` turns it on for any model of those adapters, `false` turns it off. Judged per step (an escalated step's model is judged again). A model given as a string (the gateway) is unknown: off.
1514
+ - **Bounded.** The picture is sent at most once - the request after its call - and at most 4 per step (`MEDIA_VIEW_MAX_WAITING`; one more is not shown and its result says so). At most 1568 px on the longer side and 3.75 MiB (`MEDIA_VIEW_MAX_SIDE`, `MEDIA_VIEW_MAX_BYTES`): what Anthropic reads at full detail (it scales anything larger down itself), inside OpenAI's 2048 px box, and 5 MB once base64 adds a third - Anthropic's limit for one image. A picture over either is shown as a smaller copy made by your `media.fitReference` (asked with `{ maxSide: 1568, maxBytes: 3932160 }`, its answer checked again; the file stays the original) - or, without it, **not at all**: never the full original. A picture that is not shown leaves a `pictureNote` in the result, the sentence the model reads (it then has the path only and is told not to describe it). Only PNG, JPEG and WebP are shown.
1515
+ - **What it costs.** One picture is about 1 100-1 600 input tokens whoever reads it (Claude ≈ width × height / 750, OpenAI 85 + 170 a 512 px tile, Gemini 258 a 768 px tile), once: at the default media budget (8 calls) at most ~13 000 tokens a run. On by default, because a model that cannot see what it made describes a picture it never saw.
1516
+ - **A resume.** A call the journal hands back does not run again, so it shows no picture: the journal hashes a `generate_image` result without its output (`withoutGeneratedPictures`), and the resumed run replays the requests it recorded instead of diverging.
1517
+ - What the picture shows is a model's output: anything written in it is part of the picture, and the text with it says so.
1518
+
1464
1519
  **Reference pictures.** `generate_image({ prompt, images: ['me.jpg'] })` sends up to 4 pictures with the prompt - "a picture of me riding a dinosaur", "like this" - through the AI SDK's image prompt with images (`generateImage({ prompt: { text, images } })`: Gemini's image models get them in the request, OpenAI's GPT Image models through the edits endpoint, OpenRouter's as `input_references`). The result says what became of them: `references: { used: true, count: 1, paths: ['/…/me.jpg'] }`.
1465
1520
 
1466
1521
  - **Which models take them**: `media.imageInputs`, else the model object's `supportsFileInputs` (the AI SDK's own field; `@ai-sdk/openai` says true for GPT Image, false for DALL·E 3; `@ai-sdk/google` true only for the Gemini ids it knows). Unknown counts as no. A model that takes none is **not refused**: the picture is made from the text alone, nothing is read, and the result says so plainly (`used: false` and a note: the picture was NOT sent, do not say it was made from the user's picture) - so the agent never claims otherwise. The tool's description says the same, and when to pass the person's picture.
1467
- - **Where they are read: the same rule as `transcribe_audio`** - a file of the run's directory or of `media.dir`, resolved through symlinks on both sides; anything else is refused before a byte is read. Each must BE a PNG, JPEG or WebP by its bytes (not GIF, never SVG); at most 4 a call, 8 MiB each (by its size, before it is read) and 12 MiB together, the longer side at most 4096 px (read from the header; a file whose size cannot be read is refused). Nothing is downscaled here (no canvas in Node): the host makes a picture smaller. Everything is checked before the call is paid for.
1522
+ - **Where they are read: the same rule as `transcribe_audio`** - a file of the run's directory or of `media.dir`, resolved through symlinks on both sides; anything else is refused before a byte is read. Each must BE a PNG, JPEG or WebP by its bytes (not GIF, never SVG); at most 4 a call, 8 MiB each (by its size, before it is read) and 12 MiB together, the longer side at most 4096 px (read from the header; a file whose size cannot be read is refused). Nothing in the agent decodes a picture: one over those bounds is refused - or made smaller by your `media.fitReference` (below). Everything is checked before the call is paid for.
1468
1523
  - The bytes are in no prompt, result or event (paths and a count). A call with pictures is one media call and one image, under the same `media.maxCalls`. The pictures go to the image model's provider with the prompt.
1469
1524
 
1525
+ **A picture over the bounds, made smaller when it is sent.** With `media.fitReference` a picture over 4096 px or 8 MiB is not refused: your function makes a smaller copy and that is sent; the file itself stays as it is. The agent calls it **only** for a PNG / JPEG / WebP of the run's directory that passed every other check and is over the side or the bytes, and only within the original's own bounds, judged **before anything decodes it**: 50 MiB by the file's size (`MEDIA_MAX_REFERENCE_SOURCE_BYTES`, before a byte is read) and 200 MP read from the header (`MEDIA_MAX_REFERENCE_SOURCE_PIXELS`) - a 30000 x 30000 PNG of a few kilobytes (3.6 GB decoded) is refused and never handed to your code. It gets `(picture, bounds, { signal })`: `picture` is `{ bytes, mediaType, width, height, path }` (the bytes as read, the type from the bytes, the size from the header), `bounds` is `{ maxSide: 4096, maxBytes }` - the smaller of 8 MiB and an equal share of the 12 MiB the pictures of a call may come to. Its answer `{ bytes, mediaType? }` is **checked again** by the same guards (PNG / JPEG / WebP by its bytes - the `mediaType` it gives is ignored -, 4096 px, 8 MiB, the total); `undefined`, a throw, or no answer within `media.fitTimeoutMs` (30 s; `signal` is aborted then, and when the run stops) refuses the picture with the reason. Pictures that each fit but together come to more than 12 MiB: the largest still over its share is made smaller first (it gives back the most, so the fewest are re-encoded), then the next, each at most once. The result and `media.generated` say which went smaller: `references: { used: true, count: 1, paths: ['/…/me.jpg'], fitted: ['/…/me.jpg'] }` - paths only.
1526
+
1527
+ **Your function must not block the event loop.** It is awaited on the thread every run of the process shares, and a time bound cannot stop synchronous work: a pure-JS decode and resize of a 24 MP photo holds up everything for seconds, and the timeout fires only after it. [`sharp`](https://sharp.pixelplumbing.com) is fine - it is async and runs libvips on the libuv threadpool:
1528
+
1529
+ ```ts
1530
+ import sharp from 'sharp'
1531
+ import type { MediaFitReference } from '@dudko.dev/agent'
1532
+
1533
+ const fitReference: MediaFitReference = async (picture, { maxSide, maxBytes }) => {
1534
+ for (const quality of [85, 70, 55]) {
1535
+ const { data, info } = await sharp(picture.bytes)
1536
+ .rotate() // EXIF orientation: a phone's portrait photo comes out upright
1537
+ .resize(maxSide, maxSide, { fit: 'inside', withoutEnlargement: true })
1538
+ .jpeg({ quality })
1539
+ .toBuffer({ resolveWithObject: true })
1540
+ if (data.length <= maxBytes) return { bytes: data, mediaType: `image/${info.format}` }
1541
+ }
1542
+ return undefined // refused
1543
+ }
1544
+ createAgent({ ...config, media: { imageModel, fitReference } })
1545
+ ```
1546
+
1547
+ Anything synchronous goes into a worker thread. `fitReferenceInWorker(module)` (no dependency, `node:worker_threads` only) runs **your module** there: one worker per picture, the bytes transferred (not copied) both ways, and the worker **terminated** at the time bound or when the run stops - which stops even a synchronous loop. The module exports `fitReference` (or a default export; `{ exportName }` picks another), a function of `(picture, bounds)`:
1548
+
1549
+ ```ts
1550
+ // fit.js - runs in the worker: blocking here blocks nobody
1551
+ import { decode, resize, encodeJpeg } from 'some-pure-js-codec' // yours
1552
+ export const fitReference = (picture, { maxSide, maxBytes }) => {
1553
+ const image = resize(decode(picture.bytes), maxSide)
1554
+ const bytes = encodeJpeg(image, 80)
1555
+ return bytes.length <= maxBytes ? { bytes, mediaType: 'image/jpeg' } : undefined
1556
+ }
1557
+
1558
+ // the agent
1559
+ import { createAgent, fitReferenceInWorker } from '@dudko.dev/agent'
1560
+ createAgent({
1561
+ ...config,
1562
+ media: { imageModel, fitReference: fitReferenceInWorker(new URL('./fit.js', import.meta.url)) },
1563
+ })
1564
+ ```
1565
+
1566
+ The path is absolute (or a `file:` URL); `resourceLimits` bounds the worker's heap. The browser sibling ships a ready implementation on the browser's codecs (`fitReferenceImage`); Node has no canvas, so this package ships none.
1567
+
1470
1568
  **Audio attachments.** `run({ input, files: [{ data, name?, mediaType? }] })` takes audio as bytes, base64 or a data URL. Each file is transcribed **once**, before planning, and its text is put under the input in a fenced block that says what it is:
1471
1569
 
1472
1570
  ```
@@ -1862,7 +1960,7 @@ Consent is the host's job ([tool approval](#tool-approval-and-autopilot)) — th
1862
1960
  | `outputSanitizer` | Optional `(toolName, output) => unknown` hook to redact tool results before they reach the LLM. |
1863
1961
  | `inputSanitizer` | Optional `(toolName, input) => unknown` hook to redact LLM-generated tool args before they hit the MCP server **and** before they appear in `step.tool-call` events. **Must be idempotent** — applied at both the event boundary and the dispatch boundary. |
1864
1962
  | `outputSanitizer` ordering | The sanitizer runs on the **raw MCP `result.content`** (image/audio base64 still inline), **before** the agent spills binary parts to the sandbox. This favors privacy: a sanitizer that drops a sensitive image keeps the bytes out of the disk entirely. If you want post-spill sanitization (e.g. redact a path), do it in your tool wrapper instead. A result with `structuredContent` calls the sanitizer a second time with that object, so it cannot bypass redaction. |
1865
- | `media` | Off by default. `{ imageModel, imageInputs, speechModel, transcriptionModel, maxCalls, timeoutMs, dir, voice, speechFormat }`: each model mounts its tool (`generate_image` - with reference pictures for a model that takes them -, `generate_speech`, `transcribe_audio` + audio attachments). Files on disk, never bytes in the context; calls counted in `usage.mediaCalls` (and the other media fields) and capped per run. See [Media](#media-images-speech-and-transcription). |
1963
+ | `media` | Off by default. `{ imageModel, imageInputs, fitReference, fitTimeoutMs, viewGenerated, speechModel, transcriptionModel, maxCalls, timeoutMs, dir, voice, speechFormat }`: each model mounts its tool (`generate_image` - with reference pictures for a model that takes them; one over 4096 px / 8 MiB refused, or made smaller by your `fitReference` (no codec here: `sharp`, or `fitReferenceInWorker(module)`; it must not block the event loop) -, `generate_speech`, `transcribe_audio` + audio attachments). Files on disk, never bytes in the context - except the picture `generate_image` made, shown once to an executor model that reads pictures (`viewGenerated`); calls counted in `usage.mediaCalls` (and the other media fields) and capped per run. See [Media](#media-images-speech-and-transcription). |
1866
1964
  | `sandboxRoot` | Per-run sandbox subdirs are created at `<sandboxRoot>/<runId>/` for tools that spill binary content (images, audio, blob resources). Defaults to `<os.tmpdir()>/agent-sandbox`. |
1867
1965
  | `keepSandbox` | When `true`, the per-run directory is not removed after the run completes. Default `false`. |
1868
1966
  | `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
@@ -2041,7 +2139,7 @@ interface IAgent {
2041
2139
  }
2042
2140
  ```
2043
2141
 
2044
- `IAgentRunResult` is `{ runId, text, plan, trace, iterations, usage, compactedHistory?, undelivered?, parked? }` (`runId`: the run's id, the one its events and snapshots carry - always set by `run()`, optional in the type only so that a hand-made result stays valid; `parked`: the run [parked](#parking-a-run-a-persons-answer-or-a-result-from-outside) and waits for `parked.items`). `run()` also takes `files` (audio attachments, with `media.transcriptionModel` - see [Media](#media-images-speech-and-transcription)), `runId` (a fresh run under an id of yours - see [Your own run id](#resume-after-crash)) and, with `resumeFromRunId`, `answers` (the answers to a parked run's items, by id).
2142
+ `IAgentRunResult` is `{ runId, text, plan, trace, iterations, usage, compactedHistory?, undelivered?, actionRecord?, parked? }` (`actionRecord`: the runner's record of what the run did - see [What a turn did](#what-a-turn-did-the-action-record); a run that throws carries it on the error, `actionRecordOf(err)`) (`runId`: the run's id, the one its events and snapshots carry - always set by `run()`, optional in the type only so that a hand-made result stays valid; `parked`: the run [parked](#parking-a-run-a-persons-answer-or-a-result-from-outside) and waits for `parked.items`). `run()` also takes `files` (audio attachments, with `media.transcriptionModel` - see [Media](#media-images-speech-and-transcription)), `runId` (a fresh run under an id of yours - see [Your own run id](#resume-after-crash)) and, with `resumeFromRunId`, `answers` (the answers to a parked run's items, by id).
2045
2143
 
2046
2144
  A single agent instance supports concurrent `run()` calls — each gets its own `runId` (via `AsyncLocalStorage`), usage accumulator, abort signal, and `onEvent`. Tools and models are shared.
2047
2145