@code-yeongyu/senpi-agent-core 2026.7.25-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 (142) hide show
  1. package/README.md +508 -0
  2. package/dist/agent-loop.d.ts +31 -0
  3. package/dist/agent-loop.d.ts.map +1 -0
  4. package/dist/agent-loop.js +851 -0
  5. package/dist/agent-loop.js.map +1 -0
  6. package/dist/agent.d.ts +140 -0
  7. package/dist/agent.d.ts.map +1 -0
  8. package/dist/agent.js +464 -0
  9. package/dist/agent.js.map +1 -0
  10. package/dist/harness/agent-harness.d.ts +94 -0
  11. package/dist/harness/agent-harness.d.ts.map +1 -0
  12. package/dist/harness/agent-harness.js +988 -0
  13. package/dist/harness/agent-harness.js.map +1 -0
  14. package/dist/harness/compaction/branch-summarization.d.ts +55 -0
  15. package/dist/harness/compaction/branch-summarization.d.ts.map +1 -0
  16. package/dist/harness/compaction/branch-summarization.js +172 -0
  17. package/dist/harness/compaction/branch-summarization.js.map +1 -0
  18. package/dist/harness/compaction/compaction.d.ts +107 -0
  19. package/dist/harness/compaction/compaction.d.ts.map +1 -0
  20. package/dist/harness/compaction/compaction.js +588 -0
  21. package/dist/harness/compaction/compaction.js.map +1 -0
  22. package/dist/harness/compaction/utils.d.ts +36 -0
  23. package/dist/harness/compaction/utils.d.ts.map +1 -0
  24. package/dist/harness/compaction/utils.js +136 -0
  25. package/dist/harness/compaction/utils.js.map +1 -0
  26. package/dist/harness/env/nodejs.d.ts +45 -0
  27. package/dist/harness/env/nodejs.d.ts.map +1 -0
  28. package/dist/harness/env/nodejs.js +620 -0
  29. package/dist/harness/env/nodejs.js.map +1 -0
  30. package/dist/harness/messages.d.ts +52 -0
  31. package/dist/harness/messages.d.ts.map +1 -0
  32. package/dist/harness/messages.js +102 -0
  33. package/dist/harness/messages.js.map +1 -0
  34. package/dist/harness/prompt-templates.d.ts +48 -0
  35. package/dist/harness/prompt-templates.d.ts.map +1 -0
  36. package/dist/harness/prompt-templates.js +230 -0
  37. package/dist/harness/prompt-templates.js.map +1 -0
  38. package/dist/harness/session/jsonl-repo.d.ts +26 -0
  39. package/dist/harness/session/jsonl-repo.d.ts.map +1 -0
  40. package/dist/harness/session/jsonl-repo.js +100 -0
  41. package/dist/harness/session/jsonl-repo.js.map +1 -0
  42. package/dist/harness/session/jsonl-storage.d.ts +42 -0
  43. package/dist/harness/session/jsonl-storage.d.ts.map +1 -0
  44. package/dist/harness/session/jsonl-storage.js +286 -0
  45. package/dist/harness/session/jsonl-storage.js.map +1 -0
  46. package/dist/harness/session/memory-repo.d.ts +18 -0
  47. package/dist/harness/session/memory-repo.d.ts.map +1 -0
  48. package/dist/harness/session/memory-repo.js +44 -0
  49. package/dist/harness/session/memory-repo.js.map +1 -0
  50. package/dist/harness/session/memory-storage.d.ts +33 -0
  51. package/dist/harness/session/memory-storage.d.ts.map +1 -0
  52. package/dist/harness/session/memory-storage.js +163 -0
  53. package/dist/harness/session/memory-storage.js.map +1 -0
  54. package/dist/harness/session/repo-utils.d.ts +11 -0
  55. package/dist/harness/session/repo-utils.d.ts.map +1 -0
  56. package/dist/harness/session/repo-utils.js +39 -0
  57. package/dist/harness/session/repo-utils.js.map +1 -0
  58. package/dist/harness/session/session.d.ts +49 -0
  59. package/dist/harness/session/session.d.ts.map +1 -0
  60. package/dist/harness/session/session.js +261 -0
  61. package/dist/harness/session/session.js.map +1 -0
  62. package/dist/harness/skills.d.ts +44 -0
  63. package/dist/harness/skills.d.ts.map +1 -0
  64. package/dist/harness/skills.js +311 -0
  65. package/dist/harness/skills.js.map +1 -0
  66. package/dist/harness/system-prompt.d.ts +3 -0
  67. package/dist/harness/system-prompt.d.ts.map +1 -0
  68. package/dist/harness/system-prompt.js +30 -0
  69. package/dist/harness/system-prompt.js.map +1 -0
  70. package/dist/harness/tools/bash.d.ts +27 -0
  71. package/dist/harness/tools/bash.d.ts.map +1 -0
  72. package/dist/harness/tools/bash.js +132 -0
  73. package/dist/harness/tools/bash.js.map +1 -0
  74. package/dist/harness/tools/edit-diff.d.ts +89 -0
  75. package/dist/harness/tools/edit-diff.d.ts.map +1 -0
  76. package/dist/harness/tools/edit-diff.js +386 -0
  77. package/dist/harness/tools/edit-diff.js.map +1 -0
  78. package/dist/harness/tools/edit.d.ts +19 -0
  79. package/dist/harness/tools/edit.d.ts.map +1 -0
  80. package/dist/harness/tools/edit.js +95 -0
  81. package/dist/harness/tools/edit.js.map +1 -0
  82. package/dist/harness/tools/file-mutation-queue.d.ts +4 -0
  83. package/dist/harness/tools/file-mutation-queue.d.ts.map +1 -0
  84. package/dist/harness/tools/file-mutation-queue.js +46 -0
  85. package/dist/harness/tools/file-mutation-queue.js.map +1 -0
  86. package/dist/harness/tools/image.d.ts +3 -0
  87. package/dist/harness/tools/image.d.ts.map +1 -0
  88. package/dist/harness/tools/image.js +106 -0
  89. package/dist/harness/tools/image.js.map +1 -0
  90. package/dist/harness/tools/index.d.ts +6 -0
  91. package/dist/harness/tools/index.d.ts.map +1 -0
  92. package/dist/harness/tools/index.js +5 -0
  93. package/dist/harness/tools/index.js.map +1 -0
  94. package/dist/harness/tools/path-utils.d.ts +4 -0
  95. package/dist/harness/tools/path-utils.d.ts.map +1 -0
  96. package/dist/harness/tools/path-utils.js +26 -0
  97. package/dist/harness/tools/path-utils.js.map +1 -0
  98. package/dist/harness/tools/read.d.ts +34 -0
  99. package/dist/harness/tools/read.d.ts.map +1 -0
  100. package/dist/harness/tools/read.js +110 -0
  101. package/dist/harness/tools/read.js.map +1 -0
  102. package/dist/harness/tools/tool-context.d.ts +6 -0
  103. package/dist/harness/tools/tool-context.d.ts.map +1 -0
  104. package/dist/harness/tools/tool-context.js +2 -0
  105. package/dist/harness/tools/tool-context.js.map +1 -0
  106. package/dist/harness/tools/write.d.ts +11 -0
  107. package/dist/harness/tools/write.d.ts.map +1 -0
  108. package/dist/harness/tools/write.js +31 -0
  109. package/dist/harness/tools/write.js.map +1 -0
  110. package/dist/harness/types.d.ts +682 -0
  111. package/dist/harness/types.d.ts.map +1 -0
  112. package/dist/harness/types.js +83 -0
  113. package/dist/harness/types.js.map +1 -0
  114. package/dist/harness/utils/shell-output.d.ts +22 -0
  115. package/dist/harness/utils/shell-output.d.ts.map +1 -0
  116. package/dist/harness/utils/shell-output.js +181 -0
  117. package/dist/harness/utils/shell-output.js.map +1 -0
  118. package/dist/harness/utils/truncate.d.ts +70 -0
  119. package/dist/harness/utils/truncate.d.ts.map +1 -0
  120. package/dist/harness/utils/truncate.js +296 -0
  121. package/dist/harness/utils/truncate.js.map +1 -0
  122. package/dist/index.d.ts +24 -0
  123. package/dist/index.d.ts.map +1 -0
  124. package/dist/index.js +30 -0
  125. package/dist/index.js.map +1 -0
  126. package/dist/node.d.ts +3 -0
  127. package/dist/node.d.ts.map +1 -0
  128. package/dist/node.js +3 -0
  129. package/dist/node.js.map +1 -0
  130. package/dist/proxy.d.ts +71 -0
  131. package/dist/proxy.d.ts.map +1 -0
  132. package/dist/proxy.js +280 -0
  133. package/dist/proxy.js.map +1 -0
  134. package/dist/stream-fn.d.ts +10 -0
  135. package/dist/stream-fn.d.ts.map +1 -0
  136. package/dist/stream-fn.js +17 -0
  137. package/dist/stream-fn.js.map +1 -0
  138. package/dist/types.d.ts +415 -0
  139. package/dist/types.d.ts.map +1 -0
  140. package/dist/types.js +2 -0
  141. package/dist/types.js.map +1 -0
  142. package/package.json +61 -0
