privateer-agent 0.15.4 → 0.15.6
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 +11 -0
- package/bin/boot-bundle.d.mts +2 -0
- package/bin/boot-bundle.mjs +44 -0
- package/bin/fresh-supervisor.d.mts +5 -1
- package/bin/fresh-supervisor.mjs +47 -10
- package/bin/privateer-launch.mjs +27 -3
- package/bin/privateer-subagent.mjs +5 -2
- package/bin/privateer-verify.mjs +12 -0
- package/bin/session-recovery.d.mts +53 -0
- package/bin/session-recovery.mjs +240 -0
- package/bin/session-seal-preload.mjs +17 -0
- package/bin/session-seal.d.mts +25 -0
- package/bin/session-seal.mjs +242 -0
- package/dist-boot/boot.mjs +3 -0
- package/dist-boot/c-27JKSMWL.mjs +1460 -0
- package/dist-boot/c-2BMRFV24.mjs +269 -0
- package/dist-boot/c-2CTF6JA3.mjs +166 -0
- package/dist-boot/c-2G3BBHRJ.mjs +84 -0
- package/dist-boot/c-2IDLKXX6.mjs +250 -0
- package/dist-boot/c-2NJD5VYM.mjs +8 -0
- package/dist-boot/c-2S5EEQPW.mjs +1602 -0
- package/dist-boot/c-2WRDCUVI.mjs +25 -0
- package/dist-boot/c-2YN3M256.mjs +14 -0
- package/dist-boot/c-37GM3GMU.mjs +187 -0
- package/dist-boot/c-3STKRSVO.mjs +2480 -0
- package/dist-boot/c-3TPV6TQQ.mjs +2320 -0
- package/dist-boot/c-3UVHLQDJ.mjs +225 -0
- package/dist-boot/c-42PUUZYC.mjs +697 -0
- package/dist-boot/c-4D5UMWVW.mjs +683 -0
- package/dist-boot/c-4ETZRMTA.mjs +46 -0
- package/dist-boot/c-4QT25BD5.mjs +1482 -0
- package/dist-boot/c-4WVR32AP.mjs +2579 -0
- package/dist-boot/c-5EMM567G.mjs +152 -0
- package/dist-boot/c-5FA4CV63.mjs +145 -0
- package/dist-boot/c-5GV3X3RB.mjs +14 -0
- package/dist-boot/c-5JCEPRIY.mjs +52 -0
- package/dist-boot/c-5NDKIIWT.mjs +16 -0
- package/dist-boot/c-5QL3AR26.mjs +4665 -0
- package/dist-boot/c-5XY6MFKN.mjs +5142 -0
- package/dist-boot/c-65UZIZC7.mjs +2897 -0
- package/dist-boot/c-6FUXKHOK.mjs +1969 -0
- package/dist-boot/c-6JHWQE4V.mjs +18242 -0
- package/dist-boot/c-6LOBR4I6.mjs +5280 -0
- package/dist-boot/c-6QHOZXKQ.mjs +14394 -0
- package/dist-boot/c-6ZO2SADQ.mjs +178 -0
- package/dist-boot/c-6ZORVVZP.mjs +1449 -0
- package/dist-boot/c-76QH4UCP.mjs +2441 -0
- package/dist-boot/c-77GO5L5Y.mjs +20982 -0
- package/dist-boot/c-7M23XFTN.mjs +5052 -0
- package/dist-boot/c-7TC367E2.mjs +32 -0
- package/dist-boot/c-7UOG7POX.mjs +1524 -0
- package/dist-boot/c-7VHP3FLN.mjs +376 -0
- package/dist-boot/c-A73JHZP2.mjs +13207 -0
- package/dist-boot/c-ABXULAFL.mjs +71 -0
- package/dist-boot/c-ANDD2AQO.mjs +74 -0
- package/dist-boot/c-AOY77AZL.mjs +1430 -0
- package/dist-boot/c-AXEPZ22I.mjs +108 -0
- package/dist-boot/c-B2Y7VNHU.mjs +427 -0
- package/dist-boot/c-B7VJUH73.mjs +77 -0
- package/dist-boot/c-BFW6CDVL.mjs +24 -0
- package/dist-boot/c-BHNIF2AR.mjs +188 -0
- package/dist-boot/c-BKF2O6BL.mjs +23 -0
- package/dist-boot/c-BOZXFTZN.mjs +8 -0
- package/dist-boot/c-BRNYJWZL.mjs +28 -0
- package/dist-boot/c-C3N4Z2HO.mjs +93 -0
- package/dist-boot/c-C4IV7ZFG.mjs +717 -0
- package/dist-boot/c-C5NK6UYV.mjs +793 -0
- package/dist-boot/c-C67644MB.mjs +1659 -0
- package/dist-boot/c-C6S2YB53.mjs +620 -0
- package/dist-boot/c-CDBEJSBF.mjs +37 -0
- package/dist-boot/c-CG47HBKU.mjs +435 -0
- package/dist-boot/c-CKCTWCT5.mjs +51 -0
- package/dist-boot/c-CN77DCGF.mjs +60 -0
- package/dist-boot/c-CRBXNKFO.mjs +1795 -0
- package/dist-boot/c-CRIHASQ6.mjs +973 -0
- package/dist-boot/c-CU4NGAUO.mjs +3786 -0
- package/dist-boot/c-CWRFLGQU.mjs +1883 -0
- package/dist-boot/c-CYQB2USO.mjs +32 -0
- package/dist-boot/c-DEE67DJO.mjs +379 -0
- package/dist-boot/c-DIFDBYOP.mjs +1258 -0
- package/dist-boot/c-DOSGVXDZ.mjs +34879 -0
- package/dist-boot/c-DR7XQI32.mjs +381 -0
- package/dist-boot/c-DTGPSB46.mjs +14666 -0
- package/dist-boot/c-DTHDNA4P.mjs +320 -0
- package/dist-boot/c-E4Z3Y5B5.mjs +3864 -0
- package/dist-boot/c-E66Z2TI7.mjs +203 -0
- package/dist-boot/c-EBU6RLRV.mjs +1527 -0
- package/dist-boot/c-EBZZNGSF.mjs +432 -0
- package/dist-boot/c-EC3LJ2KF.mjs +1032 -0
- package/dist-boot/c-EQBKXWNX.mjs +15829 -0
- package/dist-boot/c-EUEPIW4S.mjs +574 -0
- package/dist-boot/c-EX4YVWAT.mjs +378 -0
- package/dist-boot/c-EYZGSAJU.mjs +98 -0
- package/dist-boot/c-F75VRKY4.mjs +172 -0
- package/dist-boot/c-FH4NXKHV.mjs +177 -0
- package/dist-boot/c-FHNUCTEM.mjs +140 -0
- package/dist-boot/c-FJ5T42DS.mjs +5349 -0
- package/dist-boot/c-FPCNRL7G.mjs +1728 -0
- package/dist-boot/c-G4DLN7Q4.mjs +8 -0
- package/dist-boot/c-G56GYQFZ.mjs +2507 -0
- package/dist-boot/c-GLIOERDQ.mjs +1200 -0
- package/dist-boot/c-GMJ5HUBM.mjs +14 -0
- package/dist-boot/c-H3HSGMAQ.mjs +461 -0
- package/dist-boot/c-HIKTO6P7.mjs +275 -0
- package/dist-boot/c-I2MCJ34O.mjs +464 -0
- package/dist-boot/c-I3C6LBW4.mjs +765 -0
- package/dist-boot/c-I54OKQHW.mjs +387 -0
- package/dist-boot/c-IFSP3R4D.mjs +80 -0
- package/dist-boot/c-IZK77VB7.mjs +171 -0
- package/dist-boot/c-J3Y25UGE.mjs +54 -0
- package/dist-boot/c-J5IESS7W.mjs +27750 -0
- package/dist-boot/c-JJWZBY7L.mjs +254 -0
- package/dist-boot/c-JKTFXTGF.mjs +463 -0
- package/dist-boot/c-JN57AXQ4.mjs +77 -0
- package/dist-boot/c-KFIO6LUW.mjs +1096 -0
- package/dist-boot/c-KIEMEFWW.mjs +478 -0
- package/dist-boot/c-KIVXWBYD.mjs +28 -0
- package/dist-boot/c-KP6CRIP4.mjs +580 -0
- package/dist-boot/c-L26VOJX4.mjs +11558 -0
- package/dist-boot/c-L5GHWG5G.mjs +5988 -0
- package/dist-boot/c-M7NSQAKK.mjs +353 -0
- package/dist-boot/c-MCEWOPBW.mjs +56 -0
- package/dist-boot/c-MGPIEG7I.mjs +20 -0
- package/dist-boot/c-NREXJV3M.mjs +393 -0
- package/dist-boot/c-O5PP6CTX.mjs +162 -0
- package/dist-boot/c-OBQDHSXM.mjs +1774 -0
- package/dist-boot/c-OLQHHDD4.mjs +21 -0
- package/dist-boot/c-OXW4JQQH.mjs +319 -0
- package/dist-boot/c-P3D7ZUWN.mjs +1288 -0
- package/dist-boot/c-P4PQZVV5.mjs +948 -0
- package/dist-boot/c-P63T3XL2.mjs +26373 -0
- package/dist-boot/c-P6N5DQGZ.mjs +194 -0
- package/dist-boot/c-P7MLKQFC.mjs +58 -0
- package/dist-boot/c-PB3PZJL5.mjs +1276 -0
- package/dist-boot/c-PTN4S6G2.mjs +1259 -0
- package/dist-boot/c-PYCE5J7U.mjs +1083 -0
- package/dist-boot/c-Q4HYCRLB.mjs +19410 -0
- package/dist-boot/c-QUXMETGG.mjs +68 -0
- package/dist-boot/c-RDMJZCOX.mjs +356 -0
- package/dist-boot/c-ROGJK76M.mjs +17 -0
- package/dist-boot/c-RQJJ26T4.mjs +708 -0
- package/dist-boot/c-RSKCUPJF.mjs +7559 -0
- package/dist-boot/c-RVJU4O6P.mjs +37 -0
- package/dist-boot/c-S2RVHR3M.mjs +165 -0
- package/dist-boot/c-SKMK3PEE.mjs +91120 -0
- package/dist-boot/c-TI7SM4EG.mjs +20 -0
- package/dist-boot/c-TILJ6GXD.mjs +1235 -0
- package/dist-boot/c-TT6BCUJD.mjs +114 -0
- package/dist-boot/c-U4ITOXAN.mjs +2107 -0
- package/dist-boot/c-UGERXVO2.mjs +7120 -0
- package/dist-boot/c-UPBH5AXY.mjs +1363 -0
- package/dist-boot/c-US2PUNZL.mjs +597 -0
- package/dist-boot/c-UU4WZPPE.mjs +20 -0
- package/dist-boot/c-UWVIYPQS.mjs +39 -0
- package/dist-boot/c-V4RHQBPQ.mjs +17683 -0
- package/dist-boot/c-V5MRVK47.mjs +351 -0
- package/dist-boot/c-V6CL266R.mjs +1755 -0
- package/dist-boot/c-VJTMFKYE.mjs +14975 -0
- package/dist-boot/c-VJTRUKIB.mjs +773 -0
- package/dist-boot/c-W4IFSHPW.mjs +43 -0
- package/dist-boot/c-WETGB2CF.mjs +113 -0
- package/dist-boot/c-WO3QSZUU.mjs +1337 -0
- package/dist-boot/c-WQLH73TY.mjs +242 -0
- package/dist-boot/c-XL735JW5.mjs +500 -0
- package/dist-boot/c-Y7HADL5B.mjs +1107 -0
- package/dist-boot/c-YGQHSVSK.mjs +41 -0
- package/dist-boot/c-YMP2AMEB.mjs +10350 -0
- package/dist-boot/c-YRDO2WEF.mjs +12012 -0
- package/dist-boot/c-YUSTRATJ.mjs +8 -0
- package/dist-boot/c-Z2262R22.mjs +2697 -0
- package/dist-boot/c-Z4ALQMJC.mjs +709 -0
- package/dist-boot/c-Z5ZUQVUY.mjs +62 -0
- package/dist-boot/c-ZDZUKXF7.mjs +874 -0
- package/dist-boot/c-ZJYLGIC3.mjs +32 -0
- package/dist-boot/c-ZNA5CDMI.mjs +77 -0
- package/dist-boot/c-ZSO6DI3M.mjs +204 -0
- package/dist-boot/c-ZWUVHKMK.mjs +100 -0
- package/dist-boot/c-ZY4MESEW.mjs +832 -0
- package/dist-boot/c-ZZ5REI4L.mjs +329 -0
- package/dist-boot/cli.mjs +51 -0
- package/dist-boot/ext-anthropic-attribution.mjs +207 -0
- package/dist-boot/ext-pi-background-tasks.mjs +7234 -0
- package/dist-boot/ext-pi-subagents.mjs +37 -0
- package/dist-boot/ext-privateer-account.mjs +4426 -0
- package/dist-boot/ext-privateer-brand.mjs +5274 -0
- package/dist-boot/ext-privateer-codemode.mjs +37 -0
- package/dist-boot/ext-privateer-computer.mjs +626 -0
- package/dist-boot/ext-privateer-connect.mjs +1862 -0
- package/dist-boot/ext-privateer-context.mjs +323 -0
- package/dist-boot/ext-privateer-desktop.mjs +92 -0
- package/dist-boot/ext-privateer-final-audit.mjs +48 -0
- package/dist-boot/ext-privateer-fresh.mjs +81 -0
- package/dist-boot/ext-privateer-gate.mjs +5959 -0
- package/dist-boot/ext-privateer-hints.mjs +236 -0
- package/dist-boot/ext-privateer-media.mjs +2626 -0
- package/dist-boot/ext-privateer-models.mjs +3397 -0
- package/dist-boot/ext-privateer-posture.mjs +3006 -0
- package/dist-boot/ext-privateer-privacy.mjs +4578 -0
- package/dist-boot/ext-privateer-recovery.mjs +287 -0
- package/dist-boot/ext-privateer-speak.mjs +4754 -0
- package/dist-boot/ext-privateer-terminals.mjs +725 -0
- package/dist-boot/ext-privateer-tools.mjs +528 -0
- package/dist-boot/ext-privateer-truncation.mjs +74 -0
- package/dist-boot/ext-privateer-update.mjs +210 -0
- package/dist-boot/ext-privateer-vision.mjs +148 -0
- package/dist-boot/ext-privateer-web.mjs +543 -0
- package/dist-boot/ext-rpiv-ask-user-question.mjs +710 -0
- package/dist-boot/manifest.json +9 -0
- package/extensions/privateer-brand.ts +3 -1
- package/extensions/privateer-context.ts +4 -2
- package/extensions/privateer-final-audit.ts +17 -0
- package/extensions/privateer-gate.ts +55 -9
- package/extensions/privateer-recovery.ts +175 -0
- package/extensions/privateer-web.ts +4 -4
- package/package.json +3 -1
- package/patches/@earendil-works+pi-coding-agent+1.3.0.patch +199 -2
- package/patches/pi-background-tasks+2.6.10.patch +91 -7
- package/src/cli/chat.ts +7 -1
- package/src/config/moatManifest.json +2 -0
- package/src/config/whatsNew.json +4 -4
- package/src/context.ts +33 -5
- package/src/engine/finalAudit.ts +38 -0
- package/src/engine/stallWatchdog.ts +8 -1
- package/src/providers/account.ts +34 -3
- package/src/remote/attentionPush.ts +40 -0
- package/src/remote/liveTaskSession.ts +7 -1
- package/src/remote/relayClient.ts +38 -4
- package/src/remote/remoteBridge.ts +17 -0
- package/src/remote/transcriptSnapshot.ts +104 -0
|
@@ -0,0 +1,1363 @@
|
|
|
1
|
+
import{createRequire as __pvCR}from"node:module";import{fileURLToPath as __pvF}from"node:url";import{dirname as __pvD}from"node:path";const require=__pvCR(import.meta.url);const __pvUrl=(r)=>new URL(r,import.meta.url).href;const __pvFile=(r)=>__pvF(new URL(r,import.meta.url));
|
|
2
|
+
import {
|
|
3
|
+
validateToolArguments
|
|
4
|
+
} from "./c-YRDO2WEF.mjs";
|
|
5
|
+
import {
|
|
6
|
+
parseStreamingJson
|
|
7
|
+
} from "./c-DEE67DJO.mjs";
|
|
8
|
+
import {
|
|
9
|
+
createInitialSystemMessage,
|
|
10
|
+
getCurrentSystemMessage,
|
|
11
|
+
getCurrentSystemPrompt,
|
|
12
|
+
getCurrentTools,
|
|
13
|
+
getToolStateChanges,
|
|
14
|
+
normalizeContext,
|
|
15
|
+
toToolDeclaration
|
|
16
|
+
} from "./c-WO3QSZUU.mjs";
|
|
17
|
+
import {
|
|
18
|
+
EventStream,
|
|
19
|
+
createAssistantMessageEventStream
|
|
20
|
+
} from "./c-S2RVHR3M.mjs";
|
|
21
|
+
import {
|
|
22
|
+
__export,
|
|
23
|
+
__name
|
|
24
|
+
} from "./c-CN77DCGF.mjs";
|
|
25
|
+
|
|
26
|
+
// node_modules/@earendil-works/pi-agent-core/dist/index.js
|
|
27
|
+
var dist_exports = {};
|
|
28
|
+
__export(dist_exports, {
|
|
29
|
+
Agent: () => Agent,
|
|
30
|
+
agentLoop: () => agentLoop,
|
|
31
|
+
agentLoopContinue: () => agentLoopContinue,
|
|
32
|
+
runAgentLoop: () => runAgentLoop,
|
|
33
|
+
runAgentLoopContinue: () => runAgentLoopContinue,
|
|
34
|
+
runToolCall: () => runToolCall,
|
|
35
|
+
setDefaultStreamFn: () => setDefaultStreamFn,
|
|
36
|
+
streamProxy: () => streamProxy
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// node_modules/@earendil-works/pi-agent-core/dist/stream-fn.js
|
|
40
|
+
var defaultStreamFn;
|
|
41
|
+
function setDefaultStreamFn(streamFn) {
|
|
42
|
+
defaultStreamFn = streamFn;
|
|
43
|
+
}
|
|
44
|
+
__name(setDefaultStreamFn, "setDefaultStreamFn");
|
|
45
|
+
function getDefaultStreamFn() {
|
|
46
|
+
if (!defaultStreamFn) {
|
|
47
|
+
throw new Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");
|
|
48
|
+
}
|
|
49
|
+
return defaultStreamFn;
|
|
50
|
+
}
|
|
51
|
+
__name(getDefaultStreamFn, "getDefaultStreamFn");
|
|
52
|
+
|
|
53
|
+
// node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js
|
|
54
|
+
function agentLoop(prompts, context, config, signal, streamFn) {
|
|
55
|
+
const stream = createAgentStream();
|
|
56
|
+
void runAgentLoop(prompts, context, config, async (event) => {
|
|
57
|
+
stream.push(event);
|
|
58
|
+
}, signal, streamFn).then((messages) => {
|
|
59
|
+
stream.end(messages);
|
|
60
|
+
});
|
|
61
|
+
return stream;
|
|
62
|
+
}
|
|
63
|
+
__name(agentLoop, "agentLoop");
|
|
64
|
+
function agentLoopContinue(context, config, signal, streamFn) {
|
|
65
|
+
if (context.messages.length === 0) {
|
|
66
|
+
throw new Error("Cannot continue: no messages in context");
|
|
67
|
+
}
|
|
68
|
+
if (context.messages[context.messages.length - 1].role === "assistant") {
|
|
69
|
+
throw new Error("Cannot continue from message role: assistant");
|
|
70
|
+
}
|
|
71
|
+
const stream = createAgentStream();
|
|
72
|
+
void runAgentLoopContinue(context, config, async (event) => {
|
|
73
|
+
stream.push(event);
|
|
74
|
+
}, signal, streamFn).then((messages) => {
|
|
75
|
+
stream.end(messages);
|
|
76
|
+
});
|
|
77
|
+
return stream;
|
|
78
|
+
}
|
|
79
|
+
__name(agentLoopContinue, "agentLoopContinue");
|
|
80
|
+
async function runAgentLoop(prompts, context, config, emit, signal, streamFn) {
|
|
81
|
+
const initialMessages = declareToolChanges(context, prompts);
|
|
82
|
+
const newMessages = [...initialMessages];
|
|
83
|
+
const currentContext = {
|
|
84
|
+
...context,
|
|
85
|
+
messages: [...context.messages, ...initialMessages]
|
|
86
|
+
};
|
|
87
|
+
await emit({ type: "agent_start" });
|
|
88
|
+
await emit({ type: "turn_start" });
|
|
89
|
+
for (const message of initialMessages) {
|
|
90
|
+
await emit({ type: "message_start", message });
|
|
91
|
+
await emit({ type: "message_end", message });
|
|
92
|
+
}
|
|
93
|
+
await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
|
|
94
|
+
return newMessages;
|
|
95
|
+
}
|
|
96
|
+
__name(runAgentLoop, "runAgentLoop");
|
|
97
|
+
async function runAgentLoopContinue(context, config, emit, signal, streamFn) {
|
|
98
|
+
if (context.messages.length === 0) {
|
|
99
|
+
throw new Error("Cannot continue: no messages in context");
|
|
100
|
+
}
|
|
101
|
+
if (context.messages[context.messages.length - 1].role === "assistant") {
|
|
102
|
+
throw new Error("Cannot continue from message role: assistant");
|
|
103
|
+
}
|
|
104
|
+
const newMessages = [];
|
|
105
|
+
const currentContext = { ...context };
|
|
106
|
+
await emit({ type: "agent_start" });
|
|
107
|
+
await emit({ type: "turn_start" });
|
|
108
|
+
await runLoop(currentContext, newMessages, config, signal, emit, streamFn ?? getDefaultStreamFn());
|
|
109
|
+
return newMessages;
|
|
110
|
+
}
|
|
111
|
+
__name(runAgentLoopContinue, "runAgentLoopContinue");
|
|
112
|
+
function createAgentStream() {
|
|
113
|
+
return new EventStream((event) => event.type === "agent_end", (event) => event.type === "agent_end" ? event.messages : []);
|
|
114
|
+
}
|
|
115
|
+
__name(createAgentStream, "createAgentStream");
|
|
116
|
+
async function runLoop(initialContext, newMessages, initialConfig, signal, emit, streamFunction) {
|
|
117
|
+
let currentContext = initialContext;
|
|
118
|
+
let config = initialConfig;
|
|
119
|
+
let lastCompletedTurn;
|
|
120
|
+
let explicitContinuation = false;
|
|
121
|
+
let pendingMessages = await config.getSteeringMessages?.() || [];
|
|
122
|
+
while (true) {
|
|
123
|
+
let hasMoreToolCalls = true;
|
|
124
|
+
while (hasMoreToolCalls || pendingMessages.length > 0) {
|
|
125
|
+
let preparedMessages = [];
|
|
126
|
+
if (lastCompletedTurn) {
|
|
127
|
+
const nextTurnSnapshot = await config.prepareNextTurn?.(lastCompletedTurn);
|
|
128
|
+
if (nextTurnSnapshot) {
|
|
129
|
+
currentContext = nextTurnSnapshot.context ?? currentContext;
|
|
130
|
+
preparedMessages = nextTurnSnapshot.messages ?? [];
|
|
131
|
+
config = {
|
|
132
|
+
...config,
|
|
133
|
+
model: nextTurnSnapshot.model ?? config.model,
|
|
134
|
+
reasoning: nextTurnSnapshot.thinkingLevel === void 0 ? config.reasoning : nextTurnSnapshot.thinkingLevel === "off" ? void 0 : nextTurnSnapshot.thinkingLevel
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (pendingMessages.length === 0) {
|
|
138
|
+
pendingMessages = await config.getSteeringMessages?.() || [];
|
|
139
|
+
}
|
|
140
|
+
await emit({ type: "turn_start" });
|
|
141
|
+
}
|
|
142
|
+
for (const message2 of declareToolChanges(currentContext, [...preparedMessages, ...pendingMessages])) {
|
|
143
|
+
await emit({ type: "message_start", message: message2 });
|
|
144
|
+
await emit({ type: "message_end", message: message2 });
|
|
145
|
+
currentContext.messages.push(message2);
|
|
146
|
+
newMessages.push(message2);
|
|
147
|
+
}
|
|
148
|
+
pendingMessages = [];
|
|
149
|
+
const requestUpdate = await config.prepareRequest?.({
|
|
150
|
+
context: currentContext,
|
|
151
|
+
model: config.model,
|
|
152
|
+
thinkingLevel: config.reasoning ?? "off"
|
|
153
|
+
}, signal);
|
|
154
|
+
if (requestUpdate) {
|
|
155
|
+
currentContext = requestUpdate.context ?? currentContext;
|
|
156
|
+
config = {
|
|
157
|
+
...config,
|
|
158
|
+
model: requestUpdate.model ?? config.model,
|
|
159
|
+
reasoning: requestUpdate.thinkingLevel === void 0 ? config.reasoning : requestUpdate.thinkingLevel === "off" ? void 0 : requestUpdate.thinkingLevel
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
const message = await streamAssistantResponse(currentContext, config, signal, emit, streamFunction);
|
|
163
|
+
newMessages.push(message);
|
|
164
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
165
|
+
lastCompletedTurn = {
|
|
166
|
+
message,
|
|
167
|
+
toolResults: [],
|
|
168
|
+
context: currentContext,
|
|
169
|
+
newMessages
|
|
170
|
+
};
|
|
171
|
+
await config.finishTurn?.(lastCompletedTurn, signal);
|
|
172
|
+
await emit({ type: "turn_end", message, toolResults: [] });
|
|
173
|
+
await emit({ type: "agent_end", messages: newMessages });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const toolCalls = message.content.filter((c) => c.type === "toolCall");
|
|
177
|
+
const toolResults = [];
|
|
178
|
+
hasMoreToolCalls = false;
|
|
179
|
+
if (toolCalls.length > 0) {
|
|
180
|
+
const executedToolBatch = message.stopReason === "length" ? await failToolCallsFromTruncatedMessage(toolCalls, emit) : await executeToolCalls(currentContext, message, config, signal, emit);
|
|
181
|
+
toolResults.push(...executedToolBatch.messages);
|
|
182
|
+
hasMoreToolCalls = !executedToolBatch.terminate;
|
|
183
|
+
for (const result of toolResults) {
|
|
184
|
+
currentContext.messages.push(result);
|
|
185
|
+
newMessages.push(result);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
lastCompletedTurn = {
|
|
189
|
+
message,
|
|
190
|
+
toolResults,
|
|
191
|
+
context: currentContext,
|
|
192
|
+
newMessages
|
|
193
|
+
};
|
|
194
|
+
const decision = await config.finishTurn?.(lastCompletedTurn, signal);
|
|
195
|
+
await emit({ type: "turn_end", message, toolResults });
|
|
196
|
+
if (decision?.action === "end") {
|
|
197
|
+
await emit({ type: "agent_end", messages: newMessages });
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
explicitContinuation = decision?.action === "continue";
|
|
201
|
+
pendingMessages = await config.getSteeringMessages?.() || [];
|
|
202
|
+
if (hasMoreToolCalls || pendingMessages.length > 0) {
|
|
203
|
+
explicitContinuation = false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const followUpMessages = await config.getFollowUpMessages?.() || [];
|
|
207
|
+
if (followUpMessages.length > 0) {
|
|
208
|
+
explicitContinuation = false;
|
|
209
|
+
pendingMessages = followUpMessages;
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (explicitContinuation) {
|
|
213
|
+
explicitContinuation = false;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
await emit({ type: "agent_end", messages: newMessages });
|
|
219
|
+
}
|
|
220
|
+
__name(runLoop, "runLoop");
|
|
221
|
+
function declareToolChanges(context, pendingMessages) {
|
|
222
|
+
let systemIndex = -1;
|
|
223
|
+
for (let i = pendingMessages.length - 1; i >= 0; i--) {
|
|
224
|
+
if (pendingMessages[i].role === "system") {
|
|
225
|
+
systemIndex = i;
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const pending = pendingMessages[systemIndex];
|
|
230
|
+
const baseline = pending ? pendingMessages.map((message, index2) => index2 === systemIndex ? withToolChanges(pending, NO_CHANGES) : message) : pendingMessages;
|
|
231
|
+
const changes = getToolStateChanges(getCurrentTools([...context.messages, ...baseline]), (context.tools ?? []).map(toToolDeclaration));
|
|
232
|
+
const unchanged = changes.toolsAdded.length === 0 && changes.toolsRemoved.length === 0;
|
|
233
|
+
if (pending) {
|
|
234
|
+
if (unchanged && !pending.toolsAdded?.length && !pending.toolsRemoved?.length)
|
|
235
|
+
return pendingMessages;
|
|
236
|
+
return baseline.map((message, index2) => index2 === systemIndex ? withToolChanges(pending, changes) : message);
|
|
237
|
+
}
|
|
238
|
+
if (unchanged)
|
|
239
|
+
return pendingMessages;
|
|
240
|
+
const update = withToolChanges({ role: "system", content: "", timestamp: Date.now() }, changes);
|
|
241
|
+
const insertIndex = pendingMessages.findIndex((message) => message.role !== "system");
|
|
242
|
+
const index = insertIndex === -1 ? pendingMessages.length : insertIndex;
|
|
243
|
+
return [...pendingMessages.slice(0, index), update, ...pendingMessages.slice(index)];
|
|
244
|
+
}
|
|
245
|
+
__name(declareToolChanges, "declareToolChanges");
|
|
246
|
+
var NO_CHANGES = { toolsAdded: [], toolsRemoved: [] };
|
|
247
|
+
function withToolChanges(message, { toolsAdded, toolsRemoved }) {
|
|
248
|
+
const { toolsAdded: _added, toolsRemoved: _removed, ...rest } = message;
|
|
249
|
+
return {
|
|
250
|
+
...rest,
|
|
251
|
+
...toolsAdded.length > 0 ? { toolsAdded } : {},
|
|
252
|
+
...toolsRemoved.length > 0 ? { toolsRemoved } : {}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
__name(withToolChanges, "withToolChanges");
|
|
256
|
+
async function streamAssistantResponse(context, config, signal, emit, streamFunction) {
|
|
257
|
+
let messages = context.messages;
|
|
258
|
+
if (config.transformContext) {
|
|
259
|
+
messages = await config.transformContext(messages, signal);
|
|
260
|
+
}
|
|
261
|
+
const llmMessages = await config.convertToLlm(messages);
|
|
262
|
+
const llmContext = normalizeContext({ messages: llmMessages });
|
|
263
|
+
const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : void 0) || config.apiKey;
|
|
264
|
+
const response = await streamFunction(config.model, llmContext, {
|
|
265
|
+
...config,
|
|
266
|
+
apiKey: resolvedApiKey,
|
|
267
|
+
signal
|
|
268
|
+
});
|
|
269
|
+
const result = /* @__PURE__ */ __name(async () => Object.assign(await response.result(), { thinkingLevel: config.reasoning ?? "off" }), "result");
|
|
270
|
+
let partialMessage = null;
|
|
271
|
+
let addedPartial = false;
|
|
272
|
+
for await (const event of response) {
|
|
273
|
+
switch (event.type) {
|
|
274
|
+
case "start":
|
|
275
|
+
partialMessage = event.partial;
|
|
276
|
+
context.messages.push(partialMessage);
|
|
277
|
+
addedPartial = true;
|
|
278
|
+
await emit({ type: "message_start", message: { ...partialMessage } });
|
|
279
|
+
break;
|
|
280
|
+
case "text_start":
|
|
281
|
+
case "text_delta":
|
|
282
|
+
case "text_end":
|
|
283
|
+
case "thinking_start":
|
|
284
|
+
case "thinking_delta":
|
|
285
|
+
case "thinking_end":
|
|
286
|
+
case "toolcall_start":
|
|
287
|
+
case "toolcall_delta":
|
|
288
|
+
case "toolcall_end":
|
|
289
|
+
if (partialMessage) {
|
|
290
|
+
partialMessage = event.partial;
|
|
291
|
+
context.messages[context.messages.length - 1] = partialMessage;
|
|
292
|
+
await emit({
|
|
293
|
+
type: "message_update",
|
|
294
|
+
assistantMessageEvent: event,
|
|
295
|
+
message: { ...partialMessage }
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
break;
|
|
299
|
+
case "done":
|
|
300
|
+
case "error": {
|
|
301
|
+
const finalMessage2 = await result();
|
|
302
|
+
if (addedPartial) {
|
|
303
|
+
context.messages[context.messages.length - 1] = finalMessage2;
|
|
304
|
+
} else {
|
|
305
|
+
context.messages.push(finalMessage2);
|
|
306
|
+
}
|
|
307
|
+
if (!addedPartial) {
|
|
308
|
+
await emit({ type: "message_start", message: { ...finalMessage2 } });
|
|
309
|
+
}
|
|
310
|
+
await emit({ type: "message_end", message: finalMessage2 });
|
|
311
|
+
return finalMessage2;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const finalMessage = await result();
|
|
316
|
+
if (addedPartial) {
|
|
317
|
+
context.messages[context.messages.length - 1] = finalMessage;
|
|
318
|
+
} else {
|
|
319
|
+
context.messages.push(finalMessage);
|
|
320
|
+
await emit({ type: "message_start", message: { ...finalMessage } });
|
|
321
|
+
}
|
|
322
|
+
await emit({ type: "message_end", message: finalMessage });
|
|
323
|
+
return finalMessage;
|
|
324
|
+
}
|
|
325
|
+
__name(streamAssistantResponse, "streamAssistantResponse");
|
|
326
|
+
async function failToolCallsFromTruncatedMessage(toolCalls, emit) {
|
|
327
|
+
const messages = [];
|
|
328
|
+
for (const toolCall of toolCalls) {
|
|
329
|
+
await emit({
|
|
330
|
+
type: "tool_execution_start",
|
|
331
|
+
toolCallId: toolCall.id,
|
|
332
|
+
toolName: toolCall.name,
|
|
333
|
+
args: toolCall.arguments
|
|
334
|
+
});
|
|
335
|
+
const finalized = {
|
|
336
|
+
toolCall,
|
|
337
|
+
result: createErrorToolResult(`Tool call "${toolCall.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),
|
|
338
|
+
isError: true
|
|
339
|
+
};
|
|
340
|
+
await emitToolExecutionEnd(finalized, emit);
|
|
341
|
+
const toolResultMessage = createToolResultMessage(finalized);
|
|
342
|
+
await emitToolResultMessage(toolResultMessage, emit);
|
|
343
|
+
messages.push(toolResultMessage);
|
|
344
|
+
}
|
|
345
|
+
return { messages, terminate: false };
|
|
346
|
+
}
|
|
347
|
+
__name(failToolCallsFromTruncatedMessage, "failToolCallsFromTruncatedMessage");
|
|
348
|
+
async function executeToolCalls(currentContext, assistantMessage, config, signal, emit) {
|
|
349
|
+
const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
|
|
350
|
+
const hasSequentialToolCall = toolCalls.some((tc) => currentContext.tools?.find((t) => t.name === tc.name)?.executionMode === "sequential");
|
|
351
|
+
if (config.toolExecution === "sequential" || hasSequentialToolCall) {
|
|
352
|
+
return executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit);
|
|
353
|
+
}
|
|
354
|
+
return executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit);
|
|
355
|
+
}
|
|
356
|
+
__name(executeToolCalls, "executeToolCalls");
|
|
357
|
+
async function executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit) {
|
|
358
|
+
const finalizedCalls = [];
|
|
359
|
+
const messages = [];
|
|
360
|
+
for (const toolCall of toolCalls) {
|
|
361
|
+
await emit({
|
|
362
|
+
type: "tool_execution_start",
|
|
363
|
+
toolCallId: toolCall.id,
|
|
364
|
+
toolName: toolCall.name,
|
|
365
|
+
args: toolCall.arguments
|
|
366
|
+
});
|
|
367
|
+
const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
|
|
368
|
+
let finalized;
|
|
369
|
+
if (preparation.kind === "immediate") {
|
|
370
|
+
finalized = {
|
|
371
|
+
toolCall,
|
|
372
|
+
result: preparation.result,
|
|
373
|
+
isError: preparation.isError
|
|
374
|
+
};
|
|
375
|
+
} else {
|
|
376
|
+
const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
|
|
377
|
+
finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
|
|
378
|
+
}
|
|
379
|
+
await emitToolExecutionEnd(finalized, emit);
|
|
380
|
+
const toolResultMessage = createToolResultMessage(finalized);
|
|
381
|
+
await emitToolResultMessage(toolResultMessage, emit);
|
|
382
|
+
finalizedCalls.push(finalized);
|
|
383
|
+
messages.push(toolResultMessage);
|
|
384
|
+
if (signal?.aborted) {
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
return {
|
|
389
|
+
messages,
|
|
390
|
+
terminate: shouldTerminateToolBatch(finalizedCalls)
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
__name(executeToolCallsSequential, "executeToolCallsSequential");
|
|
394
|
+
async function executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit) {
|
|
395
|
+
const finalizedCalls = [];
|
|
396
|
+
for (const toolCall of toolCalls) {
|
|
397
|
+
await emit({
|
|
398
|
+
type: "tool_execution_start",
|
|
399
|
+
toolCallId: toolCall.id,
|
|
400
|
+
toolName: toolCall.name,
|
|
401
|
+
args: toolCall.arguments
|
|
402
|
+
});
|
|
403
|
+
const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, config, signal);
|
|
404
|
+
if (preparation.kind === "immediate") {
|
|
405
|
+
const finalized = {
|
|
406
|
+
toolCall,
|
|
407
|
+
result: preparation.result,
|
|
408
|
+
isError: preparation.isError
|
|
409
|
+
};
|
|
410
|
+
await emitToolExecutionEnd(finalized, emit);
|
|
411
|
+
finalizedCalls.push(finalized);
|
|
412
|
+
if (signal?.aborted) {
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
finalizedCalls.push(async () => {
|
|
418
|
+
if (signal?.aborted) {
|
|
419
|
+
const finalized2 = {
|
|
420
|
+
toolCall,
|
|
421
|
+
result: createErrorToolResult("Operation aborted"),
|
|
422
|
+
isError: true
|
|
423
|
+
};
|
|
424
|
+
await emitToolExecutionEnd(finalized2, emit);
|
|
425
|
+
return finalized2;
|
|
426
|
+
}
|
|
427
|
+
const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(toolCall, emit));
|
|
428
|
+
const finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
|
|
429
|
+
await emitToolExecutionEnd(finalized, emit);
|
|
430
|
+
return finalized;
|
|
431
|
+
});
|
|
432
|
+
if (signal?.aborted) {
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const orderedFinalizedCalls = await Promise.all(finalizedCalls.map((entry) => typeof entry === "function" ? entry() : Promise.resolve(entry)));
|
|
437
|
+
const messages = [];
|
|
438
|
+
for (const finalized of orderedFinalizedCalls) {
|
|
439
|
+
const toolResultMessage = createToolResultMessage(finalized);
|
|
440
|
+
await emitToolResultMessage(toolResultMessage, emit);
|
|
441
|
+
messages.push(toolResultMessage);
|
|
442
|
+
}
|
|
443
|
+
return {
|
|
444
|
+
messages,
|
|
445
|
+
terminate: shouldTerminateToolBatch(orderedFinalizedCalls)
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
__name(executeToolCallsParallel, "executeToolCallsParallel");
|
|
449
|
+
function shouldTerminateToolBatch(finalizedCalls) {
|
|
450
|
+
return finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);
|
|
451
|
+
}
|
|
452
|
+
__name(shouldTerminateToolBatch, "shouldTerminateToolBatch");
|
|
453
|
+
function prepareToolCallArguments(tool, toolCall) {
|
|
454
|
+
if (!tool.prepareArguments) {
|
|
455
|
+
return toolCall;
|
|
456
|
+
}
|
|
457
|
+
const preparedArguments = tool.prepareArguments(toolCall.arguments);
|
|
458
|
+
if (preparedArguments === toolCall.arguments) {
|
|
459
|
+
return toolCall;
|
|
460
|
+
}
|
|
461
|
+
return {
|
|
462
|
+
...toolCall,
|
|
463
|
+
arguments: preparedArguments
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
__name(prepareToolCallArguments, "prepareToolCallArguments");
|
|
467
|
+
async function prepareToolCall(currentContext, assistantMessage, toolCall, config, signal, tools = currentContext.tools ?? []) {
|
|
468
|
+
const tool = tools.find((t) => t.name === toolCall.name);
|
|
469
|
+
if (!tool) {
|
|
470
|
+
return {
|
|
471
|
+
kind: "immediate",
|
|
472
|
+
result: createErrorToolResult(`Tool ${toolCall.name} not found`),
|
|
473
|
+
isError: true
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
const preparedToolCall = prepareToolCallArguments(tool, toolCall);
|
|
478
|
+
const validatedArgs = validateToolArguments(tool, preparedToolCall);
|
|
479
|
+
if (config.beforeToolCall) {
|
|
480
|
+
const beforeResult = await config.beforeToolCall({
|
|
481
|
+
assistantMessage,
|
|
482
|
+
toolCall,
|
|
483
|
+
args: validatedArgs,
|
|
484
|
+
context: currentContext
|
|
485
|
+
}, signal);
|
|
486
|
+
if (signal?.aborted) {
|
|
487
|
+
return {
|
|
488
|
+
kind: "immediate",
|
|
489
|
+
result: createErrorToolResult("Operation aborted"),
|
|
490
|
+
isError: true
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
if (beforeResult?.block) {
|
|
494
|
+
const result = createErrorToolResult(beforeResult.reason || "Tool execution was blocked");
|
|
495
|
+
if (beforeResult.terminate === true) {
|
|
496
|
+
result.terminate = true;
|
|
497
|
+
}
|
|
498
|
+
return {
|
|
499
|
+
kind: "immediate",
|
|
500
|
+
result,
|
|
501
|
+
isError: true
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (signal?.aborted) {
|
|
506
|
+
return {
|
|
507
|
+
kind: "immediate",
|
|
508
|
+
result: createErrorToolResult("Operation aborted"),
|
|
509
|
+
isError: true
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
return {
|
|
513
|
+
kind: "prepared",
|
|
514
|
+
toolCall,
|
|
515
|
+
tool,
|
|
516
|
+
args: validatedArgs
|
|
517
|
+
};
|
|
518
|
+
} catch (error) {
|
|
519
|
+
return {
|
|
520
|
+
kind: "immediate",
|
|
521
|
+
result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
|
|
522
|
+
isError: true
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
__name(prepareToolCall, "prepareToolCall");
|
|
527
|
+
function emitToolExecutionUpdate(toolCall, emit) {
|
|
528
|
+
return (partialResult) => emit({
|
|
529
|
+
type: "tool_execution_update",
|
|
530
|
+
toolCallId: toolCall.id,
|
|
531
|
+
toolName: toolCall.name,
|
|
532
|
+
args: toolCall.arguments,
|
|
533
|
+
partialResult
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
__name(emitToolExecutionUpdate, "emitToolExecutionUpdate");
|
|
537
|
+
async function runToolCall(toolCall, options) {
|
|
538
|
+
const { assistantMessage, context, signal } = options;
|
|
539
|
+
const preparation = await prepareToolCall(context, assistantMessage, toolCall, options, signal, options.tools);
|
|
540
|
+
if (preparation.kind === "immediate") {
|
|
541
|
+
return { toolCall, result: preparation.result, isError: preparation.isError };
|
|
542
|
+
}
|
|
543
|
+
const executed = await executePreparedToolCall(preparation, signal, options.onUpdate ?? (() => {
|
|
544
|
+
}));
|
|
545
|
+
return finalizeExecutedToolCall(context, assistantMessage, preparation, executed, options, signal);
|
|
546
|
+
}
|
|
547
|
+
__name(runToolCall, "runToolCall");
|
|
548
|
+
async function executePreparedToolCall(prepared, signal, onUpdate) {
|
|
549
|
+
const updateEvents = [];
|
|
550
|
+
let acceptingUpdates = true;
|
|
551
|
+
const startedAt = performance.now();
|
|
552
|
+
const elapsed = /* @__PURE__ */ __name(() => Math.round(performance.now() - startedAt), "elapsed");
|
|
553
|
+
try {
|
|
554
|
+
const result = await prepared.tool.execute(prepared.toolCall.id, prepared.args, signal, (partialResult) => {
|
|
555
|
+
if (!acceptingUpdates)
|
|
556
|
+
return;
|
|
557
|
+
updateEvents.push(Promise.resolve(onUpdate(partialResult)));
|
|
558
|
+
});
|
|
559
|
+
const durationMs = elapsed();
|
|
560
|
+
acceptingUpdates = false;
|
|
561
|
+
await Promise.all(updateEvents);
|
|
562
|
+
return { result, isError: result.isError === true, durationMs };
|
|
563
|
+
} catch (error) {
|
|
564
|
+
const durationMs = elapsed();
|
|
565
|
+
acceptingUpdates = false;
|
|
566
|
+
await Promise.all(updateEvents);
|
|
567
|
+
return {
|
|
568
|
+
result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
|
|
569
|
+
isError: true,
|
|
570
|
+
durationMs
|
|
571
|
+
};
|
|
572
|
+
} finally {
|
|
573
|
+
acceptingUpdates = false;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
__name(executePreparedToolCall, "executePreparedToolCall");
|
|
577
|
+
async function finalizeExecutedToolCall(currentContext, assistantMessage, prepared, executed, config, signal) {
|
|
578
|
+
let result = executed.result;
|
|
579
|
+
let isError = executed.isError;
|
|
580
|
+
if (config.afterToolCall) {
|
|
581
|
+
try {
|
|
582
|
+
const afterResult = await config.afterToolCall({
|
|
583
|
+
assistantMessage,
|
|
584
|
+
toolCall: prepared.toolCall,
|
|
585
|
+
args: prepared.args,
|
|
586
|
+
result,
|
|
587
|
+
isError,
|
|
588
|
+
context: currentContext
|
|
589
|
+
}, signal);
|
|
590
|
+
if (afterResult) {
|
|
591
|
+
const structuredContent = afterResult.structuredContent ?? (afterResult.content ? void 0 : result.structuredContent);
|
|
592
|
+
result = {
|
|
593
|
+
...result,
|
|
594
|
+
content: afterResult.content ?? result.content,
|
|
595
|
+
details: afterResult.details ?? result.details,
|
|
596
|
+
usage: afterResult.usage ?? result.usage,
|
|
597
|
+
terminate: afterResult.terminate ?? result.terminate
|
|
598
|
+
};
|
|
599
|
+
if (structuredContent === void 0)
|
|
600
|
+
delete result.structuredContent;
|
|
601
|
+
else
|
|
602
|
+
result.structuredContent = structuredContent;
|
|
603
|
+
isError = afterResult.isError ?? isError;
|
|
604
|
+
}
|
|
605
|
+
} catch (error) {
|
|
606
|
+
result = createErrorToolResult(error instanceof Error ? error.message : String(error));
|
|
607
|
+
isError = true;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return {
|
|
611
|
+
toolCall: prepared.toolCall,
|
|
612
|
+
result,
|
|
613
|
+
isError,
|
|
614
|
+
durationMs: executed.durationMs
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
__name(finalizeExecutedToolCall, "finalizeExecutedToolCall");
|
|
618
|
+
function createErrorToolResult(message) {
|
|
619
|
+
return {
|
|
620
|
+
content: [{ type: "text", text: message }],
|
|
621
|
+
details: {}
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
__name(createErrorToolResult, "createErrorToolResult");
|
|
625
|
+
async function emitToolExecutionEnd(finalized, emit) {
|
|
626
|
+
await emit({
|
|
627
|
+
type: "tool_execution_end",
|
|
628
|
+
toolCallId: finalized.toolCall.id,
|
|
629
|
+
toolName: finalized.toolCall.name,
|
|
630
|
+
result: finalized.result,
|
|
631
|
+
isError: finalized.isError,
|
|
632
|
+
...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs }
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
__name(emitToolExecutionEnd, "emitToolExecutionEnd");
|
|
636
|
+
function createToolResultMessage(finalized) {
|
|
637
|
+
return {
|
|
638
|
+
role: "toolResult",
|
|
639
|
+
toolCallId: finalized.toolCall.id,
|
|
640
|
+
toolName: finalized.toolCall.name,
|
|
641
|
+
// Untyped tools (JS extensions) can return results without content; normalize
|
|
642
|
+
// so the null never enters session history or provider payloads.
|
|
643
|
+
content: finalized.result.content ?? [],
|
|
644
|
+
details: finalized.result.details,
|
|
645
|
+
usage: finalized.result.usage,
|
|
646
|
+
isError: finalized.isError,
|
|
647
|
+
...finalized.durationMs === void 0 ? {} : { durationMs: finalized.durationMs },
|
|
648
|
+
timestamp: Date.now()
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
__name(createToolResultMessage, "createToolResultMessage");
|
|
652
|
+
async function emitToolResultMessage(toolResultMessage, emit) {
|
|
653
|
+
await emit({ type: "message_start", message: toolResultMessage });
|
|
654
|
+
await emit({ type: "message_end", message: toolResultMessage });
|
|
655
|
+
}
|
|
656
|
+
__name(emitToolResultMessage, "emitToolResultMessage");
|
|
657
|
+
|
|
658
|
+
// node_modules/@earendil-works/pi-agent-core/dist/agent.js
|
|
659
|
+
function defaultConvertToLlm(messages) {
|
|
660
|
+
return messages.filter((message) => message.role === "system" || message.role === "user" || message.role === "assistant" || message.role === "toolResult");
|
|
661
|
+
}
|
|
662
|
+
__name(defaultConvertToLlm, "defaultConvertToLlm");
|
|
663
|
+
var EMPTY_USAGE = {
|
|
664
|
+
input: 0,
|
|
665
|
+
output: 0,
|
|
666
|
+
cacheRead: 0,
|
|
667
|
+
cacheWrite: 0,
|
|
668
|
+
totalTokens: 0,
|
|
669
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
670
|
+
};
|
|
671
|
+
var DEFAULT_MODEL = {
|
|
672
|
+
id: "unknown",
|
|
673
|
+
name: "unknown",
|
|
674
|
+
api: "unknown",
|
|
675
|
+
provider: "unknown",
|
|
676
|
+
baseUrl: "",
|
|
677
|
+
reasoning: false,
|
|
678
|
+
input: [],
|
|
679
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
680
|
+
contextWindow: 0,
|
|
681
|
+
maxTokens: 0
|
|
682
|
+
};
|
|
683
|
+
function createMutableAgentState(initialState) {
|
|
684
|
+
let tools = initialState?.tools?.slice() ?? [];
|
|
685
|
+
let messages = initialState?.messages?.slice() ?? [];
|
|
686
|
+
const initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));
|
|
687
|
+
if (messages[0]?.role !== "system" && initialMessage)
|
|
688
|
+
messages.unshift(initialMessage);
|
|
689
|
+
return {
|
|
690
|
+
get systemPrompt() {
|
|
691
|
+
return getCurrentSystemPrompt(messages);
|
|
692
|
+
},
|
|
693
|
+
model: initialState?.model ?? DEFAULT_MODEL,
|
|
694
|
+
thinkingLevel: initialState?.thinkingLevel ?? "off",
|
|
695
|
+
get tools() {
|
|
696
|
+
return tools;
|
|
697
|
+
},
|
|
698
|
+
set tools(nextTools) {
|
|
699
|
+
tools = nextTools.slice();
|
|
700
|
+
},
|
|
701
|
+
get messages() {
|
|
702
|
+
return messages;
|
|
703
|
+
},
|
|
704
|
+
set messages(nextMessages) {
|
|
705
|
+
messages = nextMessages.slice();
|
|
706
|
+
},
|
|
707
|
+
isStreaming: false,
|
|
708
|
+
streamingMessage: void 0,
|
|
709
|
+
pendingToolCalls: /* @__PURE__ */ new Set(),
|
|
710
|
+
errorMessage: void 0
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
__name(createMutableAgentState, "createMutableAgentState");
|
|
714
|
+
var PendingMessageQueue = class {
|
|
715
|
+
static {
|
|
716
|
+
__name(this, "PendingMessageQueue");
|
|
717
|
+
}
|
|
718
|
+
messages = [];
|
|
719
|
+
mode;
|
|
720
|
+
constructor(mode) {
|
|
721
|
+
this.mode = mode;
|
|
722
|
+
}
|
|
723
|
+
enqueue(message) {
|
|
724
|
+
this.messages.push(message);
|
|
725
|
+
}
|
|
726
|
+
hasItems() {
|
|
727
|
+
return this.messages.length > 0;
|
|
728
|
+
}
|
|
729
|
+
peek() {
|
|
730
|
+
if (this.mode === "all")
|
|
731
|
+
return this.messages.slice();
|
|
732
|
+
const first = this.messages[0];
|
|
733
|
+
return first ? [first] : [];
|
|
734
|
+
}
|
|
735
|
+
drain() {
|
|
736
|
+
const drained = this.peek();
|
|
737
|
+
this.messages = this.messages.slice(drained.length);
|
|
738
|
+
return drained;
|
|
739
|
+
}
|
|
740
|
+
clear() {
|
|
741
|
+
this.messages = [];
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
var Agent = class {
|
|
745
|
+
static {
|
|
746
|
+
__name(this, "Agent");
|
|
747
|
+
}
|
|
748
|
+
_state;
|
|
749
|
+
listeners = /* @__PURE__ */ new Set();
|
|
750
|
+
steeringQueue;
|
|
751
|
+
followUpQueue;
|
|
752
|
+
convertToLlm;
|
|
753
|
+
transformContext;
|
|
754
|
+
streamFunction;
|
|
755
|
+
getApiKey;
|
|
756
|
+
onPayload;
|
|
757
|
+
onResponse;
|
|
758
|
+
onProviderStreamEvent;
|
|
759
|
+
beforeToolCall;
|
|
760
|
+
afterToolCall;
|
|
761
|
+
finishTurn;
|
|
762
|
+
prepareRequest;
|
|
763
|
+
prepareNextTurn;
|
|
764
|
+
prepareNextTurnWithContext;
|
|
765
|
+
activeRun;
|
|
766
|
+
/** Session identifier forwarded to providers for cache-aware backends. */
|
|
767
|
+
sessionId;
|
|
768
|
+
/** Optional per-level thinking token budgets forwarded to the stream function. */
|
|
769
|
+
thinkingBudgets;
|
|
770
|
+
/** Preferred transport forwarded to the stream function. */
|
|
771
|
+
transport;
|
|
772
|
+
/** Optional cap for provider-requested retry delays. */
|
|
773
|
+
maxRetryDelayMs;
|
|
774
|
+
/** Tool execution strategy for assistant messages that contain multiple tool calls. */
|
|
775
|
+
toolExecution;
|
|
776
|
+
constructor(options) {
|
|
777
|
+
const runtimeOptions = options ?? {};
|
|
778
|
+
this._state = createMutableAgentState(runtimeOptions.initialState);
|
|
779
|
+
this.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;
|
|
780
|
+
this.transformContext = runtimeOptions.transformContext;
|
|
781
|
+
this.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();
|
|
782
|
+
this.getApiKey = runtimeOptions.getApiKey;
|
|
783
|
+
this.onPayload = runtimeOptions.onPayload;
|
|
784
|
+
this.onResponse = runtimeOptions.onResponse;
|
|
785
|
+
this.onProviderStreamEvent = runtimeOptions.onProviderStreamEvent;
|
|
786
|
+
this.beforeToolCall = runtimeOptions.beforeToolCall;
|
|
787
|
+
this.afterToolCall = runtimeOptions.afterToolCall;
|
|
788
|
+
this.finishTurn = runtimeOptions.finishTurn;
|
|
789
|
+
this.prepareRequest = runtimeOptions.prepareRequest;
|
|
790
|
+
this.prepareNextTurn = runtimeOptions.prepareNextTurn;
|
|
791
|
+
this.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;
|
|
792
|
+
this.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? "one-at-a-time");
|
|
793
|
+
this.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? "one-at-a-time");
|
|
794
|
+
this.sessionId = runtimeOptions.sessionId;
|
|
795
|
+
this.thinkingBudgets = runtimeOptions.thinkingBudgets;
|
|
796
|
+
this.transport = runtimeOptions.transport ?? "auto";
|
|
797
|
+
this.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;
|
|
798
|
+
this.toolExecution = runtimeOptions.toolExecution ?? "parallel";
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Subscribe to agent lifecycle events.
|
|
802
|
+
*
|
|
803
|
+
* Listener promises are awaited in subscription order and are included in
|
|
804
|
+
* the current run's settlement. Listeners also receive the active abort
|
|
805
|
+
* signal for the current run.
|
|
806
|
+
*
|
|
807
|
+
* `agent_end` is the final emitted event for a run, but the agent does not
|
|
808
|
+
* become idle until all awaited listeners for that event have settled.
|
|
809
|
+
*/
|
|
810
|
+
subscribe(listener) {
|
|
811
|
+
this.listeners.add(listener);
|
|
812
|
+
return () => this.listeners.delete(listener);
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Current agent state.
|
|
816
|
+
*
|
|
817
|
+
* Assigning `state.tools` or `state.messages` copies the provided top-level array.
|
|
818
|
+
*/
|
|
819
|
+
get state() {
|
|
820
|
+
return this._state;
|
|
821
|
+
}
|
|
822
|
+
/** Controls how queued steering messages are drained. */
|
|
823
|
+
set steeringMode(mode) {
|
|
824
|
+
this.steeringQueue.mode = mode;
|
|
825
|
+
}
|
|
826
|
+
get steeringMode() {
|
|
827
|
+
return this.steeringQueue.mode;
|
|
828
|
+
}
|
|
829
|
+
/** Controls how queued follow-up messages are drained. */
|
|
830
|
+
set followUpMode(mode) {
|
|
831
|
+
this.followUpQueue.mode = mode;
|
|
832
|
+
}
|
|
833
|
+
get followUpMode() {
|
|
834
|
+
return this.followUpQueue.mode;
|
|
835
|
+
}
|
|
836
|
+
/** Queue a message to be injected after the current assistant turn finishes. */
|
|
837
|
+
steer(message) {
|
|
838
|
+
this.steeringQueue.enqueue(message);
|
|
839
|
+
}
|
|
840
|
+
/** Queue a message to run only after the agent would otherwise stop. */
|
|
841
|
+
followUp(message) {
|
|
842
|
+
this.followUpQueue.enqueue(message);
|
|
843
|
+
}
|
|
844
|
+
/** Remove all queued steering messages. */
|
|
845
|
+
clearSteeringQueue() {
|
|
846
|
+
this.steeringQueue.clear();
|
|
847
|
+
}
|
|
848
|
+
/** Remove all queued follow-up messages. */
|
|
849
|
+
clearFollowUpQueue() {
|
|
850
|
+
this.followUpQueue.clear();
|
|
851
|
+
}
|
|
852
|
+
/** Remove all queued steering and follow-up messages. */
|
|
853
|
+
clearAllQueues() {
|
|
854
|
+
this.clearSteeringQueue();
|
|
855
|
+
this.clearFollowUpQueue();
|
|
856
|
+
}
|
|
857
|
+
/** Returns true when either queue still contains pending messages. */
|
|
858
|
+
hasQueuedMessages() {
|
|
859
|
+
return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
|
|
860
|
+
}
|
|
861
|
+
/** Preview the messages selected for the next turn without consuming them. */
|
|
862
|
+
peekQueuedMessages() {
|
|
863
|
+
const steering = this.steeringQueue.peek();
|
|
864
|
+
return steering.length > 0 ? steering : this.followUpQueue.peek();
|
|
865
|
+
}
|
|
866
|
+
/** Active abort signal for the current run, if any. */
|
|
867
|
+
get signal() {
|
|
868
|
+
return this.activeRun?.abortController.signal;
|
|
869
|
+
}
|
|
870
|
+
/** Abort the current run, if one is active. */
|
|
871
|
+
abort() {
|
|
872
|
+
this.activeRun?.abortController.abort();
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Resolve when the current run and all awaited event listeners have finished.
|
|
876
|
+
*
|
|
877
|
+
* This resolves after `agent_end` listeners settle.
|
|
878
|
+
*/
|
|
879
|
+
waitForIdle() {
|
|
880
|
+
return this.activeRun?.promise ?? Promise.resolve();
|
|
881
|
+
}
|
|
882
|
+
/** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */
|
|
883
|
+
reset() {
|
|
884
|
+
if (this.activeRun) {
|
|
885
|
+
throw new Error("Agent is already processing. Wait for completion before resetting.");
|
|
886
|
+
}
|
|
887
|
+
const baseline = getCurrentSystemMessage(this._state.messages);
|
|
888
|
+
this._state.messages = baseline ? [baseline] : [];
|
|
889
|
+
this._state.isStreaming = false;
|
|
890
|
+
this._state.streamingMessage = void 0;
|
|
891
|
+
this._state.pendingToolCalls = /* @__PURE__ */ new Set();
|
|
892
|
+
this._state.errorMessage = void 0;
|
|
893
|
+
this.clearFollowUpQueue();
|
|
894
|
+
this.clearSteeringQueue();
|
|
895
|
+
}
|
|
896
|
+
async prompt(input, images) {
|
|
897
|
+
if (this.activeRun) {
|
|
898
|
+
throw new Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");
|
|
899
|
+
}
|
|
900
|
+
const messages = this.normalizePromptInput(input, images);
|
|
901
|
+
await this.runPromptMessages(messages);
|
|
902
|
+
}
|
|
903
|
+
/** Continue from the current transcript. The last message must be a user or tool-result message. */
|
|
904
|
+
async continue() {
|
|
905
|
+
if (this.activeRun) {
|
|
906
|
+
throw new Error("Agent is already processing. Wait for completion before continuing.");
|
|
907
|
+
}
|
|
908
|
+
const lastMessage = this._state.messages[this._state.messages.length - 1];
|
|
909
|
+
if (!lastMessage || this._state.messages.every((message) => message.role === "system")) {
|
|
910
|
+
throw new Error("No messages to continue from");
|
|
911
|
+
}
|
|
912
|
+
if (lastMessage.role === "assistant") {
|
|
913
|
+
const queuedSteering = this.steeringQueue.drain();
|
|
914
|
+
if (queuedSteering.length > 0) {
|
|
915
|
+
await this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
const queuedFollowUps = this.followUpQueue.drain();
|
|
919
|
+
if (queuedFollowUps.length > 0) {
|
|
920
|
+
await this.runPromptMessages(queuedFollowUps);
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
throw new Error("Cannot continue from message role: assistant");
|
|
924
|
+
}
|
|
925
|
+
await this.runContinuation();
|
|
926
|
+
}
|
|
927
|
+
normalizePromptInput(input, images) {
|
|
928
|
+
if (Array.isArray(input)) {
|
|
929
|
+
return input;
|
|
930
|
+
}
|
|
931
|
+
if (typeof input !== "string") {
|
|
932
|
+
return [input];
|
|
933
|
+
}
|
|
934
|
+
const content = [{ type: "text", text: input }];
|
|
935
|
+
if (images && images.length > 0) {
|
|
936
|
+
content.push(...images);
|
|
937
|
+
}
|
|
938
|
+
return [{ role: "user", content, timestamp: Date.now() }];
|
|
939
|
+
}
|
|
940
|
+
async runPromptMessages(messages, options = {}) {
|
|
941
|
+
await this.runWithLifecycle(async (signal) => {
|
|
942
|
+
await runAgentLoop(messages, this.createContextSnapshot(), this.createLoopConfig(options), (event) => this.processEvents(event), signal, this.streamFunction);
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
async runContinuation() {
|
|
946
|
+
await this.runWithLifecycle(async (signal) => {
|
|
947
|
+
await runAgentLoopContinue(this.createContextSnapshot(), this.createLoopConfig(), (event) => this.processEvents(event), signal, this.streamFunction);
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
createContextSnapshot() {
|
|
951
|
+
return {
|
|
952
|
+
messages: this._state.messages.slice(),
|
|
953
|
+
tools: this._state.tools.slice()
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
createLoopConfig(options = {}) {
|
|
957
|
+
let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
|
|
958
|
+
return {
|
|
959
|
+
model: this._state.model,
|
|
960
|
+
reasoning: this._state.thinkingLevel === "off" ? void 0 : this._state.thinkingLevel,
|
|
961
|
+
sessionId: this.sessionId,
|
|
962
|
+
onPayload: this.onPayload,
|
|
963
|
+
onResponse: this.onResponse,
|
|
964
|
+
onProviderStreamEvent: this.onProviderStreamEvent,
|
|
965
|
+
transport: this.transport,
|
|
966
|
+
thinkingBudgets: this.thinkingBudgets,
|
|
967
|
+
maxRetryDelayMs: this.maxRetryDelayMs,
|
|
968
|
+
toolExecution: this.toolExecution,
|
|
969
|
+
beforeToolCall: this.beforeToolCall,
|
|
970
|
+
afterToolCall: this.afterToolCall,
|
|
971
|
+
finishTurn: this.finishTurn,
|
|
972
|
+
prepareRequest: this.prepareRequest,
|
|
973
|
+
prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn ? async (context) => {
|
|
974
|
+
if (this.prepareNextTurnWithContext) {
|
|
975
|
+
return await this.prepareNextTurnWithContext(context, this.signal);
|
|
976
|
+
}
|
|
977
|
+
return await this.prepareNextTurn?.(this.signal);
|
|
978
|
+
} : void 0,
|
|
979
|
+
convertToLlm: this.convertToLlm,
|
|
980
|
+
transformContext: this.transformContext,
|
|
981
|
+
getApiKey: this.getApiKey,
|
|
982
|
+
getSteeringMessages: /* @__PURE__ */ __name(async () => {
|
|
983
|
+
if (skipInitialSteeringPoll) {
|
|
984
|
+
skipInitialSteeringPoll = false;
|
|
985
|
+
return [];
|
|
986
|
+
}
|
|
987
|
+
return this.steeringQueue.drain();
|
|
988
|
+
}, "getSteeringMessages"),
|
|
989
|
+
getFollowUpMessages: /* @__PURE__ */ __name(async () => this.followUpQueue.drain(), "getFollowUpMessages")
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
async runWithLifecycle(executor) {
|
|
993
|
+
if (this.activeRun) {
|
|
994
|
+
throw new Error("Agent is already processing.");
|
|
995
|
+
}
|
|
996
|
+
const abortController = new AbortController();
|
|
997
|
+
let resolvePromise = /* @__PURE__ */ __name(() => {
|
|
998
|
+
}, "resolvePromise");
|
|
999
|
+
const promise = new Promise((resolve) => {
|
|
1000
|
+
resolvePromise = resolve;
|
|
1001
|
+
});
|
|
1002
|
+
this.activeRun = { promise, resolve: resolvePromise, abortController };
|
|
1003
|
+
this._state.isStreaming = true;
|
|
1004
|
+
this._state.streamingMessage = void 0;
|
|
1005
|
+
this._state.errorMessage = void 0;
|
|
1006
|
+
try {
|
|
1007
|
+
await executor(abortController.signal);
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
await this.handleRunFailure(error, abortController.signal.aborted);
|
|
1010
|
+
} finally {
|
|
1011
|
+
this.finishRun();
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
async handleRunFailure(error, aborted) {
|
|
1015
|
+
const failureMessage = {
|
|
1016
|
+
role: "assistant",
|
|
1017
|
+
content: [{ type: "text", text: "" }],
|
|
1018
|
+
api: this._state.model.api,
|
|
1019
|
+
provider: this._state.model.provider,
|
|
1020
|
+
model: this._state.model.id,
|
|
1021
|
+
usage: EMPTY_USAGE,
|
|
1022
|
+
stopReason: aborted ? "aborted" : "error",
|
|
1023
|
+
errorMessage: error instanceof Error ? error.message : String(error),
|
|
1024
|
+
timestamp: Date.now()
|
|
1025
|
+
};
|
|
1026
|
+
await this.processEvents({ type: "message_start", message: failureMessage });
|
|
1027
|
+
await this.processEvents({ type: "message_end", message: failureMessage });
|
|
1028
|
+
await this.processEvents({ type: "turn_end", message: failureMessage, toolResults: [] });
|
|
1029
|
+
await this.processEvents({ type: "agent_end", messages: [failureMessage] });
|
|
1030
|
+
}
|
|
1031
|
+
finishRun() {
|
|
1032
|
+
this._state.isStreaming = false;
|
|
1033
|
+
this._state.streamingMessage = void 0;
|
|
1034
|
+
this._state.pendingToolCalls = /* @__PURE__ */ new Set();
|
|
1035
|
+
this.activeRun?.resolve();
|
|
1036
|
+
this.activeRun = void 0;
|
|
1037
|
+
}
|
|
1038
|
+
/**
|
|
1039
|
+
* Reduce internal state for a loop event, then await listeners.
|
|
1040
|
+
*
|
|
1041
|
+
* `agent_end` only means no further loop events will be emitted. The run is
|
|
1042
|
+
* considered idle later, after all awaited listeners for `agent_end` finish
|
|
1043
|
+
* and `finishRun()` clears runtime-owned state.
|
|
1044
|
+
*/
|
|
1045
|
+
async processEvents(event) {
|
|
1046
|
+
switch (event.type) {
|
|
1047
|
+
case "message_start":
|
|
1048
|
+
this._state.streamingMessage = event.message;
|
|
1049
|
+
break;
|
|
1050
|
+
case "message_update":
|
|
1051
|
+
this._state.streamingMessage = event.message;
|
|
1052
|
+
break;
|
|
1053
|
+
case "message_end":
|
|
1054
|
+
this._state.streamingMessage = void 0;
|
|
1055
|
+
this._state.messages.push(event.message);
|
|
1056
|
+
break;
|
|
1057
|
+
case "tool_execution_start": {
|
|
1058
|
+
const pendingToolCalls = new Set(this._state.pendingToolCalls);
|
|
1059
|
+
pendingToolCalls.add(event.toolCallId);
|
|
1060
|
+
this._state.pendingToolCalls = pendingToolCalls;
|
|
1061
|
+
break;
|
|
1062
|
+
}
|
|
1063
|
+
case "tool_execution_end": {
|
|
1064
|
+
const pendingToolCalls = new Set(this._state.pendingToolCalls);
|
|
1065
|
+
pendingToolCalls.delete(event.toolCallId);
|
|
1066
|
+
this._state.pendingToolCalls = pendingToolCalls;
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
case "turn_end":
|
|
1070
|
+
if (event.message.role === "assistant" && event.message.errorMessage) {
|
|
1071
|
+
this._state.errorMessage = event.message.errorMessage;
|
|
1072
|
+
}
|
|
1073
|
+
break;
|
|
1074
|
+
case "agent_end":
|
|
1075
|
+
this._state.streamingMessage = void 0;
|
|
1076
|
+
break;
|
|
1077
|
+
}
|
|
1078
|
+
const signal = this.activeRun?.abortController.signal;
|
|
1079
|
+
if (!signal) {
|
|
1080
|
+
throw new Error("Agent listener invoked outside active run");
|
|
1081
|
+
}
|
|
1082
|
+
for (const listener of this.listeners) {
|
|
1083
|
+
await listener(event, signal);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
|
|
1088
|
+
// node_modules/@earendil-works/pi-agent-core/dist/proxy.js
|
|
1089
|
+
function buildProxyRequestOptions(options) {
|
|
1090
|
+
return {
|
|
1091
|
+
temperature: options.temperature,
|
|
1092
|
+
samplingParams: options.samplingParams,
|
|
1093
|
+
maxTokens: options.maxTokens,
|
|
1094
|
+
reasoning: options.reasoning,
|
|
1095
|
+
cacheRetention: options.cacheRetention,
|
|
1096
|
+
sessionId: options.sessionId,
|
|
1097
|
+
headers: options.headers,
|
|
1098
|
+
metadata: options.metadata,
|
|
1099
|
+
transport: options.transport,
|
|
1100
|
+
thinkingBudgets: options.thinkingBudgets,
|
|
1101
|
+
maxRetryDelayMs: options.maxRetryDelayMs
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
__name(buildProxyRequestOptions, "buildProxyRequestOptions");
|
|
1105
|
+
function streamProxy(model, context, options) {
|
|
1106
|
+
const stream = createAssistantMessageEventStream();
|
|
1107
|
+
(async () => {
|
|
1108
|
+
const partial = {
|
|
1109
|
+
role: "assistant",
|
|
1110
|
+
stopReason: "pending",
|
|
1111
|
+
content: [],
|
|
1112
|
+
api: model.api,
|
|
1113
|
+
provider: model.provider,
|
|
1114
|
+
model: model.id,
|
|
1115
|
+
usage: {
|
|
1116
|
+
input: 0,
|
|
1117
|
+
output: 0,
|
|
1118
|
+
cacheRead: 0,
|
|
1119
|
+
cacheWrite: 0,
|
|
1120
|
+
totalTokens: 0,
|
|
1121
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
1122
|
+
},
|
|
1123
|
+
timestamp: Date.now()
|
|
1124
|
+
};
|
|
1125
|
+
let reader;
|
|
1126
|
+
const abortHandler = /* @__PURE__ */ __name(() => {
|
|
1127
|
+
if (reader) {
|
|
1128
|
+
reader.cancel("Request aborted by user").catch(() => {
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
}, "abortHandler");
|
|
1132
|
+
if (options.signal) {
|
|
1133
|
+
options.signal.addEventListener("abort", abortHandler);
|
|
1134
|
+
}
|
|
1135
|
+
try {
|
|
1136
|
+
const response = await fetch(`${options.proxyUrl}/api/stream`, {
|
|
1137
|
+
method: "POST",
|
|
1138
|
+
headers: {
|
|
1139
|
+
Authorization: `Bearer ${options.authToken}`,
|
|
1140
|
+
"Content-Type": "application/json"
|
|
1141
|
+
},
|
|
1142
|
+
body: JSON.stringify({
|
|
1143
|
+
model,
|
|
1144
|
+
context,
|
|
1145
|
+
options: buildProxyRequestOptions(options)
|
|
1146
|
+
}),
|
|
1147
|
+
signal: options.signal
|
|
1148
|
+
});
|
|
1149
|
+
if (!response.ok) {
|
|
1150
|
+
let errorMessage = `Proxy error: ${response.status} ${response.statusText}`;
|
|
1151
|
+
try {
|
|
1152
|
+
const errorData = await response.json();
|
|
1153
|
+
if (errorData.error) {
|
|
1154
|
+
errorMessage = `Proxy error: ${errorData.error}`;
|
|
1155
|
+
}
|
|
1156
|
+
} catch {
|
|
1157
|
+
}
|
|
1158
|
+
throw new Error(errorMessage);
|
|
1159
|
+
}
|
|
1160
|
+
reader = response.body.getReader();
|
|
1161
|
+
const decoder = new TextDecoder();
|
|
1162
|
+
let buffer = "";
|
|
1163
|
+
let sawTerminalEvent = false;
|
|
1164
|
+
const processLine = /* @__PURE__ */ __name((line) => {
|
|
1165
|
+
if (!line.startsWith("data: "))
|
|
1166
|
+
return;
|
|
1167
|
+
const data = line.slice(6).trim();
|
|
1168
|
+
if (!data)
|
|
1169
|
+
return;
|
|
1170
|
+
const proxyEvent = JSON.parse(data);
|
|
1171
|
+
const event = processProxyEvent(proxyEvent, partial);
|
|
1172
|
+
if (event) {
|
|
1173
|
+
if (event.type === "done" || event.type === "error")
|
|
1174
|
+
sawTerminalEvent = true;
|
|
1175
|
+
stream.push(event);
|
|
1176
|
+
}
|
|
1177
|
+
}, "processLine");
|
|
1178
|
+
while (true) {
|
|
1179
|
+
const { done, value } = await reader.read();
|
|
1180
|
+
if (done)
|
|
1181
|
+
break;
|
|
1182
|
+
if (options.signal?.aborted) {
|
|
1183
|
+
throw new Error("Request aborted by user");
|
|
1184
|
+
}
|
|
1185
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1186
|
+
const lines = buffer.split("\n");
|
|
1187
|
+
buffer = lines.pop() || "";
|
|
1188
|
+
for (const line of lines) {
|
|
1189
|
+
processLine(line);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (options.signal?.aborted) {
|
|
1193
|
+
throw new Error("Request aborted by user");
|
|
1194
|
+
}
|
|
1195
|
+
buffer += decoder.decode();
|
|
1196
|
+
if (buffer) {
|
|
1197
|
+
processLine(buffer);
|
|
1198
|
+
}
|
|
1199
|
+
if (!sawTerminalEvent) {
|
|
1200
|
+
partial.stopReason = "error";
|
|
1201
|
+
partial.errorMessage = "Connection closed by proxy server before the response completed";
|
|
1202
|
+
stream.push({
|
|
1203
|
+
type: "error",
|
|
1204
|
+
reason: "error",
|
|
1205
|
+
error: partial
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
stream.end();
|
|
1209
|
+
} catch (error) {
|
|
1210
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1211
|
+
const reason = options.signal?.aborted ? "aborted" : "error";
|
|
1212
|
+
partial.stopReason = reason;
|
|
1213
|
+
partial.errorMessage = errorMessage;
|
|
1214
|
+
stream.push({
|
|
1215
|
+
type: "error",
|
|
1216
|
+
reason,
|
|
1217
|
+
error: partial
|
|
1218
|
+
});
|
|
1219
|
+
stream.end();
|
|
1220
|
+
} finally {
|
|
1221
|
+
if (options.signal) {
|
|
1222
|
+
options.signal.removeEventListener("abort", abortHandler);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
})();
|
|
1226
|
+
return stream;
|
|
1227
|
+
}
|
|
1228
|
+
__name(streamProxy, "streamProxy");
|
|
1229
|
+
function processProxyEvent(proxyEvent, partial) {
|
|
1230
|
+
switch (proxyEvent.type) {
|
|
1231
|
+
case "start":
|
|
1232
|
+
return { type: "start", partial };
|
|
1233
|
+
case "text_start":
|
|
1234
|
+
partial.content[proxyEvent.contentIndex] = { type: "text", text: "" };
|
|
1235
|
+
return { type: "text_start", contentIndex: proxyEvent.contentIndex, partial };
|
|
1236
|
+
case "text_delta": {
|
|
1237
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1238
|
+
if (content?.type === "text") {
|
|
1239
|
+
content.text += proxyEvent.delta;
|
|
1240
|
+
return {
|
|
1241
|
+
type: "text_delta",
|
|
1242
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1243
|
+
delta: proxyEvent.delta,
|
|
1244
|
+
partial
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
throw new Error("Received text_delta for non-text content");
|
|
1248
|
+
}
|
|
1249
|
+
case "text_end": {
|
|
1250
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1251
|
+
if (content?.type === "text") {
|
|
1252
|
+
content.textSignature = proxyEvent.contentSignature;
|
|
1253
|
+
return {
|
|
1254
|
+
type: "text_end",
|
|
1255
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1256
|
+
content: content.text,
|
|
1257
|
+
partial
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
throw new Error("Received text_end for non-text content");
|
|
1261
|
+
}
|
|
1262
|
+
case "thinking_start":
|
|
1263
|
+
partial.content[proxyEvent.contentIndex] = { type: "thinking", thinking: "" };
|
|
1264
|
+
return { type: "thinking_start", contentIndex: proxyEvent.contentIndex, partial };
|
|
1265
|
+
case "thinking_delta": {
|
|
1266
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1267
|
+
if (content?.type === "thinking") {
|
|
1268
|
+
content.thinking += proxyEvent.delta;
|
|
1269
|
+
return {
|
|
1270
|
+
type: "thinking_delta",
|
|
1271
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1272
|
+
delta: proxyEvent.delta,
|
|
1273
|
+
partial
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
throw new Error("Received thinking_delta for non-thinking content");
|
|
1277
|
+
}
|
|
1278
|
+
case "thinking_end": {
|
|
1279
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1280
|
+
if (content?.type === "thinking") {
|
|
1281
|
+
content.thinkingSignature = proxyEvent.contentSignature;
|
|
1282
|
+
return {
|
|
1283
|
+
type: "thinking_end",
|
|
1284
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1285
|
+
content: content.thinking,
|
|
1286
|
+
partial
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
throw new Error("Received thinking_end for non-thinking content");
|
|
1290
|
+
}
|
|
1291
|
+
case "toolcall_start":
|
|
1292
|
+
partial.content[proxyEvent.contentIndex] = {
|
|
1293
|
+
type: "toolCall",
|
|
1294
|
+
id: proxyEvent.id,
|
|
1295
|
+
name: proxyEvent.toolName,
|
|
1296
|
+
arguments: {},
|
|
1297
|
+
partialJson: ""
|
|
1298
|
+
};
|
|
1299
|
+
return { type: "toolcall_start", contentIndex: proxyEvent.contentIndex, partial };
|
|
1300
|
+
case "toolcall_delta": {
|
|
1301
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1302
|
+
if (content?.type === "toolCall") {
|
|
1303
|
+
content.partialJson += proxyEvent.delta;
|
|
1304
|
+
content.arguments = parseStreamingJson(content.partialJson) || {};
|
|
1305
|
+
partial.content[proxyEvent.contentIndex] = { ...content };
|
|
1306
|
+
return {
|
|
1307
|
+
type: "toolcall_delta",
|
|
1308
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1309
|
+
delta: proxyEvent.delta,
|
|
1310
|
+
partial
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
throw new Error("Received toolcall_delta for non-toolCall content");
|
|
1314
|
+
}
|
|
1315
|
+
case "toolcall_end": {
|
|
1316
|
+
const content = partial.content[proxyEvent.contentIndex];
|
|
1317
|
+
if (content?.type === "toolCall") {
|
|
1318
|
+
Object.assign(content, proxyEvent.toolCall);
|
|
1319
|
+
delete content.partialJson;
|
|
1320
|
+
return {
|
|
1321
|
+
type: "toolcall_end",
|
|
1322
|
+
contentIndex: proxyEvent.contentIndex,
|
|
1323
|
+
toolCall: content,
|
|
1324
|
+
partial
|
|
1325
|
+
};
|
|
1326
|
+
}
|
|
1327
|
+
return void 0;
|
|
1328
|
+
}
|
|
1329
|
+
case "done":
|
|
1330
|
+
partial.stopReason = proxyEvent.reason;
|
|
1331
|
+
partial.usage = proxyEvent.usage;
|
|
1332
|
+
if (proxyEvent.providerThinkingLevel !== void 0) {
|
|
1333
|
+
partial.providerThinkingLevel = proxyEvent.providerThinkingLevel;
|
|
1334
|
+
}
|
|
1335
|
+
return { type: "done", reason: proxyEvent.reason, message: partial };
|
|
1336
|
+
case "error":
|
|
1337
|
+
partial.stopReason = proxyEvent.reason;
|
|
1338
|
+
partial.errorMessage = proxyEvent.errorMessage;
|
|
1339
|
+
partial.usage = proxyEvent.usage;
|
|
1340
|
+
if (proxyEvent.providerThinkingLevel !== void 0) {
|
|
1341
|
+
partial.providerThinkingLevel = proxyEvent.providerThinkingLevel;
|
|
1342
|
+
}
|
|
1343
|
+
return { type: "error", reason: proxyEvent.reason, error: partial };
|
|
1344
|
+
default: {
|
|
1345
|
+
const _exhaustiveCheck = proxyEvent;
|
|
1346
|
+
console.warn(`Unhandled proxy event type: ${proxyEvent.type}`);
|
|
1347
|
+
return void 0;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
__name(processProxyEvent, "processProxyEvent");
|
|
1352
|
+
|
|
1353
|
+
export {
|
|
1354
|
+
setDefaultStreamFn,
|
|
1355
|
+
agentLoop,
|
|
1356
|
+
agentLoopContinue,
|
|
1357
|
+
runAgentLoop,
|
|
1358
|
+
runAgentLoopContinue,
|
|
1359
|
+
runToolCall,
|
|
1360
|
+
Agent,
|
|
1361
|
+
streamProxy,
|
|
1362
|
+
dist_exports
|
|
1363
|
+
};
|