@astralyn/pi 1.4.9 → 1.4.11
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/CHANGELOG.md +69 -0
- package/dist/bundle/chunks/{chunk-BAGHIP5J.js → chunk-NUQMVNKQ.js} +3 -3
- package/dist/bundle/chunks/{chunk-3PKXUKTB.js → chunk-PUU43PDV.js} +121 -136
- package/dist/bundle/chunks/{chunk-F66AY3WR.js → chunk-TH3QDDPD.js} +1 -1
- package/dist/bundle/chunks/{execute-P22VMM2H.js → execute-VLAIP26K.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-VKMBQTR2.js → virtual-modules-63XNTSVN.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts +34 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +99 -5
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +14 -7
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/isolated-session.d.ts +7 -2
- package/dist/core/isolated-session.d.ts.map +1 -1
- package/dist/core/isolated-session.js +7 -3
- package/dist/core/isolated-session.js.map +1 -1
- package/dist/core/session-manager.d.ts +17 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +29 -0
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/tasks/delivery.d.ts +31 -12
- package/dist/core/tasks/delivery.d.ts.map +1 -1
- package/dist/core/tasks/delivery.js +97 -36
- package/dist/core/tasks/delivery.js.map +1 -1
- package/dist/core/tasks/execution.d.ts +27 -14
- package/dist/core/tasks/execution.d.ts.map +1 -1
- package/dist/core/tasks/execution.js +90 -86
- package/dist/core/tasks/execution.js.map +1 -1
- package/dist/core/tasks/limits.d.ts +7 -11
- package/dist/core/tasks/limits.d.ts.map +1 -1
- package/dist/core/tasks/limits.js +8 -16
- package/dist/core/tasks/limits.js.map +1 -1
- package/dist/core/tasks/output.d.ts +9 -1
- package/dist/core/tasks/output.d.ts.map +1 -1
- package/dist/core/tasks/output.js +23 -10
- package/dist/core/tasks/output.js.map +1 -1
- package/dist/core/tasks/presentation.d.ts +1 -1
- package/dist/core/tasks/presentation.d.ts.map +1 -1
- package/dist/core/tasks/presentation.js +6 -4
- package/dist/core/tasks/presentation.js.map +1 -1
- package/dist/core/tasks/record.d.ts +41 -29
- package/dist/core/tasks/record.d.ts.map +1 -1
- package/dist/core/tasks/record.js +82 -37
- package/dist/core/tasks/record.js.map +1 -1
- package/dist/core/tasks/reminder.js +2 -2
- package/dist/core/tasks/reminder.js.map +1 -1
- package/dist/core/tasks/runtime.d.ts +15 -23
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +50 -178
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/scheduler.d.ts +3 -1
- package/dist/core/tasks/scheduler.d.ts.map +1 -1
- package/dist/core/tasks/scheduler.js +16 -12
- package/dist/core/tasks/scheduler.js.map +1 -1
- package/dist/core/tasks/session.d.ts +24 -6
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +70 -22
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/store.d.ts +17 -4
- package/dist/core/tasks/store.d.ts.map +1 -1
- package/dist/core/tasks/store.js +45 -48
- package/dist/core/tasks/store.js.map +1 -1
- package/dist/core/tasks/types.d.ts +64 -93
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js +7 -0
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/shell-execution.d.ts.map +1 -1
- package/dist/core/tools/shell-execution.js +2 -1
- package/dist/core/tools/shell-execution.js.map +1 -1
- package/dist/core/tools/shell-tool.d.ts.map +1 -1
- package/dist/core/tools/shell-tool.js +20 -13
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/extensions/agent/activity-lines.d.ts +10 -0
- package/dist/extensions/agent/activity-lines.d.ts.map +1 -0
- package/dist/extensions/agent/activity-lines.js +76 -0
- package/dist/extensions/agent/activity-lines.js.map +1 -0
- package/dist/extensions/agent/activity.d.ts +25 -4
- package/dist/extensions/agent/activity.d.ts.map +1 -1
- package/dist/extensions/agent/activity.js +76 -21
- package/dist/extensions/agent/activity.js.map +1 -1
- package/dist/extensions/agent/artifacts.d.ts +15 -0
- package/dist/extensions/agent/artifacts.d.ts.map +1 -0
- package/dist/extensions/agent/artifacts.js +44 -0
- package/dist/extensions/agent/artifacts.js.map +1 -0
- package/dist/extensions/agent/progress.d.ts +30 -4
- package/dist/extensions/agent/progress.d.ts.map +1 -1
- package/dist/extensions/agent/progress.js +84 -11
- package/dist/extensions/agent/progress.js.map +1 -1
- package/dist/extensions/agent/render.d.ts.map +1 -1
- package/dist/extensions/agent/render.js +8 -24
- package/dist/extensions/agent/render.js.map +1 -1
- package/dist/extensions/agent/report.d.ts +11 -3
- package/dist/extensions/agent/report.d.ts.map +1 -1
- package/dist/extensions/agent/report.js +32 -7
- package/dist/extensions/agent/report.js.map +1 -1
- package/dist/extensions/agent/tool.d.ts.map +1 -1
- package/dist/extensions/agent/tool.js +20 -5
- package/dist/extensions/agent/tool.js.map +1 -1
- package/dist/extensions/agent/types.d.ts +2 -0
- package/dist/extensions/agent/types.d.ts.map +1 -1
- package/dist/extensions/agent/types.js.map +1 -1
- package/dist/extensions/agent/worker.d.ts +7 -0
- package/dist/extensions/agent/worker.d.ts.map +1 -1
- package/dist/extensions/agent/worker.js +9 -3
- package/dist/extensions/agent/worker.js.map +1 -1
- package/dist/extensions/cached-compaction/summary.d.ts +1 -1
- package/dist/extensions/cached-compaction/summary.d.ts.map +1 -1
- package/dist/extensions/cached-compaction/summary.js +13 -16
- package/dist/extensions/cached-compaction/summary.js.map +1 -1
- package/dist/extensions/search/index.d.ts.map +1 -1
- package/dist/extensions/search/index.js +6 -7
- package/dist/extensions/search/index.js.map +1 -1
- package/dist/extensions/tasks/tool/actions.d.ts +1 -2
- package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/actions.js +12 -80
- package/dist/extensions/tasks/tool/actions.js.map +1 -1
- package/dist/extensions/tasks/tool/constants.d.ts +1 -3
- package/dist/extensions/tasks/tool/constants.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/constants.js +1 -3
- package/dist/extensions/tasks/tool/constants.js.map +1 -1
- package/dist/extensions/tasks/tool/schema.d.ts +2 -3
- package/dist/extensions/tasks/tool/schema.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/schema.js +10 -18
- package/dist/extensions/tasks/tool/schema.js.map +1 -1
- package/dist/extensions/tasks/tool/types.d.ts +1 -17
- package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/types.js.map +1 -1
- package/dist/extensions/tasks/tool.d.ts +1 -2
- package/dist/extensions/tasks/tool.d.ts.map +1 -1
- package/dist/extensions/tasks/tool.js +5 -6
- package/dist/extensions/tasks/tool.js.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.js +2 -2
- package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
- package/dist/extensions/tasks/ui/footer.d.ts +37 -0
- package/dist/extensions/tasks/ui/footer.d.ts.map +1 -0
- package/dist/extensions/tasks/ui/footer.js +129 -0
- package/dist/extensions/tasks/ui/footer.js.map +1 -0
- package/dist/extensions/tasks/ui/frame.d.ts +36 -0
- package/dist/extensions/tasks/ui/frame.d.ts.map +1 -0
- package/dist/extensions/tasks/ui/frame.js +33 -0
- package/dist/extensions/tasks/ui/frame.js.map +1 -0
- package/dist/extensions/tasks/ui/help.d.ts +6 -0
- package/dist/extensions/tasks/ui/help.d.ts.map +1 -0
- package/dist/extensions/tasks/ui/help.js +53 -0
- package/dist/extensions/tasks/ui/help.js.map +1 -0
- package/dist/extensions/tasks/ui/inspector.d.ts +4 -3
- package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/inspector.js +25 -6
- package/dist/extensions/tasks/ui/inspector.js.map +1 -1
- package/dist/extensions/tasks/ui/layout.d.ts +15 -18
- package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/layout.js +162 -255
- package/dist/extensions/tasks/ui/layout.js.map +1 -1
- package/dist/extensions/tasks/ui/list.d.ts +3 -1
- package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/list.js +19 -14
- package/dist/extensions/tasks/ui/list.js.map +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts +17 -5
- package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/manager.js +147 -90
- package/dist/extensions/tasks/ui/manager.js.map +1 -1
- package/dist/extensions/tasks/ui/model.d.ts +32 -5
- package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/model.js +7 -7
- package/dist/extensions/tasks/ui/model.js.map +1 -1
- package/dist/extensions/tasks/ui/panes.d.ts +40 -0
- package/dist/extensions/tasks/ui/panes.d.ts.map +1 -0
- package/dist/extensions/tasks/ui/panes.js +144 -0
- package/dist/extensions/tasks/ui/panes.js.map +1 -0
- package/dist/extensions/tasks/ui/render.d.ts +2 -16
- package/dist/extensions/tasks/ui/render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/render.js +13 -85
- package/dist/extensions/tasks/ui/render.js.map +1 -1
- package/dist/extensions/tasks/ui/viewport.d.ts +12 -4
- package/dist/extensions/tasks/ui/viewport.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/viewport.js +23 -7
- package/dist/extensions/tasks/ui/viewport.js.map +1 -1
- package/dist/extensions/tasks/ui/views.d.ts +12 -6
- package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/views.js +39 -32
- package/dist/extensions/tasks/ui/views.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +11 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +43 -17
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +38 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +11 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +48 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +2 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +2 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/bundled/extensions/agent.md +39 -7
- package/docs/bundled/extensions/statusline.md +1 -1
- package/docs/bundled/tasks.md +28 -37
- package/docs/bundled/tool-presentation.md +1 -1
- package/docs/extensions.md +15 -13
- package/docs/json.md +3 -0
- package/docs/models-configuration.md +1 -1
- package/docs/models.md +7 -85
- package/docs/rpc.md +14 -0
- package/docs/sdk.md +12 -2
- package/docs/session-format.md +11 -5
- package/docs/sessions.md +1 -1
- package/docs/usage.md +2 -0
- package/package.json +3 -4
- package/dist/modes/interactive/tool-view/tool-execution.d.ts +0 -14
- package/dist/modes/interactive/tool-view/tool-execution.d.ts.map +0 -1
- package/dist/modes/interactive/tool-view/tool-execution.js +0 -13
- package/dist/modes/interactive/tool-view/tool-execution.js.map +0 -1
- package/docs/images/doom-extension.png +0 -0
- package/docs/images/exy.png +0 -0
- package/npm-shrinkwrap.json +0 -4207
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,75 @@ This file records `@astralyn/pi` releases beginning with the first Fork-owned re
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [1.4.11] - 2026-11-01
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- Repository and release automation now use `package-lock.json` with npm 12. Published installations no longer pin transitive dependency resolutions through `npm-shrinkwrap.json`; direct dependencies remain exact and CI continues to install a reproducible tree with `npm ci`.
|
|
12
|
+
|
|
13
|
+
### Removed
|
|
14
|
+
|
|
15
|
+
- The `tasks` tool's `wait` action and its `waitMs` parameter, along with `TasksContext.wait()`/`waitAny()` and their types. Background completions already wake the model automatically, so the model now continues independent work or ends its turn instead of blocking. Steering no longer has wait-only interruption semantics. Saved `tasks wait` results in old sessions render as their saved text. Hosts that must outlast background work use `AgentSession.waitForQuiescence()`.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- Print and JSON mode now enable managed background execution, so their existing quiescence waits can outlast background work and print the completion turn; RPC mode enables the same execution and delivery path for clients using its quiescence APIs. Ordinary SDK sessions remain opt-in.
|
|
20
|
+
- `tasks read` honours `sinceBytes`, so a read continues from the `next sinceBytes` offset it reported. Previously only `wait` applied the offset and `read` silently ignored it.
|
|
21
|
+
|
|
22
|
+
## [1.4.10] - 2026-11-01
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- `AgentSession.waitForQuiescence(signal?)`, `AgentSession.isQuiescent` and a `session_quiescent` session event report when no run, compaction, retry, unsettled background task or pending completion turn remains. Failed deliveries do not count, so the wait cannot deadlock on them.
|
|
27
|
+
- RPC: `get_state` reports `isQuiescent`, and `RpcClient.waitForQuiescence()` and `collectEventsUntilQuiescent()` wait for background completion turns that `waitForIdle()` and `collectEvents()` miss.
|
|
28
|
+
- `AgentSession.acknowledgeTaskDelivery(id)` tells the session that a direct SDK waiter consumed a background result, so the model is not notified about it again.
|
|
29
|
+
- Background outcomes of `TasksContext.execute()` carry `reason: "submitted" | "detached"`, so executors no longer re-derive how their caller was released.
|
|
30
|
+
- `TaskExecution.present` and `ctx.tasks.presentOutput(id, width, theme)` let an executor render its running task's Output in `/tasks` with its own styling. The presenter lives in memory with the running execution: it is never persisted, absent from snapshots and dropped at settlement, and a throwing presenter falls back to the default view.
|
|
31
|
+
- A saved session owns an artifacts directory beside its file (`<name>/` for `<name>.jsonl`). `SessionManager.getArtifactDir()`, also on `ctx.sessionManager`, returns it, or `undefined` for a session that is not persisted. `SessionManager.createAt(path, cwd, options?)` creates a persisted session at an exact path.
|
|
32
|
+
- In a saved session, each Agent keeps its complete report (`report.md`) and its child transcript (`transcript.jsonl`, a Pi session file linked to the main session through `parentSession`) in `<session>/agents/<task-id>/`. The `Full output:` path of an oversized report now stays valid after `pi -c` and Tasks retention. Details of a settled Agent show `Tool calls`, `Edited` (files changed through `edit` and `write`), `Report` and `Transcript`, and the report returned to the model ends with `Edited (edit/write): …` when the Agent changed files.
|
|
33
|
+
|
|
34
|
+
### Changed
|
|
35
|
+
|
|
36
|
+
- Print mode and `--mode json` wait for background tasks and the turns that deliver their results before printing the final response and exiting, instead of ending the process (and killing the work) after the prompt's own turn. A stderr line names the tasks being waited for. Ctrl+C (`SIGINT`) now cleans up like `SIGTERM` and exits 130; a second signal exits immediately.
|
|
37
|
+
- `/tasks` panel:
|
|
38
|
+
- On wide terminals the list takes 40% of the width (34–60 columns). Pane titles and the reading or scroll state live in the borders.
|
|
39
|
+
- The inspector opens with the selected task's full title in bold and a `Label · Status · Mode · runtime` line, separated from the content by a rule.
|
|
40
|
+
- Details starts at the task ID instead of repeating source and status, and long values wrap within their column.
|
|
41
|
+
- Output shows an executor's human-readable display in place of its model-facing result when it has one.
|
|
42
|
+
- A settled report opens at its first line instead of its end, keeps the position you scroll to, and shows its scroll range in the bottom border when it overflows.
|
|
43
|
+
- Only a log streams from its file. A report always shows what its executor published, so an oversized Agent report renders as Markdown from its beginning instead of as a tail preview, and Details labels its saved file `Full report`.
|
|
44
|
+
- `/tasks` in a narrow terminal: Escape returns from the inspector to the list and closes the panel only from the list. The footer names the action (`Esc back` or `Esc close`) and drops its lowest-priority hints first.
|
|
45
|
+
- `/tasks` notices appear only when an action did not do what was asked, as a toned warning (`!`) or error (`×`) that clears on the next input or after about four seconds. Successful stop and background requests no longer show a message, and a pending stop confirmation marks its target row with `stop?`.
|
|
46
|
+
- Agent in `/tasks` and the Transcript:
|
|
47
|
+
- A finished Agent's Output shows only its final report, whatever its outcome; its tool calls no longer follow the report.
|
|
48
|
+
- While an Agent runs, Output is a compact list of its tool calls with no heading: one `glyph tool target · duration` row per call with the tool names aligned (up to 8 characters), a `… N earlier tool calls` line for calls no longer retained, and one line holding the first line of a failed call's error. The expanded Transcript row uses the same columns.
|
|
49
|
+
- Paths inside the Agent's working directory appear relative, with forward slashes; paths outside it stay absolute.
|
|
50
|
+
- Tool-call durations read `42ms`, `6.2s`, then `1m 5s`.
|
|
51
|
+
- A running Agent's tool calls are styled in `/tasks` Output as in the Transcript's expanded row (status-colored glyph, tool name, muted target, dim duration, error line), fitted to the pane width, with the running call's elapsed time. Both views share one renderer, so the Transcript's expanded row now also shows a failed call's error line.
|
|
52
|
+
- Tool-call glyphs are the task status markers used elsewhere in `/tasks`: `×` for a failed call and `○` for a cancelled one instead of `✗` and `⊘`, and a running call shows the animated running-task spinner in the accent color instead of a dim `…`, which was also easy to confuse with the earlier-calls line. The plain fallback shows `›` for a running call.
|
|
53
|
+
- Styled rows right-align durations in one column that ends at the longest row, so short and clipped targets no longer leave their durations at different positions.
|
|
54
|
+
- Background-task guidance tells the model to end its turn instead of waiting, because a finished task starts a new turn for it automatically. Agent guidance reserves `background: true` for when there is independent work to do meanwhile and points to the foreground otherwise. Agent and shell handoffs, the post-compaction reminder and the `tasks` prompt snippet no longer suggest `tasks wait`, `tasks` reserves `wait` for when the user asks to block on a task, and an expired wait, including one on a single task, says not to wait again. The default `tasks wait` window grows from 20 seconds to 4 minutes, the longest that keeps the next request inside a five-minute prompt cache; a wait still returns as soon as its task finishes.
|
|
55
|
+
- Background completion cards no longer end with "Preview of the saved result.", and a failed shell task's card and model notification state its error once instead of repeating it at the end of the output.
|
|
56
|
+
- Deleting a session from `/resume` also removes its artifacts directory and its `.tasks-late.jsonl` sidecar, which were previously left behind. The `trash` CLI receives every path in one call. Files that could not be removed are reported.
|
|
57
|
+
- `/tasks` Details no longer repeats a path when a Details row already names the saved output file.
|
|
58
|
+
- Concurrency lanes are namespaced by executor kind, so two executors can no longer share a lane by choosing the same key.
|
|
59
|
+
- **Breaking:** background work, submitted or detached, is admitted only while the `tasks` tool is active, because the model could otherwise start work it cannot read, wait for or stop. When `builtin:tasks` is disabled or the tool is deactivated, `background: true` and every detach path are rejected without starting anything; work admitted earlier keeps running and delivering.
|
|
60
|
+
- **Breaking (extension and SDK API):** a task's `mode` is `background` only once its caller has been released with a background outcome. A detach requested while the executor is still preparing waits for its acceptance, and a task answered inline stays `foreground` everywhere: `tasks list`, the statusline count, the `waitAny` cohort and saved records.
|
|
61
|
+
- **Breaking (extension and SDK API):** a terminal task snapshot's `display` comes only from its completion; the last progress display no longer survives settlement. In `/tasks`, `display` replaces the result as the human view instead of being appended to it.
|
|
62
|
+
- **Breaking (extension and SDK API):** `ctx.tasks.read()`, `tasks read`, and settled `tasks wait` and `waitAny` calls without `mode` read a report (`output: "report"`, such as an Agent's) from its start instead of its end, as its foreground result and completion notification already do. Logs, such as a shell command's output, still read from their end. An explicit `mode` selects the direction; `sinceBytes` anchors it, with `head` continuing forward from the offset and `tail` keeping the newest unread window.
|
|
63
|
+
|
|
64
|
+
### Removed
|
|
65
|
+
|
|
66
|
+
- **Breaking (SDK):** `session.tasks.markDelivered()` and the other delivery-ledger methods of `TaskRuntime` (`pendingNotifications()`, `claimNotification()`, `releaseNotification()`, `holdDelivery()`) are removed, along with `TaskDeliveryLedger`. Completion delivery is owned by the session; use `session.acknowledgeTaskDelivery(id)` after consuming a result directly.
|
|
67
|
+
|
|
68
|
+
### Fixed
|
|
69
|
+
|
|
70
|
+
- A standalone `TaskRuntime` with background enabled no longer keeps every settled background record forever and then rejects all background work once its retention limit is reached.
|
|
71
|
+
- A task moved to the background while its executor was still preparing, and then answered inline, is no longer reported and saved as a background task.
|
|
72
|
+
- Following a report's returned `next sinceBytes` now reads the next forward window instead of skipping to its tail. Continuation offsets use raw source bytes even when output is not valid UTF-8, and expanded `tasks read`/`wait` Transcript rows preserve the same end of the result that was read.
|
|
73
|
+
- Timed-out, interrupted and closed task waits release their runtime subscriptions instead of retaining one Promise reaction per observation until settlement.
|
|
74
|
+
- `/tasks` no longer polls a log that has no attached output file only to discard the published result it reads; the retention-limit error now names task pins and delivery leases instead of removed runtime claims.
|
|
75
|
+
|
|
7
76
|
## [1.4.9] - 2026-10-31
|
|
8
77
|
|
|
9
78
|
### Added
|
|
@@ -153,7 +153,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
|
|
|
153
153
|
`)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
154
154
|
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
155
155
|
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str2,maxBytes){let buf=Buffer.from(str2,"utf-8");if(buf.length<=maxBytes)return str2;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}function truncateMiddle(content,maxBytes){let buf=Buffer.from(content,"utf-8"),totalLines=splitLinesForCounting(content).length;if(buf.length<=maxBytes)return{content,truncated:!1,removedChars:0,totalBytes:buf.length,totalLines};let isBoundary=index3=>index3>=buf.length||(buf[index3]&192)!==128,headEnd=Math.floor(maxBytes/2);for(;headEnd>0&&!isBoundary(headEnd);)headEnd--;let tailStart=buf.length-(maxBytes-Math.floor(maxBytes/2));for(;tailStart<buf.length&&!isBoundary(tailStart);)tailStart++;let head=buf.subarray(0,headEnd).toString("utf-8"),tail=buf.subarray(tailStart).toString("utf-8"),removedChars=Array.from(buf.subarray(headEnd,tailStart).toString("utf-8")).length;return{content:`${head}\u2026${removedChars} chars truncated\u2026${tail}`,truncated:!0,removedChars,totalBytes:buf.length,totalLines}}import{open}from"node:fs/promises";function finiteLimit(value,fallback,ceiling){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.min(ceiling,Math.floor(value)))}var TASK_RESULT_BYTES=48*1024,TASK_DETAILS_BYTES=120*1024,TASK_READ_BYTES=8*1024,TASK_INPUT_BYTES=24*1024,TASK_TITLE_BYTES=1024,TASK_LABEL_BYTES=256,TASK_FACTS=16,TASK_FACT_BYTES=1024,TASK_ERROR_BYTES=4096,TASK_PATH_BYTES=8192;function errorText(error,fallback="Task execution failed (unprintable error)"){try{return boundText(error instanceof Error?error.message:String(error),TASK_ERROR_BYTES)}catch{return fallback}}function boundReadBytes(bytes){return finiteLimit(bytes,TASK_READ_BYTES,TASK_RESULT_BYTES)}function alignedSlice(buffer,start,end){for(;start<end&&(buffer[start]&192)===128;)start++;if(end<buffer.length)for(;end>start&&(buffer[end]&192)===128;)end--;let lead=end-1;for(;lead>=start&&(buffer[lead]&192)===128;)lead--;if(lead>=start){let byte=buffer[lead],width=byte>=240?4:byte>=224?3:byte>=192?2:1;end-lead<width&&(end=lead)}return buffer.subarray(start,end)}function boundText(text2,bytes=TASK_RESULT_BYTES){let limit=finiteLimit(bytes,TASK_RESULT_BYTES,TASK_RESULT_BYTES),prefix=text2.slice(0,limit+1),buffer=Buffer.from(prefix);return alignedSlice(buffer,0,Math.min(limit,buffer.length)).toString("utf8")}function boundTaskText(text2,bytes=TASK_RESULT_BYTES){let bounded=boundText(text2,bytes);return{text:bounded,truncated:bounded!==text2}}function boundInput(input){let text2=boundTaskText(input.text,TASK_INPUT_BYTES);return{label:boundText(input.label,TASK_LABEL_BYTES),text:text2.text,truncated:input.truncated||text2.truncated,...input.language?{language:boundText(input.language,64)}:{}}}function boundFacts(facts){return facts.slice(0,TASK_FACTS).map(([label,value])=>[boundText(label,TASK_LABEL_BYTES),boundText(value,TASK_FACT_BYTES)])}function boundTail(text2,bytes){let buffer=Buffer.from(text2);return buffer.length<=bytes?{text:text2,truncated:!1}:{text:alignedSlice(buffer,buffer.length-bytes,buffer.length).toString("utf8"),truncated:!0}}function resultText(result){let remaining=TASK_RESULT_BYTES,parts=[],truncated=!1;for(let block of result.content){if(remaining<=0){truncated=!0;break}let source=block.type==="text"?block.text:"[Image omitted from task output]",text2=boundText(source,remaining);(block.type!=="text"||text2!==source)&&(truncated=!0),parts.push(text2),remaining-=Math.max(1,Buffer.byteLength(text2)+1)}return{text:boundText(parts.join(`
|
|
156
|
-
`)),truncated}}function readWindow(size,options){let bytes=boundReadBytes(options.bytes),since=finiteLimit(options.sinceBytes,0,Number.MAX_SAFE_INTEGER),floor=since>size?0:since,start=options.sinceBytes!==void 0?Math.max(floor,size-bytes):options.mode==="head"?0:Math.max(0,size-bytes);return{start,length:Math.min(bytes,size-start),floor}}function outputSlice(size,floor,slice,fromByte){return{text:slice.toString("utf8"),totalBytes:size,truncated:slice.length<size-floor,fromByte}}async function readOutputSlice(path5,options={}){let file=await open(path5,"r");try{let{size}=await file.stat(),{start,length,floor}=readWindow(size,options),buffer=Buffer.alloc(Math.min(length+1,size-start)),{bytesRead}=await file.read(buffer,0,buffer.length,start),slice=alignedSlice(buffer.subarray(0,bytesRead),0,Math.min(length,bytesRead));return outputSlice(size,floor,slice,start+slice.byteOffset-buffer.byteOffset)}finally{await file.close()}}function sliceText(text2,options={}){let buffer=Buffer.from(text2),{start,length,floor}=readWindow(buffer.length,options),slice=alignedSlice(buffer,start,start+length);return outputSlice(buffer.length,floor,slice,slice.byteOffset-buffer.byteOffset)}var TASK_TERMINAL_STATUSES=["completed","partial","failed","cancelled","timeout"],TASK_KIND_PATTERN=/^[a-z][a-z0-9-]{0,63}$/,TASK_BACKGROUND_REJECTION="Background execution is not permitted in this host. Run with background: false or omit background. No work was started.";function isTaskTerminal(status){return TASK_TERMINAL_STATUSES.includes(status)}var TaskLookupError=class extends Error{constructor(kind,matches){super(kind==="ambiguous"?"Ambiguous task ID":"Unknown task ID"),this.name="TaskLookupError",this.kind=kind,this.matches=matches}};var TASK_RECORD_TYPE="task-record",TASK_SNAPSHOT_VERSION=3;function plainObject(value){if(value===null||typeof value!="object"||Array.isArray(value))throw new Error("Expected object");let prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)throw new Error("Expected plain object");return value}function field(object,key){let descriptor=Object.getOwnPropertyDescriptor(object,key);if(descriptor&&!("value"in descriptor))throw new Error("Unexpected accessor");return descriptor?.value}function text(value,bytes){if(typeof value!="string")throw new Error("Expected string");return boundText(value,bytes)}function exact(value,bytes){if(typeof value!="string"||!value||Buffer.byteLength(value)>bytes||value.includes("\0"))throw new Error("Invalid identity or path");return value}function optional(source,key,read){let value=field(source,key);return value===void 0?void 0:read(value)}function taskText(value,bytes){let source=plainObject(value),original=field(source,"text"),truncated=field(source,"truncated");if(typeof truncated!="boolean")throw new Error("Expected truncation flag");let bounded=text(original,bytes);return{text:bounded,truncated:truncated||bounded!==original}}function taskInput(value){let source=plainObject(value),language=optional(source,"language",item=>text(item,64));return{label:text(field(source,"label"),TASK_LABEL_BYTES),...taskText(source,TASK_INPUT_BYTES),...language?{language}:{}}}function taskFacts(value){if(!Array.isArray(value))throw new Error("Expected facts");return value.slice(0,TASK_FACTS).map(row=>{if(!Array.isArray(row)||row.length!==2)throw new Error("Expected fact");return[text(row[0],TASK_LABEL_BYTES),text(row[1],TASK_FACT_BYTES)]})}function timestamp(value){if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new Error("Expected time");return value}function readPersistedTask(value){try{let source=plainObject(value),kind=field(source,"kind"),mode=field(source,"mode"),status=field(source,"status"),output=field(source,"output");if(typeof kind!="string"||!TASK_KIND_PATTERN.test(kind)||mode!=="foreground"&&mode!=="background"||output!=="log"&&output!=="report"||typeof status!="string"||!isTaskTerminal(status))return;let startedAt=timestamp(field(source,"startedAt")),endedAt=timestamp(field(source,"endedAt"));if(endedAt<startedAt)return;let id=exact(field(source,"id"),512);if(!id.startsWith(`${kind}-`)||id.length<=kind.length+1)return;let anchor=field(source,"anchorId"),task={id,kind,label:text(field(source,"label"),TASK_LABEL_BYTES),title:text(field(source,"title"),TASK_TITLE_BYTES),output,toolCallId:exact(field(source,"toolCallId"),512),anchorId:anchor===null?null:exact(anchor,8192),mode,status,startedAt,endedAt},input=optional(source,"input",taskInput),facts=optional(source,"facts",taskFacts),outputPath=optional(source,"outputPath",item=>exact(item,TASK_PATH_BYTES)),result=optional(source,"result",item=>taskText(item,TASK_RESULT_BYTES)),display=optional(source,"display",item=>taskText(item,TASK_RESULT_BYTES)),error=optional(source,"error",item=>text(item,TASK_ERROR_BYTES));return{...task,...input?{input}:{},...facts?{facts}:{},...outputPath?{outputPath}:{},...result?{result}:{},...display?{display}:{},...error!==void 0?{error}:{}}}catch{return}}function readVersionedTask(value){try{let source=plainObject(value);return field(source,"version")===TASK_SNAPSHOT_VERSION?readPersistedTask(field(source,"task")):void 0}catch{return}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function emptyUsage(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function cacheHitPercent({input,cacheRead,cacheWrite}){let promptTokens=input+cacheRead+cacheWrite;return(cacheRead>0||cacheWrite>0)&&promptTokens>0?cacheRead/promptTokens*100:void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isUsageValue(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0}var LEGACY_TASK_USAGE_TYPE="task-usage";function settledTaskId(entry){if(entry.type!=="custom"||!isRecord(entry.data))return;let data=entry.data;if(entry.customType===TASK_RECORD_TYPE)return data.version===TASK_SNAPSHOT_VERSION&&isRecord(data.task)?data.task.id:void 0;if(entry.customType===LEGACY_TASK_USAGE_TYPE)return data.version===1?data.taskId:void 0}function getTaskUsageRecord(entry){let taskId=settledTaskId(entry);if(typeof taskId!="string"||!taskId.trim()||entry.type!=="custom")return;let usage=entry.data.usage;if(!isRecord(usage)||!isRecord(usage.cost))return;let{input,output,cacheRead,cacheWrite,totalTokens,reasoning,cacheWrite1h}=usage,cost=usage.cost;if(!(!isUsageValue(input)||!isUsageValue(output)||!isUsageValue(cacheRead)||!isUsageValue(cacheWrite)||!isUsageValue(totalTokens)||!isUsageValue(cost.input)||!isUsageValue(cost.output)||!isUsageValue(cost.cacheRead)||!isUsageValue(cost.cacheWrite)||!isUsageValue(cost.total)||reasoning!==void 0&&!isUsageValue(reasoning)||cacheWrite1h!==void 0&&!isUsageValue(cacheWrite1h)))return{taskId,usage:{input,output,cacheRead,cacheWrite,totalTokens,...reasoning===void 0?{}:{reasoning},...cacheWrite1h===void 0?{}:{cacheWrite1h},cost:{input:cost.input,output:cost.output,cacheRead:cost.cacheRead,cacheWrite:cost.cacheWrite,total:cost.total}}}}function*accountedUsageEntries(entries){let backgroundTasks=new Set;for(let entry of entries)if(entry.type==="message"&&entry.message.role==="assistant")yield{key:`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage:entry.message.usage};else if(entry.type==="usage")yield{key:`${entry.provider}/${entry.model}`,usage:entry.usage};else if(entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage)yield{key:"Tools/summaries",usage:entry.message.usage};else if((entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage)yield{key:"Tools/summaries",usage:entry.usage};else{let record=getTaskUsageRecord(entry);if(!record||backgroundTasks.has(record.taskId))continue;backgroundTasks.add(record.taskId),yield{key:"Tools/summaries",usage:record.usage}}}function getAccountedUsages(entries){return Array.from(accountedUsageEntries(entries),({usage})=>usage)}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let{key,usage}of accountedUsageEntries(entries)){let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b2)=>b2.cost-a.cost)}import*as os2 from"node:os";import{pathToFileURL as pathToFileURL2}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path5){if(typeof path5!="string")return"";let home=os2.homedir();return path5.startsWith(home)?`~${path5.slice(home.length)}`:path5}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL2(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text2){return text2.replace(/\t/g," ")}function normalizeDisplayText(text2){return text2.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
|
|
156
|
+
`)),truncated}}function taskReadRange(slice){let from=slice.fromByte??0;return{from,to:slice.endByte??from+Buffer.byteLength(slice.text)}}function taskReadBytes(slice){let{from,to}=taskReadRange(slice);return to-from}function readWindow(size,options){let bytes=boundReadBytes(options.bytes),since=finiteLimit(options.sinceBytes,0,Number.MAX_SAFE_INTEGER),floor=since>size?0:since,start=options.mode==="head"?options.sinceBytes!==void 0?floor:0:Math.max(floor,size-bytes);return{start,length:Math.min(bytes,size-start),floor}}function outputSlice(size,slice,fromByte,earlierTruncated){let endByte=fromByte+slice.byteLength;return{text:slice.toString("utf8"),totalBytes:size,truncated:earlierTruncated||endByte<size,fromByte,endByte}}async function readOutputSlice(path5,options={}){let file=await open(path5,"r");try{let{size}=await file.stat(),{start,length,floor}=readWindow(size,options),buffer=Buffer.alloc(Math.min(length+1,size-start)),{bytesRead}=await file.read(buffer,0,buffer.length,start),slice=alignedSlice(buffer.subarray(0,bytesRead),0,Math.min(length,bytesRead));return outputSlice(size,slice,start+slice.byteOffset-buffer.byteOffset,options.mode!=="head"&&start>floor)}finally{await file.close()}}function sliceText(text2,options={}){let buffer=Buffer.from(text2),{start,length,floor}=readWindow(buffer.length,options),slice=alignedSlice(buffer,start,start+length);return outputSlice(buffer.length,slice,slice.byteOffset-buffer.byteOffset,options.mode!=="head"&&start>floor)}var TASK_TERMINAL_STATUSES=["completed","partial","failed","cancelled","timeout"],TASK_KIND_PATTERN=/^[a-z][a-z0-9-]{0,63}$/,TASKS_TOOL_NAME="tasks",TASK_MANAGEMENT_REJECTION=`Background execution needs the ${TASKS_TOOL_NAME} tool to read and stop the work, and it is not active. Activate the ${TASKS_TOOL_NAME} tool or run in the foreground. No work was started.`,TASK_BACKGROUND_REJECTION="Background execution is not permitted in this host. Run with background: false or omit background. No work was started.";function isTaskTerminal(status){return TASK_TERMINAL_STATUSES.includes(status)}var TaskLookupError=class extends Error{constructor(kind,matches){super(kind==="ambiguous"?"Ambiguous task ID":"Unknown task ID"),this.name="TaskLookupError",this.kind=kind,this.matches=matches}};var TASK_RECORD_TYPE="task-record",TASK_SNAPSHOT_VERSION=3;function plainObject(value){if(value===null||typeof value!="object"||Array.isArray(value))throw new Error("Expected object");let prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)throw new Error("Expected plain object");return value}function field(object,key){let descriptor=Object.getOwnPropertyDescriptor(object,key);if(descriptor&&!("value"in descriptor))throw new Error("Unexpected accessor");return descriptor?.value}function text(value,bytes){if(typeof value!="string")throw new Error("Expected string");return boundText(value,bytes)}function exact(value,bytes){if(typeof value!="string"||!value||Buffer.byteLength(value)>bytes||value.includes("\0"))throw new Error("Invalid identity or path");return value}function optional(source,key,read){let value=field(source,key);return value===void 0?void 0:read(value)}function taskText(value,bytes){let source=plainObject(value),original=field(source,"text"),truncated=field(source,"truncated");if(typeof truncated!="boolean")throw new Error("Expected truncation flag");let bounded=text(original,bytes);return{text:bounded,truncated:truncated||bounded!==original}}function taskInput(value){let source=plainObject(value),language=optional(source,"language",item=>text(item,64));return{label:text(field(source,"label"),TASK_LABEL_BYTES),...taskText(source,TASK_INPUT_BYTES),...language?{language}:{}}}function taskFacts(value){if(!Array.isArray(value))throw new Error("Expected facts");return value.slice(0,TASK_FACTS).map(row=>{if(!Array.isArray(row)||row.length!==2)throw new Error("Expected fact");return[text(row[0],TASK_LABEL_BYTES),text(row[1],TASK_FACT_BYTES)]})}function timestamp(value){if(typeof value!="number"||!Number.isSafeInteger(value)||value<0)throw new Error("Expected time");return value}function readPersistedTask(value){try{let source=plainObject(value),kind=field(source,"kind"),mode=field(source,"mode"),status=field(source,"status"),output=field(source,"output");if(typeof kind!="string"||!TASK_KIND_PATTERN.test(kind)||mode!=="foreground"&&mode!=="background"||output!=="log"&&output!=="report"||typeof status!="string"||!isTaskTerminal(status))return;let startedAt=timestamp(field(source,"startedAt")),endedAt=timestamp(field(source,"endedAt"));if(endedAt<startedAt)return;let id=exact(field(source,"id"),512);if(!id.startsWith(`${kind}-`)||id.length<=kind.length+1)return;let anchor=field(source,"anchorId"),task={id,kind,label:text(field(source,"label"),TASK_LABEL_BYTES),title:text(field(source,"title"),TASK_TITLE_BYTES),output,toolCallId:exact(field(source,"toolCallId"),512),anchorId:anchor===null?null:exact(anchor,8192),mode,status,startedAt,endedAt},input=optional(source,"input",taskInput),facts=optional(source,"facts",taskFacts),outputPath=optional(source,"outputPath",item=>exact(item,TASK_PATH_BYTES)),result=optional(source,"result",item=>taskText(item,TASK_RESULT_BYTES)),display=optional(source,"display",item=>taskText(item,TASK_RESULT_BYTES)),error=optional(source,"error",item=>text(item,TASK_ERROR_BYTES));return{...task,...input?{input}:{},...facts?{facts}:{},...outputPath?{outputPath}:{},...result?{result}:{},...display?{display}:{},...error!==void 0?{error}:{}}}catch{return}}function readVersionedTask(value){try{let source=plainObject(value);return field(source,"version")===TASK_SNAPSHOT_VERSION?readPersistedTask(field(source,"task")):void 0}catch{return}}function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{input:first.input+second.input,output:first.output+second.output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total}}}function emptyUsage(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function cacheHitPercent({input,cacheRead,cacheWrite}){let promptTokens=input+cacheRead+cacheWrite;return(cacheRead>0||cacheWrite>0)&&promptTokens>0?cacheRead/promptTokens*100:void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isUsageValue(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0}var LEGACY_TASK_USAGE_TYPE="task-usage";function settledTaskId(entry){if(entry.type!=="custom"||!isRecord(entry.data))return;let data=entry.data;if(entry.customType===TASK_RECORD_TYPE)return data.version===TASK_SNAPSHOT_VERSION&&isRecord(data.task)?data.task.id:void 0;if(entry.customType===LEGACY_TASK_USAGE_TYPE)return data.version===1?data.taskId:void 0}function getTaskUsageRecord(entry){let taskId=settledTaskId(entry);if(typeof taskId!="string"||!taskId.trim()||entry.type!=="custom")return;let usage=entry.data.usage;if(!isRecord(usage)||!isRecord(usage.cost))return;let{input,output,cacheRead,cacheWrite,totalTokens,reasoning,cacheWrite1h}=usage,cost=usage.cost;if(!(!isUsageValue(input)||!isUsageValue(output)||!isUsageValue(cacheRead)||!isUsageValue(cacheWrite)||!isUsageValue(totalTokens)||!isUsageValue(cost.input)||!isUsageValue(cost.output)||!isUsageValue(cost.cacheRead)||!isUsageValue(cost.cacheWrite)||!isUsageValue(cost.total)||reasoning!==void 0&&!isUsageValue(reasoning)||cacheWrite1h!==void 0&&!isUsageValue(cacheWrite1h)))return{taskId,usage:{input,output,cacheRead,cacheWrite,totalTokens,...reasoning===void 0?{}:{reasoning},...cacheWrite1h===void 0?{}:{cacheWrite1h},cost:{input:cost.input,output:cost.output,cacheRead:cost.cacheRead,cacheWrite:cost.cacheWrite,total:cost.total}}}}function*accountedUsageEntries(entries){let backgroundTasks=new Set;for(let entry of entries)if(entry.type==="message"&&entry.message.role==="assistant")yield{key:`${entry.message.provider}/${entry.message.responseModel??entry.message.model}`,usage:entry.message.usage};else if(entry.type==="usage")yield{key:`${entry.provider}/${entry.model}`,usage:entry.usage};else if(entry.type==="message"&&entry.message.role==="toolResult"&&entry.message.usage)yield{key:"Tools/summaries",usage:entry.message.usage};else if((entry.type==="branch_summary"||entry.type==="compaction")&&entry.usage)yield{key:"Tools/summaries",usage:entry.usage};else{let record=getTaskUsageRecord(entry);if(!record||backgroundTasks.has(record.taskId))continue;backgroundTasks.add(record.taskId),yield{key:"Tools/summaries",usage:record.usage}}}function getAccountedUsages(entries){return Array.from(accountedUsageEntries(entries),({usage})=>usage)}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let{key,usage}of accountedUsageEntries(entries)){let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).filter(entry=>entry.cost>0||entry.tokens>0).sort((a,b2)=>b2.cost-a.cost)}import*as os2 from"node:os";import{pathToFileURL as pathToFileURL2}from"node:url";var ST="(?:\\u0007|\\u001B\\u005C|\\u009C)",OSC_START="\\u001B\\]",CSI_START="[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?",CSI_FINAL="[\\dA-PR-TZcf-nq-uy=><~]",ansiRegex=new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`,"g"),unfinishedAnsiAtEndRegex=new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`),MAX_PENDING_ANSI_LENGTH=256;function splitIncompleteAnsiSuffix(value){if(!value.includes("\x1B")&&!value.includes("\x9B"))return{complete:value,pending:""};let windowStart=Math.max(0,value.length-MAX_PENDING_ANSI_LENGTH),match=unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));if(!match)return{complete:value,pending:""};let splitAt=windowStart+match.index;return{complete:value.slice(0,splitAt),pending:value.slice(splitAt)}}function stripAnsi(value){if(typeof value!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);return!value.includes("\x1B")&&!value.includes("\x9B")?value:value.replace(ansiRegex,"")}function shortenPath(path5){if(typeof path5!="string")return"";let home=os2.homedir();return path5.startsWith(home)?`~${path5.slice(home.length)}`:path5}function linkPath(styledText,rawPath,cwd){if(!getCapabilities().hyperlinks)return styledText;let absolutePath=resolvePath(rawPath,cwd);return hyperlink(styledText,pathToFileURL2(absolutePath).href)}function str(value){return typeof value=="string"?value:value==null?"":null}function parseLineNumber(value){return typeof value=="string"&&value.trim()!==""&&(value=Number(value)),typeof value=="number"&&Number.isFinite(value)?value:void 0}function formatReadLineRange(offset,limit){if(offset==null&&limit==null)return"";let start=offset==null?1:parseLineNumber(offset);if(start===void 0)return"";if(limit==null)return`:${start}`;let count=parseLineNumber(limit);if(count===void 0)return"";let end=start+count-1;return`:${start}${end?`-${end}`:""}`}function replaceTabs(text2){return text2.replace(/\t/g," ")}function normalizeDisplayText(text2){return text2.replace(/\r/g,"")}function getTextOutput(result,showImages){if(!result)return"";let textBlocks=result.content.filter(c=>c.type==="text"),imageBlocks=result.content.filter(c=>c.type==="image"),output=textBlocks.map(c=>sanitizeBinaryOutput(stripAnsi(c.text||"")).replace(/\r/g,"")).join(`
|
|
157
157
|
`),caps=getCapabilities();if(imageBlocks.length>0&&(!caps.images||!showImages)){let imageIndicators=imageBlocks.map(img=>{let mimeType=img.mimeType??"image/unknown",dims=img.data&&img.mimeType?getImageDimensions(img.data,img.mimeType)??void 0:void 0;return imageFallback(mimeType,dims)}).join(`
|
|
158
158
|
`);output=output?`${output}
|
|
159
159
|
${imageIndicators}`:imageIndicators}return output}var COLLAPSED_ARGS_CHARS=100;function formatToolCallWithArgs(title,args,theme2,expanded){let header=theme2.fg("toolTitle",theme2.bold(title));if(args==null)return header;let entries=typeof args=="object"&&!Array.isArray(args)?Object.entries(args):[["args",args]];if(entries.length===0)return header;if(expanded){let lines=entries.map(([key,value])=>{let text2=typeof value=="string"?value:JSON.stringify(value,null,2)??String(value);return` ${key}: ${replaceTabs(text2).replace(/\r/g,"").split(`
|
|
@@ -206,7 +206,7 @@ Hint: `,RECEIVED_ARGUMENTS_MAX_BYTES=2*1024,RECEIVED_ARGUMENTS_MAX_LINES=40,FIEL
|
|
|
206
206
|
|
|
207
207
|
Hint: ${hints.join(`
|
|
208
208
|
Hint: `)}`:head;if(markerIndex!==-1){let bounded=truncateHead(received,{maxBytes:RECEIVED_ARGUMENTS_MAX_BYTES,maxLines:RECEIVED_ARGUMENTS_MAX_LINES});enriched+=`${RECEIVED_ARGUMENTS_MARKER}${bounded.content}`,bounded.truncated&&(enriched+=`
|
|
209
|
-
\u2026 (arguments truncated)`)}return new Error(enriched)}function wrapPrepareArguments(definition){let tool={name:definition.name,description:definition.description,parameters:definition.parameters};return raw=>{let args=definition.prepareArguments?definition.prepareArguments(raw):raw;try{validateToolArguments(tool,{type:"toolCall",id:"",name:definition.name,arguments:args})}catch(error){throw enrichValidationError(error,definition.parameters,args)}return args}}function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:wrapPrepareArguments(definition),executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-
|
|
209
|
+
\u2026 (arguments truncated)`)}return new Error(enriched)}function wrapPrepareArguments(definition){let tool={name:definition.name,description:definition.description,parameters:definition.parameters};return raw=>{let args=definition.prepareArguments?definition.prepareArguments(raw):raw;try{validateToolArguments(tool,{type:"toolCall",id:"",name:definition.name,arguments:args})}catch(error){throw enrichValidationError(error,definition.parameters,args)}return args}}function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:wrapPrepareArguments(definition),executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-VLAIP26K.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
|
|
210
210
|
${theme2.fg("error",call.error.split(`
|
|
211
211
|
`).join(`
|
|
212
212
|
`))}`),line}var codemodeRenderers={renderCall(args,theme2,context){startToolTimer(context);let code=str(args?.code),title=theme2.fg("toolTitle",theme2.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme2.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
@@ -227,4 +227,4 @@ ${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}
|
|
|
227
227
|
|
|
228
228
|
`)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field2])=>{let nested=depth>0?describeFields(field2,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(schema){let type=renderToolOutputType(schema);return type==="string"?"a string":`\`${describeFields(schema,1)??type.replace(/\s+/g," ")}\``}function describeScriptCall(tool){return`${tool.description.trim()}
|
|
229
229
|
|
|
230
|
-
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{typebox_exports,build_exports,envApiKeyAuth,lazyOAuth,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,fauxProvider,isContextOverflow,isRecoverableLength,getOverflowPatterns,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryAssistantCall,isRetryableAssistantError,StringEnum,value_exports2 as value_exports,Compile,compile_exports,validateToolCall,validateToolArguments,Z,fuzzyMatch,fuzzyFilter,visibleWidth,stripTerminalSequences,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,decodeKittyPrintable,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,isFocusable,CURSOR_MARKER,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,isAppleTerminalSession,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,SETTINGS_DEFAULTS,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyLabel,keyText,keyDisplayText,keyHint,rawKeyHint,finiteLimit,TASK_RESULT_BYTES,TASK_DETAILS_BYTES,TASK_READ_BYTES,TASK_TITLE_BYTES,TASK_LABEL_BYTES,TASK_ERROR_BYTES,TASK_PATH_BYTES,errorText,boundReadBytes,boundText,boundTaskText,boundInput,boundFacts,boundTail,resultText,readOutputSlice,sliceText,TASK_KIND_PATTERN,TASK_BACKGROUND_REJECTION,isTaskTerminal,TaskLookupError,TASK_RECORD_TYPE,TASK_SNAPSHOT_VERSION,readVersionedTask,splitIncompleteAnsiSuffix,stripAnsi,createOutputFilePath,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,createUsageTotals,addUsageToTotals,combineUsage,emptyUsage,cacheHitPercent,getTaskUsageRecord,getAccountedUsages,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,truncateToVisualLines,VisualLinePreview,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|
|
230
|
+
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{typebox_exports,build_exports,envApiKeyAuth,lazyOAuth,fauxText,fauxThinking,fauxToolCall,fauxAssistantMessage,createFauxCore,fauxProvider,isContextOverflow,isRecoverableLength,getOverflowPatterns,DEFAULT_MAX_AGENT_RETRY_DELAY_MS,retryDelayMs,retryAssistantCall,isRetryableAssistantError,StringEnum,value_exports2 as value_exports,Compile,compile_exports,validateToolCall,validateToolArguments,Z,fuzzyMatch,fuzzyFilter,visibleWidth,stripTerminalSequences,wrapTextWithAnsi,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,Key,matchesKey,decodeKittyPrintable,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,hyperlink,isFocusable,CURSOR_MARKER,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,isAppleTerminalSession,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,SETTINGS_DEFAULTS,FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguages,SYSTEM_THEME_NAME,THEME_TOKENS,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,getResolvedThemeColors,getThemeExportColors,highlightCode,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyLabel,keyText,keyDisplayText,keyHint,rawKeyHint,finiteLimit,TASK_RESULT_BYTES,TASK_DETAILS_BYTES,TASK_READ_BYTES,TASK_TITLE_BYTES,TASK_LABEL_BYTES,TASK_FACT_BYTES,TASK_ERROR_BYTES,TASK_PATH_BYTES,errorText,boundReadBytes,boundText,boundTaskText,boundInput,boundFacts,boundTail,resultText,taskReadRange,taskReadBytes,readOutputSlice,sliceText,TASK_KIND_PATTERN,TASKS_TOOL_NAME,TASK_MANAGEMENT_REJECTION,TASK_BACKGROUND_REJECTION,isTaskTerminal,TaskLookupError,TASK_RECORD_TYPE,TASK_SNAPSHOT_VERSION,readVersionedTask,splitIncompleteAnsiSuffix,stripAnsi,createOutputFilePath,writeOutputFile,createOutputFileStream,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,truncateMiddle,createUsageTotals,addUsageToTotals,combineUsage,emptyUsage,cacheHitPercent,getTaskUsageRecord,getAccountedUsages,getUsageCostBreakdown,wrapToolDefinition,createToolDefinitionFromAgentTool,shortenPath,str,formatReadLineRange,replaceTabs,normalizeDisplayText,getTextOutput,formatToolCallWithArgs,startToolTimer,toolTimerText,invalidArgText,renderToolPath,truncateToVisualLines,VisualLinePreview,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|