my-durable 0.0.0-stage → 0.0.2

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.
Files changed (259) hide show
  1. package/.env.example +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +328 -2
  4. package/ai_docs/durable_pi/announcement.md +860 -0
  5. package/ai_docs/durable_pi/changelog.md +51 -0
  6. package/ai_docs/durable_pi/chord-delta-findings.md +362 -0
  7. package/ai_docs/durable_pi/coding-agent-integration.md +70 -0
  8. package/ai_docs/durable_pi/pico-v5-chord-usage.md +391 -0
  9. package/ai_docs/durable_pi/pico-v5-handoff.md +921 -0
  10. package/ai_docs/durable_pi/readme.md +617 -0
  11. package/ai_docs/durable_pi/sources.md +22 -0
  12. package/ai_docs/durable_pi/spec.md +4696 -0
  13. package/ai_docs/durable_pi/vacation-planner.md +57 -0
  14. package/ai_docs/pi/chord.md +268 -0
  15. package/ai_docs/pi/cli-integration.md +110 -0
  16. package/ai_docs/pi/cli.md +325 -0
  17. package/ai_docs/pi/codemode.md +211 -0
  18. package/ai_docs/pi/compaction.md +467 -0
  19. package/ai_docs/pi/configuration.md +51 -0
  20. package/ai_docs/pi/containerization.md +187 -0
  21. package/ai_docs/pi/custom-provider.md +177 -0
  22. package/ai_docs/pi/environment-variables.md +102 -0
  23. package/ai_docs/pi/extensions.md +278 -0
  24. package/ai_docs/pi/how-pi-works.md +53 -0
  25. package/ai_docs/pi/index.md +43 -0
  26. package/ai_docs/pi/json.md +230 -0
  27. package/ai_docs/pi/keybindings.md +198 -0
  28. package/ai_docs/pi/llama-cpp.md +118 -0
  29. package/ai_docs/pi/mcp.md +274 -0
  30. package/ai_docs/pi/message-types.md +265 -0
  31. package/ai_docs/pi/models.md +209 -0
  32. package/ai_docs/pi/overview.md +166 -0
  33. package/ai_docs/pi/packages.md +133 -0
  34. package/ai_docs/pi/pi-agent-core.md +568 -0
  35. package/ai_docs/pi/pi-ai.md +1942 -0
  36. package/ai_docs/pi/prompt-templates.md +63 -0
  37. package/ai_docs/pi/providers.md +204 -0
  38. package/ai_docs/pi/quickstart.md +140 -0
  39. package/ai_docs/pi/readme.md +99 -0
  40. package/ai_docs/pi/rpc-commands.md +864 -0
  41. package/ai_docs/pi/rpc-extension-ui.md +204 -0
  42. package/ai_docs/pi/rpc.md +197 -0
  43. package/ai_docs/pi/sdk.md +151 -0
  44. package/ai_docs/pi/security.md +103 -0
  45. package/ai_docs/pi/session-format.md +297 -0
  46. package/ai_docs/pi/sessions.md +70 -0
  47. package/ai_docs/pi/settings.md +173 -0
  48. package/ai_docs/pi/shell-aliases.md +97 -0
  49. package/ai_docs/pi/skills.md +97 -0
  50. package/ai_docs/pi/slash-commands.md +64 -0
  51. package/ai_docs/pi/sources.md +57 -0
  52. package/ai_docs/pi/terminal-setup.md +223 -0
  53. package/ai_docs/pi/termux.md +121 -0
  54. package/ai_docs/pi/themes.md +140 -0
  55. package/ai_docs/pi/tmux.md +59 -0
  56. package/ai_docs/pi/toolkit.md +168 -0
  57. package/ai_docs/pi/tui.md +129 -0
  58. package/ai_docs/pi/usage.md +98 -0
  59. package/ai_docs/pi/virtual-models.md +118 -0
  60. package/ai_docs/pi/windows.md +71 -0
  61. package/apps/dpi-backend/.nvmrc +1 -0
  62. package/apps/dpi-backend/API.md +99 -0
  63. package/apps/dpi-backend/README.md +119 -0
  64. package/apps/dpi-backend/deploy/backend.env.example +9 -0
  65. package/apps/dpi-backend/deploy/dpi-backend.plist +26 -0
  66. package/apps/dpi-backend/deploy/dpi-backend.service +22 -0
  67. package/apps/dpi-backend/package.json +33 -0
  68. package/apps/dpi-backend/prompts/one_sentence.md +3 -0
  69. package/apps/dpi-backend/prompts/smart_ass_opus_fix.md +169 -0
  70. package/apps/dpi-backend/scripts/check-contract.mjs +151 -0
  71. package/apps/dpi-backend/scripts/migrate-playground.ts +66 -0
  72. package/apps/dpi-backend/scripts/record-nested-fixture.mts +154 -0
  73. package/apps/dpi-backend/scripts/token.ts +57 -0
  74. package/apps/dpi-backend/src/addons.ts +139 -0
  75. package/apps/dpi-backend/src/auth.ts +20 -0
  76. package/apps/dpi-backend/src/config.ts +54 -0
  77. package/apps/dpi-backend/src/contract-check.ts +118 -0
  78. package/apps/dpi-backend/src/errors.ts +50 -0
  79. package/apps/dpi-backend/src/extensions.ts +510 -0
  80. package/apps/dpi-backend/src/faux.ts +80 -0
  81. package/apps/dpi-backend/src/history.ts +165 -0
  82. package/apps/dpi-backend/src/idempotency.ts +20 -0
  83. package/apps/dpi-backend/src/jev.ts +43 -0
  84. package/apps/dpi-backend/src/jobs.ts +790 -0
  85. package/apps/dpi-backend/src/main.ts +76 -0
  86. package/apps/dpi-backend/src/model-catalog.ts +180 -0
  87. package/apps/dpi-backend/src/pairing-files.ts +142 -0
  88. package/apps/dpi-backend/src/pairing.ts +459 -0
  89. package/apps/dpi-backend/src/routes.ts +217 -0
  90. package/apps/dpi-backend/src/shared-state.ts +85 -0
  91. package/apps/dpi-backend/src/store.ts +1240 -0
  92. package/apps/dpi-backend/src/streams.ts +256 -0
  93. package/apps/dpi-backend/src/tunnel.ts +955 -0
  94. package/apps/dpi-backend/tsconfig.json +13 -0
  95. package/apps/dpi-playground/README.md +83 -0
  96. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CFGc7lHT.js +77 -0
  97. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DFdKpwm_.css +1 -0
  98. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/anthropic.png +0 -0
  99. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/deepseek.png +0 -0
  100. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/durable-pi.svg +14 -0
  101. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/gemini.png +0 -0
  102. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/grok.png +0 -0
  103. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/kimi.png +0 -0
  104. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/lab.png +0 -0
  105. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/meta.png +0 -0
  106. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/minimax.png +0 -0
  107. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/openai.png +0 -0
  108. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/qwen.png +0 -0
  109. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/xiaomi.png +0 -0
  110. package/apps/dpi-playground/apps/dpi-playground-fe/dist/icons/zai.png +0 -0
  111. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +16 -0
  112. package/apps/dpi-playground/apps/dpi-playground-fe/index.html +15 -0
  113. package/apps/dpi-playground/apps/dpi-playground-fe/package.json +5 -0
  114. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/anthropic.png +0 -0
  115. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/deepseek.png +0 -0
  116. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/durable-pi.svg +14 -0
  117. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/gemini.png +0 -0
  118. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/grok.png +0 -0
  119. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/kimi.png +0 -0
  120. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/lab.png +0 -0
  121. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/meta.png +0 -0
  122. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/minimax.png +0 -0
  123. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/openai.png +0 -0
  124. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/qwen.png +0 -0
  125. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/xiaomi.png +0 -0
  126. package/apps/dpi-playground/apps/dpi-playground-fe/public/icons/zai.png +0 -0
  127. package/apps/dpi-playground/apps/dpi-playground-fe/src/App.vue +180 -0
  128. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/commands.ts +119 -0
  129. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/composables.ts +129 -0
  130. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/hub.ts +40 -0
  131. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/icon-path.ts +7 -0
  132. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/ids.ts +2 -0
  133. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/jobs.ts +80 -0
  134. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/link-policy.ts +16 -0
  135. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/markdown-policy.ts +115 -0
  136. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/markdown.ts +60 -0
  137. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/pair-close.ts +23 -0
  138. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/pair-handoff.ts +56 -0
  139. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/pair.ts +166 -0
  140. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/qrcode.ts +323 -0
  141. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/signature.ts +146 -0
  142. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/store.ts +373 -0
  143. package/apps/dpi-playground/apps/dpi-playground-fe/src/client/stream.ts +183 -0
  144. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/AgentView.vue +342 -0
  145. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Composer.vue +198 -0
  146. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ContextBar.vue +254 -0
  147. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/DeviceCredentialsDialog.vue +40 -0
  148. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/DeviceIcon.vue +56 -0
  149. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/DirBrowser.vue +95 -0
  150. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ExtensionsPanel.vue +96 -0
  151. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/HelpDialog.vue +69 -0
  152. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Inspector.vue +425 -0
  153. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/JobCard.vue +221 -0
  154. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/MobileNav.vue +39 -0
  155. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/ModelPicker.vue +71 -0
  156. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +236 -0
  157. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NewSessionDialog.vue +114 -0
  158. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/OfflinePanel.vue +128 -0
  159. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PairDeviceWizard.vue +433 -0
  160. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/PromptDialog.vue +89 -0
  161. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/StateEditor.vue +179 -0
  162. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TasksPanel.vue +280 -0
  163. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/Toast.vue +11 -0
  164. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TokenManager.vue +175 -0
  165. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TopBar.vue +114 -0
  166. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TranscriptItem.vue +152 -0
  167. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TreeRow.vue +195 -0
  168. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/TunnelStatusBar.vue +107 -0
  169. package/apps/dpi-playground/apps/dpi-playground-fe/src/extensions.css +105 -0
  170. package/apps/dpi-playground/apps/dpi-playground-fe/src/jobs.css +655 -0
  171. package/apps/dpi-playground/apps/dpi-playground-fe/src/main.ts +22 -0
  172. package/apps/dpi-playground/apps/dpi-playground-fe/src/network.css +675 -0
  173. package/apps/dpi-playground/apps/dpi-playground-fe/src/style.css +3203 -0
  174. package/apps/dpi-playground/apps/dpi-playground-fe/tsconfig.json +16 -0
  175. package/apps/dpi-playground/apps/dpi-playground-fe/vite.config.ts +14 -0
  176. package/apps/dpi-playground/apps/dpi-playground-hub/package.json +5 -0
  177. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +406 -0
  178. package/apps/dpi-playground/apps/dpi-playground-hub/src/client-ip.ts +72 -0
  179. package/apps/dpi-playground/apps/dpi-playground-hub/src/credentials.ts +265 -0
  180. package/apps/dpi-playground/apps/dpi-playground-hub/src/guard.ts +43 -0
  181. package/apps/dpi-playground/apps/dpi-playground-hub/src/http-errors.ts +156 -0
  182. package/apps/dpi-playground/apps/dpi-playground-hub/src/identity.ts +60 -0
  183. package/apps/dpi-playground/apps/dpi-playground-hub/src/limiter.ts +165 -0
  184. package/apps/dpi-playground/apps/dpi-playground-hub/src/main.ts +460 -0
  185. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +320 -0
  186. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +277 -0
  187. package/apps/dpi-playground/apps/dpi-playground-hub/src/pairing.ts +816 -0
  188. package/apps/dpi-playground/apps/dpi-playground-hub/src/proxy.ts +128 -0
  189. package/apps/dpi-playground/apps/dpi-playground-hub/src/rotation.ts +583 -0
  190. package/apps/dpi-playground/apps/dpi-playground-hub/src/seed.ts +11 -0
  191. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +108 -0
  192. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-token.ts +11 -0
  193. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +560 -0
  194. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel.ts +873 -0
  195. package/apps/dpi-playground/apps/dpi-playground-hub/tsconfig.json +13 -0
  196. package/apps/dpi-playground/package.json +37 -0
  197. package/apps/dpi-sdk/README.md +74 -0
  198. package/apps/dpi-sdk/package.json +20 -0
  199. package/apps/dpi-sdk/scripts/net.ts +73 -0
  200. package/apps/dpi-sdk/src/api.ts +631 -0
  201. package/apps/dpi-sdk/src/app-state.ts +111 -0
  202. package/apps/dpi-sdk/src/client.ts +330 -0
  203. package/apps/dpi-sdk/src/errors.ts +16 -0
  204. package/apps/dpi-sdk/src/jobs.ts +99 -0
  205. package/apps/dpi-sdk/src/models.ts +472 -0
  206. package/apps/dpi-sdk/src/node/chunk.ts +488 -0
  207. package/apps/dpi-sdk/src/node/config.ts +175 -0
  208. package/apps/dpi-sdk/src/node/drivers.ts +402 -0
  209. package/apps/dpi-sdk/src/node/ops.ts +114 -0
  210. package/apps/dpi-sdk/src/node/private-dir.ts +48 -0
  211. package/apps/dpi-sdk/src/node/registry-migration.ts +549 -0
  212. package/apps/dpi-sdk/src/node/registry.ts +390 -0
  213. package/apps/dpi-sdk/src/node/sse-writer.ts +151 -0
  214. package/apps/dpi-sdk/src/protocol/backoff.ts +31 -0
  215. package/apps/dpi-sdk/src/protocol/limits.ts +199 -0
  216. package/apps/dpi-sdk/src/protocol/pairing.ts +311 -0
  217. package/apps/dpi-sdk/src/protocol/rest-routes.ts +105 -0
  218. package/apps/dpi-sdk/src/protocol/tunnel.ts +331 -0
  219. package/apps/dpi-sdk/src/sse.ts +117 -0
  220. package/apps/dpi-sdk/src/transcript.ts +291 -0
  221. package/apps/dpi-sdk/tsconfig.json +13 -0
  222. package/apps/dpi-sdk/w +20 -0
  223. package/apps/dpi-tui/README.md +54 -0
  224. package/apps/dpi-tui/bin/dpi-tui.mjs +5 -0
  225. package/apps/dpi-tui/package.json +20 -0
  226. package/apps/dpi-tui/src/app.ts +433 -0
  227. package/apps/dpi-tui/src/commands.ts +151 -0
  228. package/apps/dpi-tui/src/main.ts +122 -0
  229. package/apps/dpi-tui/src/pairing.ts +287 -0
  230. package/apps/dpi-tui/src/pickers.ts +238 -0
  231. package/apps/dpi-tui/src/render.ts +164 -0
  232. package/apps/dpi-tui/src/theme.ts +57 -0
  233. package/apps/dpi-tui/tsconfig.json +14 -0
  234. package/bin/device.mjs +5 -0
  235. package/bin/hub.mjs +5 -0
  236. package/bin/tui.mjs +5 -0
  237. package/deploy/Caddyfile +120 -0
  238. package/docs/verification.md +102 -0
  239. package/dpi-network.example.yaml +62 -0
  240. package/images/01_durable_agent_network.svg +185 -0
  241. package/images/02_pi_made_durable.svg +204 -0
  242. package/images/03_restart_mid_tool.svg +168 -0
  243. package/images/07_one_api_every_client.svg +123 -0
  244. package/images/08_device_session_agent.svg +123 -0
  245. package/images/09_compact_keep_history.svg +143 -0
  246. package/images/10_shared_app_state.svg +177 -0
  247. package/images/11_durable_jobs_wait.svg +141 -0
  248. package/images/12_tools_change_mid_run.svg +231 -0
  249. package/images/13_hook_blocks_tool.svg +122 -0
  250. package/images/14_fork_at_any_entry.svg +119 -0
  251. package/images/15_web_client.png +0 -0
  252. package/images/16_terminal_client.svg +43 -0
  253. package/images/17_devices_are_data.svg +182 -0
  254. package/images/18_should_every_agent_be_durable.svg +118 -0
  255. package/images/19_sqlite_on_every_device.svg +155 -0
  256. package/images/20_admission_and_effects.svg +134 -0
  257. package/justfile +33 -0
  258. package/package.json +41 -4
  259. package/scripts/verify.mjs +210 -0