package/README.md ADDED
@@ -0,0 +1,508 @@
1
+ # @earendil-works/pi-agent-core
2
+
3
+ Stateful agent with tool execution and event streaming. Built on `@earendil-works/pi-ai`.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @earendil-works/pi-agent-core
9
+ ```
10
+
11
+ ### SQLite session backends
12
+
13
+ The SQLite session backend and the `node:sqlite` adapter live in a separate package, `@earendil-works/pi-storage-sqlite-node`, so the core package does not pull in runtime builtins or native SQLite dependencies by default. The backend accepts a runtime-specific SQLite factory, allowing other storage backends to ship as their own packages in the future.
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`. In parallel mode, a tool call targeting a tool with `executionMode: "sequential"` runs as an exclusive barrier: it waits for all previously scheduled calls in the batch to finish, and later calls wait for it to complete. Parallel tools before or after the barrier still execute concurrently with each other.
121
+
122
+ The `beforeToolCall` hook runs after `tool_execution_start` and validated argument parsing. It can block execution. The `afterToolCall` hook runs after tool execution finishes and before `tool_execution_end` and final tool result message events are emitted.
123
+
124
+ Tools can also 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
+ Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
127
+
128
+ ```typescript
129
+ const stream = agentLoop(
130
+ prompts,
131
+ context,
132
+ {
133
+ model,
134
+ convertToLlm,
135
+ shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
136
+ return shouldCompactBeforeNextTurn(context.messages);
137
+ },
138
+ },
139
+ undefined,
140
+ models.streamSimple.bind(models),
141
+ );
142
+ ```
143
+
144
+ `shouldStopAfterTurn` runs after `turn_end` is emitted and after the assistant response and any tool executions have completed normally. If it returns `true`, the loop emits `agent_end` and exits before polling steering or follow-up queues, and before starting another LLM call. It does not abort the provider stream, does not cancel running tools, and does not alter the assistant message stop reason.
145
+
146
+ 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.
147
+
148
+ ### continue() Event Sequence
149
+
150
+ `continue()` resumes from existing context without adding a new message. Use it for retries after errors.
151
+
152
+ ```typescript
153
+ // After an error, retry from current state
154
+ await agent.continue();
155
+ ```
156
+
157
+ The last message in context must be `user` or `toolResult` (not `assistant`).
158
+
159
+ ### Event Types
160
+
161
+ | Event | Description |
162
+ |-------|-------------|
163
+ | `agent_start` | Agent begins processing |
164
+ | `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
165
+ | `turn_start` | New turn begins (one LLM call + tool executions) |
166
+ | `turn_end` | Turn completes with assistant message and tool results |
167
+ | `message_start` | Any message begins (user, assistant, toolResult) |
168
+ | `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
169
+ | `message_end` | Message completes |
170
+ | `tool_execution_start` | Tool begins |
171
+ | `tool_execution_update` | Tool streams progress |
172
+ | `tool_execution_end` | Tool completes |
173
+
174
+ `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.
175
+
176
+ ## Agent Options
177
+
178
+ ```typescript
179
+ const agent = new Agent({
180
+ // Initial state
181
+ initialState: {
182
+ systemPrompt: string,
183
+ model: Model<any>,
184
+ thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max",
185
+ tools: AgentTool<any>[],
186
+ messages: AgentMessage[],
187
+ },
188
+
189
+ // Convert AgentMessage[] to LLM Message[] (required for custom message types)
190
+ convertToLlm: (messages) => messages.filter(...),
191
+
192
+ // Transform context before convertToLlm (for pruning, compaction)
193
+ transformContext: async (messages, signal) => pruneOldMessages(messages),
194
+
195
+ // Steering mode: "one-at-a-time" (default) or "all"
196
+ steeringMode: "one-at-a-time",
197
+
198
+ // Follow-up mode: "one-at-a-time" (default) or "all"
199
+ followUpMode: "one-at-a-time",
200
+
201
+ // Required stream function
202
+ streamFn: models.streamSimple.bind(models),
203
+
204
+ // Session ID for provider caching
205
+ sessionId: "session-123",
206
+
207
+ // Dynamic API key resolution (for expiring OAuth tokens)
208
+ getApiKey: async (provider) => refreshToken(),
209
+
210
+ // Tool execution mode: "parallel" (default) or "sequential"
211
+ toolExecution: "parallel",
212
+
213
+ // Preflight each tool call after args are validated. Can block execution.
214
+ beforeToolCall: async ({ toolCall, args, context }) => {
215
+ if (toolCall.name === "bash") {
216
+ return { block: true, reason: "bash is disabled" };
217
+ }
218
+ },
219
+
220
+ // Postprocess each tool result before final tool events are emitted.
221
+ afterToolCall: async ({ toolCall, result, isError, context }) => {
222
+ if (toolCall.name === "notify_done" && !isError) {
223
+ return { terminate: true };
224
+ }
225
+ if (!isError) {
226
+ return { details: { ...result.details, audited: true } };
227
+ }
228
+ },
229
+
230
+ // Custom thinking budgets for token-based providers
231
+ thinkingBudgets: {
232
+ minimal: 128,
233
+ low: 512,
234
+ medium: 1024,
235
+ high: 2048,
236
+ },
237
+ });
238
+ ```
239
+
240
+ ## Agent State
241
+
242
+ ```typescript
243
+ interface AgentState {
244
+ systemPrompt: string;
245
+ model: Model<any>;
246
+ thinkingLevel: ThinkingLevel;
247
+ tools: AgentTool<any>[];
248
+ messages: AgentMessage[];
249
+ readonly isStreaming: boolean;
250
+ readonly streamingMessage?: AgentMessage;
251
+ readonly pendingToolCalls: ReadonlySet<string>;
252
+ readonly errorMessage?: string;
253
+ }
254
+ ```
255
+
256
+ Access state via `agent.state`.
257
+
258
+ 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.
259
+
260
+ During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
261
+
262
+ `agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
263
+
264
+ ## Methods
265
+
266
+ ### Prompting
267
+
268
+ ```typescript
269
+ // Text prompt
270
+ await agent.prompt("Hello");
271
+
272
+ // With images
273
+ await agent.prompt("What's in this image?", [
274
+ { type: "image", data: base64Data, mimeType: "image/jpeg" }
275
+ ]);
276
+
277
+ // AgentMessage directly
278
+ await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
279
+
280
+ // Continue from current context (last message must be user or toolResult)
281
+ await agent.continue();
282
+ ```
283
+
284
+ ### State Management
285
+
286
+ ```typescript
287
+ agent.state.systemPrompt = "New prompt";
288
+ agent.state.model = getModel("openai", "gpt-4o");
289
+ agent.state.thinkingLevel = "medium";
290
+ agent.state.tools = [myTool];
291
+ agent.toolExecution = "sequential";
292
+ agent.beforeToolCall = async ({ toolCall }) => undefined;
293
+ agent.afterToolCall = async ({ toolCall, result }) => undefined;
294
+ agent.state.messages = newMessages; // top-level array is copied
295
+ agent.state.messages.push(message);
296
+ agent.reset();
297
+ ```
298
+
299
+ ### Session and Thinking Budgets
300
+
301
+ ```typescript
302
+ agent.sessionId = "session-123";
303
+
304
+ agent.thinkingBudgets = {
305
+ minimal: 128,
306
+ low: 512,
307
+ medium: 1024,
308
+ high: 2048,
309
+ };
310
+ ```
311
+
312
+ ### Control
313
+
314
+ ```typescript
315
+ agent.abort(); // Cancel current operation
316
+ await agent.waitForIdle(); // Wait for completion
317
+ ```
318
+
319
+ ### Events
320
+
321
+ ```typescript
322
+ const unsubscribe = agent.subscribe(async (event, signal) => {
323
+ if (event.type === "agent_end") {
324
+ // Final barrier work for the run
325
+ await flushSessionState(signal);
326
+ }
327
+ });
328
+ unsubscribe();
329
+ ```
330
+
331
+ ## Steering and Follow-up
332
+
333
+ Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
334
+
335
+ ```typescript
336
+ agent.steeringMode = "one-at-a-time";
337
+ agent.followUpMode = "one-at-a-time";
338
+
339
+ // While agent is running tools
340
+ agent.steer({
341
+ role: "user",
342
+ content: "Stop! Do this instead.",
343
+ timestamp: Date.now(),
344
+ });
345
+
346
+ // After the agent finishes its current work
347
+ agent.followUp({
348
+ role: "user",
349
+ content: "Also summarize the result.",
350
+ timestamp: Date.now(),
351
+ });
352
+
353
+ const steeringMode = agent.steeringMode;
354
+ const followUpMode = agent.followUpMode;
355
+
356
+ agent.clearSteeringQueue();
357
+ agent.clearFollowUpQueue();
358
+ agent.clearAllQueues();
359
+ ```
360
+
361
+ Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
362
+
363
+ When steering messages are detected after a turn completes:
364
+ 1. All tool calls from the current assistant message have already finished
365
+ 2. Steering messages are injected
366
+ 3. The LLM responds on the next turn
367
+
368
+ 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.
369
+
370
+ ## Custom Message Types
371
+
372
+ Extend `AgentMessage` via declaration merging:
373
+
374
+ ```typescript
375
+ declare module "@earendil-works/pi-agent-core" {
376
+ interface CustomAgentMessages {
377
+ notification: { role: "notification"; text: string; timestamp: number };
378
+ }
379
+ }
380
+
381
+ // Now valid
382
+ const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
383
+ ```
384
+
385
+ Handle custom types in `convertToLlm`:
386
+
387
+ ```typescript
388
+ const agent = new Agent({
389
+ streamFn: models.streamSimple.bind(models),
390
+ convertToLlm: (messages) => messages.flatMap(m => {
391
+ if (m.role === "notification") return []; // Filter out
392
+ return [m];
393
+ }),
394
+ });
395
+ ```
396
+
397
+ ## Tools
398
+
399
+ Define tools using `AgentTool`:
400
+
401
+ ```typescript
402
+ import { Type } from "typebox";
403
+
404
+ const readFileTool: AgentTool = {
405
+ name: "read_file",
406
+ label: "Read File", // For UI display
407
+ description: "Read a file's contents",
408
+ parameters: Type.Object({
409
+ path: Type.String({ description: "File path" }),
410
+ }),
411
+ // Override execution mode for this tool (optional).
412
+ // "sequential" makes this tool an exclusive barrier in parallel batches:
413
+ // it runs alone, but parallel tools before or after it still run concurrently.
414
+ // "parallel" allows concurrent execution with other tool calls.
415
+ // If omitted, the global toolExecution config applies.
416
+ executionMode: "sequential",
417
+ execute: async (toolCallId, params, signal, onUpdate) => {
418
+ const content = await fs.readFile(params.path, "utf-8");
419
+
420
+ // Optional: stream progress
421
+ onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
422
+
423
+ // Optional: add `terminate: true` here to skip the automatic follow-up LLM call
424
+ // when every finalized tool result in the batch does the same.
425
+ return {
426
+ content: [{ type: "text", text: content }],
427
+ details: { path: params.path, size: content.length },
428
+ };
429
+ },
430
+ };
431
+
432
+ agent.state.tools = [readFileTool];
433
+ ```
434
+
435
+ ### Error Handling
436
+
437
+ **Throw an error** when a tool fails. Do not return error messages as content.
438
+
439
+ ```typescript
440
+ execute: async (toolCallId, params, signal, onUpdate) => {
441
+ if (!fs.existsSync(params.path)) {
442
+ throw new Error(`File not found: ${params.path}`);
443
+ }
444
+ // Return content only on success
445
+ return { content: [{ type: "text", text: "..." }] };
446
+ }
447
+ ```
448
+
449
+ Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
450
+
451
+ Return `terminate: true` from `execute()` 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.
452
+
453
+ ## Proxy Usage
454
+
455
+ For browser apps that proxy through a backend:
456
+
457
+ ```typescript
458
+ import { Agent, streamProxy } from "@earendil-works/pi-agent-core";
459
+
460
+ const agent = new Agent({
461
+ streamFn: (model, context, options) =>
462
+ streamProxy(model, context, {
463
+ ...options,
464
+ authToken: "...",
465
+ proxyUrl: "https://your-server.com",
466
+ }),
467
+ });
468
+ ```
469
+
470
+ ## Low-Level API
471
+
472
+ For direct control without the Agent class:
473
+
474
+ ```typescript
475
+ import { agentLoop, agentLoopContinue } from "@earendil-works/pi-agent-core";
476
+
477
+ const context: AgentContext = {
478
+ systemPrompt: "You are helpful.",
479
+ messages: [],
480
+ tools: [],
481
+ };
482
+
483
+ const config: AgentLoopConfig = {
484
+ model: getModel("openai", "gpt-4o"),
485
+ convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
486
+ toolExecution: "parallel", // overridden by per-tool executionMode if set
487
+ beforeToolCall: async ({ toolCall, args, context }) => undefined,
488
+ afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
489
+ };
490
+
491
+ const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
492
+
493
+ const streamFn = models.streamSimple.bind(models);
494
+ for await (const event of agentLoop([userMessage], context, config, undefined, streamFn)) {
495
+ console.log(event.type);
496
+ }
497
+
498
+ // Continue from existing context
499
+ for await (const event of agentLoopContinue(context, config, undefined, streamFn)) {
500
+ console.log(event.type);
501
+ }
502
+ ```
503
+
504
+ 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()`.
505
+
506
+ ## License
507
+
508
+ MIT
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Agent loop that works with AgentMessage throughout.
3
+ * Transforms to Message[] only at the LLM call boundary.
4
+ */
5
+ import { EventStream } from "@earendil-works/pi-ai";
6
+ import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, AgentTool, AgentToolCall, StreamFn } from "./types.ts";
7
+ export type AgentEventSink = (event: AgentEvent) => Promise<void> | void;
8
+ /**
9
+ * Start an agent loop with a new prompt message.
10
+ * The prompt is added to the context and events are emitted for it.
11
+ */
12
+ export declare function agentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, signal: AbortSignal | undefined, streamFn: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
13
+ /**
14
+ * Continue an agent loop from the current context without adding a new message.
15
+ * Used for retries - context already has user message or tool results.
16
+ *
17
+ * **Important:** The last message in context must convert to a `user` or `toolResult` message
18
+ * via `convertToLlm`. If it doesn't, the LLM provider will reject the request.
19
+ * This cannot be validated here since `convertToLlm` is only called once per turn.
20
+ */
21
+ export declare function agentLoopContinue(context: AgentContext, config: AgentLoopConfig, signal: AbortSignal | undefined, streamFn: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
22
+ export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal: AbortSignal | undefined, streamFn: StreamFn): Promise<AgentMessage[]>;
23
+ export declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal: AbortSignal | undefined, streamFn: StreamFn): Promise<AgentMessage[]>;
24
+ export interface PreparedAgentToolCall {
25
+ toolCall: AgentToolCall;
26
+ tool: AgentTool;
27
+ args: unknown;
28
+ }
29
+ export declare function prepareAgentToolCallArguments(tool: AgentTool, toolCall: AgentToolCall): AgentToolCall;
30
+ export declare function prepareAgentToolCall(tool: AgentTool, toolCall: AgentToolCall): PreparedAgentToolCall;
31
+ //# sourceMappingURL=agent-loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-loop.d.ts","sourceRoot":"","sources":["../src/agent-loop.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAIN,WAAW,EAGX,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EAEf,YAAY,EACZ,SAAS,EACT,aAAa,EAEb,QAAQ,EACR,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,cAAc,GAAG,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAEzE;;;GAGG;AACH,wBAAgB,SAAS,CACxB,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAiBzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAChC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,WAAW,CAAC,UAAU,EAAE,YAAY,EAAE,CAAC,CAwBzC;AAED,wBAAsB,YAAY,CACjC,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,YAAY,EAAE,CAAC,CAgBzB;AAED,wBAAsB,oBAAoB,CACzC,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,eAAe,EACvB,IAAI,EAAE,cAAc,EACpB,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,QAAQ,GAChB,OAAO,CAAC,YAAY,EAAE,CAAC,CAiBzB;AAowBD,MAAM,WAAW,qBAAqB;IACrC,QAAQ,EAAE,aAAa,CAAC;IACxB,IAAI,EAAE,SAAS,CAAC;IAChB,IAAI,EAAE,OAAO,CAAC;CACd;AAED,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,GAAG,aAAa,CAYrG;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,GAAG,qBAAqB,CAOpG"}