@ponythewhite/base-context-agent 1.0.0
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/LICENSE +23 -0
- package/NOTICE +22 -0
- package/README.md +551 -0
- package/dist/LICENSE +23 -0
- package/dist/NOTICE +22 -0
- package/dist/agent-loop.d.ts +24 -0
- package/dist/agent-loop.d.ts.map +1 -0
- package/dist/agent-loop.js +897 -0
- package/dist/agent-loop.js.map +1 -0
- package/dist/agent.d.ts +144 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +569 -0
- package/dist/agent.js.map +1 -0
- package/dist/build-info.json +14 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/invocation-output.d.ts +30 -0
- package/dist/invocation-output.d.ts.map +1 -0
- package/dist/invocation-output.js +125 -0
- package/dist/invocation-output.js.map +1 -0
- package/dist/proxy.d.ts +59 -0
- package/dist/proxy.d.ts.map +1 -0
- package/dist/proxy.js +268 -0
- package/dist/proxy.js.map +1 -0
- package/dist/types.d.ts +512 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mario Zechner
|
|
4
|
+
Copyright (c) 2026 Prime Intellect
|
|
5
|
+
Copyright (c) 2026 BaseModelAI and Jacek Dąbrowski
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Synerise base-context is a source-owned fork of Prime Agent v0.9.3.
|
|
2
|
+
Repository: https://github.com/BaseModelAI/base-context
|
|
3
|
+
Fork ancestor: 915c78f42c248b08238dd27fcd4bcab32c60beab
|
|
4
|
+
|
|
5
|
+
Upstream: https://github.com/PrimeIntellect-ai/prime-agent
|
|
6
|
+
Copyright (c) 2025 Mario Zechner
|
|
7
|
+
Copyright (c) 2026 Prime Intellect
|
|
8
|
+
Fork modifications: Copyright (c) 2026 BaseModelAI and Jacek Dąbrowski
|
|
9
|
+
|
|
10
|
+
Distributed under the MIT License. See LICENSE.
|
|
11
|
+
Provider names and model identifiers identify their respective providers;
|
|
12
|
+
this fork is not an official Prime Intellect release.
|
|
13
|
+
|
|
14
|
+
Prime Agent builds on Mario Zechner's Pi project:
|
|
15
|
+
https://github.com/badlogic/pi-mono
|
|
16
|
+
|
|
17
|
+
We also credit Prime Intellect's PrimeRL authors for their open-source
|
|
18
|
+
reinforcement-learning work: https://github.com/PrimeIntellect-ai/prime-rl
|
|
19
|
+
This acknowledgement does not imply that PrimeRL is a runtime dependency
|
|
20
|
+
or that upstream authors endorse this fork.
|
|
21
|
+
|
|
22
|
+
Third-party dependencies retain their own licenses and notices.
|
package/README.md
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
# Synerise base-context Agent SDK
|
|
2
|
+
|
|
3
|
+
Stateful agent runtime with native context and recovery ownership.
|
|
4
|
+
|
|
5
|
+
Part of **[Synerise base-context](https://github.com/BaseModelAI/base-context)**. Forked from Prime Intellect's [Prime Agent](https://github.com/PrimeIntellect-ai/prime-agent), built on Mario Zechner's Pi. MIT; see [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
6
|
+
|
|
7
|
+
## Workspace Package
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @ponythewhite/base-context-agent
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { Agent } from "@ponythewhite/base-context-agent";
|
|
17
|
+
import { getModel } from "@ponythewhite/base-context-ai";
|
|
18
|
+
|
|
19
|
+
const agent = new Agent({
|
|
20
|
+
initialState: {
|
|
21
|
+
systemPrompt: "You are a helpful assistant.",
|
|
22
|
+
model: getModel("anthropic", "claude-sonnet-4-20250514"),
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
agent.subscribe((event) => {
|
|
27
|
+
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
|
|
28
|
+
// Stream just the new text chunk
|
|
29
|
+
process.stdout.write(event.assistantMessageEvent.delta);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
await agent.prompt("Hello!");
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Core Concepts
|
|
37
|
+
|
|
38
|
+
### AgentMessage vs LLM Message
|
|
39
|
+
|
|
40
|
+
The agent works with `AgentMessage`, a flexible type that can include:
|
|
41
|
+
- Standard LLM messages (`user`, `assistant`, `toolResult`)
|
|
42
|
+
- Custom app-specific message types via declaration merging
|
|
43
|
+
|
|
44
|
+
LLMs only understand `user`, `assistant`, and `toolResult`. The `convertToLlm` function bridges this gap by filtering and transforming messages before each LLM call.
|
|
45
|
+
|
|
46
|
+
### Message Flow
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
AgentMessage[] → transformContext() → AgentMessage[] → convertToLlm() → Message[] → LLM
|
|
50
|
+
(optional) (required)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
1. **transformContext**: Prune old messages, inject external context
|
|
54
|
+
2. **convertToLlm**: Filter out UI-only messages, convert custom types to LLM format
|
|
55
|
+
|
|
56
|
+
## Event Flow
|
|
57
|
+
|
|
58
|
+
The agent emits events for UI updates. Understanding the event sequence helps build responsive interfaces.
|
|
59
|
+
|
|
60
|
+
### prompt() Event Sequence
|
|
61
|
+
|
|
62
|
+
When you call `prompt("Hello")`:
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
prompt("Hello")
|
|
66
|
+
├─ agent_start
|
|
67
|
+
├─ turn_start
|
|
68
|
+
├─ message_start { message: userMessage } // Your prompt
|
|
69
|
+
├─ message_end { message: userMessage }
|
|
70
|
+
├─ message_start { message: assistantMessage } // LLM starts responding
|
|
71
|
+
├─ message_update { message: partial... } // Streaming chunks
|
|
72
|
+
├─ message_update { message: partial... }
|
|
73
|
+
├─ message_end { message: assistantMessage } // Complete response
|
|
74
|
+
├─ turn_end { message, toolResults: [] }
|
|
75
|
+
└─ agent_end { messages: [...] }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### With Tool Calls
|
|
79
|
+
|
|
80
|
+
If the assistant calls tools, the loop continues:
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
prompt("Read config.json")
|
|
84
|
+
├─ agent_start
|
|
85
|
+
├─ turn_start
|
|
86
|
+
├─ message_start/end { userMessage }
|
|
87
|
+
├─ message_start { assistantMessage with toolCall }
|
|
88
|
+
├─ message_update...
|
|
89
|
+
├─ message_end { assistantMessage }
|
|
90
|
+
├─ tool_execution_start { toolCallId, toolName, args }
|
|
91
|
+
├─ tool_execution_update { partialResult } // If tool streams
|
|
92
|
+
├─ tool_execution_end { toolCallId, result }
|
|
93
|
+
├─ message_start/end { toolResultMessage }
|
|
94
|
+
├─ turn_end { message, toolResults: [toolResult] }
|
|
95
|
+
│
|
|
96
|
+
├─ turn_start // Next turn
|
|
97
|
+
├─ message_start { assistantMessage } // LLM responds to tool result
|
|
98
|
+
├─ message_update...
|
|
99
|
+
├─ message_end
|
|
100
|
+
├─ turn_end
|
|
101
|
+
└─ agent_end
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Tool execution mode is configurable:
|
|
105
|
+
|
|
106
|
+
- `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
|
|
107
|
+
- `sequential`: execute tool calls one by one, matching the historical behavior
|
|
108
|
+
|
|
109
|
+
In parallel mode, tool completion events follow tool completion order, but persisted toolResult messages still follow assistant source order.
|
|
110
|
+
|
|
111
|
+
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.
|
|
112
|
+
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
Low-level loop callers can set `shouldStopAfterTurn` to stop gracefully after the current turn completes:
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
const stream = agentLoop(prompts, context, {
|
|
121
|
+
model,
|
|
122
|
+
convertToLlm,
|
|
123
|
+
shouldStopAfterTurn: async ({ message, toolResults, context, newMessages }) => {
|
|
124
|
+
return shouldCompactBeforeNextTurn(context.messages);
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`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.
|
|
130
|
+
|
|
131
|
+
### Native checkpoint control
|
|
132
|
+
|
|
133
|
+
At the same completed-turn boundary, `Agent` and `AgentLoopConfig` can use
|
|
134
|
+
`getTurnOutcome(context, signal)` instead of the boolean stop hook. Its
|
|
135
|
+
`GetTurnOutcomeContext` includes `hasMoreToolCalls`, the loop's finalized tool-batch
|
|
136
|
+
decision. An all-terminate batch sets this to `false`; the last message's role is
|
|
137
|
+
not a substitute.
|
|
138
|
+
|
|
139
|
+
The callback returns `AgentTurnOutcome`, synchronously or asynchronously:
|
|
140
|
+
`proceed`, `finish`, `checkpoint_then_continue` or `cancelled`. Only `proceed`
|
|
141
|
+
continues the ordinary queue-polling policy. The other results end this invocation.
|
|
142
|
+
When the typed callback is present, the loop does not also call
|
|
143
|
+
`shouldStopAfterTurn`. The boolean API remains available otherwise.
|
|
144
|
+
|
|
145
|
+
The native session consumes checkpoint intent through its existing compaction
|
|
146
|
+
and input-dispatch owners. `checkpoint_then_continue` is not a checkpoint ACK.
|
|
147
|
+
Normal success resumption follows the canonical write and owned setup/release.
|
|
148
|
+
Recoverable skip/failure retains the existing resume policy; abort does not resume.
|
|
149
|
+
A known ACK plus later setup or release failure retains the checkpoint and blocks automatic
|
|
150
|
+
resumption. Accepted queued input takes priority and can consume the interrupted
|
|
151
|
+
boundary without leaving an extra continuation. This is transient control, not a
|
|
152
|
+
new persisted restart protocol. See the [compaction guide](../coding-agent/docs/compaction.md).
|
|
153
|
+
|
|
154
|
+
### Native continuation control
|
|
155
|
+
|
|
156
|
+
At a natural stop, `Agent` and `AgentLoopConfig` can use the optional
|
|
157
|
+
`getContinuationOutcome(context, signal)` callback. It returns a promise of the
|
|
158
|
+
exported `AgentContinuationOutcome` type. The native session binds this callback. Only `continue` requests another model turn. `wait_for_owned_work`,
|
|
159
|
+
`finish` and `cancelled` end the current low-level invocation. A message body or
|
|
160
|
+
`turn_end` event is not a control instruction.
|
|
161
|
+
|
|
162
|
+
`wait_for_owned_work` does not wait for the invocation's own idle barrier. The
|
|
163
|
+
existing goal wakeup owner resumes work after descendant settlement and terminal
|
|
164
|
+
notice delivery. Goal and autonomous-work priority is unchanged. This is not a
|
|
165
|
+
new scheduler, cancellation policy or checkpoint transition.
|
|
166
|
+
|
|
167
|
+
`getContinuationOutcome` takes precedence over the existing `getContinuationMessages`
|
|
168
|
+
callback; the loop does not call both. Without a typed owner, the existing array
|
|
169
|
+
callback keeps its behavior. Explicit stop hooks, steering, follow-ups and finalized
|
|
170
|
+
tool results keep their existing precedence. The native owner retains the original
|
|
171
|
+
session and input-pump ownership across waits; late control cannot start a turn on
|
|
172
|
+
a replacement session.
|
|
173
|
+
|
|
174
|
+
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.
|
|
175
|
+
|
|
176
|
+
### continue() Event Sequence
|
|
177
|
+
|
|
178
|
+
`continue()` resumes from existing context without adding a new message. Use it for retries after errors.
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
// After an error, retry from current state
|
|
182
|
+
await agent.continue();
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
The last message in context must be `user` or `toolResult` (not `assistant`).
|
|
186
|
+
|
|
187
|
+
### Event Types
|
|
188
|
+
|
|
189
|
+
| Event | Description |
|
|
190
|
+
|-------|-------------|
|
|
191
|
+
| `agent_start` | Agent begins processing |
|
|
192
|
+
| `agent_end` | Final event for the run. Awaited subscribers for this event still count toward settlement |
|
|
193
|
+
| `turn_start` | New turn begins (one LLM call + tool executions) |
|
|
194
|
+
| `turn_end` | Turn completes with assistant message and tool results |
|
|
195
|
+
| `message_start` | Any message begins (user, assistant, toolResult) |
|
|
196
|
+
| `message_update` | **Assistant only.** Includes `assistantMessageEvent` with delta |
|
|
197
|
+
| `message_end` | Message completes |
|
|
198
|
+
| `tool_execution_start` | Tool begins |
|
|
199
|
+
| `tool_execution_update` | Tool streams progress |
|
|
200
|
+
| `tool_execution_end` | Tool completes |
|
|
201
|
+
|
|
202
|
+
`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.
|
|
203
|
+
|
|
204
|
+
## Agent Options
|
|
205
|
+
|
|
206
|
+
```typescript
|
|
207
|
+
const agent = new Agent({
|
|
208
|
+
// Initial state
|
|
209
|
+
initialState: {
|
|
210
|
+
systemPrompt: string,
|
|
211
|
+
model: Model<any>,
|
|
212
|
+
thinkingLevel: "off" | "minimal" | "low" | "medium" | "high" | "xhigh",
|
|
213
|
+
tools: AgentTool<any>[],
|
|
214
|
+
messages: AgentMessage[],
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
// Convert AgentMessage[] to LLM Message[] (required for custom message types)
|
|
218
|
+
convertToLlm: (messages) => messages.filter(...),
|
|
219
|
+
|
|
220
|
+
// Transform context before convertToLlm (for pruning, compaction)
|
|
221
|
+
transformContext: async (messages, signal) => pruneOldMessages(messages),
|
|
222
|
+
|
|
223
|
+
// Steering mode: "one-at-a-time" (default) or "all"
|
|
224
|
+
steeringMode: "one-at-a-time",
|
|
225
|
+
|
|
226
|
+
// Follow-up mode: "one-at-a-time" (default) or "all"
|
|
227
|
+
followUpMode: "one-at-a-time",
|
|
228
|
+
|
|
229
|
+
// Custom stream function (for proxy backends)
|
|
230
|
+
streamFn: streamProxy,
|
|
231
|
+
|
|
232
|
+
// Session ID for provider caching
|
|
233
|
+
sessionId: "session-123",
|
|
234
|
+
|
|
235
|
+
// Dynamic API key resolution (for expiring OAuth tokens)
|
|
236
|
+
getApiKey: async (provider) => refreshToken(),
|
|
237
|
+
|
|
238
|
+
// Tool execution mode: "parallel" (default) or "sequential"
|
|
239
|
+
toolExecution: "parallel",
|
|
240
|
+
|
|
241
|
+
// Preflight each tool call after args are validated. Can block execution.
|
|
242
|
+
beforeToolCall: async ({ toolCall, args, context }) => {
|
|
243
|
+
if (toolCall.name === "bash") {
|
|
244
|
+
return { block: true, reason: "bash is disabled" };
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
|
|
248
|
+
// Postprocess each tool result before final tool events are emitted.
|
|
249
|
+
afterToolCall: async ({ toolCall, result, isError, context }) => {
|
|
250
|
+
if (toolCall.name === "notify_done" && !isError) {
|
|
251
|
+
return { terminate: true };
|
|
252
|
+
}
|
|
253
|
+
if (!isError) {
|
|
254
|
+
return { details: { ...result.details, audited: true } };
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
|
|
258
|
+
// Custom thinking budgets for token-based providers
|
|
259
|
+
thinkingBudgets: {
|
|
260
|
+
minimal: 128,
|
|
261
|
+
low: 512,
|
|
262
|
+
medium: 1024,
|
|
263
|
+
high: 2048,
|
|
264
|
+
},
|
|
265
|
+
});
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Agent State
|
|
269
|
+
|
|
270
|
+
```typescript
|
|
271
|
+
interface AgentState {
|
|
272
|
+
systemPrompt: string;
|
|
273
|
+
model: Model<any>;
|
|
274
|
+
thinkingLevel: ThinkingLevel;
|
|
275
|
+
tools: AgentTool<any>[];
|
|
276
|
+
messages: AgentMessage[];
|
|
277
|
+
readonly isStreaming: boolean;
|
|
278
|
+
readonly streamingMessage?: AgentMessage;
|
|
279
|
+
readonly pendingToolCalls: ReadonlySet<string>;
|
|
280
|
+
readonly errorMessage?: string;
|
|
281
|
+
}
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Access state via `agent.state`.
|
|
285
|
+
|
|
286
|
+
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.
|
|
287
|
+
|
|
288
|
+
During streaming, `agent.state.streamingMessage` contains the current partial assistant message.
|
|
289
|
+
|
|
290
|
+
`agent.state.isStreaming` remains `true` until the run fully settles, including awaited `agent_end` subscribers.
|
|
291
|
+
|
|
292
|
+
## Methods
|
|
293
|
+
|
|
294
|
+
### Prompting
|
|
295
|
+
|
|
296
|
+
```typescript
|
|
297
|
+
// Text prompt
|
|
298
|
+
await agent.prompt("Hello");
|
|
299
|
+
|
|
300
|
+
// With images
|
|
301
|
+
await agent.prompt("What's in this image?", [
|
|
302
|
+
{ type: "image", data: base64Data, mimeType: "image/jpeg" }
|
|
303
|
+
]);
|
|
304
|
+
|
|
305
|
+
// AgentMessage directly
|
|
306
|
+
await agent.prompt({ role: "user", content: "Hello", timestamp: Date.now() });
|
|
307
|
+
|
|
308
|
+
// Continue from current context (last message must be user or toolResult)
|
|
309
|
+
await agent.continue();
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
### State Management
|
|
313
|
+
|
|
314
|
+
```typescript
|
|
315
|
+
agent.state.systemPrompt = "New prompt";
|
|
316
|
+
agent.state.model = getModel("openai", "gpt-4o");
|
|
317
|
+
agent.state.thinkingLevel = "medium";
|
|
318
|
+
agent.state.tools = [myTool];
|
|
319
|
+
agent.toolExecution = "sequential";
|
|
320
|
+
agent.beforeToolCall = async ({ toolCall }) => undefined;
|
|
321
|
+
agent.afterToolCall = async ({ toolCall, result }) => undefined;
|
|
322
|
+
agent.state.messages = newMessages; // top-level array is copied
|
|
323
|
+
agent.state.messages.push(message);
|
|
324
|
+
agent.reset();
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
### Session and Thinking Budgets
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
agent.sessionId = "session-123";
|
|
331
|
+
|
|
332
|
+
agent.thinkingBudgets = {
|
|
333
|
+
minimal: 128,
|
|
334
|
+
low: 512,
|
|
335
|
+
medium: 1024,
|
|
336
|
+
high: 2048,
|
|
337
|
+
};
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### Native bounded outputs
|
|
341
|
+
|
|
342
|
+
A native owner can bind a copied output policy with `agent.bindOutputOwner(...)`.
|
|
343
|
+
The coding-agent SDK enables this for owned persistent sessions. Generic Agents keep
|
|
344
|
+
complete, unbounded invocation arrays unless an owner supplies a policy.
|
|
345
|
+
|
|
346
|
+
Successful `newMessages`, callback values and `agent_end.messages` remain complete.
|
|
347
|
+
Native values are detached after the actual `message_end` mutation/persistence job.
|
|
348
|
+
Runtime subjects and tool/action identities stay unchanged. Updates accepted before
|
|
349
|
+
terminal settlement are joined once; later canonical updates do not retroactively change
|
|
350
|
+
returned snapshots.
|
|
351
|
+
|
|
352
|
+
An output refusal emits `agent_end` with `refusal` and no `messages`. Its `kind` is
|
|
353
|
+
`output_limit`; `limit` is `messages`, `source_bytes` or `value_encoding`. The descriptor
|
|
354
|
+
also carries `maxMessages` and `maxSourceBytes`. `AgentOutputLimitError` rejects the raw
|
|
355
|
+
loop, stream `result()` and Agent invocation. It is not a provider retry or a successful
|
|
356
|
+
empty result. Already accepted parallel tools/publications settle before refusal.
|
|
357
|
+
|
|
358
|
+
### Control
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
agent.abort(); // Cancel current operation
|
|
362
|
+
await agent.waitForIdle(); // Wait for completion
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### Events
|
|
366
|
+
|
|
367
|
+
```typescript
|
|
368
|
+
const unsubscribe = agent.subscribe(async (event, signal) => {
|
|
369
|
+
if (event.type === "agent_end") {
|
|
370
|
+
// Final barrier work for the run
|
|
371
|
+
await flushSessionState(signal);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
unsubscribe();
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
## Steering and Follow-up
|
|
378
|
+
|
|
379
|
+
Steering messages let you interrupt the agent while tools are running. Follow-up messages let you queue work after the agent would otherwise stop.
|
|
380
|
+
|
|
381
|
+
```typescript
|
|
382
|
+
agent.steeringMode = "one-at-a-time";
|
|
383
|
+
agent.followUpMode = "one-at-a-time";
|
|
384
|
+
|
|
385
|
+
// While agent is running tools
|
|
386
|
+
agent.steer({
|
|
387
|
+
role: "user",
|
|
388
|
+
content: "Stop! Do this instead.",
|
|
389
|
+
timestamp: Date.now(),
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// After the agent finishes its current work
|
|
393
|
+
agent.followUp({
|
|
394
|
+
role: "user",
|
|
395
|
+
content: "Also summarize the result.",
|
|
396
|
+
timestamp: Date.now(),
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const steeringMode = agent.steeringMode;
|
|
400
|
+
const followUpMode = agent.followUpMode;
|
|
401
|
+
|
|
402
|
+
agent.clearSteeringQueue();
|
|
403
|
+
agent.clearFollowUpQueue();
|
|
404
|
+
agent.clearAllQueues();
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
Use clearSteeringQueue, clearFollowUpQueue, or clearAllQueues to drop queued messages.
|
|
408
|
+
|
|
409
|
+
When steering messages are detected after a turn completes:
|
|
410
|
+
1. All tool calls from the current assistant message have already finished
|
|
411
|
+
2. Steering messages are injected
|
|
412
|
+
3. The LLM responds on the next turn
|
|
413
|
+
|
|
414
|
+
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.
|
|
415
|
+
|
|
416
|
+
## Custom Message Types
|
|
417
|
+
|
|
418
|
+
Extend `AgentMessage` via declaration merging:
|
|
419
|
+
|
|
420
|
+
```typescript
|
|
421
|
+
declare module "@ponythewhite/base-context-agent" {
|
|
422
|
+
interface CustomAgentMessages {
|
|
423
|
+
notification: { role: "notification"; text: string; timestamp: number };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Now valid
|
|
428
|
+
const msg: AgentMessage = { role: "notification", text: "Info", timestamp: Date.now() };
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
Handle custom types in `convertToLlm`:
|
|
432
|
+
|
|
433
|
+
```typescript
|
|
434
|
+
const agent = new Agent({
|
|
435
|
+
convertToLlm: (messages) => messages.flatMap(m => {
|
|
436
|
+
if (m.role === "notification") return []; // Filter out
|
|
437
|
+
return [m];
|
|
438
|
+
}),
|
|
439
|
+
});
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
## Tools
|
|
443
|
+
|
|
444
|
+
Define tools using `AgentTool`:
|
|
445
|
+
|
|
446
|
+
```typescript
|
|
447
|
+
import { Type } from "typebox";
|
|
448
|
+
|
|
449
|
+
const readFileTool: AgentTool = {
|
|
450
|
+
name: "read_file",
|
|
451
|
+
label: "Read File", // For UI display
|
|
452
|
+
description: "Read a file's contents",
|
|
453
|
+
parameters: Type.Object({
|
|
454
|
+
path: Type.String({ description: "File path" }),
|
|
455
|
+
}),
|
|
456
|
+
// Override execution mode for this tool (optional).
|
|
457
|
+
// "sequential" forces the entire batch to run one at a time.
|
|
458
|
+
// "parallel" allows concurrent execution with other tool calls.
|
|
459
|
+
// If omitted, the global toolExecution config applies.
|
|
460
|
+
executionMode: "sequential",
|
|
461
|
+
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
462
|
+
const content = await fs.readFile(params.path, "utf-8");
|
|
463
|
+
|
|
464
|
+
// Optional: stream progress
|
|
465
|
+
onUpdate?.({ content: [{ type: "text", text: "Reading..." }], details: {} });
|
|
466
|
+
|
|
467
|
+
// Optional: add `terminate: true` here to skip the automatic follow-up LLM call
|
|
468
|
+
// when every finalized tool result in the batch does the same.
|
|
469
|
+
return {
|
|
470
|
+
content: [{ type: "text", text: content }],
|
|
471
|
+
details: { path: params.path, size: content.length },
|
|
472
|
+
};
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
agent.state.tools = [readFileTool];
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
### Error Handling
|
|
480
|
+
|
|
481
|
+
**Throw an error** when a tool fails. Do not return error messages as content.
|
|
482
|
+
|
|
483
|
+
```typescript
|
|
484
|
+
execute: async (toolCallId, params, signal, onUpdate) => {
|
|
485
|
+
if (!fs.existsSync(params.path)) {
|
|
486
|
+
throw new Error(`File not found: ${params.path}`);
|
|
487
|
+
}
|
|
488
|
+
// Return content only on success
|
|
489
|
+
return { content: [{ type: "text", text: "..." }] };
|
|
490
|
+
}
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
Thrown errors are caught by the agent and reported to the LLM as tool errors with `isError: true`.
|
|
494
|
+
|
|
495
|
+
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.
|
|
496
|
+
|
|
497
|
+
## Proxy Usage
|
|
498
|
+
|
|
499
|
+
For browser apps that proxy through a backend:
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
import { Agent, streamProxy } from "@ponythewhite/base-context-agent";
|
|
503
|
+
|
|
504
|
+
const agent = new Agent({
|
|
505
|
+
streamFn: (model, context, options) =>
|
|
506
|
+
streamProxy(model, context, {
|
|
507
|
+
...options,
|
|
508
|
+
authToken: "...",
|
|
509
|
+
proxyUrl: "https://your-server.com",
|
|
510
|
+
}),
|
|
511
|
+
});
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
## Low-Level API
|
|
515
|
+
|
|
516
|
+
For direct control without the Agent class:
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
import { agentLoop, agentLoopContinue } from "@ponythewhite/base-context-agent";
|
|
520
|
+
|
|
521
|
+
const context: AgentContext = {
|
|
522
|
+
systemPrompt: "You are helpful.",
|
|
523
|
+
messages: [],
|
|
524
|
+
tools: [],
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
const config: AgentLoopConfig = {
|
|
528
|
+
model: getModel("openai", "gpt-4o"),
|
|
529
|
+
convertToLlm: (msgs) => msgs.filter(m => ["user", "assistant", "toolResult"].includes(m.role)),
|
|
530
|
+
toolExecution: "parallel", // overridden by per-tool executionMode if set
|
|
531
|
+
beforeToolCall: async ({ toolCall, args, context }) => undefined,
|
|
532
|
+
afterToolCall: async ({ toolCall, result, isError, context }) => undefined,
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const userMessage = { role: "user", content: "Hello", timestamp: Date.now() };
|
|
536
|
+
|
|
537
|
+
for await (const event of agentLoop([userMessage], context, config)) {
|
|
538
|
+
console.log(event.type);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// Continue from existing context
|
|
542
|
+
for await (const event of agentLoopContinue(context, config)) {
|
|
543
|
+
console.log(event.type);
|
|
544
|
+
}
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
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()`.
|
|
548
|
+
|
|
549
|
+
## License
|
|
550
|
+
|
|
551
|
+
MIT
|
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mario Zechner
|
|
4
|
+
Copyright (c) 2026 Prime Intellect
|
|
5
|
+
Copyright (c) 2026 BaseModelAI and Jacek Dąbrowski
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/dist/NOTICE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Synerise base-context is a source-owned fork of Prime Agent v0.9.3.
|
|
2
|
+
Repository: https://github.com/BaseModelAI/base-context
|
|
3
|
+
Fork ancestor: 915c78f42c248b08238dd27fcd4bcab32c60beab
|
|
4
|
+
|
|
5
|
+
Upstream: https://github.com/PrimeIntellect-ai/prime-agent
|
|
6
|
+
Copyright (c) 2025 Mario Zechner
|
|
7
|
+
Copyright (c) 2026 Prime Intellect
|
|
8
|
+
Fork modifications: Copyright (c) 2026 BaseModelAI and Jacek Dąbrowski
|
|
9
|
+
|
|
10
|
+
Distributed under the MIT License. See LICENSE.
|
|
11
|
+
Provider names and model identifiers identify their respective providers;
|
|
12
|
+
this fork is not an official Prime Intellect release.
|
|
13
|
+
|
|
14
|
+
Prime Agent builds on Mario Zechner's Pi project:
|
|
15
|
+
https://github.com/badlogic/pi-mono
|
|
16
|
+
|
|
17
|
+
We also credit Prime Intellect's PrimeRL authors for their open-source
|
|
18
|
+
reinforcement-learning work: https://github.com/PrimeIntellect-ai/prime-rl
|
|
19
|
+
This acknowledgement does not imply that PrimeRL is a runtime dependency
|
|
20
|
+
or that upstream authors endorse this fork.
|
|
21
|
+
|
|
22
|
+
Third-party dependencies retain their own licenses and notices.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent loop that works with AgentMessage throughout.
|
|
3
|
+
* Transforms to Message[] only at the LLM call boundary.
|
|
4
|
+
*/
|
|
5
|
+
import { EventStream } from "@ponythewhite/base-context-ai";
|
|
6
|
+
import type { AgentContext, AgentEvent, AgentLoopConfig, AgentMessage, StreamFn } from "./types.js";
|
|
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, 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, streamFn?: StreamFn): EventStream<AgentEvent, AgentMessage[]>;
|
|
22
|
+
export declare function runAgentLoop(prompts: AgentMessage[], context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn): Promise<AgentMessage[]>;
|
|
23
|
+
export declare function runAgentLoopContinue(context: AgentContext, config: AgentLoopConfig, emit: AgentEventSink, signal?: AbortSignal, streamFn?: StreamFn): Promise<AgentMessage[]>;
|
|
24
|
+
//# sourceMappingURL=agent-loop.d.ts.map
|