@@ -0,0 +1,568 @@
1
+ > Source: [packages/agent/README.md](https://github.com/earendil-works/pi/blob/b78e6a9085343ec0f308c3d377da72528b4cf7ee/packages/agent/README.md)
2
+ > Retrieved with Firecrawl: 2026-10-05. Repository snapshot: `b78e6a9085343ec0f308c3d377da72528b4cf7ee`.
3
+ > Relative documentation links point to local copies where available, otherwise to the source snapshot.
4
+
5
+ # @earendil-works/pi-agent-core
6
+
7
+ Stateful agent with tool execution and event streaming. Built on `@earendil-works/pi-ai`.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @earendil-works/pi-agent-core
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { Agent } from "@earendil-works/pi-agent-core";
19
+ import { createModels } from "@earendil-works/pi-ai";
20
+ import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic";
21
+
22
+ const models = createModels();
23
+ models.setProvider(anthropicProvider());
24
+ const model = models.getModel("anthropic", "claude-sonnet-4-6");
25
+ if (!model) throw new Error("Model not found");
26
+
27
+ const agent = new Agent({
28
+ initialState: {
29
+ systemPrompt: "You are a helpful assistant.",
30
+ model,
31
+ },
32
+ streamFn: models.streamSimple.bind(models),
33
+ });
34
+
35
+ agent.subscribe((event) => {
36
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
37
+ // Stream just the new text chunk
38
+ process.stdout.write(event.assistantMessageEvent.delta);
39
+ }
40
+ });
41
+
42
+ await agent.prompt("Hello!");
43
+ ```
44
+
45
+ ## Core Concepts
46
+
47
+ ### AgentMessage vs LLM Message
48
+
49
+ The agent works with `AgentMessage`, a flexible type that can include:
50
+ - Standard LLM messages (`user`, `assistant`, `toolResult`)
51
+ - Custom app-specific message types via declaration merging
52
+
53
+ LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
54
+
55
+ ### Message Flow
56
+
57
+ ```
58
+ AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
59
+ (optional) (required)
60
+ ```
61
+
62
+ 1. **transformContext**: Prune old messages, inject external context
63
+ 2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
64
+
65
+ ## Event Flow
66
+
67
+ The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
68
+
69
+ ### prompt() Event Sequence
70
+
71
+ When you call `prompt("Hello")`:
72
+
73
+ ```
74
+ prompt("Hello")
75
+ ├─ agent_start
76
+ ├─ turn_start
77
+ ├─ message_start { message: userMessage } // Your prompt
78
+ ├─ message_end { message: userMessage }
79
+ ├─ message_start { message: assistantMessage } // LLM starts responding
80
+ ├─ message_update { message: partial... } // Streaming chunks
81
+ ├─ message_update { message: partial... }
82
+ ├─ message_end { message: assistantMessage } // Complete response
83
+ ├─ turn_end { message, toolResults: [] }
84
+ └─ agent_end { messages: [...] }
85
+ ```
86
+
87
+ ### With Tool Calls
88
+
89
+ If the assistant calls tools, the loop continues:
90
+
91
+ ```
92
+ prompt("Read config.json")
93
+ ├─ agent_start
94
+ ├─ turn_start
95
+ ├─ message_start/end { userMessage }
96
+ ├─ message_start { assistantMessage with toolCall }
97
+ ├─ message_update...
98
+ ├─ message_end { assistantMessage }
99
+ ├─ tool_execution_start { toolCallId, toolName, args }
100
+ ├─ tool_execution_update { partialResult } // If tool streams
101
+ ├─ tool_execution_end { toolCallId, result }
102
+ ├─ message_start/end { toolResultMessage }
103
+ ├─ turn_end { message, toolResults: [toolResult] }
104
+ │
105
+ ├─ turn_start // Next turn
106
+ ├─ message_start { assistantMessage } // LLM responds to tool result
107
+ ├─ message_update...
108
+ ├─ message_end
109
+ ├─ turn_end
110
+ └─ agent_end
111
+ ```
112
+
113
+ Tool execution mode is configurable:
114
+
115
+ - `parallel` (default): preflight tool calls sequentially, execute allowed tools concurrently, emit `tool_execution_end` as soon as each tool is finalized, then emit toolResult messages and `turn_end.toolResults` in assistant source order
116
+ - `sequential`: execute tool calls one by one, matching the historical behavior
117
+
118
+ In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
119
+
120
+ The mode can be set globally via `toolExecution` in the agent config, or per-tool via `executionMode` on `AgentTool`. If any tool call in a batch targets a tool with `executionMode: "sequential"`, the entire batch executes sequentially regardless of the global setting.
121
+
122
+ The `beforeToolCall` hook runs after `tool_execution_start` and validated argument parsing. It can block execution and attach `terminate: true` to the blocked result. The `afterToolCall` hook runs after tool execution finishes and before `tool_execution_end` and final tool result message events are emitted.
123
+
124
+ Tools, blocked `beforeToolCall` results, and `afterToolCall` overrides can return `terminate: true` to hint that the automatic follow-up LLM call should be skipped. The loop only stops early when every finalized tool result in that batch sets `terminate: true`. Mixed batches continue normally.
125
+
126
+ When you use the `Agent` class, assistant `message_end` processing is treated as a barrier before tool preflight begins. That means `beforeToolCall` sees agent state that already includes the assistant message that requested the tool call.
127
+
128
+ ### Request preparation and turn finalization
129
+
130
+ `prepareRequest` runs immediately before every conversational provider request, including the first. Use it to install canonical persisted context after pending input has been emitted:
131
+
132
+ ```typescript
133
+ agent.prepareRequest = async ({ context }) => ({
134
+ context: { ...context, messages: await session.loadModelContext() },
135
+ });
136
+ ```
137
+
138
+ `prepareRequest` does not poll queues. Steering queued while it runs waits for the next normal steering poll.
139
+
140
+ `finishTurn` runs after the assistant and all tool results are finalized, but before `turn_end`. It runs for normal, error, and aborted responses:
141
+
142
+ ```typescript
143
+ agent.finishTurn = async ({ message }) => {
144
+ if (message.stopReason === "error" || message.stopReason === "aborted") return;
145
+ if (shouldEndRun(message)) return { action: "end" };
146
+ return needsAnotherResponse(message) ? { action: "continue" } : undefined;
147
+ };
148
+ ```
149
+
150
+ Returning `undefined` preserves normal scheduling. `{ action: "end" }` stops immediately after `turn_end`, before polling steering or follow-up queues or preparing another request. On a normal response, `{ action: "continue" }` ensures one next provider request. If tool results, steering, or a follow-up already cause that request, they satisfy the decision and no additional request is made; otherwise the loop makes one context-only request. Error and aborted responses remain hard exits, so their decisions are ignored. `finishTurn` runs again after the next request, so returning `{ action: "continue" }` unconditionally creates an endless loop.
151
+
152
+ To migrate from the removed `shouldStopAfterTurn`, return `{ action: "end" }`. Guard error and aborted responses to preserve the old hook's normal-response-only invocation, especially when the predicate has side effects or assumes a successful response:
153
+
154
+ ```typescript
155
+ finishTurn: async (turn, signal) => {
156
+ if (turn.message.stopReason === "error" || turn.message.stopReason === "aborted") return;
157
+ return (await shouldStop(turn, signal)) ? { action: "end" } : undefined;
158
+ },
159
+ ```
160
+
161
+ Each provider turn follows this lifecycle:
162
+
163
+ ```text
164
+ selected input events
165
+ → prepareRequest
166
+ → provider response
167
+ → tool results
168
+ → finishTurn
169
+ → turn_end
170
+ → existing continuation scheduling or agent_end
171
+ ```
172
+
173
+ ### continue() and queued input
174
+
175
+ `continue()` retains its existing queue behavior. Empty and system-only transcripts reject without consuming queues. A non-assistant tail continues from existing context: steering is polled at startup, while follow-up input waits until the response naturally stops.
176
+
177
+ ```typescript
178
+ agent.followUp({ role: "user", content: "After the retry", timestamp: Date.now() });
179
+ await agent.continue(); // The first request retries the existing user/toolResult tail.
180
+ ```
181
+
182
+ An assistant tail cannot be sent directly, so `continue()` falls back to one queued steering batch, then one queued follow-up batch. Queue mode still controls whether that selected batch contains one message or all messages:
183
+
184
+ ```typescript
185
+ agent.steer({ role: "user", content: "Continue from here", timestamp: Date.now() });
186
+ await agent.continue(); // Uses the queued message only because the tail is assistant.
187
+ ```
188
+
189
+ ### Event Types
190
+
191
+ | Event | Description |
192
+ |-------|-------------|
193
+ | `agent_start` | Agent begins processing |
194
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
195
+ | `turn_start` | New turn begins (one LLM call + tool executions) |
196
+ | `turn_end` | Turn completes with assistant message and tool results |
197
+ | `message_start` | Any message begins (user, assistant, toolResult) |
198
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
199
+ | `message_end` | Message completes |
200
+ | `tool_execution_start` | Tool begins |
201
+ | `tool_execution_update` | Tool streams progress |
202
+ | `tool_execution_end` | Tool completes |
203
+
204
+ `Agent.subscribe()` listeners are awaited in registration order. `agent_end` means no more loop events will be emitted, but `await agent.waitForIdle()` and `await agent.prompt(...)` only settle after awaited `agent_end` listeners finish.
205
+
206
+ ## Agent Options
207
+
208
+ ```typescript
209
+ const agent = new Agent({
210
+ // Initial state. systemPrompt and tools become the leading system message
211
+ // unless messages already starts with one.
212
+ initialState: {
213
+ systemPrompt: string,
214
+ model: Model<any>,
215
+ thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max",
216
+ tools: AgentTool<any>[],
217
+ messages: AgentMessage[],
218
+ },
219
+
220
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types)
221
+ convertToLlm: (messages) => messages.filter(...),
222
+
223
+ // Transform context before convertToLlm (for pruning, compaction)
224
+ transformContext: async (messages, signal) => pruneOldMessages(messages),
225
+
226
+ // Steering mode: "one-at-a-time" (default) or "all"
227
+ steeringMode: "one-at-a-time",
228
+
229
+ // Follow-up mode: "one-at-a-time" (default) or "all"
230
+ followUpMode: "one-at-a-time",
231
+
232
+ // Required stream function. Receives a TranscriptContext: the prompt and tools
233
+ // are in the transcript's system messages, not on the context.
234
+ streamFn: models.streamSimple.bind(models),
235
+
236
+ // Session ID for provider caching
237
+ sessionId: "session-123",
238
+
239
+ // Dynamic API key resolution (for expiring OAuth tokens)
240
+ getApiKey: async (provider) => refreshToken(),
241
+
242
+ // Tool execution mode: "parallel" (default) or "sequential"
243
+ toolExecution: "parallel",
244
+
245
+ // Preflight each tool call after args are validated. Can block execution.
246
+ beforeToolCall: async ({ toolCall, args, context }) => {
247
+ if (toolCall.name === "bash") {
248
+ return { block: true, reason: "bash is disabled", terminate: true };
249
+ }
250
+ },
251
+
252
+ // Postprocess each tool result before final tool events are emitted.
253
+ afterToolCall: async ({ toolCall, result, isError, context }) => {
254
+ if (toolCall.name === "notify_done" && !isError) {
255
+ return { terminate: true };
256
+ }
257
+ if (!isError) {
258
+ return { details: { ...result.details, audited: true } };
259
+ }
260
+ },
261
+
262
+ // Rebuild finalized context immediately before every provider request.
263
+ prepareRequest: async ({ context }, signal) => {
264
+ return { context: { ...context, messages: await loadCanonicalMessages(signal) } };
265
+ },
266
+
267
+ // Finalize a completed turn before turn_end is emitted.
268
+ // `continue` ensures one next request; existing tool/queue scheduling can satisfy it.
269
+ // `end` ends this run after turn_end without polling queues.
270
+ finishTurn: async ({ message, toolResults }, signal) => {
271
+ return shouldContinue(message, toolResults) ? { action: "continue" } : undefined;
272
+ },
273
+
274
+ // Custom thinking budgets for token-based providers
275
+ thinkingBudgets: {
276
+ minimal: 128,
277
+ low: 512,
278
+ medium: 1024,
279
+ high: 2048,
280
+ },
281
+ });
282
+ ```
283
+
284
+ ## Agent State
285
+
286
+ ```typescript
287
+ interface AgentState {
288
+ model: Model<any>;
289
+ thinkingLevel: ThinkingLevel;
290
+ tools: AgentTool<any>[];
291
+ messages: AgentMessage[];
292
+ readonly isStreaming: boolean;
293
+ readonly streamingMessage?: AgentMessage;
294
+ readonly pendingToolCalls: ReadonlySet<string>;
295
+ readonly errorMessage?: string;
296
+ }
297
+ ```
298
+
299
+ Access state via `agent.state`.
300
+
301
+ Assigning `agent.state.tools = [...]` or `agent.state.messages = [...]` copies the top-level array before storing it. Mutating the returned array mutates the current agent state.
302
+
303
+ The transcript owns the system prompt and tool declarations: the leading system message is the prompt, later system messages patch it (see `SystemMessage` in pi-ai). `agent.state.systemPrompt` is read-only and replays the transcript. `agent.state.tools` is the executable loadout; before every request the loop diffs it against the tools the transcript declares and, if they differ, announces the change in a system message (merged into a pending system message when one exists). pi-ai's `getCurrentSystemMessage(messages)` returns the replayed head, including declared tools, for any message array, including agent transcripts with custom message roles.
304
+
305
+ To change the prompt mid-conversation, append a system message with `content` (added instructions) or `sections` (named replacements):
306
+
307
+ ```typescript
308
+ await agent.prompt([
309
+ { role: "system", content: "", sections: { skills: "<skills>...</skills>" }, timestamp: Date.now() },
310
+ { role: "user", content: "Continue", timestamp: Date.now() },
311
+ ]);
312
+ ```
313
+
314
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
315
+
316
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
317
+
318
+ ## Methods
319
+
320
+ ### Prompting
321
+
322
+ ```typescript
323
+ // Text prompt
324
+ await agent.prompt("Hello");
325
+
326
+ // With images
327
+ await agent.prompt("What's in this image?", [
328
+ { type: "image", data: base64Data, mimeType: "image/jpeg" }
329
+ ]);
330
+
331
+ // AgentMessage directly
332
+ await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
333
+
334
+ // Continue existing non-assistant input; an assistant tail may use queued input as fallback
335
+ await agent.continue();
336
+ ```
337
+
338
+ ### State Management
339
+
340
+ ```typescript
341
+ agent.state.model = getModel("openai", "gpt-4o");
342
+ agent.state.thinkingLevel = "medium";
343
+ agent.state.tools = [myTool];
344
+ agent.toolExecution = "sequential";
345
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
346
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
347
+ agent.prepareRequest = async ({ context }) => ({
348
+ context: { ...context, messages: await loadCanonicalMessages() },
349
+ });
350
+ agent.finishTurn = async () => undefined;
351
+ agent.state.messages = newMessages; // top-level array is copied
352
+ agent.state.messages.push(message);
353
+ const nextQueuedMessages = agent.peekQueuedMessages(); // respects queue modes; does not consume
354
+ agent.reset();
355
+ ```
356
+
357
+ ### Session and Thinking Budgets
358
+
359
+ ```typescript
360
+ agent.sessionId = "session-123";
361
+
362
+ agent.thinkingBudgets = {
363
+ minimal: 128,
364
+ low: 512,
365
+ medium: 1024,
366
+ high: 2048,
367
+ };
368
+ ```
369
+
370
+ ### Control
371
+
372
+ ```typescript
373
+ agent.abort(); // Cancel current operation
374
+ await agent.waitForIdle(); // Wait for completion
375
+ ```
376
+
377
+ ### Events
378
+
379
+ ```typescript
380
+ const unsubscribe = agent.subscribe(async (event, signal) => {
381
+ if (event.type === "agent_end") {
382
+ // Final barrier work for the run
383
+ await flushSessionState(signal);
384
+ }
385
+ });
386
+ unsubscribe();
387
+ ```
388
+
389
+ ## Steering and Follow-up
390
+
391
+ Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
392
+
393
+ ```typescript
394
+ agent.steeringMode = "one-at-a-time";
395
+ agent.followUpMode = "one-at-a-time";
396
+
397
+ // While agent is running tools
398
+ agent.steer({
399
+ role: "user",
400
+ content: "Stop! Do this instead.",
401
+ timestamp: Date.now(),
402
+ });
403
+
404
+ // After the agent finishes its current work
405
+ agent.followUp({
406
+ role: "user",
407
+ content: "Also summarize the result.",
408
+ timestamp: Date.now(),
409
+ });
410
+
411
+ const steeringMode = agent.steeringMode;
412
+ const followUpMode = agent.followUpMode;
413
+
414
+ agent.clearSteeringQueue();
415
+ agent.clearFollowUpQueue();
416
+ agent.clearAllQueues();
417
+ ```
418
+
419
+ Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
420
+
421
+ When steering messages are detected after a turn completes:
422
+ 1. All tool calls from the current assistant message have already finished
423
+ 2. Steering messages are injected
424
+ 3. The LLM responds on the next turn
425
+
426
+ 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.
427
+
428
+ ## Custom Message Types
429
+
430
+ Extend `AgentMessage` via declaration merging:
431
+
432
+ ```typescript
433
+ declare module "@earendil-works/pi-agent-core" {
434
+ interface CustomAgentMessages {
435
+ notification: { role: "notification"; text: string; timestamp: number };
436
+ }
437
+ }
438
+
439
+ // Now valid
440
+ const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
441
+ ```
442
+
443
+ Handle custom types in `convertToLlm`:
444
+
445
+ ```typescript
446
+ const agent = new Agent({
447
+ streamFn: models.streamSimple.bind(models),
448
+ convertToLlm: (messages) => messages.flatMap(m => {
449
+ if (m.role === "notification") return []; // Filter out
450
+ return [m];
451
+ }),
452
+ });
453
+ ```
454
+
455
+ ## Tools
456
+
457
+ Define tools using `AgentTool`:
458
+
459
+ ```typescript
460
+ import { Type } from "typebox";
461
+
462
+ const readFileTool: AgentTool = {
463
+ name: "read_file",
464
+ label: "Read File", // For UI display
465
+ description: "Read a file's contents",
466
+ parameters: Type.Object({
467
+ path: Type.String({ description: "File path" }),
468
+ }),
469
+ // Override execution mode for this tool (optional).
470
+ // "sequential" forces the entire batch to run one at a time.
471
+ // "parallel" allows concurrent execution with other tool calls.
472
+ // If omitted, the global toolExecution config applies.
473
+ executionMode: "sequential",
474
+ execute: async (toolCallId, params, signal, onUpdate) => {
475
+ const content = await fs.readFile(params.path, "utf-8");
476
+
477
+ // Optional: stream progress
478
+ onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
479
+
480
+ // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
481
+ // when every finalized tool result in the batch does the same.
482
+ return {
483
+ content: [{ type: "text", text: content }],
484
+ details: { path: params.path, size: content.length },
485
+ };
486
+ },
487
+ };
488
+
489
+ agent.state.tools = [readFileTool];
490
+ ```
491
+
492
+ ### Error Handling
493
+
494
+ **Throw an error** when a tool fails. Do not return error messages as content.
495
+
496
+ ```typescript
497
+ execute: async (toolCallId, params, signal, onUpdate) => {
498
+ if (!fs.existsSync(params.path)) {
499
+ throw new Error(`File not found: ${params.path}`);
500
+ }
501
+ // Return content only on success
502
+ return { content: [{ type: "text", text: "..." }] };
503
+ }
504
+ ```
505
+
506
+ Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
507
+
508
+ Return `terminate: true` from `execute()`, a blocked `beforeToolCall`, or `afterToolCall` to hint that the agent should stop after the current tool batch. This only takes effect when every finalized tool result in the batch is terminating. The hint is runtime-only; emitted `toolResult` transcript messages remain standard LLM tool results.
509
+
510
+ ### MCP and Codemode
511
+
512
+ `@earendil-works/pi-mcp` connects to MCP servers and `@earendil-works/pi-codemode` runs model-written JavaScript that calls tools. [examples/mcp-codemode](https://github.com/earendil-works/pi/blob/b78e6a9085343ec0f308c3d377da72528b4cf7ee/packages/agent/examples/mcp-codemode) wraps both as `AgentTool`s: one tool per MCP tool, and a `codemode` tool whose scripts call the agent's tools through `runToolCall()`, so `beforeToolCall` and `afterToolCall` apply to those calls too.
513
+
514
+ ## Proxy Usage
515
+
516
+ For browser apps that proxy through a backend:
517
+
518
+ ```typescript
519
+ import { Agent, streamProxy } from "@earendil-works/pi-agent-core";
520
+
521
+ const agent = new Agent({
522
+ streamFn: (model, context, options) =>
523
+ streamProxy(model, context, {
524
+ ...options,
525
+ authToken: "...",
526
+ proxyUrl: "https://your-server.com",
527
+ }),
528
+ });
529
+ ```
530
+
531
+ ## Low-Level API
532
+
533
+ For direct control without the Agent class:
534
+
535
+ ```typescript
536
+ import { agentLoop, agentLoopContinue } from "@earendil-works/pi-agent-core";
537
+
538
+ const context: AgentContext = {
539
+ messages: [{ role: "system", content: "You are helpful.", timestamp: Date.now() }],
540
+ tools: [],
541
+ };
542
+
543
+ const config: AgentLoopConfig = {
544
+ model: getModel("openai", "gpt-4o"),
545
+ convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
546
+ toolExecution: "parallel", // overridden by per-tool executionMode if set
547
+ beforeToolCall: async ({ toolCall, args, context }) => undefined,
548
+ afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
549
+ };
550
+
551
+ const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
552
+
553
+ const streamFn = models.streamSimple.bind(models);
554
+ for await (const event of agentLoop([userMessage], context, config, undefined, streamFn)) {
555
+ console.log(event.type);
556
+ }
557
+
558
+ // Continue from existing context
559
+ for await (const event of agentLoopContinue(context, config, undefined, streamFn)) {
560
+ console.log(event.type);
561
+ }
562
+ ```
563
+
564
+ These low-level streams are observational. They preserve event order, but they do not wait for your async event handling to settle before later producer phases continue. If you need message processing to act as a barrier before tool preflight, use the `Agent` class instead of raw `agentLoop()` or `agentLoopContinue()`.
565
+
566
+ ## License
567
+
568
+ MIT