agent.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import {
  2. type ImageContent,
  3. type Message,
  4. type Model,
  5. type SimpleStreamOptions,
  6. streamSimple,
  7. type TextContent,
  8. type ThinkingBudgets,
  9. type Transport,
  10. } from "@earendil-works/pi-ai";
  11. import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.ts";
  12. import type {
  13. AfterToolCallContext,
  14. AfterToolCallResult,
  15. AgentContext,
  16. AgentEvent,
  17. AgentLoopConfig,
  18. AgentLoopTurnUpdate,
  19. AgentMessage,
  20. AgentState,
  21. AgentTool,
  22. BeforeToolCallContext,
  23. BeforeToolCallResult,
  24. QueueMode,
  25. ShouldStopAfterTurnContext,
  26. StreamFn,
  27. ToolExecutionMode,
  28. } from "./types.ts";
  29. export type { QueueMode } from "./types.ts";
  30. function defaultConvertToLlm(messages: AgentMessage[]): Message[] {
  31. return messages.filter(
  32. (message) => message.role === "user" || message.role === "assistant" || message.role === "toolResult",
  33. );
  34. }
  35. const EMPTY_USAGE = {
  36. input: 0,
  37. output: 0,
  38. cacheRead: 0,
  39. cacheWrite: 0,
  40. totalTokens: 0,
  41. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
  42. };
  43. const DEFAULT_MODEL = {
  44. id: "unknown",
  45. name: "unknown",
  46. api: "unknown",
  47. provider: "unknown",
  48. baseUrl: "",
  49. reasoning: false,
  50. input: [],
  51. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  52. contextWindow: 0,
  53. maxTokens: 0,
  54. } satisfies Model<any>;
  55. type MutableAgentState = Omit<AgentState, "isStreaming" | "streamingMessage" | "pendingToolCalls" | "errorMessage"> & {
  56. isStreaming: boolean;
  57. streamingMessage?: AgentMessage;
  58. pendingToolCalls: Set<string>;
  59. errorMessage?: string;
  60. };
  61. function createMutableAgentState(
  62. initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>,
  63. ): MutableAgentState {
  64. let tools = initialState?.tools?.slice() ?? [];
  65. let messages = initialState?.messages?.slice() ?? [];
  66. return {
  67. systemPrompt: initialState?.systemPrompt ?? "",
  68. model: initialState?.model ?? DEFAULT_MODEL,
  69. thinkingLevel: initialState?.thinkingLevel ?? "off",
  70. get tools() {
  71. return tools;
  72. },
  73. set tools(nextTools: AgentTool<any>[]) {
  74. tools = nextTools.slice();
  75. },
  76. get messages() {
  77. return messages;
  78. },
  79. set messages(nextMessages: AgentMessage[]) {
  80. messages = nextMessages.slice();
  81. },
  82. isStreaming: false,
  83. streamingMessage: undefined,
  84. pendingToolCalls: new Set<string>(),
  85. errorMessage: undefined,
  86. };
  87. }
  88. /** Options for constructing an {@link Agent}. */
  89. export interface AgentOptions {
  90. initialState?: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
  91. convertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
  92. transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
  93. streamFn?: StreamFn;
  94. getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
  95. onPayload?: SimpleStreamOptions["onPayload"];
  96. onResponse?: SimpleStreamOptions["onResponse"];
  97. beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
  98. onToolExecutionStart?: (context: BeforeToolCallContext) => void;
  99. afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
  100. prepareNextTurn?: (
  101. signal?: AbortSignal,
  102. ) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
  103. shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
  104. shouldStopAfterSteering?: () => boolean | Promise<boolean>;
  105. steeringMode?: QueueMode;
  106. followUpMode?: QueueMode;
  107. sessionId?: string;
  108. thinkingBudgets?: ThinkingBudgets;
  109. transport?: Transport;
  110. maxRetryDelayMs?: number;
  111. toolExecution?: ToolExecutionMode;
  112. }
  113. class PendingMessageQueue {
  114. private messages: AgentMessage[][] = [];
  115. public mode: QueueMode;
  116. constructor(mode: QueueMode) {
  117. this.mode = mode;
  118. }
  119. enqueue(message: AgentMessage): void {
  120. this.messages.push([message]);
  121. }
  122. enqueueBatch(messages: readonly AgentMessage[]): void {
  123. if (messages.length > 0) this.messages.push([...messages]);
  124. }
  125. hasItems(): boolean {
  126. return this.messages.length > 0;
  127. }
  128. drain(): AgentMessage[] {
  129. if (this.mode === "all") {
  130. const drained = this.messages.flat();
  131. this.messages = [];
  132. return drained;
  133. }
  134. const first = this.messages[0];
  135. if (!first) {
  136. return [];
  137. }
  138. this.messages = this.messages.slice(1);
  139. return first;
  140. }
  141. clear(): void {
  142. this.messages = [];
  143. }
  144. }
  145. type ActiveRun = {
  146. promise: Promise<void>;
  147. resolve: () => void;
  148. abortController: AbortController;
  149. };
  150. /**
  151. * Stateful wrapper around the low-level agent loop.
  152. *
  153. * `Agent` owns the current transcript, emits lifecycle events, executes tools,
  154. * and exposes queueing APIs for steering and follow-up messages.
  155. */
  156. export class Agent {
  157. private _state: MutableAgentState;
  158. private readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();
  159. private readonly steeringQueue: PendingMessageQueue;
  160. private readonly followUpQueue: PendingMessageQueue;
  161. public convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;
  162. public transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;
  163. public streamFn: StreamFn;
  164. public getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;
  165. public onPayload?: SimpleStreamOptions["onPayload"];
  166. public onResponse?: SimpleStreamOptions["onResponse"];
  167. public beforeToolCall?: (
  168. context: BeforeToolCallContext,
  169. signal?: AbortSignal,
  170. ) => Promise<BeforeToolCallResult | undefined>;
  171. public onToolExecutionStart?: (context: BeforeToolCallContext) => void;
  172. public afterToolCall?: (
  173. context: AfterToolCallContext,
  174. signal?: AbortSignal,
  175. ) => Promise<AfterToolCallResult | undefined>;
  176. public prepareNextTurn?: (
  177. signal?: AbortSignal,
  178. ) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
  179. public shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext) => boolean | Promise<boolean>;
  180. public shouldStopAfterSteering?: () => boolean | Promise<boolean>;
  181. private activeRun?: ActiveRun;
  182. /** Session identifier forwarded to providers for cache-aware backends. */
  183. public sessionId?: string;
  184. /** Optional per-level thinking token budgets forwarded to the stream function. */
  185. public thinkingBudgets?: ThinkingBudgets;
  186. /** Preferred transport forwarded to the stream function. */
  187. public transport: Transport;
  188. /** Optional cap for provider-requested retry delays. */
  189. public maxRetryDelayMs?: number;
  190. /** Tool execution strategy for assistant messages that contain multiple tool calls. */
  191. public toolExecution: ToolExecutionMode;
  192. constructor(options: AgentOptions = {}) {
  193. this._state = createMutableAgentState(options.initialState);
  194. this.convertToLlm = options.convertToLlm ?? defaultConvertToLlm;
  195. this.transformContext = options.transformContext;
  196. this.streamFn = options.streamFn ?? streamSimple;
  197. this.getApiKey = options.getApiKey;
  198. this.onPayload = options.onPayload;
  199. this.onResponse = options.onResponse;
  200. this.beforeToolCall = options.beforeToolCall;
  201. this.onToolExecutionStart = options.onToolExecutionStart;
  202. this.afterToolCall = options.afterToolCall;
  203. this.prepareNextTurn = options.prepareNextTurn;
  204. this.shouldStopAfterTurn = options.shouldStopAfterTurn;
  205. this.shouldStopAfterSteering = options.shouldStopAfterSteering;
  206. this.steeringQueue = new PendingMessageQueue(options.steeringMode ?? "one-at-a-time");
  207. this.followUpQueue = new PendingMessageQueue(options.followUpMode ?? "one-at-a-time");
  208. this.sessionId = options.sessionId;
  209. this.thinkingBudgets = options.thinkingBudgets;
  210. this.transport = options.transport ?? "auto";
  211. this.maxRetryDelayMs = options.maxRetryDelayMs;
  212. this.toolExecution = options.toolExecution ?? "parallel";
  213. }
  214. /**
  215. * Subscribe to agent lifecycle events.
  216. *
  217. * Listener promises are awaited in subscription order and are included in
  218. * the current run's settlement. Listeners also receive the active abort
  219. * signal for the current run.
  220. *
  221. * `agent_end` is the final emitted event for a run, but the agent does not
  222. * become idle until all awaited listeners for that event have settled.
  223. */
  224. subscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {
  225. this.listeners.add(listener);
  226. return () => this.listeners.delete(listener);
  227. }
  228. /**
  229. * Current agent state.
  230. *
  231. * Assigning `state.tools` or `state.messages` copies the provided top-level array.
  232. */
  233. get state(): AgentState {
  234. return this._state;
  235. }
  236. /** Controls how queued steering messages are drained. */
  237. set steeringMode(mode: QueueMode) {
  238. this.steeringQueue.mode = mode;
  239. }
  240. get steeringMode(): QueueMode {
  241. return this.steeringQueue.mode;
  242. }
  243. /** Controls how queued follow-up messages are drained. */
  244. set followUpMode(mode: QueueMode) {
  245. this.followUpQueue.mode = mode;
  246. }
  247. get followUpMode(): QueueMode {
  248. return this.followUpQueue.mode;
  249. }
  250. /** Queue a message to be injected after the current assistant turn finishes. */
  251. steer(message: AgentMessage): void {
  252. this.steeringQueue.enqueue(message);
  253. }
  254. /** Queue an explicit atomic group for one steering consumption boundary. */
  255. steerBatch(messages: readonly AgentMessage[]): void {
  256. this.steeringQueue.enqueueBatch(messages);
  257. }
  258. /** Queue a message to run only after the agent would otherwise stop. */
  259. followUp(message: AgentMessage): void {
  260. this.followUpQueue.enqueue(message);
  261. }
  262. /** Remove all queued steering messages. */
  263. clearSteeringQueue(): void {
  264. this.steeringQueue.clear();
  265. }
  266. /** Remove all queued follow-up messages. */
  267. clearFollowUpQueue(): void {
  268. this.followUpQueue.clear();
  269. }
  270. /** Remove all queued steering and follow-up messages. */
  271. clearAllQueues(): void {
  272. this.clearSteeringQueue();
  273. this.clearFollowUpQueue();
  274. }
  275. /** Returns true when either queue still contains pending messages. */
  276. hasQueuedMessages(): boolean {
  277. return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
  278. }
  279. /** Active abort signal for the current run, if any. */
  280. get signal(): AbortSignal | undefined {
  281. return this.activeRun?.abortController.signal;
  282. }
  283. /** Abort the current run, if one is active. */
  284. abort(): void {
  285. this.activeRun?.abortController.abort();
  286. }
  287. /**
  288. * Resolve when the current run and all awaited event listeners have finished.
  289. *
  290. * This resolves after `agent_end` listeners settle.
  291. */
  292. waitForIdle(): Promise<void> {
  293. return this.activeRun?.promise ?? Promise.resolve();
  294. }
  295. /** Clear transcript state, runtime state, and queued messages. */
  296. reset(): void {
  297. this._state.messages = [];
  298. this._state.isStreaming = false;
  299. this._state.streamingMessage = undefined;
  300. this._state.pendingToolCalls = new Set<string>();
  301. this._state.errorMessage = undefined;
  302. this.clearFollowUpQueue();
  303. this.clearSteeringQueue();
  304. }
  305. /** Start a new prompt from text, a single message, or a batch of messages. */
  306. async prompt(message: AgentMessage | AgentMessage[]): Promise<void>;
  307. async prompt(input: string, images?: ImageContent[]): Promise<void>;
  308. async prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {
  309. if (this.activeRun) {
  310. throw new Error(
  311. "Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.",
  312. );
  313. }
  314. const messages = this.normalizePromptInput(input, images);
  315. await this.runPromptMessages(messages);
  316. }
  317. /** Continue from the current transcript. The last message must be a user or tool-result message. */
  318. async continue(): Promise<void> {
  319. if (this.activeRun) {
  320. throw new Error("Agent is already processing. Wait for completion before continuing.");
  321. }
  322. const lastMessage = this._state.messages[this._state.messages.length - 1];
  323. if (!lastMessage) {
  324. throw new Error("No messages to continue from");
  325. }
  326. if (lastMessage.role === "assistant") {
  327. const queuedSteering = this.steeringQueue.drain();
  328. if (queuedSteering.length > 0) {
  329. await this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });
  330. return;
  331. }
  332. const queuedFollowUps = this.followUpQueue.drain();
  333. if (queuedFollowUps.length > 0) {
  334. await this.runPromptMessages(queuedFollowUps);
  335. return;
  336. }
  337. throw new Error("Cannot continue from message role: assistant");
  338. }
  339. await this.runContinuation();
  340. }
  341. private normalizePromptInput(
  342. input: string | AgentMessage | AgentMessage[],
  343. images?: ImageContent[],
  344. ): AgentMessage[] {
  345. if (Array.isArray(input)) {
  346. return input;
  347. }
  348. if (typeof input !== "string") {
  349. return [input];
  350. }
  351. const content: Array<TextContent | ImageContent> = [{ type: "text", text: input }];
  352. if (images && images.length > 0) {
  353. content.push(...images);
  354. }
  355. return [{ role: "user", content, timestamp: Date.now() }];
  356. }
  357. private async runPromptMessages(
  358. messages: AgentMessage[],
  359. options: { skipInitialSteeringPoll?: boolean } = {},
  360. ): Promise<void> {
  361. await this.runWithLifecycle(async (signal) => {
  362. await runAgentLoop(
  363. messages,
  364. this.createContextSnapshot(),
  365. this.createLoopConfig(options),
  366. (event) => this.processEvents(event),
  367. signal,
  368. this.streamFn,
  369. );
  370. });
  371. }
  372. private async runContinuation(): Promise<void> {
  373. await this.runWithLifecycle(async (signal) => {
  374. await runAgentLoopContinue(
  375. this.createContextSnapshot(),
  376. this.createLoopConfig(),
  377. (event) => this.processEvents(event),
  378. signal,
  379. this.streamFn,
  380. );
  381. });
  382. }
  383. private createContextSnapshot(): AgentContext {
  384. return {
  385. systemPrompt: this._state.systemPrompt,
  386. messages: this._state.messages.slice(),
  387. tools: this._state.tools.slice(),
  388. };
  389. }
  390. private createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {
  391. let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
  392. return {
  393. model: this._state.model,
  394. reasoning: this._state.thinkingLevel === "off" ? undefined : this._state.thinkingLevel,
  395. sessionId: this.sessionId,
  396. onPayload: this.onPayload,
  397. onResponse: this.onResponse,
  398. transport: this.transport,
  399. thinkingBudgets: this.thinkingBudgets,
  400. maxRetryDelayMs: this.maxRetryDelayMs,
  401. toolExecution: this.toolExecution,
  402. beforeToolCall: this.beforeToolCall,
  403. onToolExecutionStart: this.onToolExecutionStart,
  404. afterToolCall: this.afterToolCall,
  405. prepareNextTurn: this.prepareNextTurn ? async () => await this.prepareNextTurn?.(this.signal) : undefined,
  406. shouldStopAfterTurn: this.shouldStopAfterTurn,
  407. shouldStopAfterSteering: this.shouldStopAfterSteering,
  408. convertToLlm: this.convertToLlm,
  409. transformContext: this.transformContext,
  410. getApiKey: this.getApiKey,
  411. getSteeringMessages: async () => {
  412. if (skipInitialSteeringPoll) {
  413. skipInitialSteeringPoll = false;
  414. return [];
  415. }
  416. return this.steeringQueue.drain();
  417. },
  418. getFollowUpMessages: async () => this.followUpQueue.drain(),
  419. };
  420. }
  421. private async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {
  422. if (this.activeRun) {
  423. throw new Error("Agent is already processing.");
  424. }
  425. const abortController = new AbortController();
  426. let resolvePromise = () => {};
  427. const promise = new Promise<void>((resolve) => {
  428. resolvePromise = resolve;
  429. });
  430. this.activeRun = { promise, resolve: resolvePromise, abortController };
  431. this._state.isStreaming = true;
  432. this._state.streamingMessage = undefined;
  433. this._state.errorMessage = undefined;
  434. try {
  435. await executor(abortController.signal);
  436. } catch (error) {
  437. await this.handleRunFailure(error, abortController.signal.aborted);
  438. } finally {
  439. this.finishRun();
  440. }
  441. }
  442. private async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {
  443. const failureMessage = {
  444. role: "assistant",
  445. content: [{ type: "text", text: "" }],
  446. api: this._state.model.api,
  447. provider: this._state.model.provider,
  448. model: this._state.model.id,
  449. usage: EMPTY_USAGE,
  450. stopReason: aborted ? "aborted" : "error",
  451. errorMessage: error instanceof Error ? error.message : String(error),
  452. timestamp: Date.now(),
  453. } satisfies AgentMessage;
  454. await this.processEvents({ type: "message_start", message: failureMessage });
  455. await this.processEvents({ type: "message_end", message: failureMessage });
  456. await this.processEvents({ type: "turn_end", message: failureMessage, toolResults: [] });
  457. await this.processEvents({ type: "agent_end", messages: [failureMessage] });
  458. }
  459. private finishRun(): void {
  460. this._state.isStreaming = false;
  461. this._state.streamingMessage = undefined;
  462. this._state.pendingToolCalls = new Set<string>();
  463. this.activeRun?.resolve();
  464. this.activeRun = undefined;
  465. }
  466. /**
  467. * Reduce internal state for a loop event, then await listeners.
  468. *
  469. * `agent_end` only means no further loop events will be emitted. The run is
  470. * considered idle later, after all awaited listeners for `agent_end` finish
  471. * and `finishRun()` clears runtime-owned state.
  472. */
  473. private async processEvents(event: AgentEvent): Promise<void> {
  474. switch (event.type) {
  475. case "message_start":
  476. this._state.streamingMessage = event.message;
  477. break;
  478. case "message_update":
  479. this._state.streamingMessage = event.message;
  480. break;
  481. case "message_end":
  482. this._state.streamingMessage = undefined;
  483. this._state.messages.push(event.message);
  484. break;
  485. case "tool_execution_start": {
  486. const pendingToolCalls = new Set(this._state.pendingToolCalls);
  487. pendingToolCalls.add(event.toolCallId);
  488. this._state.pendingToolCalls = pendingToolCalls;
  489. break;
  490. }
  491. case "tool_execution_end": {
  492. const pendingToolCalls = new Set(this._state.pendingToolCalls);
  493. pendingToolCalls.delete(event.toolCallId);
  494. this._state.pendingToolCalls = pendingToolCalls;
  495. break;
  496. }
  497. case "turn_end":
  498. if (event.message.role === "assistant" && event.message.errorMessage) {
  499. this._state.errorMessage = event.message.errorMessage;
  500. }
  501. break;
  502. case "agent_end":
  503. this._state.streamingMessage = undefined;
  504. break;
  505. }
  506. const signal = this.activeRun?.abortController.signal;
  507. if (!signal) {
  508. throw new Error("Agent listener invoked outside active run");
  509. }
  510. for (const listener of this.listeners) {
  511. await listener(event, signal);
  512. }
  513. }
  514. }