@nvrland/pi-agent-core 0.65.2-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +456 -0
- package/dist/agent-loop.d.ts +24 -0
- package/dist/agent-loop.d.ts.map +1 -0
- package/dist/agent-loop.js +404 -0
- package/dist/agent-loop.js.map +1 -0
- package/dist/agent.d.ts +115 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +395 -0
- package/dist/agent.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/proxy.d.ts +85 -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 +323 -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 +42 -0
package/dist/agent.js
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { streamSimple, } from "@mariozechner/pi-ai";
|
|
2
|
+
import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";
|
|
3
|
+
function defaultConvertToLlm(messages) {
|
|
4
|
+
return messages.filter((message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult");
|
|
5
|
+
}
|
|
6
|
+
const EMPTY_USAGE = {
|
|
7
|
+
input: 0,
|
|
8
|
+
output: 0,
|
|
9
|
+
cacheRead: 0,
|
|
10
|
+
cacheWrite: 0,
|
|
11
|
+
totalTokens: 0,
|
|
12
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
13
|
+
};
|
|
14
|
+
const DEFAULT_MODEL = {
|
|
15
|
+
id: "unknown",
|
|
16
|
+
name: "unknown",
|
|
17
|
+
api: "unknown",
|
|
18
|
+
provider: "unknown",
|
|
19
|
+
baseUrl: "",
|
|
20
|
+
reasoning: false,
|
|
21
|
+
input: [],
|
|
22
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
23
|
+
contextWindow: 0,
|
|
24
|
+
maxTokens: 0,
|
|
25
|
+
};
|
|
26
|
+
function createMutableAgentState(initialState) {
|
|
27
|
+
let tools = initialState?.tools?.slice() ?? [];
|
|
28
|
+
let messages = initialState?.messages?.slice() ?? [];
|
|
29
|
+
return {
|
|
30
|
+
systemPrompt: initialState?.systemPrompt ?? "",
|
|
31
|
+
model: initialState?.model ?? DEFAULT_MODEL,
|
|
32
|
+
thinkingLevel: initialState?.thinkingLevel ?? "off",
|
|
33
|
+
get tools() {
|
|
34
|
+
return tools;
|
|
35
|
+
},
|
|
36
|
+
set tools(nextTools) {
|
|
37
|
+
tools = nextTools.slice();
|
|
38
|
+
},
|
|
39
|
+
get messages() {
|
|
40
|
+
return messages;
|
|
41
|
+
},
|
|
42
|
+
set messages(nextMessages) {
|
|
43
|
+
messages = nextMessages.slice();
|
|
44
|
+
},
|
|
45
|
+
isStreaming: false,
|
|
46
|
+
streamingMessage: undefined,
|
|
47
|
+
pendingToolCalls: new Set(),
|
|
48
|
+
errorMessage: undefined,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
class PendingMessageQueue {
|
|
52
|
+
mode;
|
|
53
|
+
messages = [];
|
|
54
|
+
constructor(mode) {
|
|
55
|
+
this.mode = mode;
|
|
56
|
+
}
|
|
57
|
+
enqueue(message) {
|
|
58
|
+
this.messages.push(message);
|
|
59
|
+
}
|
|
60
|
+
hasItems() {
|
|
61
|
+
return this.messages.length > 0;
|
|
62
|
+
}
|
|
63
|
+
drain() {
|
|
64
|
+
if (this.mode === "all") {
|
|
65
|
+
const drained = this.messages.slice();
|
|
66
|
+
this.messages = [];
|
|
67
|
+
return drained;
|
|
68
|
+
}
|
|
69
|
+
const first = this.messages[0];
|
|
70
|
+
if (!first) {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
this.messages = this.messages.slice(1);
|
|
74
|
+
return [first];
|
|
75
|
+
}
|
|
76
|
+
clear() {
|
|
77
|
+
this.messages = [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Stateful wrapper around the low-level agent loop.
|
|
82
|
+
*
|
|
83
|
+
* `Agent` owns the current transcript, emits lifecycle events, executes tools,
|
|
84
|
+
* and exposes queueing APIs for steering and follow-up messages.
|
|
85
|
+
*/
|
|
86
|
+
export class Agent {
|
|
87
|
+
_state;
|
|
88
|
+
listeners = new Set();
|
|
89
|
+
steeringQueue;
|
|
90
|
+
followUpQueue;
|
|
91
|
+
convertToLlm;
|
|
92
|
+
transformContext;
|
|
93
|
+
streamFn;
|
|
94
|
+
getApiKey;
|
|
95
|
+
onPayload;
|
|
96
|
+
beforeToolCall;
|
|
97
|
+
afterToolCall;
|
|
98
|
+
activeRun;
|
|
99
|
+
/** Session identifier forwarded to providers for cache-aware backends. */
|
|
100
|
+
sessionId;
|
|
101
|
+
/** Optional per-level thinking token budgets forwarded to the stream function. */
|
|
102
|
+
thinkingBudgets;
|
|
103
|
+
/** Preferred transport forwarded to the stream function. */
|
|
104
|
+
transport;
|
|
105
|
+
/** Optional cap for provider-requested retry delays. */
|
|
106
|
+
maxRetryDelayMs;
|
|
107
|
+
/** Tool execution strategy for assistant messages that contain multiple tool calls. */
|
|
108
|
+
toolExecution;
|
|
109
|
+
constructor(options = {}) {
|
|
110
|
+
this._state = createMutableAgentState(options.initialState);
|
|
111
|
+
this.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;
|
|
112
|
+
this.transformContext = options.transformContext;
|
|
113
|
+
this.streamFn = options.streamFn ?? streamSimple;
|
|
114
|
+
this.getApiKey = options.getApiKey;
|
|
115
|
+
this.onPayload = options.onPayload;
|
|
116
|
+
this.beforeToolCall = options.beforeToolCall;
|
|
117
|
+
this.afterToolCall = options.afterToolCall;
|
|
118
|
+
this.steeringQueue = new PendingMessageQueue(options.steeringMode ?? "one-at-a-time");
|
|
119
|
+
this.followUpQueue = new PendingMessageQueue(options.followUpMode ?? "one-at-a-time");
|
|
120
|
+
this.sessionId = options.sessionId;
|
|
121
|
+
this.thinkingBudgets = options.thinkingBudgets;
|
|
122
|
+
this.transport = options.transport ?? "sse";
|
|
123
|
+
this.maxRetryDelayMs = options.maxRetryDelayMs;
|
|
124
|
+
this.toolExecution = options.toolExecution ?? "parallel";
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Subscribe to agent lifecycle events.
|
|
128
|
+
*
|
|
129
|
+
* Listener promises are awaited in subscription order and are included in
|
|
130
|
+
* the current run's settlement. Listeners also receive the active abort
|
|
131
|
+
* signal for the current run.
|
|
132
|
+
*
|
|
133
|
+
* `agent_end` is the final emitted event for a run, but the agent does not
|
|
134
|
+
* become idle until all awaited listeners for that event have settled.
|
|
135
|
+
*/
|
|
136
|
+
subscribe(listener) {
|
|
137
|
+
this.listeners.add(listener);
|
|
138
|
+
return () => this.listeners.delete(listener);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Current agent state.
|
|
142
|
+
*
|
|
143
|
+
* Assigning `state.tools` or `state.messages` copies the provided top-level array.
|
|
144
|
+
*/
|
|
145
|
+
get state() {
|
|
146
|
+
return this._state;
|
|
147
|
+
}
|
|
148
|
+
/** Controls how queued steering messages are drained. */
|
|
149
|
+
set steeringMode(mode) {
|
|
150
|
+
this.steeringQueue.mode = mode;
|
|
151
|
+
}
|
|
152
|
+
get steeringMode() {
|
|
153
|
+
return this.steeringQueue.mode;
|
|
154
|
+
}
|
|
155
|
+
/** Controls how queued follow-up messages are drained. */
|
|
156
|
+
set followUpMode(mode) {
|
|
157
|
+
this.followUpQueue.mode = mode;
|
|
158
|
+
}
|
|
159
|
+
get followUpMode() {
|
|
160
|
+
return this.followUpQueue.mode;
|
|
161
|
+
}
|
|
162
|
+
/** Queue a message to be injected after the current assistant turn finishes. */
|
|
163
|
+
steer(message) {
|
|
164
|
+
this.steeringQueue.enqueue(message);
|
|
165
|
+
}
|
|
166
|
+
/** Queue a message to run only after the agent would otherwise stop. */
|
|
167
|
+
followUp(message) {
|
|
168
|
+
this.followUpQueue.enqueue(message);
|
|
169
|
+
}
|
|
170
|
+
/** Remove all queued steering messages. */
|
|
171
|
+
clearSteeringQueue() {
|
|
172
|
+
this.steeringQueue.clear();
|
|
173
|
+
}
|
|
174
|
+
/** Remove all queued follow-up messages. */
|
|
175
|
+
clearFollowUpQueue() {
|
|
176
|
+
this.followUpQueue.clear();
|
|
177
|
+
}
|
|
178
|
+
/** Remove all queued steering and follow-up messages. */
|
|
179
|
+
clearAllQueues() {
|
|
180
|
+
this.clearSteeringQueue();
|
|
181
|
+
this.clearFollowUpQueue();
|
|
182
|
+
}
|
|
183
|
+
/** Returns true when either queue still contains pending messages. */
|
|
184
|
+
hasQueuedMessages() {
|
|
185
|
+
return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
|
|
186
|
+
}
|
|
187
|
+
/** Active abort signal for the current run, if any. */
|
|
188
|
+
get signal() {
|
|
189
|
+
return this.activeRun?.abortController.signal;
|
|
190
|
+
}
|
|
191
|
+
/** Abort the current run, if one is active. */
|
|
192
|
+
abort() {
|
|
193
|
+
this.activeRun?.abortController.abort();
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Resolve when the current run and all awaited event listeners have finished.
|
|
197
|
+
*
|
|
198
|
+
* This resolves after `agent_end` listeners settle.
|
|
199
|
+
*/
|
|
200
|
+
waitForIdle() {
|
|
201
|
+
return this.activeRun?.promise ?? Promise.resolve();
|
|
202
|
+
}
|
|
203
|
+
/** Clear transcript state, runtime state, and queued messages. */
|
|
204
|
+
reset() {
|
|
205
|
+
this._state.messages = [];
|
|
206
|
+
this._state.isStreaming = false;
|
|
207
|
+
this._state.streamingMessage = undefined;
|
|
208
|
+
this._state.pendingToolCalls = new Set();
|
|
209
|
+
this._state.errorMessage = undefined;
|
|
210
|
+
this.clearFollowUpQueue();
|
|
211
|
+
this.clearSteeringQueue();
|
|
212
|
+
}
|
|
213
|
+
async prompt(input, images) {
|
|
214
|
+
if (this.activeRun) {
|
|
215
|
+
throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");
|
|
216
|
+
}
|
|
217
|
+
const messages = this.normalizePromptInput(input, images);
|
|
218
|
+
await this.runPromptMessages(messages);
|
|
219
|
+
}
|
|
220
|
+
/** Continue from the current transcript. The last message must be a user or tool-result message. */
|
|
221
|
+
async continue() {
|
|
222
|
+
if (this.activeRun) {
|
|
223
|
+
throw new Error("Agent is already processing. Wait for completion before continuing.");
|
|
224
|
+
}
|
|
225
|
+
const lastMessage = this._state.messages[this._state.messages.length - 1];
|
|
226
|
+
if (!lastMessage) {
|
|
227
|
+
throw new Error("No messages to continue from");
|
|
228
|
+
}
|
|
229
|
+
if (lastMessage.role === "assistant") {
|
|
230
|
+
const queuedSteering = this.steeringQueue.drain();
|
|
231
|
+
if (queuedSteering.length > 0) {
|
|
232
|
+
await this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const queuedFollowUps = this.followUpQueue.drain();
|
|
236
|
+
if (queuedFollowUps.length > 0) {
|
|
237
|
+
await this.runPromptMessages(queuedFollowUps);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
throw new Error("Cannot continue from message role: assistant");
|
|
241
|
+
}
|
|
242
|
+
await this.runContinuation();
|
|
243
|
+
}
|
|
244
|
+
normalizePromptInput(input, images) {
|
|
245
|
+
if (Array.isArray(input)) {
|
|
246
|
+
return input;
|
|
247
|
+
}
|
|
248
|
+
if (typeof input !== "string") {
|
|
249
|
+
return [input];
|
|
250
|
+
}
|
|
251
|
+
const content = [{ type: "text", text: input }];
|
|
252
|
+
if (images && images.length > 0) {
|
|
253
|
+
content.push(...images);
|
|
254
|
+
}
|
|
255
|
+
return [{ role: "user", content, timestamp: Date.now() }];
|
|
256
|
+
}
|
|
257
|
+
async runPromptMessages(messages, options = {}) {
|
|
258
|
+
await this.runWithLifecycle(async (signal) => {
|
|
259
|
+
await runAgentLoop(messages, this.createContextSnapshot(), this.createLoopConfig(options), (event) => this.processEvents(event), signal, this.streamFn);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
async runContinuation() {
|
|
263
|
+
await this.runWithLifecycle(async (signal) => {
|
|
264
|
+
await runAgentLoopContinue(this.createContextSnapshot(), this.createLoopConfig(), (event) => this.processEvents(event), signal, this.streamFn);
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
createContextSnapshot() {
|
|
268
|
+
return {
|
|
269
|
+
systemPrompt: this._state.systemPrompt,
|
|
270
|
+
messages: this._state.messages.slice(),
|
|
271
|
+
tools: this._state.tools.slice(),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
createLoopConfig(options = {}) {
|
|
275
|
+
let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
|
|
276
|
+
return {
|
|
277
|
+
model: this._state.model,
|
|
278
|
+
reasoning: this._state.thinkingLevel === "off" ? undefined : this._state.thinkingLevel,
|
|
279
|
+
sessionId: this.sessionId,
|
|
280
|
+
onPayload: this.onPayload,
|
|
281
|
+
transport: this.transport,
|
|
282
|
+
thinkingBudgets: this.thinkingBudgets,
|
|
283
|
+
maxRetryDelayMs: this.maxRetryDelayMs,
|
|
284
|
+
toolExecution: this.toolExecution,
|
|
285
|
+
beforeToolCall: this.beforeToolCall,
|
|
286
|
+
afterToolCall: this.afterToolCall,
|
|
287
|
+
convertToLlm: this.convertToLlm,
|
|
288
|
+
transformContext: this.transformContext,
|
|
289
|
+
getApiKey: this.getApiKey,
|
|
290
|
+
getSteeringMessages: async () => {
|
|
291
|
+
if (skipInitialSteeringPoll) {
|
|
292
|
+
skipInitialSteeringPoll = false;
|
|
293
|
+
return [];
|
|
294
|
+
}
|
|
295
|
+
return this.steeringQueue.drain();
|
|
296
|
+
},
|
|
297
|
+
getFollowUpMessages: async () => this.followUpQueue.drain(),
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
async runWithLifecycle(executor) {
|
|
301
|
+
if (this.activeRun) {
|
|
302
|
+
throw new Error("Agent is already processing.");
|
|
303
|
+
}
|
|
304
|
+
const abortController = new AbortController();
|
|
305
|
+
let resolvePromise = () => { };
|
|
306
|
+
const promise = new Promise((resolve) => {
|
|
307
|
+
resolvePromise = resolve;
|
|
308
|
+
});
|
|
309
|
+
this.activeRun = { promise, resolve: resolvePromise, abortController };
|
|
310
|
+
this._state.isStreaming = true;
|
|
311
|
+
this._state.streamingMessage = undefined;
|
|
312
|
+
this._state.errorMessage = undefined;
|
|
313
|
+
try {
|
|
314
|
+
await executor(abortController.signal);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
await this.handleRunFailure(error, abortController.signal.aborted);
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
this.finishRun();
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
async handleRunFailure(error, aborted) {
|
|
324
|
+
const failureMessage = {
|
|
325
|
+
role: "assistant",
|
|
326
|
+
content: [{ type: "text", text: "" }],
|
|
327
|
+
api: this._state.model.api,
|
|
328
|
+
provider: this._state.model.provider,
|
|
329
|
+
model: this._state.model.id,
|
|
330
|
+
usage: EMPTY_USAGE,
|
|
331
|
+
stopReason: aborted ? "aborted" : "error",
|
|
332
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
333
|
+
timestamp: Date.now(),
|
|
334
|
+
};
|
|
335
|
+
this._state.messages.push(failureMessage);
|
|
336
|
+
this._state.errorMessage = failureMessage.errorMessage;
|
|
337
|
+
await this.processEvents({ type: "agent_end", messages: [failureMessage] });
|
|
338
|
+
}
|
|
339
|
+
finishRun() {
|
|
340
|
+
this._state.isStreaming = false;
|
|
341
|
+
this._state.streamingMessage = undefined;
|
|
342
|
+
this._state.pendingToolCalls = new Set();
|
|
343
|
+
this.activeRun?.resolve();
|
|
344
|
+
this.activeRun = undefined;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Reduce internal state for a loop event, then await listeners.
|
|
348
|
+
*
|
|
349
|
+
* `agent_end` only means no further loop events will be emitted. The run is
|
|
350
|
+
* considered idle later, after all awaited listeners for `agent_end` finish
|
|
351
|
+
* and `finishRun()` clears runtime-owned state.
|
|
352
|
+
*/
|
|
353
|
+
async processEvents(event) {
|
|
354
|
+
switch (event.type) {
|
|
355
|
+
case "message_start":
|
|
356
|
+
this._state.streamingMessage = event.message;
|
|
357
|
+
break;
|
|
358
|
+
case "message_update":
|
|
359
|
+
this._state.streamingMessage = event.message;
|
|
360
|
+
break;
|
|
361
|
+
case "message_end":
|
|
362
|
+
this._state.streamingMessage = undefined;
|
|
363
|
+
this._state.messages.push(event.message);
|
|
364
|
+
break;
|
|
365
|
+
case "tool_execution_start": {
|
|
366
|
+
const pendingToolCalls = new Set(this._state.pendingToolCalls);
|
|
367
|
+
pendingToolCalls.add(event.toolCallId);
|
|
368
|
+
this._state.pendingToolCalls = pendingToolCalls;
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
case "tool_execution_end": {
|
|
372
|
+
const pendingToolCalls = new Set(this._state.pendingToolCalls);
|
|
373
|
+
pendingToolCalls.delete(event.toolCallId);
|
|
374
|
+
this._state.pendingToolCalls = pendingToolCalls;
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
case "turn_end":
|
|
378
|
+
if (event.message.role === "assistant" && event.message.errorMessage) {
|
|
379
|
+
this._state.errorMessage = event.message.errorMessage;
|
|
380
|
+
}
|
|
381
|
+
break;
|
|
382
|
+
case "agent_end":
|
|
383
|
+
this._state.streamingMessage = undefined;
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
const signal = this.activeRun?.abortController.signal;
|
|
387
|
+
if (!signal) {
|
|
388
|
+
throw new Error("Agent listener invoked outside active run");
|
|
389
|
+
}
|
|
390
|
+
for (const listener of this.listeners) {
|
|
391
|
+
await listener(event, signal);
|
|
392
|
+
}
|
|
393
|
+
}
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AAC,gBAAgB,GAAG,gBAAgB,CAAC;gBAChD,MAAM;YACP,CAAC;YAED,KAAK,UAAU;gBACd,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,WAAW,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;oBACtE,IAAI,CAAC,MAAM,CAAC,YAAY,GAAG,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n} from \"@mariozechner/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.js\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.js\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) => message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype QueueMode = \"all\" | \"one-at-a-time\";\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\nfunction createMutableAgentState(\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>,\n): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\n\treturn {\n\t\tsystemPrompt: initialState?.systemPrompt ?? \"\",\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: Partial<Omit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">>;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn?: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\n\tconstructor(public mode: QueueMode) {}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFn: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions = {}) {\n\t\tthis._state = createMutableAgentState(options.initialState);\n\t\tthis.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = options.transformContext;\n\t\tthis.streamFn = options.streamFn ?? streamSimple;\n\t\tthis.getApiKey = options.getApiKey;\n\t\tthis.onPayload = options.onPayload;\n\t\tthis.beforeToolCall = options.beforeToolCall;\n\t\tthis.afterToolCall = options.afterToolCall;\n\t\tthis.steeringQueue = new PendingMessageQueue(options.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(options.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.thinkingBudgets = options.thinkingBudgets;\n\t\tthis.transport = options.transport ?? \"sse\";\n\t\tthis.maxRetryDelayMs = options.maxRetryDelayMs;\n\t\tthis.toolExecution = options.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear transcript state, runtime state, and queued messages. */\n\treset(): void {\n\t\tthis._state.messages = [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFn,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tsystemPrompt: this._state.systemPrompt,\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tthis._state.messages.push(failureMessage);\n\t\tthis._state.errorMessage = failureMessage.errorMessage;\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,CAAC;AAE3B,cAAc,iBAAiB,CAAC;AAEhC,cAAc,YAAY,CAAC;AAE3B,cAAc,YAAY,CAAC","sourcesContent":["// Core Agent\nexport * from \"./agent.js\";\n// Loop functions\nexport * from \"./agent-loop.js\";\n// Proxy utilities\nexport * from \"./proxy.js\";\n// Types\nexport * from \"./types.js\";\n"]}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,cAAc,YAAY,CAAC;AAC3B,iBAAiB;AACjB,cAAc,iBAAiB,CAAC;AAChC,kBAAkB;AAClB,cAAc,YAAY,CAAC;AAC3B,QAAQ;AACR,cAAc,YAAY,CAAC","sourcesContent":["// Core Agent\nexport * from \"./agent.js\";\n// Loop functions\nexport * from \"./agent-loop.js\";\n// Proxy utilities\nexport * from \"./proxy.js\";\n// Types\nexport * from \"./types.js\";\n"]}
|
package/dist/proxy.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Proxy stream function for apps that route LLM calls through a server.
|
|
3
|
+
* The server manages auth and proxies requests to LLM providers.
|
|
4
|
+
*/
|
|
5
|
+
import { type AssistantMessage, type AssistantMessageEvent, type Context, EventStream, type Model, type SimpleStreamOptions, type StopReason } from "@mariozechner/pi-ai";
|
|
6
|
+
declare class ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
|
|
7
|
+
constructor();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Proxy event types - server sends these with partial field stripped to reduce bandwidth.
|
|
11
|
+
*/
|
|
12
|
+
export type ProxyAssistantMessageEvent = {
|
|
13
|
+
type: "start";
|
|
14
|
+
} | {
|
|
15
|
+
type: "text_start";
|
|
16
|
+
contentIndex: number;
|
|
17
|
+
} | {
|
|
18
|
+
type: "text_delta";
|
|
19
|
+
contentIndex: number;
|
|
20
|
+
delta: string;
|
|
21
|
+
} | {
|
|
22
|
+
type: "text_end";
|
|
23
|
+
contentIndex: number;
|
|
24
|
+
contentSignature?: string;
|
|
25
|
+
} | {
|
|
26
|
+
type: "thinking_start";
|
|
27
|
+
contentIndex: number;
|
|
28
|
+
} | {
|
|
29
|
+
type: "thinking_delta";
|
|
30
|
+
contentIndex: number;
|
|
31
|
+
delta: string;
|
|
32
|
+
} | {
|
|
33
|
+
type: "thinking_end";
|
|
34
|
+
contentIndex: number;
|
|
35
|
+
contentSignature?: string;
|
|
36
|
+
} | {
|
|
37
|
+
type: "toolcall_start";
|
|
38
|
+
contentIndex: number;
|
|
39
|
+
id: string;
|
|
40
|
+
toolName: string;
|
|
41
|
+
} | {
|
|
42
|
+
type: "toolcall_delta";
|
|
43
|
+
contentIndex: number;
|
|
44
|
+
delta: string;
|
|
45
|
+
} | {
|
|
46
|
+
type: "toolcall_end";
|
|
47
|
+
contentIndex: number;
|
|
48
|
+
} | {
|
|
49
|
+
type: "done";
|
|
50
|
+
reason: Extract<StopReason, "stop" | "length" | "toolUse">;
|
|
51
|
+
usage: AssistantMessage["usage"];
|
|
52
|
+
} | {
|
|
53
|
+
type: "error";
|
|
54
|
+
reason: Extract<StopReason, "aborted" | "error">;
|
|
55
|
+
errorMessage?: string;
|
|
56
|
+
usage: AssistantMessage["usage"];
|
|
57
|
+
};
|
|
58
|
+
export interface ProxyStreamOptions extends SimpleStreamOptions {
|
|
59
|
+
/** Auth token for the proxy server */
|
|
60
|
+
authToken: string;
|
|
61
|
+
/** Proxy server URL (e.g., "https://genai.example.com") */
|
|
62
|
+
proxyUrl: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Stream function that proxies through a server instead of calling LLM providers directly.
|
|
66
|
+
* The server strips the partial field from delta events to reduce bandwidth.
|
|
67
|
+
* We reconstruct the partial message client-side.
|
|
68
|
+
*
|
|
69
|
+
* Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.
|
|
70
|
+
*
|
|
71
|
+
* @example
|
|
72
|
+
* ```typescript
|
|
73
|
+
* const agent = new Agent({
|
|
74
|
+
* streamFn: (model, context, options) =>
|
|
75
|
+
* streamProxy(model, context, {
|
|
76
|
+
* ...options,
|
|
77
|
+
* authToken: await getAuthToken(),
|
|
78
|
+
* proxyUrl: "https://genai.example.com",
|
|
79
|
+
* }),
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream;
|
|
84
|
+
export {};
|
|
85
|
+
//# sourceMappingURL=proxy.d.ts.map
|
|
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AAK,EAAE,MAAM,CAAA;CAAE,GAC/D;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAC9C;IACA,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAAC;IAC3D,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;CAChC,GACD;IACA,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE,SAAS,GAAG,OAAO,CAAC,CAAC;IACjD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;CAChC,CAAC;AAEL,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC9D,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,kBAAkB,GAAG,uBAAuB,CAyHrH","sourcesContent":["/**\n * Proxy stream function for apps that route LLM calls through a server.\n * The server manages auth and proxies requests to LLM providers.\n */\n\n// Internal import for JSON parsing utility\nimport {\n\ttype AssistantMessage,\n\ttype AssistantMessageEvent,\n\ttype Context,\n\tEventStream,\n\ttype Model,\n\tparseStreamingJson,\n\ttype SimpleStreamOptions,\n\ttype StopReason,\n\ttype ToolCall,\n} from \"@mariozechner/pi-ai\";\n\n// Create stream class matching ProxyMessageEventStream\nclass ProxyMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {\n\tconstructor() {\n\t\tsuper(\n\t\t\t(event) => event.type === \"done\" || event.type === \"error\",\n\t\t\t(event) => {\n\t\t\t\tif (event.type === \"done\") return event.message;\n\t\t\t\tif (event.type === \"error\") return event.error;\n\t\t\t\tthrow new Error(\"Unexpected event type\");\n\t\t\t},\n\t\t);\n\t}\n}\n\n/**\n * Proxy event types - server sends these with partial field stripped to reduce bandwidth.\n */\nexport type ProxyAssistantMessageEvent =\n\t| { type: \"start\" }\n\t| { type: \"text_start\"; contentIndex: number }\n\t| { type: \"text_delta\"; contentIndex: number; delta: string }\n\t| { type: \"text_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"thinking_start\"; contentIndex: number }\n\t| { type: \"thinking_delta\"; contentIndex: number; delta: string }\n\t| { type: \"thinking_end\"; contentIndex: number; contentSignature?: string }\n\t| { type: \"toolcall_start\"; contentIndex: number; id: string; toolName: string }\n\t| { type: \"toolcall_delta\"; contentIndex: number; delta: string }\n\t| { type: \"toolcall_end\"; contentIndex: number }\n\t| {\n\t\t\ttype: \"done\";\n\t\t\treason: Extract<StopReason, \"stop\" | \"length\" | \"toolUse\">;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\treason: Extract<StopReason, \"aborted\" | \"error\">;\n\t\t\terrorMessage?: string;\n\t\t\tusage: AssistantMessage[\"usage\"];\n\t };\n\nexport interface ProxyStreamOptions extends SimpleStreamOptions {\n\t/** Auth token for the proxy server */\n\tauthToken: string;\n\t/** Proxy server URL (e.g., \"https://genai.example.com\") */\n\tproxyUrl: string;\n}\n\n/**\n * Stream function that proxies through a server instead of calling LLM providers directly.\n * The server strips the partial field from delta events to reduce bandwidth.\n * We reconstruct the partial message client-side.\n *\n * Use this as the `streamFn` option when creating an Agent that needs to go through a proxy.\n *\n * @example\n * ```typescript\n * const agent = new Agent({\n * streamFn: (model, context, options) =>\n * streamProxy(model, context, {\n * ...options,\n * authToken: await getAuthToken(),\n * proxyUrl: \"https://genai.example.com\",\n * }),\n * });\n * ```\n */\nexport function streamProxy(model: Model<any>, context: Context, options: ProxyStreamOptions): ProxyMessageEventStream {\n\tconst stream = new ProxyMessageEventStream();\n\n\t(async () => {\n\t\t// Initialize the partial message that we'll build up from events\n\t\tconst partial: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: \"stop\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\tlet reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n\t\tconst abortHandler = () => {\n\t\t\tif (reader) {\n\t\t\t\treader.cancel(\"Request aborted by user\").catch(() => {});\n\t\t\t}\n\t\t};\n\n\t\tif (options.signal) {\n\t\t\toptions.signal.addEventListener(\"abort\", abortHandler);\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch(`${options.proxyUrl}/api/stream`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${options.authToken}`,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\ttemperature: options.temperature,\n\t\t\t\t\t\tmaxTokens: options.maxTokens,\n\t\t\t\t\t\treasoning: options.reasoning,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tlet errorMessage = `Proxy error: ${response.status} ${response.statusText}`;\n\t\t\t\ttry {\n\t\t\t\t\tconst errorData = (await response.json()) as { error?: string };\n\t\t\t\t\tif (errorData.error) {\n\t\t\t\t\t\terrorMessage = `Proxy error: ${errorData.error}`;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Couldn't parse error response\n\t\t\t\t}\n\t\t\t\tthrow new Error(errorMessage);\n\t\t\t}\n\n\t\t\treader = response.body!.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\n\t\t\t\tif (options.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t\t}\n\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() || \"\";\n\n\t\t\t\tfor (const line of lines) {\n\t\t\t\t\tif (line.startsWith(\"data: \")) {\n\t\t\t\t\t\tconst data = line.slice(6).trim();\n\t\t\t\t\t\tif (data) {\n\t\t\t\t\t\t\tconst proxyEvent = JSON.parse(data) as ProxyAssistantMessageEvent;\n\t\t\t\t\t\t\tconst event = processProxyEvent(proxyEvent, partial);\n\t\t\t\t\t\t\tif (event) {\n\t\t\t\t\t\t\t\tstream.push(event);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (options.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request aborted by user\");\n\t\t\t}\n\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\tconst reason = options.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\tpartial.stopReason = reason;\n\t\t\tpartial.errorMessage = errorMessage;\n\t\t\tstream.push({\n\t\t\t\ttype: \"error\",\n\t\t\t\treason,\n\t\t\t\terror: partial,\n\t\t\t});\n\t\t\tstream.end();\n\t\t} finally {\n\t\t\tif (options.signal) {\n\t\t\t\toptions.signal.removeEventListener(\"abort\", abortHandler);\n\t\t\t}\n\t\t}\n\t})();\n\n\treturn stream;\n}\n\n/**\n * Process a proxy event and update the partial message.\n */\nfunction processProxyEvent(\n\tproxyEvent: ProxyAssistantMessageEvent,\n\tpartial: AssistantMessage,\n): AssistantMessageEvent | undefined {\n\tswitch (proxyEvent.type) {\n\t\tcase \"start\":\n\t\t\treturn { type: \"start\", partial };\n\n\t\tcase \"text_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"text\", text: \"\" };\n\t\t\treturn { type: \"text_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"text_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.text += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_delta for non-text content\");\n\t\t}\n\n\t\tcase \"text_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"text\") {\n\t\t\t\tcontent.textSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.text,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received text_end for non-text content\");\n\t\t}\n\n\t\tcase \"thinking_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = { type: \"thinking\", thinking: \"\" };\n\t\t\treturn { type: \"thinking_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"thinking_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinking += proxyEvent.delta;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_delta for non-thinking content\");\n\t\t}\n\n\t\tcase \"thinking_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"thinking\") {\n\t\t\t\tcontent.thinkingSignature = proxyEvent.contentSignature;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tcontent: content.thinking,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received thinking_end for non-thinking content\");\n\t\t}\n\n\t\tcase \"toolcall_start\":\n\t\t\tpartial.content[proxyEvent.contentIndex] = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: proxyEvent.id,\n\t\t\t\tname: proxyEvent.toolName,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: \"\",\n\t\t\t} satisfies ToolCall & { partialJson: string } as ToolCall;\n\t\t\treturn { type: \"toolcall_start\", contentIndex: proxyEvent.contentIndex, partial };\n\n\t\tcase \"toolcall_delta\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\t(content as any).partialJson += proxyEvent.delta;\n\t\t\t\tcontent.arguments = parseStreamingJson((content as any).partialJson) || {};\n\t\t\t\tpartial.content[proxyEvent.contentIndex] = { ...content }; // Trigger reactivity\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\tdelta: proxyEvent.delta,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow new Error(\"Received toolcall_delta for non-toolCall content\");\n\t\t}\n\n\t\tcase \"toolcall_end\": {\n\t\t\tconst content = partial.content[proxyEvent.contentIndex];\n\t\t\tif (content?.type === \"toolCall\") {\n\t\t\t\tdelete (content as any).partialJson;\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: proxyEvent.contentIndex,\n\t\t\t\t\ttoolCall: content,\n\t\t\t\t\tpartial,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\n\t\tcase \"done\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"done\", reason: proxyEvent.reason, message: partial };\n\n\t\tcase \"error\":\n\t\t\tpartial.stopReason = proxyEvent.reason;\n\t\t\tpartial.errorMessage = proxyEvent.errorMessage;\n\t\t\tpartial.usage = proxyEvent.usage;\n\t\t\treturn { type: \"error\", reason: proxyEvent.reason, error: partial };\n\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck: never = proxyEvent;\n\t\t\tconsole.warn(`Unhandled proxy event type: ${(proxyEvent as any).type}`);\n\t\t\treturn undefined;\n\t\t}\n\t}\n}\n"]}
|