@bastani/atomic 0.10.14-alpha.1 → 0.10.15-alpha.1
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 +29 -0
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +3 -3
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +3 -3
- package/dist/_shared/mode-shared-2QJSCUM6.js +3 -3
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
- package/dist/_shared/runtime-O4KCSG4C.js +2 -2
- package/dist/_shared/{sdk-B5LEWGGI.js → sdk-OHKMDJ74.js} +27 -5
- package/dist/_shared/{sdk-B5LEWGGI.js.map → sdk-OHKMDJ74.js.map} +1 -1
- package/dist/_shared/session-data-AHTU7IS6.js +2 -2
- package/dist/_shared/startup-0-0-Q3MWKUK4.js +2 -2
- package/dist/_shared/startup-0-1-M6OWAYHH.js +2 -2
- package/dist/_shared/{startup-0-2-5QHPCEON.js → startup-0-2-2HUMCPKX.js} +14 -16
- package/dist/_shared/startup-0-2-2HUMCPKX.js.map +1 -0
- package/dist/_shared/startup-0-3-4ZYBYQNM.js +3 -3
- package/dist/_shared/startup-0-4-ZMJV547D.js +3 -3
- package/dist/_shared/startup-0-5-YDW47QX6.js +3 -3
- package/dist/_shared/startup-10-0-TDQNBDDL.js +3 -3
- package/dist/_shared/startup-14-0-MLX36RBG.js +1 -1
- package/dist/_shared/startup-15-0-YUKGAC63.js +1 -1
- package/dist/_shared/startup-15-1-4S7FLMNG.js +6 -30
- package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
- package/dist/_shared/startup-8-0-34CBHPZH.js +3 -3
- package/dist/_shared/startup-8-1-LZFXSD3Z.js +3 -3
- package/dist/_shared/storage-command-7MGXLJGZ.js +2 -2
- package/dist/_shared/storage-status-K7PX2RXA.js +3 -3
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/index.bundle.mjs +1 -1
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/auth-cli.code.js +1 -1
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +3 -3
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +1 -1
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +1 -1
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +1 -1
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +1 -1
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/compaction/compactor.d.ts +0 -8
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +2 -2
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/intercom-broker-control-host.code.js +1 -1
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +2 -2
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/sdk.code.js +1 -1
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.js +3 -3
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/storage/index.js +2 -2
- package/dist/core/storage/node-sqlite-thread.js +2 -2
- package/dist/core/storage/node-sqlite.js +2 -2
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +2 -2
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +2 -2
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/expanded-child-details.code.js +2 -2
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-staging.code.js +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-window.code.js +2 -2
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +2 -2
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +1 -1
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +2 -2
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.impl.js +3 -3
- package/dist/core/storage/session/sql-session-store.js +3 -3
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/structured-output/index.code.js +1 -1
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +2 -2
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +2 -2
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/worktree-snapshot/blob-store.js +2 -2
- package/dist/core/worktree-snapshot/errors.code.js +1 -1
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +1 -1
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.code.js +1 -1
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.d.ts +21 -1
- package/dist/index.js +2 -2
- package/dist/main-first-time-setup.code.js +1 -1
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/modes/print-mode.js +1 -1
- package/dist/package-manager-cli.code.js +2 -2
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/6.js +1 -1
- package/dist/utils/startup-database-spare.code.js +1 -1
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/docs/background-tasks/reference.md +182 -0
- package/docs/background-tasks.md +98 -405
- package/docs/build.md +67 -27
- package/docs/changelog.mdx +9 -0
- package/docs/codemode.md +108 -39
- package/docs/compaction/branch-summaries.md +54 -0
- package/docs/compaction/custom-compactors.md +161 -0
- package/docs/compaction/memory-compaction.md +77 -0
- package/docs/compaction/reference.md +86 -38
- package/docs/compaction.md +51 -252
- package/docs/computer-use.md +169 -321
- package/docs/containerization.md +71 -57
- package/docs/custom-provider/api-reference.md +119 -25
- package/docs/custom-provider/oauth.md +114 -132
- package/docs/custom-provider/override.md +37 -27
- package/docs/custom-provider/registration.md +107 -83
- package/docs/custom-provider/streaming.md +85 -71
- package/docs/custom-provider.md +85 -52
- package/docs/development.md +39 -29
- package/docs/docs.json +76 -63
- package/docs/environment-variables.md +94 -44
- package/docs/extensions/api-reference.md +86 -43
- package/docs/extensions/authoring.md +162 -154
- package/docs/extensions/events.md +80 -25
- package/docs/extensions/examples.md +90 -85
- package/docs/extensions/ui.md +206 -82
- package/docs/extensions.md +79 -108
- package/docs/getting-started/authentication.md +67 -36
- package/docs/getting-started/first-session.md +53 -43
- package/docs/getting-started/installation.md +116 -89
- package/docs/getting-started/project-instructions.md +48 -34
- package/docs/guides/configuration.md +82 -20
- package/docs/guides/non-interactive.md +66 -24
- package/docs/guides/resume-on-any-machine.md +135 -82
- package/docs/guides/team-setup.md +114 -105
- package/docs/guides.md +76 -32
- package/docs/herdr.md +15 -16
- package/docs/how-atomic-works.md +140 -0
- package/docs/index.md +58 -44
- package/docs/intercom/operations.md +141 -151
- package/docs/intercom/reference.md +85 -108
- package/docs/intercom.md +84 -145
- package/docs/json.md +120 -67
- package/docs/keybindings.md +85 -49
- package/docs/libraries/agent-core.md +137 -275
- package/docs/libraries/ai.md +100 -84
- package/docs/libraries/codemode.md +210 -300
- package/docs/libraries/schema.md +59 -53
- package/docs/libraries/storage-postgres.md +49 -35
- package/docs/libraries/telemetry.md +153 -354
- package/docs/libraries/tui.md +265 -393
- package/docs/libraries.md +42 -26
- package/docs/llama-cpp.md +171 -161
- package/docs/mcp-servers.md +90 -51
- package/docs/models/choose-a-model.md +188 -0
- package/docs/models/reference.md +74 -30
- package/docs/models.md +153 -88
- package/docs/orchestration/migrating-workflows.md +23 -16
- package/docs/orchestration/patterns.md +39 -44
- package/docs/orchestration.md +65 -26
- package/docs/packages/authoring.md +51 -29
- package/docs/packages/reference.md +42 -21
- package/docs/packages.md +69 -58
- package/docs/programmatic.md +118 -24
- package/docs/prompt-templates.md +84 -83
- package/docs/providers/reference.md +43 -48
- package/docs/providers.md +219 -451
- package/docs/quickstart.md +140 -120
- package/docs/reference/cli.md +135 -97
- package/docs/reference.md +20 -18
- package/docs/rpc/examples.md +76 -20
- package/docs/rpc/extension-ui.md +64 -38
- package/docs/rpc/protocol.md +361 -110
- package/docs/rpc.md +57 -17
- package/docs/sdk/reference.md +409 -534
- package/docs/sdk/storage.md +53 -13
- package/docs/sdk/structured-decisions.md +82 -56
- package/docs/sdk/web-server.md +57 -43
- package/docs/sdk.md +106 -84
- package/docs/security.md +42 -64
- package/docs/session-format.md +62 -38
- package/docs/sessions.md +99 -214
- package/docs/settings.md +165 -195
- package/docs/shell-aliases.md +9 -6
- package/docs/skills/authoring.md +69 -48
- package/docs/skills/reference.md +51 -20
- package/docs/skills.md +99 -148
- package/docs/slash-commands.md +129 -0
- package/docs/storage/custom-adapters.md +160 -85
- package/docs/storage/jsonl.md +81 -66
- package/docs/storage/postgres/pgbouncer.md +120 -126
- package/docs/storage/postgres/tuning.md +120 -143
- package/docs/storage/postgres.md +314 -330
- package/docs/storage/sqlite.md +71 -42
- package/docs/storage.md +298 -302
- package/docs/subagents/authoring.md +55 -38
- package/docs/subagents/reference.md +73 -33
- package/docs/subagents.md +119 -187
- package/docs/terminal-setup.md +50 -38
- package/docs/termux.md +67 -41
- package/docs/themes/reference.md +23 -19
- package/docs/themes.md +142 -127
- package/docs/tmux.md +47 -55
- package/docs/tools.md +147 -109
- package/docs/tui/reference.md +166 -214
- package/docs/tui.md +196 -341
- package/docs/usage.md +118 -138
- package/docs/verification.md +79 -51
- package/docs/web-access.md +121 -101
- package/docs/windows.md +26 -27
- package/docs/worktree-snapshots/reference.md +245 -0
- package/docs/worktree-snapshots.md +71 -259
- package/package.json +8 -8
- package/dist/_shared/startup-0-2-5QHPCEON.js.map +0 -1
- package/docs/guides/intercom.md +0 -32
- package/docs/guides/orchestration.md +0 -28
- package/docs/guides/subagents.md +0 -37
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: "@bastani/atomic-agent-core"
|
|
3
3
|
sidebarTitle: "@bastani/atomic-agent-core"
|
|
4
|
-
description: "Stateful agent loop with tool execution, event streaming, steering,
|
|
4
|
+
description: "Stateful agent loop with tool execution, event streaming, steering, follow-up messages, and proxy streaming."
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
Stateful agent with tool execution and event streaming, built on [`@bastani/atomic-ai`](/libraries/ai) (requires Node.js 24.20+). Atomic's sessions run on this
|
|
7
|
+
Stateful agent loop with tool execution and event streaming, built on [`@bastani/atomic-ai`](/libraries/ai) (requires Node.js 24.20+). Atomic's sessions run on this loop, and you can use it directly to build custom agents. Atomic's [TypeScript SDK](/sdk) wraps it with sessions, tools, extensions, and compaction, so prefer the SDK when you want Atomic's built-in behavior. See [Standalone libraries](/libraries) for all standalone packages.
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
@@ -36,7 +36,6 @@ const agent = new Agent({
|
|
|
36
36
|
|
|
37
37
|
agent.subscribe((event) => {
|
|
38
38
|
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
39
|
-
// Stream just the new text chunk
|
|
40
39
|
process.stdout.write(event.assistantMessageEvent.delta);
|
|
41
40
|
}
|
|
42
41
|
});
|
|
@@ -48,31 +47,20 @@ await agent.prompt("Hello!");
|
|
|
48
47
|
|
|
49
48
|
### AgentMessage vs LLM Message
|
|
50
49
|
|
|
51
|
-
The agent works with `AgentMessage`, which
|
|
52
|
-
|
|
53
|
-
- Standard LLM messages (`system`, `user`, `assistant`, and `toolResult`)
|
|
54
|
-
- Custom app-specific message types added through declaration merging
|
|
55
|
-
|
|
56
|
-
LLMs accept only `system`, `user`, `assistant`, and `toolResult` messages. `convertToLlm` filters and transforms custom message types before each LLM call.
|
|
57
|
-
|
|
58
|
-
### Message flow
|
|
50
|
+
The agent works with `AgentMessage`, which includes standard LLM messages (`system`, `user`, `assistant`, and `toolResult`) plus any custom app-specific message types added through declaration merging. Because LLMs accept only standard message roles, `convertToLlm` filters or transforms custom types before each request:
|
|
59
51
|
|
|
60
52
|
```text
|
|
61
53
|
AgentMessage[] -> transformContext() -> AgentMessage[] -> convertToLlm() -> Message[] -> LLM
|
|
62
54
|
(optional) (required)
|
|
63
55
|
```
|
|
64
56
|
|
|
65
|
-
1. **`transformContext
|
|
66
|
-
2. **`convertToLlm
|
|
57
|
+
1. **`transformContext`:** Prune old messages or inject external context.
|
|
58
|
+
2. **`convertToLlm`:** Filter out UI-only messages and convert custom types to LLM messages.
|
|
67
59
|
|
|
68
60
|
## Event flow
|
|
69
61
|
|
|
70
|
-
The agent emits events as turns run so your interface can update incrementally.
|
|
71
|
-
|
|
72
62
|
### `prompt()` event sequence
|
|
73
63
|
|
|
74
|
-
When you call `prompt("Hello")`:
|
|
75
|
-
|
|
76
64
|
```text
|
|
77
65
|
prompt("Hello")
|
|
78
66
|
├─ agent_start
|
|
@@ -81,7 +69,6 @@ prompt("Hello")
|
|
|
81
69
|
├─ message_end { message: userMessage }
|
|
82
70
|
├─ message_start { message: assistantMessage } // LLM starts responding
|
|
83
71
|
├─ message_update { message: partial... } // Streaming chunks
|
|
84
|
-
├─ message_update { message: partial... }
|
|
85
72
|
├─ message_end { message: assistantMessage } // Complete response
|
|
86
73
|
├─ turn_end { message, toolResults: [] }
|
|
87
74
|
└─ agent_end { messages: [...] }
|
|
@@ -89,7 +76,7 @@ prompt("Hello")
|
|
|
89
76
|
|
|
90
77
|
### With tool calls
|
|
91
78
|
|
|
92
|
-
If the assistant calls tools, the loop
|
|
79
|
+
If the assistant calls tools, the loop executes them and starts another turn:
|
|
93
80
|
|
|
94
81
|
```text
|
|
95
82
|
prompt("Read config.json")
|
|
@@ -113,108 +100,101 @@ prompt("Read config.json")
|
|
|
113
100
|
└─ agent_end
|
|
114
101
|
```
|
|
115
102
|
|
|
116
|
-
Tool execution mode is configurable
|
|
117
|
-
|
|
118
|
-
- `parallel` (default): preflight tool calls sequentially, run allowed tools concurrently, emit `tool_execution_end` as each tool finishes, then emit `toolResult` messages and `turn_end.toolResults` in assistant source order.
|
|
119
|
-
- `sequential`: run tool calls one at a time in assistant source order.
|
|
103
|
+
Tool execution mode is configurable globally via `toolExecution` in `AgentOptions` or per tool via `executionMode` on `AgentTool`:
|
|
120
104
|
|
|
121
|
-
|
|
105
|
+
- **`parallel` (default):** Preflights tool calls sequentially, runs allowed tools concurrently, emits `tool_execution_end` in completion order, then emits `toolResult` messages and `turn_end.toolResults` in assistant source order.
|
|
106
|
+
- **`sequential`:** Runs tool calls one at a time in assistant source order. If any call in a batch targets a tool with `executionMode: "sequential"`, the entire batch runs sequentially.
|
|
122
107
|
|
|
123
|
-
|
|
108
|
+
`beforeToolCall` runs after `tool_execution_start` and argument validation (and after assistant `message_end` processing settles on `Agent`, so agent state already contains the assistant message). It can block execution and attach `terminate: true`. `afterToolCall` runs after execution finishes and before `tool_execution_end` and final tool-result events.
|
|
124
109
|
|
|
125
|
-
`
|
|
110
|
+
**`afterToolCall` merge rules:** Overrides merge field-by-field (`content`, `details`, `structuredContent`, `isError`, `usage`, `terminate`) with no deep merge. Returning `content` **without** `structuredContent` drops the original `structuredContent` so the two cannot go out of sync; pass `structuredContent` alongside `content` to preserve it.
|
|
126
111
|
|
|
127
|
-
|
|
112
|
+
Tools, blocked `beforeToolCall` results, and `afterToolCall` overrides can return `terminate: true` to skip the automatic follow-up LLM call—taking effect only when every finalized tool result in that batch sets `terminate: true`.
|
|
128
113
|
|
|
129
|
-
|
|
114
|
+
### Turn lifecycle hooks
|
|
130
115
|
|
|
131
|
-
|
|
116
|
+
Each provider turn follows this exact sequence:
|
|
132
117
|
|
|
133
|
-
|
|
118
|
+
```text
|
|
119
|
+
selected input events
|
|
120
|
+
-> prepareRequest (before every request, including turn 1)
|
|
121
|
+
-> provider response
|
|
122
|
+
-> tool results
|
|
123
|
+
-> finishTurn (before turn_end; decides continue / end / default)
|
|
124
|
+
-> turn_end
|
|
125
|
+
-> continuation check
|
|
126
|
+
-> prepareNextTurn / prepareNextTurnWithContext (only when starting another turn)
|
|
127
|
+
-> next turn OR agent_end
|
|
128
|
+
```
|
|
134
129
|
|
|
135
|
-
|
|
130
|
+
| Hook | When it runs | Return shape | Use it for |
|
|
131
|
+
| --- | --- | --- | --- |
|
|
132
|
+
| `prepareRequest` | Immediately before **every** conversational provider request (including the first), after pending messages are emitted; does not poll queues. | `AgentRequestUpdate` (`{ context?, model?, thinkingLevel? }`) or `undefined` | Installing canonical persisted context, model, or thinking level for the request. |
|
|
133
|
+
| `finishTurn` | After the assistant message and all tool results finalize, before `turn_end` (runs on normal, error, and aborted responses). | `{ action: "continue" } \| { action: "end" } \| undefined` | Stopping a run immediately after `turn_end` without polling queues (`"end"`), or forcing one more request on a normal response (`"continue"`). |
|
|
134
|
+
| `prepareNextTurn` / `prepareNextTurnWithContext` | After `turn_end` only when the loop will continue to another turn, immediately before the next turn starts. | `AgentLoopTurnUpdate` (`{ context?, messages?, model?, thinkingLevel? }`) or `undefined` | Swapping context, model, thinking level, or appending lifecycle-emitted `messages` between turns (for example, post-turn compaction or dynamic tool/model transitions). |
|
|
136
135
|
|
|
137
136
|
```typescript
|
|
137
|
+
// Install canonical context right before every request
|
|
138
138
|
agent.prepareRequest = async ({ context }) => ({
|
|
139
139
|
context: { ...context, messages: await session.loadModelContext() },
|
|
140
140
|
});
|
|
141
|
-
```
|
|
142
141
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
`finishTurn` runs after the assistant message and all tool results are finalized, before `turn_end`. It runs for normal, error, and aborted responses:
|
|
146
|
-
|
|
147
|
-
```typescript
|
|
142
|
+
// Decide whether to stop or force continuation before turn_end
|
|
148
143
|
agent.finishTurn = async ({ message }) => {
|
|
149
144
|
if (message.stopReason === "error" || message.stopReason === "aborted") return;
|
|
150
145
|
if (shouldEndRun(message)) return { action: "end" };
|
|
151
146
|
return needsAnotherResponse(message) ? { action: "continue" } : undefined;
|
|
152
147
|
};
|
|
153
|
-
```
|
|
154
|
-
|
|
155
|
-
Returning `undefined` keeps normal scheduling. Returning `{ action: "end" }` stops immediately after `turn_end` without polling steering or follow-up queues or starting another request.
|
|
156
|
-
|
|
157
|
-
On a normal response, returning `{ action: "continue" }` guarantees one more provider request. If tool results, steering messages, or follow-up messages already schedule that request, no extra request is sent; otherwise the loop sends one context-only request. Error and aborted responses remain hard exits whose decisions are ignored. Because `finishTurn` runs again after the next request, returning `{ action: "continue" }` unconditionally creates an infinite loop.
|
|
158
|
-
|
|
159
|
-
To migrate from the removed `shouldStopAfterTurn` hook, return `{ action: "end" }`. Guard error and aborted responses so your predicate runs only on successful turns:
|
|
160
148
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
149
|
+
// Update state or append messages between turns when another turn is scheduled
|
|
150
|
+
agent.prepareNextTurnWithContext = async (turn, signal) => {
|
|
151
|
+
// turn: { message, toolResults, context, newMessages }
|
|
152
|
+
const updated = await maybeCompactBetweenTurns(turn.context, signal);
|
|
153
|
+
return updated ? { context: updated } : undefined;
|
|
154
|
+
};
|
|
166
155
|
```
|
|
167
156
|
|
|
168
|
-
|
|
157
|
+
On `Agent`, `prepareNextTurnWithContext(context, signal)` receives the completed turn's `PrepareNextTurnContext` (`{ message, toolResults, context, newMessages }`) and takes precedence over `prepareNextTurn(signal)` if both are set. On the low-level `agentLoop()` `AgentLoopConfig`, `prepareNextTurn(context)` always receives `PrepareNextTurnContext`.
|
|
169
158
|
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
-> finishTurn
|
|
176
|
-
-> turn_end
|
|
177
|
-
-> continuation scheduling or agent_end
|
|
178
|
-
```
|
|
159
|
+
On `finishTurn`, returning `{ action: "continue" }` on a normal response guarantees one more provider request (satisfied by tool results, steering, or follow-up scheduling when present, or a context-only request otherwise). Error and aborted responses remain hard exits whose `finishTurn` decisions are ignored. Do not return `{ action: "continue" }` unconditionally or the loop will run forever.
|
|
160
|
+
|
|
161
|
+
<Note>
|
|
162
|
+
**Migrating from `shouldStopAfterTurn`:** Replace the removed `shouldStopAfterTurn` hook with `finishTurn`, guarding `error`/`aborted` responses and returning `{ action: "end" }` when you want the run to stop after `turn_end`.
|
|
163
|
+
</Note>
|
|
179
164
|
|
|
180
165
|
### `continue()` and queued input
|
|
181
166
|
|
|
182
|
-
Empty and system-only transcripts reject `continue()` without consuming queues. A non-assistant tail continues from existing context
|
|
167
|
+
Empty and system-only transcripts reject `continue()` without consuming queues. A non-assistant tail continues from existing context (steering is polled at startup; follow-up input waits until the response stops naturally).
|
|
183
168
|
|
|
184
|
-
|
|
185
|
-
agent.followUp({ role: "user", content: "After the retry", timestamp: Date.now() });
|
|
186
|
-
await agent.continue(); // The first request retries the existing user/toolResult tail.
|
|
187
|
-
```
|
|
188
|
-
|
|
189
|
-
An assistant tail cannot be sent directly, so `continue()` falls back to one queued steering batch, or else one queued follow-up batch. Queue mode still determines whether that batch takes one message or all queued messages:
|
|
169
|
+
An assistant tail cannot be sent directly, so `continue()` falls back to one queued steering batch, or else one queued follow-up batch (respecting queue mode):
|
|
190
170
|
|
|
191
171
|
```typescript
|
|
192
172
|
agent.steer({ role: "user", content: "Continue from here", timestamp: Date.now() });
|
|
193
|
-
await agent.continue(); //
|
|
173
|
+
await agent.continue(); // Consumes the queued message because the tail is an assistant message
|
|
194
174
|
```
|
|
195
175
|
|
|
196
176
|
### Event types
|
|
197
177
|
|
|
198
178
|
| Event | Description |
|
|
199
|
-
|
|
179
|
+
| --- | --- |
|
|
200
180
|
| `agent_start` | Agent begins processing |
|
|
201
|
-
| `agent_end` | Final event for the run
|
|
181
|
+
| `agent_end` | Final event for the run; awaited subscribers for this event still count toward settlement |
|
|
202
182
|
| `turn_start` | New turn begins (one LLM call + tool executions) |
|
|
203
183
|
| `turn_end` | Turn completes with assistant message and tool results |
|
|
204
|
-
| `message_start` | Any message begins (user
|
|
205
|
-
| `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
|
|
184
|
+
| `message_start` | Any message begins (`user`, `assistant`, `toolResult`) |
|
|
185
|
+
| `message_update` | **Assistant only.** Includes `assistantMessageEvent` with streaming delta |
|
|
206
186
|
| `message_end` | Message completes |
|
|
207
187
|
| `tool_execution_start` | Tool begins |
|
|
208
188
|
| `tool_execution_update` | Tool streams progress |
|
|
209
189
|
| `tool_execution_end` | Tool completes |
|
|
210
190
|
|
|
211
|
-
`Agent.subscribe()` listeners receive `(event, signal)` and are awaited in registration order.
|
|
191
|
+
`Agent.subscribe()` listeners receive `(event, signal)` and are awaited in registration order. Thrown or rejected listener errors propagate to the caller awaiting `prompt()` or `continue()`. `await agent.waitForIdle()` and `await agent.prompt(...)` settle only after awaited `agent_end` listeners finish.
|
|
212
192
|
|
|
213
193
|
## Agent options
|
|
214
194
|
|
|
215
195
|
```typescript
|
|
216
196
|
const agent = new Agent({
|
|
217
|
-
// Initial state
|
|
197
|
+
// Initial state: systemPrompt and tools seed the leading system message
|
|
218
198
|
// unless messages already starts with one.
|
|
219
199
|
initialState: {
|
|
220
200
|
systemPrompt: string,
|
|
@@ -224,94 +204,68 @@ const agent = new Agent({
|
|
|
224
204
|
messages: AgentMessage[],
|
|
225
205
|
},
|
|
226
206
|
|
|
227
|
-
// Convert AgentMessage[] to LLM Message[] (required for custom message types; must not throw
|
|
207
|
+
// Convert AgentMessage[] to LLM Message[] (required for custom message types; must not throw)
|
|
228
208
|
convertToLlm: (messages) => messages.filter(...),
|
|
229
209
|
|
|
230
|
-
// Transform context before convertToLlm (for pruning
|
|
210
|
+
// Transform context before convertToLlm (for pruning or compaction)
|
|
231
211
|
transformContext: async (messages, signal) => pruneOldMessages(messages),
|
|
232
212
|
|
|
233
|
-
//
|
|
213
|
+
// Queue drain modes: "one-at-a-time" (default) or "all"
|
|
234
214
|
steeringMode: "one-at-a-time",
|
|
235
|
-
|
|
236
|
-
// Follow-up mode: "one-at-a-time" (default) or "all"
|
|
237
215
|
followUpMode: "one-at-a-time",
|
|
238
216
|
|
|
239
|
-
// Required stream function
|
|
240
|
-
// are in the transcript's system messages, not on the context.
|
|
217
|
+
// Required stream function receiving a TranscriptContext
|
|
241
218
|
streamFn: models.streamSimple.bind(models),
|
|
242
219
|
|
|
243
220
|
// Session ID for provider caching
|
|
244
221
|
sessionId: "session-123",
|
|
245
222
|
|
|
246
|
-
//
|
|
247
|
-
// DEFAULT_AGENT_IDENTITY ({ attribution: ATOMIC_ATTRIBUTION }: attribution headers name Atomic).
|
|
248
|
-
// Pass { attribution: null } to send no attribution headers.
|
|
223
|
+
// Client identity (merged over DEFAULT_AGENT_IDENTITY; pass { attribution: null } to omit attribution)
|
|
249
224
|
identity: { attribution: { name: "my-app", url: "https://my-app.example" } },
|
|
250
225
|
|
|
251
226
|
// Dynamic API key resolution (for expiring OAuth tokens)
|
|
252
227
|
getApiKey: async (provider) => refreshToken(),
|
|
253
228
|
|
|
254
|
-
//
|
|
229
|
+
// Transport, retry cap, and request/response inspection hooks
|
|
255
230
|
transport: "sse",
|
|
256
231
|
maxRetryDelayMs: 60_000,
|
|
257
232
|
onPayload: (payload, model) => payload,
|
|
258
233
|
onResponse: (response) => {},
|
|
259
234
|
onProviderStreamEvent: (event) => {},
|
|
260
235
|
|
|
261
|
-
// Tool execution mode
|
|
236
|
+
// Tool execution mode ("parallel" default, or "sequential") and unknown-tool text
|
|
262
237
|
toolExecution: "parallel",
|
|
263
|
-
|
|
264
|
-
// Custom error text when the model calls an unregistered tool name
|
|
265
238
|
unknownToolMessage: (toolName) => `Tool "${toolName}" is not available.`,
|
|
266
239
|
|
|
267
|
-
//
|
|
268
|
-
beforeToolCall: async ({ toolCall
|
|
269
|
-
if (toolCall.name === "bash") {
|
|
270
|
-
return { block: true, reason: "bash is disabled", terminate: true };
|
|
271
|
-
}
|
|
272
|
-
},
|
|
273
|
-
|
|
274
|
-
// Postprocess each tool result before final tool events are emitted.
|
|
275
|
-
afterToolCall: async ({ toolCall, result, isError, context }) => {
|
|
276
|
-
if (toolCall.name === "notify_done" && !isError) {
|
|
277
|
-
return { terminate: true };
|
|
278
|
-
}
|
|
279
|
-
if (!isError) {
|
|
280
|
-
return { details: { ...result.details, audited: true } };
|
|
281
|
-
}
|
|
240
|
+
// Tool preflight and postprocessing hooks
|
|
241
|
+
beforeToolCall: async ({ toolCall }) => {
|
|
242
|
+
if (toolCall.name === "bash") return { block: true, reason: "bash is disabled", terminate: true };
|
|
282
243
|
},
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
return { context: { ...context, messages: await loadCanonicalMessages(signal) } };
|
|
244
|
+
afterToolCall: async ({ toolCall, result, isError }) => {
|
|
245
|
+
if (toolCall.name === "notify_done" && !isError) return { terminate: true };
|
|
246
|
+
if (!isError) return { details: { ...result.details, audited: true } };
|
|
287
247
|
},
|
|
288
248
|
|
|
289
|
-
//
|
|
249
|
+
// Turn lifecycle hooks (see "Turn lifecycle hooks" above)
|
|
250
|
+
prepareRequest: async ({ context }, signal) => ({
|
|
251
|
+
context: { ...context, messages: await loadCanonicalMessages(signal) },
|
|
252
|
+
}),
|
|
290
253
|
prepareNextTurn: async (signal) => undefined,
|
|
291
|
-
prepareNextTurnWithContext: async (
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
// `continue` ensures one next request; existing tool/queue scheduling can satisfy it.
|
|
295
|
-
// `end` ends this run after turn_end without polling queues.
|
|
296
|
-
finishTurn: async ({ message, toolResults }, signal) => {
|
|
297
|
-
return shouldContinue(message, toolResults) ? { action: "continue" } : undefined;
|
|
298
|
-
},
|
|
254
|
+
prepareNextTurnWithContext: async (turn, signal) => undefined,
|
|
255
|
+
finishTurn: async ({ message, toolResults }, signal) =>
|
|
256
|
+
shouldContinue(message, toolResults) ? { action: "continue" } : undefined,
|
|
299
257
|
|
|
300
258
|
// Custom thinking budgets for token-based providers
|
|
301
|
-
thinkingBudgets: {
|
|
302
|
-
minimal: 128,
|
|
303
|
-
low: 512,
|
|
304
|
-
medium: 1024,
|
|
305
|
-
high: 2048,
|
|
306
|
-
},
|
|
259
|
+
thinkingBudgets: { minimal: 128, low: 512, medium: 1024, high: 2048 },
|
|
307
260
|
});
|
|
308
261
|
```
|
|
309
262
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
- **`StreamFn
|
|
313
|
-
- **`convertToLlm
|
|
314
|
-
- **`setDefaultStreamFn(streamFn | undefined)
|
|
263
|
+
<Note>
|
|
264
|
+
**No-throw contracts (`StreamFn` and `convertToLlm`):**
|
|
265
|
+
- **`StreamFn`** must never throw or reject for request, model, or runtime failures. Always return an `AssistantMessageEventStream` and report failures via stream `error` events and a final `AssistantMessage` with `stopReason: "error"` or `"aborted"` and `errorMessage`.
|
|
266
|
+
- **`convertToLlm`** must never throw or reject; filter or normalize custom messages deterministically.
|
|
267
|
+
- **`setDefaultStreamFn(streamFn | undefined)`** sets a process-wide fallback `StreamFn` when callers omit `streamFn`.
|
|
268
|
+
</Note>
|
|
315
269
|
|
|
316
270
|
## Agent state
|
|
317
271
|
|
|
@@ -329,13 +283,9 @@ interface AgentState {
|
|
|
329
283
|
}
|
|
330
284
|
```
|
|
331
285
|
|
|
332
|
-
|
|
286
|
+
Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it, while mutating the returned array mutates current state. `agent.state.isStreaming` stays `true` until awaited `agent_end` subscribers finish.
|
|
333
287
|
|
|
334
|
-
The transcript owns the system prompt and tool declarations.
|
|
335
|
-
|
|
336
|
-
`agent.state.tools` holds the executable tools. Before every request, the loop compares `agent.state.tools` against the tools declared in the transcript and announces any difference in a system message, merging into a pending system message when one exists. `getCurrentSystemMessage(messages)` from `@bastani/atomic-ai` returns the replayed head, including declared tools, for any message array including agent transcripts with custom message roles.
|
|
337
|
-
|
|
338
|
-
To change the prompt mid-conversation, append a system message with `content` (added instructions) or `sections` (named replacements):
|
|
288
|
+
The transcript owns the system prompt and tool declarations: `agent.state.systemPrompt` is read-only and replays the transcript's system messages (see `SystemMessage` in [`@bastani/atomic-ai`](/libraries/ai)). Before each request, the loop diffs `agent.state.tools` against declared tools in the transcript and appends a system-message update when they change. To update the prompt mid-conversation, append a system message:
|
|
339
289
|
|
|
340
290
|
```typescript
|
|
341
291
|
await agent.prompt([
|
|
@@ -344,125 +294,53 @@ await agent.prompt([
|
|
|
344
294
|
]);
|
|
345
295
|
```
|
|
346
296
|
|
|
347
|
-
During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
|
|
348
|
-
|
|
349
|
-
`agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
|
|
350
|
-
|
|
351
297
|
## Methods
|
|
352
298
|
|
|
353
|
-
### Prompting
|
|
354
|
-
|
|
355
299
|
```typescript
|
|
356
|
-
//
|
|
300
|
+
// Prompting and continuation
|
|
357
301
|
await agent.prompt("Hello");
|
|
358
|
-
|
|
359
|
-
// With images
|
|
360
|
-
await agent.prompt("What's in this image?", [
|
|
361
|
-
{ type: "image", data: base64Data, mimeType: "image/jpeg" }
|
|
362
|
-
]);
|
|
363
|
-
|
|
364
|
-
// AgentMessage directly
|
|
302
|
+
await agent.prompt("Describe this", [{ type: "image", data: base64Data, mimeType: "image/jpeg" }]);
|
|
365
303
|
await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
|
|
366
|
-
|
|
367
|
-
// Continue existing non-assistant input; an assistant tail may use queued input as fallback
|
|
368
304
|
await agent.continue();
|
|
369
|
-
```
|
|
370
|
-
|
|
371
|
-
### State management
|
|
372
305
|
|
|
373
|
-
|
|
306
|
+
// State and configuration
|
|
374
307
|
const nextModel = models.getModel("openai", "gpt-4o");
|
|
375
308
|
if (nextModel) agent.state.model = nextModel;
|
|
376
309
|
agent.state.thinkingLevel = "medium";
|
|
377
310
|
agent.state.tools = [myTool];
|
|
378
|
-
agent.toolExecution = "sequential";
|
|
379
|
-
agent.beforeToolCall = async ({ toolCall }) => undefined;
|
|
380
|
-
agent.afterToolCall = async ({ toolCall, result }) => undefined;
|
|
381
|
-
agent.prepareRequest = async ({ context }) => ({
|
|
382
|
-
context: { ...context, messages: await loadCanonicalMessages() },
|
|
383
|
-
});
|
|
384
|
-
agent.finishTurn = async () => undefined;
|
|
385
|
-
agent.state.messages = newMessages; // top-level array is copied
|
|
386
|
-
agent.state.messages.push(message);
|
|
387
|
-
const nextQueuedMessages = agent.peekQueuedMessages(); // respects queue modes; does not consume
|
|
388
|
-
agent.reset();
|
|
389
|
-
```
|
|
390
|
-
|
|
391
|
-
### Session and thinking budgets
|
|
392
|
-
|
|
393
|
-
```typescript
|
|
394
311
|
agent.sessionId = "session-123";
|
|
312
|
+
agent.thinkingBudgets = { minimal: 128, low: 512, medium: 1024, high: 2048 };
|
|
313
|
+
const queued = agent.peekQueuedMessages(); // inspects next batch without consuming
|
|
314
|
+
agent.reset();
|
|
395
315
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
medium: 1024,
|
|
400
|
-
high: 2048,
|
|
401
|
-
};
|
|
402
|
-
```
|
|
403
|
-
|
|
404
|
-
### Control
|
|
405
|
-
|
|
406
|
-
```typescript
|
|
407
|
-
agent.abort(); // Cancel current operation
|
|
408
|
-
await agent.waitForIdle(); // Wait for completion
|
|
409
|
-
```
|
|
410
|
-
|
|
411
|
-
### Events
|
|
412
|
-
|
|
413
|
-
```typescript
|
|
316
|
+
// Lifecycle control and events
|
|
317
|
+
agent.abort();
|
|
318
|
+
await agent.waitForIdle();
|
|
414
319
|
const unsubscribe = agent.subscribe(async (event, signal) => {
|
|
415
|
-
if (event.type === "agent_end")
|
|
416
|
-
// Final barrier work for the run
|
|
417
|
-
await flushSessionState(signal);
|
|
418
|
-
}
|
|
320
|
+
if (event.type === "agent_end") await flushSessionState(signal);
|
|
419
321
|
});
|
|
420
322
|
unsubscribe();
|
|
421
323
|
```
|
|
422
324
|
|
|
423
325
|
## Steering and follow-up
|
|
424
326
|
|
|
425
|
-
Steering messages
|
|
327
|
+
Steering messages interrupt the agent after the current turn's tool batch completes; follow-up messages run only after no tool calls or steering messages remain:
|
|
426
328
|
|
|
427
329
|
```typescript
|
|
428
|
-
agent.steeringMode = "one-at-a-time";
|
|
429
|
-
agent.followUpMode = "one-at-a-time";
|
|
430
|
-
|
|
431
|
-
// While agent is running tools
|
|
432
|
-
agent.steer({
|
|
433
|
-
role: "user",
|
|
434
|
-
content: "Stop! Do this instead.",
|
|
435
|
-
timestamp: Date.now(),
|
|
436
|
-
});
|
|
437
|
-
|
|
438
|
-
// After the agent finishes its current work
|
|
439
|
-
agent.followUp({
|
|
440
|
-
role: "user",
|
|
441
|
-
content: "Also summarize the result.",
|
|
442
|
-
timestamp: Date.now(),
|
|
443
|
-
});
|
|
330
|
+
agent.steeringMode = "one-at-a-time"; // or "all"
|
|
331
|
+
agent.followUpMode = "one-at-a-time"; // or "all"
|
|
444
332
|
|
|
445
|
-
|
|
446
|
-
|
|
333
|
+
agent.steer({ role: "user", content: "Stop! Do this instead.", timestamp: Date.now() });
|
|
334
|
+
agent.followUp({ role: "user", content: "Also summarize the result.", timestamp: Date.now() });
|
|
447
335
|
|
|
448
336
|
agent.clearSteeringQueue();
|
|
449
337
|
agent.clearFollowUpQueue();
|
|
450
338
|
agent.clearAllQueues();
|
|
451
339
|
```
|
|
452
340
|
|
|
453
|
-
Use `clearSteeringQueue()`, `clearFollowUpQueue()`, or `clearAllQueues()` to drop queued messages.
|
|
454
|
-
|
|
455
|
-
When steering messages are detected after a turn completes:
|
|
456
|
-
|
|
457
|
-
1. All tool calls from the current assistant message have already finished.
|
|
458
|
-
2. Steering messages are injected.
|
|
459
|
-
3. The LLM responds on the next turn.
|
|
460
|
-
|
|
461
|
-
Follow-up messages are checked only when there are no more tool calls and no steering messages. If any are queued, they are injected and another turn runs.
|
|
462
|
-
|
|
463
341
|
## Custom message types
|
|
464
342
|
|
|
465
|
-
Extend `AgentMessage`
|
|
343
|
+
Extend `AgentMessage` with declaration merging and handle your custom roles inside `convertToLlm`:
|
|
466
344
|
|
|
467
345
|
```typescript
|
|
468
346
|
declare module "@bastani/atomic-agent-core" {
|
|
@@ -471,53 +349,31 @@ declare module "@bastani/atomic-agent-core" {
|
|
|
471
349
|
}
|
|
472
350
|
}
|
|
473
351
|
|
|
474
|
-
// Now valid
|
|
475
|
-
const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
|
|
476
|
-
```
|
|
477
|
-
|
|
478
|
-
Handle custom types in `convertToLlm`:
|
|
479
|
-
|
|
480
|
-
```typescript
|
|
481
352
|
const agent = new Agent({
|
|
482
353
|
streamFn: models.streamSimple.bind(models),
|
|
483
|
-
convertToLlm: (messages) => messages.flatMap(m =>
|
|
484
|
-
if (m.role === "notification") return []; // Filter out
|
|
485
|
-
return [m];
|
|
486
|
-
}),
|
|
354
|
+
convertToLlm: (messages) => messages.flatMap((m) => (m.role === "notification" ? [] : [m])),
|
|
487
355
|
});
|
|
488
356
|
```
|
|
489
357
|
|
|
490
358
|
## Tools
|
|
491
359
|
|
|
492
|
-
Define tools with `AgentTool
|
|
360
|
+
Define tools with `AgentTool` using any JSON Schema (using `@bastani/atomic-schema` builders types `params` automatically):
|
|
493
361
|
|
|
494
362
|
```typescript
|
|
495
363
|
import { obj, str } from "@bastani/atomic-schema";
|
|
496
364
|
|
|
497
|
-
const readFileParameters = obj({
|
|
498
|
-
path: str({ description: "File path" }),
|
|
499
|
-
});
|
|
365
|
+
const readFileParameters = obj({ path: str({ description: "File path" }) });
|
|
500
366
|
|
|
501
367
|
const readFileTool: AgentTool<typeof readFileParameters> = {
|
|
502
368
|
name: "read_file",
|
|
503
|
-
label: "Read File",
|
|
369
|
+
label: "Read File",
|
|
504
370
|
description: "Read a file's contents",
|
|
505
371
|
parameters: readFileParameters,
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
// "sequential" forces the entire batch to run one at a time.
|
|
510
|
-
// "parallel" allows concurrent execution with other tool calls.
|
|
511
|
-
// If omitted, the global toolExecution config applies.
|
|
512
|
-
executionMode: "sequential",
|
|
513
|
-
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
372
|
+
outputSchema: obj({ path: str(), content: str() }), // optional structuredContent schema
|
|
373
|
+
executionMode: "sequential", // optional override ("sequential" forces the batch sequential)
|
|
374
|
+
execute: async (_toolCallId, params, _signal, onUpdate) => {
|
|
514
375
|
const content = await fs.readFile(params.path, "utf-8");
|
|
515
|
-
|
|
516
|
-
// Optional: stream progress
|
|
517
376
|
onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
|
|
518
|
-
|
|
519
|
-
// Optional: add `terminate: true` here to skip the automatic follow-up LLM call
|
|
520
|
-
// when every finalized tool result in the batch does the same.
|
|
521
377
|
return {
|
|
522
378
|
content: [{ type: "text", text: content }],
|
|
523
379
|
structuredContent: { path: params.path, content },
|
|
@@ -531,28 +387,14 @@ agent.state.tools = [readFileTool];
|
|
|
531
387
|
|
|
532
388
|
### Error handling
|
|
533
389
|
|
|
534
|
-
Throw an error or return
|
|
535
|
-
|
|
536
|
-
```typescript
|
|
537
|
-
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
538
|
-
if (!fs.existsSync(params.path)) {
|
|
539
|
-
throw new Error(`File not found: ${params.path}`);
|
|
540
|
-
}
|
|
541
|
-
// Return content only on success
|
|
542
|
-
return { content: [{ type: "text", text: "..." }], details: {} };
|
|
543
|
-
}
|
|
544
|
-
```
|
|
545
|
-
|
|
546
|
-
The agent catches thrown errors and reports them to the LLM as tool errors with `isError: true`. Returning `{ content, details, structuredContent, isError: true }` reports the same error status to the model while keeping `details` and `structuredContent` for UI and programmatic callers.
|
|
547
|
-
|
|
548
|
-
Return `terminate: true` from `execute()`, a blocked `beforeToolCall`, or `afterToolCall` to skip the follow-up LLM call after the current tool batch. This takes effect only when every finalized tool result in the batch sets `terminate: true`. The hint is runtime-only, so emitted `toolResult` transcript messages remain standard LLM tool results.
|
|
390
|
+
Throw an error or return `{ content, details, structuredContent?, isError: true }` when a tool fails (do not only describe the failure in text). Returning `isError: true` preserves `details` and `structuredContent` for UI and programmatic callers.
|
|
549
391
|
|
|
550
392
|
### MCP, Codemode, and `runToolCall()`
|
|
551
393
|
|
|
552
|
-
[`@bastani/atomic-codemode`](/libraries/codemode)
|
|
394
|
+
When embedding [`@bastani/atomic-codemode`](/libraries/codemode) or MCP wrappers, invoke nested tools through `runToolCall()` so argument validation, `beforeToolCall`, and `afterToolCall` run consistently:
|
|
553
395
|
|
|
554
396
|
```typescript
|
|
555
|
-
import { type
|
|
397
|
+
import { type AgentToolCallOutcome, runToolCall } from "@bastani/atomic-agent-core";
|
|
556
398
|
|
|
557
399
|
const outcome: AgentToolCallOutcome = await runToolCall(toolCall, {
|
|
558
400
|
tools,
|
|
@@ -565,11 +407,11 @@ const outcome: AgentToolCallOutcome = await runToolCall(toolCall, {
|
|
|
565
407
|
// outcome: { result: AgentToolResult<unknown>, isError: boolean, durationMs?: number }
|
|
566
408
|
```
|
|
567
409
|
|
|
568
|
-
|
|
410
|
+
See [Using with agent-core](/libraries/codemode#using-with-agent-core) for a full example.
|
|
569
411
|
|
|
570
412
|
## Proxy usage
|
|
571
413
|
|
|
572
|
-
For browser apps that
|
|
414
|
+
For browser apps that route LLM requests through a backend server without exposing provider API keys, pass `streamProxy()` as `streamFn`:
|
|
573
415
|
|
|
574
416
|
```typescript
|
|
575
417
|
import { Agent, streamProxy } from "@bastani/atomic-agent-core";
|
|
@@ -584,9 +426,32 @@ const agent = new Agent({
|
|
|
584
426
|
});
|
|
585
427
|
```
|
|
586
428
|
|
|
429
|
+
### Proxy server HTTP and SSE contract
|
|
430
|
+
|
|
431
|
+
Your backend must expose `POST <proxyUrl>/api/stream`:
|
|
432
|
+
|
|
433
|
+
- **Request headers:** `Authorization: Bearer <authToken>` and `Content-Type: application/json`.
|
|
434
|
+
- **Request JSON body:** `{ model, context, options }`, where `model` is the serialized `Model`, `context` is the `TranscriptContext`, and `options` contains the serializable `SimpleStreamOptions` fields (`temperature`, `samplingParams`, `maxTokens`, `reasoning`, `cacheRetention`, `sessionId`, `disableContinuation`, `headers`, `metadata`, `transport`, `thinkingBudgets`, `maxRetryDelayMs`).
|
|
435
|
+
- **Error responses:** On non-2xx HTTP responses, `streamProxy()` reads `{ "error": "..." }` from a JSON response body when present (otherwise using the HTTP status text) and surfaces a stream `error` event.
|
|
436
|
+
- **Streaming response (SSE):** Return newline-delimited `data: <JSON>` lines where each payload is a `ProxyAssistantMessageEvent` (the same event vocabulary as `AssistantMessageEvent`, with `partial` omitted to reduce bandwidth—`streamProxy()` reconstructs `partial` client-side):
|
|
437
|
+
|
|
438
|
+
| `type` | Required fields | Optional fields |
|
|
439
|
+
| --- | --- | --- |
|
|
440
|
+
| `start` | — | — |
|
|
441
|
+
| `text_start` / `thinking_start` | `contentIndex` | — |
|
|
442
|
+
| `text_delta` / `thinking_delta` | `contentIndex`, `delta` | — |
|
|
443
|
+
| `text_end` / `thinking_end` | `contentIndex` | `contentSignature` |
|
|
444
|
+
| `toolcall_start` | `contentIndex`, `id`, `toolName` | — |
|
|
445
|
+
| `toolcall_delta` | `contentIndex`, `delta` | — |
|
|
446
|
+
| `toolcall_end` | `contentIndex`, `toolCall` | — |
|
|
447
|
+
| `done` | `reason` (`"stop"` \| `"length"` \| `"toolUse"`), `usage` | `providerThinkingLevel` |
|
|
448
|
+
| `error` | `reason` (`"aborted"` \| `"error"`), `usage` | `errorMessage`, `providerThinkingLevel` |
|
|
449
|
+
|
|
450
|
+
If the server closes the HTTP stream cleanly without sending a terminal `done` or `error` event, `streamProxy()` synthesizes an `error` event (`"Connection closed by proxy server before the response completed"`) instead of hanging.
|
|
451
|
+
|
|
587
452
|
## Low-level API
|
|
588
453
|
|
|
589
|
-
|
|
454
|
+
Use `agentLoop()` and `agentLoopContinue()` directly when you do not want the stateful `Agent` wrapper:
|
|
590
455
|
|
|
591
456
|
```typescript
|
|
592
457
|
import {
|
|
@@ -612,22 +477,19 @@ const config: AgentLoopConfig = {
|
|
|
612
477
|
model,
|
|
613
478
|
convertToLlm: (msgs) =>
|
|
614
479
|
msgs.filter((m) => ["system", "user", "assistant", "toolResult"].includes(m.role)),
|
|
615
|
-
toolExecution: "parallel",
|
|
616
|
-
beforeToolCall: async ({ toolCall, args, context }) => undefined,
|
|
617
|
-
afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
|
|
480
|
+
toolExecution: "parallel",
|
|
618
481
|
};
|
|
619
482
|
|
|
620
483
|
const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
|
|
621
|
-
|
|
622
484
|
const streamFn = models.streamSimple.bind(models);
|
|
485
|
+
|
|
623
486
|
for await (const event of agentLoop([userMessage], context, config, undefined, streamFn)) {
|
|
624
487
|
console.log(event.type);
|
|
625
488
|
}
|
|
626
489
|
|
|
627
|
-
// Continue from existing context
|
|
628
490
|
for await (const event of agentLoopContinue(context, config, undefined, streamFn)) {
|
|
629
491
|
console.log(event.type);
|
|
630
492
|
}
|
|
631
493
|
```
|
|
632
494
|
|
|
633
|
-
|
|
495
|
+
Low-level streams are observational: they preserve event order without waiting for async consumer work before later producer phases continue. Use the `Agent` class when async event handling must act as a barrier before tool preflight or completion.
|