@earendil-works/pi-agent-core 0.86.1 → 0.87.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ImageContent, type Message, type SimpleStreamOptions, type ThinkingBudgets, type Transport } from "@earendil-works/pi-ai";
2
- import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentLoopTurnUpdate, AgentMessage, AgentState, BeforeToolCallContext, BeforeToolCallResult, PrepareNextTurnContext, QueueMode, ShouldStopAfterTurnContext, StreamFn, ToolExecutionMode } from "./types.ts";
2
+ import type { AfterToolCallContext, AfterToolCallResult, AgentEvent, AgentLoopTurnUpdate, AgentMessage, AgentState, BeforeToolCallContext, BeforeToolCallResult, FinishTurn, PrepareNextTurnContext, PrepareRequest, QueueMode, StreamFn, ToolExecutionMode } from "./types.ts";
3
3
  export type { QueueMode } from "./types.ts";
4
4
  /** Initial state for {@link Agent}. `systemPrompt` and `tools` become the leading system message unless `messages` already starts with one. */
5
5
  export type AgentInitialState = Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | "streamingMessage" | "errorMessage">>;
@@ -14,7 +14,8 @@ export interface AgentOptions {
14
14
  onResponse?: SimpleStreamOptions["onResponse"];
15
15
  beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
16
16
  afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
17
- shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;
17
+ finishTurn?: FinishTurn;
18
+ prepareRequest?: PrepareRequest;
18
19
  prepareNextTurn?: (signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
19
20
  prepareNextTurnWithContext?: (context: PrepareNextTurnContext, signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
20
21
  steeringMode?: QueueMode;
@@ -44,7 +45,8 @@ export declare class Agent {
44
45
  onResponse?: SimpleStreamOptions["onResponse"];
45
46
  beforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;
46
47
  afterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;
47
- shouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;
48
+ finishTurn?: FinishTurn;
49
+ prepareRequest?: PrepareRequest;
48
50
  prepareNextTurn?: (signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
49
51
  prepareNextTurnWithContext?: (context: PrepareNextTurnContext, signal?: AbortSignal) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;
50
52
  private activeRun?;
@@ -94,6 +96,8 @@ export declare class Agent {
94
96
  clearAllQueues(): void;
95
97
  /** Returns true when either queue still contains pending messages. */
96
98
  hasQueuedMessages(): boolean;
99
+ /** Preview the messages selected for the next turn without consuming them. */
100
+ peekQueuedMessages(): AgentMessage[];
97
101
  /** Active abort signal for the current run, if any. */
98
102
  get signal(): AbortSignal | undefined;
99
103
  /** Abort the current run, if one is active. */
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAExB,KAAK,eAAe,EACpB,KAAK,SAAS,EAEd,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,mBAAmB,EACnB,YAAY,EACZ,UAAU,EAEV,qBAAqB,EACrB,oBAAoB,EACpB,sBAAsB,EACtB,SAAS,EACT,0BAA0B,EAC1B,QAAQ,EACR,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3B","sourcesContent":["import {\n\tcreateInitialSystemMessage,\n\tgetCurrentSystemMessage,\n\tgetCurrentSystemPrompt,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n\ttoToolDeclaration,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) =>\n\t\t\tmessage.role === \"system\" ||\n\t\t\tmessage.role === \"user\" ||\n\t\t\tmessage.role === \"assistant\" ||\n\t\t\tmessage.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\n/** Initial state for {@link Agent}. `systemPrompt` and `tools` become the leading system message unless `messages` already starts with one. */\nexport type AgentInitialState = Partial<\n\tOmit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">\n>;\n\nfunction createMutableAgentState(initialState?: AgentInitialState): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\tconst initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));\n\tif (messages[0]?.role !== \"system\" && initialMessage) messages.unshift(initialMessage);\n\n\treturn {\n\t\tget systemPrompt() {\n\t\t\treturn getCurrentSystemPrompt(messages);\n\t\t},\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: AgentInitialState;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic shouldStopAfterTurn?: (\n\t\tcontext: ShouldStopAfterTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => boolean | Promise<boolean>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tconst baseline = getCurrentSystemMessage(this._state.messages);\n\t\tthis._state.messages = baseline ? [baseline] : [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage || this._state.messages.every((message) => message.role === \"system\")) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst shouldStopAfterTurn = this.shouldStopAfterTurn;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tshouldStopAfterTurn: shouldStopAfterTurn\n\t\t\t\t? async (context) => await shouldStopAfterTurn(context, this.signal)\n\t\t\t\t: undefined,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,KAAK,YAAY,EACjB,KAAK,OAAO,EAEZ,KAAK,mBAAmB,EAExB,KAAK,eAAe,EACpB,KAAK,SAAS,EAEd,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EACX,oBAAoB,EACpB,mBAAmB,EAEnB,UAAU,EAEV,mBAAmB,EACnB,YAAY,EACZ,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OAAO,CAAC,SAAS;YAeH,aAAa;CAgD3B","sourcesContent":["import {\n\tcreateInitialSystemMessage,\n\tgetCurrentSystemMessage,\n\tgetCurrentSystemPrompt,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n\ttoToolDeclaration,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinishTurn,\n\tPrepareNextTurnContext,\n\tPrepareRequest,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) =>\n\t\t\tmessage.role === \"system\" ||\n\t\t\tmessage.role === \"user\" ||\n\t\t\tmessage.role === \"assistant\" ||\n\t\t\tmessage.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\n/** Initial state for {@link Agent}. `systemPrompt` and `tools` become the leading system message unless `messages` already starts with one. */\nexport type AgentInitialState = Partial<\n\tOmit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">\n>;\n\nfunction createMutableAgentState(initialState?: AgentInitialState): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\tconst initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));\n\tif (messages[0]?.role !== \"system\" && initialMessage) messages.unshift(initialMessage);\n\n\treturn {\n\t\tget systemPrompt() {\n\t\t\treturn getCurrentSystemPrompt(messages);\n\t\t},\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: AgentInitialState;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tfinishTurn?: FinishTurn;\n\tprepareRequest?: PrepareRequest;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tpeek(): AgentMessage[] {\n\t\tif (this.mode === \"all\") return this.messages.slice();\n\t\tconst first = this.messages[0];\n\t\treturn first ? [first] : [];\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tconst drained = this.peek();\n\t\tthis.messages = this.messages.slice(drained.length);\n\t\treturn drained;\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic finishTurn?: FinishTurn;\n\tpublic prepareRequest?: PrepareRequest;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.finishTurn = runtimeOptions.finishTurn;\n\t\tthis.prepareRequest = runtimeOptions.prepareRequest;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Preview the messages selected for the next turn without consuming them. */\n\tpeekQueuedMessages(): AgentMessage[] {\n\t\tconst steering = this.steeringQueue.peek();\n\t\treturn steering.length > 0 ? steering : this.followUpQueue.peek();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tconst baseline = getCurrentSystemMessage(this._state.messages);\n\t\tthis._state.messages = baseline ? [baseline] : [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage || this._state.messages.every((message) => message.role === \"system\")) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tfinishTurn: this.finishTurn,\n\t\t\tprepareRequest: this.prepareRequest,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
package/dist/agent.js CHANGED
@@ -69,18 +69,16 @@ class PendingMessageQueue {
69
69
  hasItems() {
70
70
  return this.messages.length > 0;
71
71
  }
72
- drain() {
73
- if (this.mode === "all") {
74
- const drained = this.messages.slice();
75
- this.messages = [];
76
- return drained;
77
- }
72
+ peek() {
73
+ if (this.mode === "all")
74
+ return this.messages.slice();
78
75
  const first = this.messages[0];
79
- if (!first) {
80
- return [];
81
- }
82
- this.messages = this.messages.slice(1);
83
- return [first];
76
+ return first ? [first] : [];
77
+ }
78
+ drain() {
79
+ const drained = this.peek();
80
+ this.messages = this.messages.slice(drained.length);
81
+ return drained;
84
82
  }
85
83
  clear() {
86
84
  this.messages = [];
@@ -105,7 +103,8 @@ export class Agent {
105
103
  onResponse;
106
104
  beforeToolCall;
107
105
  afterToolCall;
108
- shouldStopAfterTurn;
106
+ finishTurn;
107
+ prepareRequest;
109
108
  prepareNextTurn;
110
109
  prepareNextTurnWithContext;
111
110
  activeRun;
@@ -131,7 +130,8 @@ export class Agent {
131
130
  this.onResponse = runtimeOptions.onResponse;
132
131
  this.beforeToolCall = runtimeOptions.beforeToolCall;
133
132
  this.afterToolCall = runtimeOptions.afterToolCall;
134
- this.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;
133
+ this.finishTurn = runtimeOptions.finishTurn;
134
+ this.prepareRequest = runtimeOptions.prepareRequest;
135
135
  this.prepareNextTurn = runtimeOptions.prepareNextTurn;
136
136
  this.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;
137
137
  this.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? "one-at-a-time");
@@ -203,6 +203,11 @@ export class Agent {
203
203
  hasQueuedMessages() {
204
204
  return this.steeringQueue.hasItems() || this.followUpQueue.hasItems();
205
205
  }
206
+ /** Preview the messages selected for the next turn without consuming them. */
207
+ peekQueuedMessages() {
208
+ const steering = this.steeringQueue.peek();
209
+ return steering.length > 0 ? steering : this.followUpQueue.peek();
210
+ }
206
211
  /** Active abort signal for the current run, if any. */
207
212
  get signal() {
208
213
  return this.activeRun?.abortController.signal;
@@ -295,7 +300,6 @@ export class Agent {
295
300
  }
296
301
  createLoopConfig(options = {}) {
297
302
  let skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;
298
- const shouldStopAfterTurn = this.shouldStopAfterTurn;
299
303
  return {
300
304
  model: this._state.model,
301
305
  reasoning: this._state.thinkingLevel === "off" ? undefined : this._state.thinkingLevel,
@@ -308,9 +312,8 @@ export class Agent {
308
312
  toolExecution: this.toolExecution,
309
313
  beforeToolCall: this.beforeToolCall,
310
314
  afterToolCall: this.afterToolCall,
311
- shouldStopAfterTurn: shouldStopAfterTurn
312
- ? async (context) => await shouldStopAfterTurn(context, this.signal)
313
- : undefined,
315
+ finishTurn: this.finishTurn,
316
+ prepareRequest: this.prepareRequest,
314
317
  prepareNextTurn: this.prepareNextTurnWithContext || this.prepareNextTurn
315
318
  ? async (context) => {
316
319
  if (this.prepareNextTurnWithContext) {
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,0BAA0B,EAC1B,uBAAuB,EACvB,sBAAsB,EAQtB,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAsBpD,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CACX,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,YAAY,CAC9B,CAAC;AAAA,CACF;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;CACpE,CAAC;AAEF,MAAM,aAAa,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G,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\tcreateInitialSystemMessage,\n\tgetCurrentSystemMessage,\n\tgetCurrentSystemPrompt,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n\ttoToolDeclaration,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tPrepareNextTurnContext,\n\tQueueMode,\n\tShouldStopAfterTurnContext,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) =>\n\t\t\tmessage.role === \"system\" ||\n\t\t\tmessage.role === \"user\" ||\n\t\t\tmessage.role === \"assistant\" ||\n\t\t\tmessage.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\n/** Initial state for {@link Agent}. `systemPrompt` and `tools` become the leading system message unless `messages` already starts with one. */\nexport type AgentInitialState = Partial<\n\tOmit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">\n>;\n\nfunction createMutableAgentState(initialState?: AgentInitialState): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\tconst initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));\n\tif (messages[0]?.role !== \"system\" && initialMessage) messages.unshift(initialMessage);\n\n\treturn {\n\t\tget systemPrompt() {\n\t\t\treturn getCurrentSystemPrompt(messages);\n\t\t},\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: AgentInitialState;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tshouldStopAfterTurn?: (context: ShouldStopAfterTurnContext, signal?: AbortSignal) => boolean | Promise<boolean>;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tif (this.mode === \"all\") {\n\t\t\tconst drained = this.messages.slice();\n\t\t\tthis.messages = [];\n\t\t\treturn drained;\n\t\t}\n\n\t\tconst first = this.messages[0];\n\t\tif (!first) {\n\t\t\treturn [];\n\t\t}\n\t\tthis.messages = this.messages.slice(1);\n\t\treturn [first];\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic shouldStopAfterTurn?: (\n\t\tcontext: ShouldStopAfterTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => boolean | Promise<boolean>;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.shouldStopAfterTurn = runtimeOptions.shouldStopAfterTurn;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tconst baseline = getCurrentSystemMessage(this._state.messages);\n\t\tthis._state.messages = baseline ? [baseline] : [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage || this._state.messages.every((message) => message.role === \"system\")) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\tconst shouldStopAfterTurn = this.shouldStopAfterTurn;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tshouldStopAfterTurn: shouldStopAfterTurn\n\t\t\t\t? async (context) => await shouldStopAfterTurn(context, this.signal)\n\t\t\t\t: undefined,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,0BAA0B,EAC1B,uBAAuB,EACvB,sBAAsB,EAQtB,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAuBpD,SAAS,mBAAmB,CAAC,QAAwB,EAAa;IACjE,OAAO,QAAQ,CAAC,MAAM,CACrB,CAAC,OAAO,EAAE,EAAE,CACX,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,YAAY,CAC9B,CAAC;AAAA,CACF;AAED,MAAM,WAAW,GAAG;IACnB,KAAK,EAAE,CAAC;IACR,MAAM,EAAE,CAAC;IACT,SAAS,EAAE,CAAC;IACZ,UAAU,EAAE,CAAC;IACb,WAAW,EAAE,CAAC;IACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;CACpE,CAAC;AAEF,MAAM,aAAa,GAAG;IACrB,EAAE,EAAE,SAAS;IACb,IAAI,EAAE,SAAS;IACf,GAAG,EAAE,SAAS;IACd,QAAQ,EAAE,SAAS;IACnB,OAAO,EAAE,EAAE;IACX,SAAS,EAAE,KAAK;IAChB,KAAK,EAAE,EAAE;IACT,IAAI,EAA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CAAC,YAAY,CAAC;gBACvD,CAAC;gBACD,MAAM;YAEP,KAAK,WAAW;gBACf,IAAI,CAAC,MAAM,CAAC,gBAAgB,GAAG,SAAS,CAAC;gBACzC,MAAM;QACR,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,MAAM,CAAC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;QAC9D,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,MAAM,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/B,CAAC;IAAA,CACD;CACD","sourcesContent":["import {\n\tcreateInitialSystemMessage,\n\tgetCurrentSystemMessage,\n\tgetCurrentSystemPrompt,\n\ttype ImageContent,\n\ttype Message,\n\ttype Model,\n\ttype SimpleStreamOptions,\n\ttype TextContent,\n\ttype ThinkingBudgets,\n\ttype Transport,\n\ttoToolDeclaration,\n} from \"@earendil-works/pi-ai\";\nimport { runAgentLoop, runAgentLoopContinue } from \"./agent-loop.ts\";\nimport { getDefaultStreamFn } from \"./stream-fn.ts\";\nimport type {\n\tAfterToolCallContext,\n\tAfterToolCallResult,\n\tAgentContext,\n\tAgentEvent,\n\tAgentLoopConfig,\n\tAgentLoopTurnUpdate,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tBeforeToolCallContext,\n\tBeforeToolCallResult,\n\tFinishTurn,\n\tPrepareNextTurnContext,\n\tPrepareRequest,\n\tQueueMode,\n\tStreamFn,\n\tToolExecutionMode,\n} from \"./types.ts\";\n\nexport type { QueueMode } from \"./types.ts\";\n\nfunction defaultConvertToLlm(messages: AgentMessage[]): Message[] {\n\treturn messages.filter(\n\t\t(message) =>\n\t\t\tmessage.role === \"system\" ||\n\t\t\tmessage.role === \"user\" ||\n\t\t\tmessage.role === \"assistant\" ||\n\t\t\tmessage.role === \"toolResult\",\n\t);\n}\n\nconst EMPTY_USAGE = {\n\tinput: 0,\n\toutput: 0,\n\tcacheRead: 0,\n\tcacheWrite: 0,\n\ttotalTokens: 0,\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n};\n\nconst DEFAULT_MODEL = {\n\tid: \"unknown\",\n\tname: \"unknown\",\n\tapi: \"unknown\",\n\tprovider: \"unknown\",\n\tbaseUrl: \"\",\n\treasoning: false,\n\tinput: [],\n\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\tcontextWindow: 0,\n\tmaxTokens: 0,\n} satisfies Model<any>;\n\ntype MutableAgentState = Omit<AgentState, \"isStreaming\" | \"streamingMessage\" | \"pendingToolCalls\" | \"errorMessage\"> & {\n\tisStreaming: boolean;\n\tstreamingMessage?: AgentMessage;\n\tpendingToolCalls: Set<string>;\n\terrorMessage?: string;\n};\n\n/** Initial state for {@link Agent}. `systemPrompt` and `tools` become the leading system message unless `messages` already starts with one. */\nexport type AgentInitialState = Partial<\n\tOmit<AgentState, \"pendingToolCalls\" | \"isStreaming\" | \"streamingMessage\" | \"errorMessage\">\n>;\n\nfunction createMutableAgentState(initialState?: AgentInitialState): MutableAgentState {\n\tlet tools = initialState?.tools?.slice() ?? [];\n\tlet messages = initialState?.messages?.slice() ?? [];\n\tconst initialMessage = createInitialSystemMessage(initialState?.systemPrompt, tools.map(toToolDeclaration));\n\tif (messages[0]?.role !== \"system\" && initialMessage) messages.unshift(initialMessage);\n\n\treturn {\n\t\tget systemPrompt() {\n\t\t\treturn getCurrentSystemPrompt(messages);\n\t\t},\n\t\tmodel: initialState?.model ?? DEFAULT_MODEL,\n\t\tthinkingLevel: initialState?.thinkingLevel ?? \"off\",\n\t\tget tools() {\n\t\t\treturn tools;\n\t\t},\n\t\tset tools(nextTools: AgentTool<any>[]) {\n\t\t\ttools = nextTools.slice();\n\t\t},\n\t\tget messages() {\n\t\t\treturn messages;\n\t\t},\n\t\tset messages(nextMessages: AgentMessage[]) {\n\t\t\tmessages = nextMessages.slice();\n\t\t},\n\t\tisStreaming: false,\n\t\tstreamingMessage: undefined,\n\t\tpendingToolCalls: new Set<string>(),\n\t\terrorMessage: undefined,\n\t};\n}\n\n/** Options for constructing an {@link Agent}. */\nexport interface AgentOptions {\n\tinitialState?: AgentInitialState;\n\tconvertToLlm?: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\ttransformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tstreamFn: StreamFn;\n\tgetApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tonPayload?: SimpleStreamOptions[\"onPayload\"];\n\tonResponse?: SimpleStreamOptions[\"onResponse\"];\n\tbeforeToolCall?: (context: BeforeToolCallContext, signal?: AbortSignal) => Promise<BeforeToolCallResult | undefined>;\n\tafterToolCall?: (context: AfterToolCallContext, signal?: AbortSignal) => Promise<AfterToolCallResult | undefined>;\n\tfinishTurn?: FinishTurn;\n\tprepareRequest?: PrepareRequest;\n\tprepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tsteeringMode?: QueueMode;\n\tfollowUpMode?: QueueMode;\n\tsessionId?: string;\n\tthinkingBudgets?: ThinkingBudgets;\n\ttransport?: Transport;\n\tmaxRetryDelayMs?: number;\n\ttoolExecution?: ToolExecutionMode;\n}\n\nclass PendingMessageQueue {\n\tprivate messages: AgentMessage[] = [];\n\tpublic mode: QueueMode;\n\n\tconstructor(mode: QueueMode) {\n\t\tthis.mode = mode;\n\t}\n\n\tenqueue(message: AgentMessage): void {\n\t\tthis.messages.push(message);\n\t}\n\n\thasItems(): boolean {\n\t\treturn this.messages.length > 0;\n\t}\n\n\tpeek(): AgentMessage[] {\n\t\tif (this.mode === \"all\") return this.messages.slice();\n\t\tconst first = this.messages[0];\n\t\treturn first ? [first] : [];\n\t}\n\n\tdrain(): AgentMessage[] {\n\t\tconst drained = this.peek();\n\t\tthis.messages = this.messages.slice(drained.length);\n\t\treturn drained;\n\t}\n\n\tclear(): void {\n\t\tthis.messages = [];\n\t}\n}\n\ntype ActiveRun = {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n\tabortController: AbortController;\n};\n\n/**\n * Stateful wrapper around the low-level agent loop.\n *\n * `Agent` owns the current transcript, emits lifecycle events, executes tools,\n * and exposes queueing APIs for steering and follow-up messages.\n */\nexport class Agent {\n\tprivate _state: MutableAgentState;\n\tprivate readonly listeners = new Set<(event: AgentEvent, signal: AbortSignal) => Promise<void> | void>();\n\tprivate readonly steeringQueue: PendingMessageQueue;\n\tprivate readonly followUpQueue: PendingMessageQueue;\n\n\tpublic convertToLlm: (messages: AgentMessage[]) => Message[] | Promise<Message[]>;\n\tpublic transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;\n\tpublic streamFunction: StreamFn;\n\tpublic getApiKey?: (provider: string) => Promise<string | undefined> | string | undefined;\n\tpublic onPayload?: SimpleStreamOptions[\"onPayload\"];\n\tpublic onResponse?: SimpleStreamOptions[\"onResponse\"];\n\tpublic beforeToolCall?: (\n\t\tcontext: BeforeToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<BeforeToolCallResult | undefined>;\n\tpublic afterToolCall?: (\n\t\tcontext: AfterToolCallContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AfterToolCallResult | undefined>;\n\tpublic finishTurn?: FinishTurn;\n\tpublic prepareRequest?: PrepareRequest;\n\tpublic prepareNextTurn?: (\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tpublic prepareNextTurnWithContext?: (\n\t\tcontext: PrepareNextTurnContext,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentLoopTurnUpdate | undefined> | AgentLoopTurnUpdate | undefined;\n\tprivate activeRun?: ActiveRun;\n\t/** Session identifier forwarded to providers for cache-aware backends. */\n\tpublic sessionId?: string;\n\t/** Optional per-level thinking token budgets forwarded to the stream function. */\n\tpublic thinkingBudgets?: ThinkingBudgets;\n\t/** Preferred transport forwarded to the stream function. */\n\tpublic transport: Transport;\n\t/** Optional cap for provider-requested retry delays. */\n\tpublic maxRetryDelayMs?: number;\n\t/** Tool execution strategy for assistant messages that contain multiple tool calls. */\n\tpublic toolExecution: ToolExecutionMode;\n\n\tconstructor(options: AgentOptions) {\n\t\t// Older compiled consumers may omit options or streamFn even though the current API requires them.\n\t\tconst runtimeOptions: Partial<AgentOptions> = options ?? {};\n\t\tthis._state = createMutableAgentState(runtimeOptions.initialState);\n\t\tthis.convertToLlm = runtimeOptions.convertToLlm ?? defaultConvertToLlm;\n\t\tthis.transformContext = runtimeOptions.transformContext;\n\t\tthis.streamFunction = runtimeOptions.streamFn ?? getDefaultStreamFn();\n\t\tthis.getApiKey = runtimeOptions.getApiKey;\n\t\tthis.onPayload = runtimeOptions.onPayload;\n\t\tthis.onResponse = runtimeOptions.onResponse;\n\t\tthis.beforeToolCall = runtimeOptions.beforeToolCall;\n\t\tthis.afterToolCall = runtimeOptions.afterToolCall;\n\t\tthis.finishTurn = runtimeOptions.finishTurn;\n\t\tthis.prepareRequest = runtimeOptions.prepareRequest;\n\t\tthis.prepareNextTurn = runtimeOptions.prepareNextTurn;\n\t\tthis.prepareNextTurnWithContext = runtimeOptions.prepareNextTurnWithContext;\n\t\tthis.steeringQueue = new PendingMessageQueue(runtimeOptions.steeringMode ?? \"one-at-a-time\");\n\t\tthis.followUpQueue = new PendingMessageQueue(runtimeOptions.followUpMode ?? \"one-at-a-time\");\n\t\tthis.sessionId = runtimeOptions.sessionId;\n\t\tthis.thinkingBudgets = runtimeOptions.thinkingBudgets;\n\t\tthis.transport = runtimeOptions.transport ?? \"auto\";\n\t\tthis.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;\n\t\tthis.toolExecution = runtimeOptions.toolExecution ?? \"parallel\";\n\t}\n\n\t/**\n\t * Subscribe to agent lifecycle events.\n\t *\n\t * Listener promises are awaited in subscription order and are included in\n\t * the current run's settlement. Listeners also receive the active abort\n\t * signal for the current run.\n\t *\n\t * `agent_end` is the final emitted event for a run, but the agent does not\n\t * become idle until all awaited listeners for that event have settled.\n\t */\n\tsubscribe(listener: (event: AgentEvent, signal: AbortSignal) => Promise<void> | void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\t/**\n\t * Current agent state.\n\t *\n\t * Assigning `state.tools` or `state.messages` copies the provided top-level array.\n\t */\n\tget state(): AgentState {\n\t\treturn this._state;\n\t}\n\n\t/** Controls how queued steering messages are drained. */\n\tset steeringMode(mode: QueueMode) {\n\t\tthis.steeringQueue.mode = mode;\n\t}\n\n\tget steeringMode(): QueueMode {\n\t\treturn this.steeringQueue.mode;\n\t}\n\n\t/** Controls how queued follow-up messages are drained. */\n\tset followUpMode(mode: QueueMode) {\n\t\tthis.followUpQueue.mode = mode;\n\t}\n\n\tget followUpMode(): QueueMode {\n\t\treturn this.followUpQueue.mode;\n\t}\n\n\t/** Queue a message to be injected after the current assistant turn finishes. */\n\tsteer(message: AgentMessage): void {\n\t\tthis.steeringQueue.enqueue(message);\n\t}\n\n\t/** Queue a message to run only after the agent would otherwise stop. */\n\tfollowUp(message: AgentMessage): void {\n\t\tthis.followUpQueue.enqueue(message);\n\t}\n\n\t/** Remove all queued steering messages. */\n\tclearSteeringQueue(): void {\n\t\tthis.steeringQueue.clear();\n\t}\n\n\t/** Remove all queued follow-up messages. */\n\tclearFollowUpQueue(): void {\n\t\tthis.followUpQueue.clear();\n\t}\n\n\t/** Remove all queued steering and follow-up messages. */\n\tclearAllQueues(): void {\n\t\tthis.clearSteeringQueue();\n\t\tthis.clearFollowUpQueue();\n\t}\n\n\t/** Returns true when either queue still contains pending messages. */\n\thasQueuedMessages(): boolean {\n\t\treturn this.steeringQueue.hasItems() || this.followUpQueue.hasItems();\n\t}\n\n\t/** Preview the messages selected for the next turn without consuming them. */\n\tpeekQueuedMessages(): AgentMessage[] {\n\t\tconst steering = this.steeringQueue.peek();\n\t\treturn steering.length > 0 ? steering : this.followUpQueue.peek();\n\t}\n\n\t/** Active abort signal for the current run, if any. */\n\tget signal(): AbortSignal | undefined {\n\t\treturn this.activeRun?.abortController.signal;\n\t}\n\n\t/** Abort the current run, if one is active. */\n\tabort(): void {\n\t\tthis.activeRun?.abortController.abort();\n\t}\n\n\t/**\n\t * Resolve when the current run and all awaited event listeners have finished.\n\t *\n\t * This resolves after `agent_end` listeners settle.\n\t */\n\twaitForIdle(): Promise<void> {\n\t\treturn this.activeRun?.promise ?? Promise.resolve();\n\t}\n\n\t/** Clear conversation state and queues while retaining the replayed prompt/tool baseline. */\n\treset(): void {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before resetting.\");\n\t\t}\n\n\t\tconst baseline = getCurrentSystemMessage(this._state.messages);\n\t\tthis._state.messages = baseline ? [baseline] : [];\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis._state.errorMessage = undefined;\n\t\tthis.clearFollowUpQueue();\n\t\tthis.clearSteeringQueue();\n\t}\n\n\t/** Start a new prompt from text, a single message, or a batch of messages. */\n\tasync prompt(message: AgentMessage | AgentMessage[]): Promise<void>;\n\tasync prompt(input: string, images?: ImageContent[]): Promise<void>;\n\tasync prompt(input: string | AgentMessage | AgentMessage[], images?: ImageContent[]): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.\",\n\t\t\t);\n\t\t}\n\t\tconst messages = this.normalizePromptInput(input, images);\n\t\tawait this.runPromptMessages(messages);\n\t}\n\n\t/** Continue from the current transcript. The last message must be a user or tool-result message. */\n\tasync continue(): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing. Wait for completion before continuing.\");\n\t\t}\n\n\t\tconst lastMessage = this._state.messages[this._state.messages.length - 1];\n\t\tif (!lastMessage || this._state.messages.every((message) => message.role === \"system\")) {\n\t\t\tthrow new Error(\"No messages to continue from\");\n\t\t}\n\n\t\tif (lastMessage.role === \"assistant\") {\n\t\t\tconst queuedSteering = this.steeringQueue.drain();\n\t\t\tif (queuedSteering.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedSteering, { skipInitialSteeringPoll: true });\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst queuedFollowUps = this.followUpQueue.drain();\n\t\t\tif (queuedFollowUps.length > 0) {\n\t\t\t\tawait this.runPromptMessages(queuedFollowUps);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error(\"Cannot continue from message role: assistant\");\n\t\t}\n\n\t\tawait this.runContinuation();\n\t}\n\n\tprivate normalizePromptInput(\n\t\tinput: string | AgentMessage | AgentMessage[],\n\t\timages?: ImageContent[],\n\t): AgentMessage[] {\n\t\tif (Array.isArray(input)) {\n\t\t\treturn input;\n\t\t}\n\n\t\tif (typeof input !== \"string\") {\n\t\t\treturn [input];\n\t\t}\n\n\t\tconst content: Array<TextContent | ImageContent> = [{ type: \"text\", text: input }];\n\t\tif (images && images.length > 0) {\n\t\t\tcontent.push(...images);\n\t\t}\n\t\treturn [{ role: \"user\", content, timestamp: Date.now() }];\n\t}\n\n\tprivate async runPromptMessages(\n\t\tmessages: AgentMessage[],\n\t\toptions: { skipInitialSteeringPoll?: boolean } = {},\n\t): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoop(\n\t\t\t\tmessages,\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(options),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate async runContinuation(): Promise<void> {\n\t\tawait this.runWithLifecycle(async (signal) => {\n\t\t\tawait runAgentLoopContinue(\n\t\t\t\tthis.createContextSnapshot(),\n\t\t\t\tthis.createLoopConfig(),\n\t\t\t\t(event) => this.processEvents(event),\n\t\t\t\tsignal,\n\t\t\t\tthis.streamFunction,\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate createContextSnapshot(): AgentContext {\n\t\treturn {\n\t\t\tmessages: this._state.messages.slice(),\n\t\t\ttools: this._state.tools.slice(),\n\t\t};\n\t}\n\n\tprivate createLoopConfig(options: { skipInitialSteeringPoll?: boolean } = {}): AgentLoopConfig {\n\t\tlet skipInitialSteeringPoll = options.skipInitialSteeringPoll === true;\n\t\treturn {\n\t\t\tmodel: this._state.model,\n\t\t\treasoning: this._state.thinkingLevel === \"off\" ? undefined : this._state.thinkingLevel,\n\t\t\tsessionId: this.sessionId,\n\t\t\tonPayload: this.onPayload,\n\t\t\tonResponse: this.onResponse,\n\t\t\ttransport: this.transport,\n\t\t\tthinkingBudgets: this.thinkingBudgets,\n\t\t\tmaxRetryDelayMs: this.maxRetryDelayMs,\n\t\t\ttoolExecution: this.toolExecution,\n\t\t\tbeforeToolCall: this.beforeToolCall,\n\t\t\tafterToolCall: this.afterToolCall,\n\t\t\tfinishTurn: this.finishTurn,\n\t\t\tprepareRequest: this.prepareRequest,\n\t\t\tprepareNextTurn:\n\t\t\t\tthis.prepareNextTurnWithContext || this.prepareNextTurn\n\t\t\t\t\t? async (context) => {\n\t\t\t\t\t\t\tif (this.prepareNextTurnWithContext) {\n\t\t\t\t\t\t\t\treturn await this.prepareNextTurnWithContext(context, this.signal);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn await this.prepareNextTurn?.(this.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\tconvertToLlm: this.convertToLlm,\n\t\t\ttransformContext: this.transformContext,\n\t\t\tgetApiKey: this.getApiKey,\n\t\t\tgetSteeringMessages: async () => {\n\t\t\t\tif (skipInitialSteeringPoll) {\n\t\t\t\t\tskipInitialSteeringPoll = false;\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn this.steeringQueue.drain();\n\t\t\t},\n\t\t\tgetFollowUpMessages: async () => this.followUpQueue.drain(),\n\t\t};\n\t}\n\n\tprivate async runWithLifecycle(executor: (signal: AbortSignal) => Promise<void>): Promise<void> {\n\t\tif (this.activeRun) {\n\t\t\tthrow new Error(\"Agent is already processing.\");\n\t\t}\n\n\t\tconst abortController = new AbortController();\n\t\tlet resolvePromise = () => {};\n\t\tconst promise = new Promise<void>((resolve) => {\n\t\t\tresolvePromise = resolve;\n\t\t});\n\t\tthis.activeRun = { promise, resolve: resolvePromise, abortController };\n\n\t\tthis._state.isStreaming = true;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.errorMessage = undefined;\n\n\t\ttry {\n\t\t\tawait executor(abortController.signal);\n\t\t} catch (error) {\n\t\t\tawait this.handleRunFailure(error, abortController.signal.aborted);\n\t\t} finally {\n\t\t\tthis.finishRun();\n\t\t}\n\t}\n\n\tprivate async handleRunFailure(error: unknown, aborted: boolean): Promise<void> {\n\t\tconst failureMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [{ type: \"text\", text: \"\" }],\n\t\t\tapi: this._state.model.api,\n\t\t\tprovider: this._state.model.provider,\n\t\t\tmodel: this._state.model.id,\n\t\t\tusage: EMPTY_USAGE,\n\t\t\tstopReason: aborted ? \"aborted\" : \"error\",\n\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\ttimestamp: Date.now(),\n\t\t} satisfies AgentMessage;\n\t\tawait this.processEvents({ type: \"message_start\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"message_end\", message: failureMessage });\n\t\tawait this.processEvents({ type: \"turn_end\", message: failureMessage, toolResults: [] });\n\t\tawait this.processEvents({ type: \"agent_end\", messages: [failureMessage] });\n\t}\n\n\tprivate finishRun(): void {\n\t\tthis._state.isStreaming = false;\n\t\tthis._state.streamingMessage = undefined;\n\t\tthis._state.pendingToolCalls = new Set<string>();\n\t\tthis.activeRun?.resolve();\n\t\tthis.activeRun = undefined;\n\t}\n\n\t/**\n\t * Reduce internal state for a loop event, then await listeners.\n\t *\n\t * `agent_end` only means no further loop events will be emitted. The run is\n\t * considered idle later, after all awaited listeners for `agent_end` finish\n\t * and `finishRun()` clears runtime-owned state.\n\t */\n\tprivate async processEvents(event: AgentEvent): Promise<void> {\n\t\tswitch (event.type) {\n\t\t\tcase \"message_start\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_update\":\n\t\t\t\tthis._state.streamingMessage = event.message;\n\t\t\t\tbreak;\n\n\t\t\tcase \"message_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tthis._state.messages.push(event.message);\n\t\t\t\tbreak;\n\n\t\t\tcase \"tool_execution_start\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.add(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"tool_execution_end\": {\n\t\t\t\tconst pendingToolCalls = new Set(this._state.pendingToolCalls);\n\t\t\t\tpendingToolCalls.delete(event.toolCallId);\n\t\t\t\tthis._state.pendingToolCalls = pendingToolCalls;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis._state.errorMessage = event.message.errorMessage;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"agent_end\":\n\t\t\t\tthis._state.streamingMessage = undefined;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst signal = this.activeRun?.abortController.signal;\n\t\tif (!signal) {\n\t\t\tthrow new Error(\"Agent listener invoked outside active run\");\n\t\t}\n\t\tfor (const listener of this.listeners) {\n\t\t\tawait listener(event, signal);\n\t\t}\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"chord.d.ts","sourceRoot":"","sources":["../../../src/harness/pico3/chord.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAiB,KAAK,sBAAsB,EAAE,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAEvH,OAAO,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,KAAK,EACX,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,EACL,SAAS,EAET,EAAE,EACF,UAAU,EACV,QAAQ,EACR,SAAS,EACT,SAAS,EACT,MAAM,YAAY,CAAC;AAGpB,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,GAAG;IAC1D,MAAM,EAAE;QAAE,MAAM,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC;CAChC,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC,yBAAyB,CAAC,CAAC;IAC1D,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC;IAClD,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC;IAClD,UAAU,CAAC,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,SAAS,GAAG,gBAAgB,GAAG,WAAW,CAAC,CAAC;IACtF,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,C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AE,OAAO,CAAC,EAC/C,WAAW,EAAE,CAAC,OAAO,EAAE,yBAAyB,KAAK,sBAAsB,CAAC,yBAAyB,CAAC,EACtG,GAAG,EAAE,OAAO,EACZ,IAAI,GAAE,sBAA2B,GAC/B,OAAO,CAAC,eAAe,CAAC,CAI1B","sourcesContent":["import { type Context, defineService, type MutableReplicatedState, type ReplicatedState } from \"@earendil-works/chord\";\nimport type { Op, Path, Seg } from \"@earendil-works/chord/delta\";\nimport type { ConversationHandle, Harness } from \"./harness.ts\";\nimport type {\n\tConversationSpec,\n\tConversationView,\n\tEntry,\n\tEntryScan,\n\tEnvelope,\n\tId,\n\tJsonObject,\n\tNewEntry,\n\tSendInput,\n\tViewEvent,\n} from \"./types.ts\";\nimport { WATCH_CAPACITY, type Watch } from \"./view.ts\";\n\nexport type PublishedConversationView = ConversationView & {\n\tcommit: { events: ViewEvent[] };\n};\n\nexport interface PicoConversationService {\n\treadonly view: ReplicatedState<PublishedConversationView>;\n\tsend(input: SendInput, ctx: Context): Promise<Id>;\n\twrite(entry: NewEntry, ctx: Context): Promise<Id>;\n\tinputAbort(id: Id, ctx: Context): Promise<\"aborted\" | \"already_placed\" | \"not_found\">;\n\tconfigSet(patch: JsonObject, ctx: Context): Promise<void>;\n\tabort(ctx: Context): Promise<void>;\n\treset(handoff: string | null, ctx: Context): Promise<void>;\n\tcollapse(instructions: string | null, ctx: Context): Promise<Id>;\n\tfork(at: Id | \"start\", spec: Omit<ConversationSpec, \"parent\">, ctx: Context): Promise<Id>;\n\tentries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n}\n\n/** Local registration/control plane and remote keyed conversation contract used by Chord facets. */\nexport const PicoHarnessService = defineService<Harness>(\"pi.harness\", { local: true });\nexport const PicoConversationService = defineService<PicoConversationService>(\"pi.conversation\");\n\nexport function createPicoConversationService<Cfg extends object>(\n\tharness: Pick<Harness, \"abortInput\" | \"entries\">,\n\tconversation: ConversationHandle<Cfg>,\n\tview: ReplicatedState<PublishedConversationView>,\n): PicoConversationService {\n\treturn {\n\t\tview,\n\t\tsend: (input, ctx) => conversation.send(input, ctx).then((handle) => handle.id),\n\t\twrite: (entry, ctx) => conversation.write(entry, ctx),\n\t\tinputAbort: (id, ctx) => harness.abortInput(id, ctx, conversation.id),\n\t\tconfigSet: (patch, ctx) => conversation.config.set(patch as never, ctx),\n\t\tabort: (ctx) => conversation.abort(ctx),\n\t\treset: (handoff, ctx) => conversation.reset(handoff ?? undefined, ctx),\n\t\tcollapse: (instructions, ctx) => conversation.collapse(instructions ?? undefined, ctx),\n\t\tfork: (at, spec, ctx) => conversation.fork(at, spec, ctx).then((child) => child.id),\n\t\tentries: (scan, ctx) => harness.entries({ ...scan, conversationId: conversation.id }, ctx),\n\t};\n}\n\nexport interface ChordViewBridge {\n\treadonly view: MutableReplicatedState<PublishedConversationView>;\n\treadonly closed: boolean;\n\tclose(): void;\n}\n\nexport interface ChordViewBridgeOptions {\n\tcapacity?: number;\n\t/** Called after the raw watch is closed. The owner should close and respawn its keyed service instance. */\n\tonFailure?: (error: Error) => void;\n}\n\n/**\n * Adapt Pico's commit-granular envelopes to one Chord publication per commit.\n * The raw listener only enqueues. Applying ops and publishing happen together,\n * off the Session line, with no await between them.\n */\nexport async function attachChordView(\n\tconversation: Pick<ConversationHandle, \"watch\">,\n\tcreateState: (initial: PublishedConversationView) => MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions = {},\n): Promise<ChordViewBridge> {\n\tconst watch = await conversation.watch(ctx);\n\tconst view = createState({ ...structuredClone(watch.view), commit: { events: [] } });\n\treturn bridgeWatch(watch, view, ctx, opts);\n}\n\nfunction bridgeWatch(\n\twatch: Watch,\n\tview: MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions,\n): ChordViewBridge {\n\tconst capacity = opts.capacity ?? WATCH_CAPACITY;\n\tif (!Number.isSafeInteger(capacity) || capacity < 1)\n\t\tthrow new RangeError(\"Chord view queue capacity must be positive\");\n\tconst queue: Envelope[] = [];\n\tlet scheduled = false;\n\tlet closed = false;\n\tconst fail = (cause: unknown) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tqueue.length = 0;\n\t\twatch.stop();\n\t\ttry {\n\t\t\topts.onFailure?.(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t} catch {}\n\t};\n\tconst drain = () => {\n\t\tscheduled = false;\n\t\twhile (!closed && queue.length > 0) {\n\t\t\tconst envelope = queue.shift()!;\n\t\t\ttry {\n\t\t\t\tapplyTracked(view.state, envelope.ops);\n\t\t\t\tview.state.commit.events = structuredClone(envelope.events);\n\t\t\t\tview.publish(ctx);\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t}\n\t};\n\twatch.start((envelope) => {\n\t\tif (closed) return;\n\t\tif (queue.length >= capacity) {\n\t\t\tfail(new Error(`Pico-to-Chord view queue exceeded ${capacity} envelopes`));\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(envelope);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tqueueMicrotask(drain);\n\t});\n\treturn {\n\t\tview,\n\t\tget closed() {\n\t\t\treturn closed;\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tqueue.length = 0;\n\t\t\twatch.stop();\n\t\t},\n\t};\n}\n\nfunction applyTracked(root: PublishedConversationView, ops: readonly Op[]): void {\n\tfor (const op of ops) {\n\t\tif (op[0] === \"r\") throw new Error(\"live Pico envelope unexpectedly replaced the view root\");\n\t\tconst path = op[1];\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target)) throw new Error(`Pico splice path is not an array: ${path.join(\".\")}`);\n\t\t\ttarget.splice(op[2], op[3], ...structuredClone(op[4]));\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = resolve(root, path.slice(0, -1));\n\t\tif (parent === null || typeof parent !== \"object\")\n\t\t\tthrow new Error(`Pico operation parent is not an object: ${path.join(\".\")}`);\n\t\tconst key = path[path.length - 1]!;\n\t\tif (op[0] === \"d\") {\n\t\t\tif (Array.isArray(parent)) parent.splice(key as number, 1);\n\t\t\telse delete (parent as Record<PropertyKey, unknown>)[key];\n\t\t\tcontinue;\n\t\t}\n\t\tconst record = parent as Record<PropertyKey, unknown>;\n\t\tif (op[0] === \"s\") record[key] = structuredClone(op[2]);\n\t\telse if (op[0] === \"a\") record[key] = `${String(record[key])}${op[2]}`;\n\t\telse record[key] = String(record[key]).slice(op[2]);\n\t}\n}\n\nfunction resolve(root: unknown, path: Path): unknown {\n\tlet value = root;\n\tfor (const segment of path) {\n\t\tif (value === null || typeof value !== \"object\") return undefined;\n\t\tvalue = (value as Record<Seg, unknown>)[segment];\n\t}\n\treturn value;\n}\n"]}
1
+ {"version":3,"file":"chord.d.ts","sourceRoot":"","sources":["../../../src/harness/pico3/chord.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,OAAO,EAGZ,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,KAAK,EACX,gBAAgB,EAChB,gBAAgB,EAChB,KAAK,EACL,SAAS,EAET,EAAE,EACF,UAAU,EACV,QAAQ,EACR,SAAS,EACT,SAAS,EACT,MAAM,YAAY,CAAC;AAGpB,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,GAAG;IAC1D,MAAM,EAAE;QAAE,MAAM,EAAE,SAAS,EAAE,CAAA;KAAE,CAAC;CAChC,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC,yBAAyB,CAAC,CAAC;IAC1D,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC;IAClD,KAAK,CAAC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IAAI,EAAE,sBAAsB,CAAC,yBAAyB,CAAC,CAAC;IACjE,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,KAAK,IAAI,IAAI,CAAC;CACd;AAED,MAAM,WAAW,sBAAsB;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,2GAA2G;IAC3G,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CACnC;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CACpC,YAAY,EAAE,IAAI,CAAC,kBAAkB,EAAE,OAAO,CAAC,EAC/C,WAAW,EAAE,CAAC,OAAO,EAAE,yBAAyB,KAAK,sBAAsB,CAAC,yBAAyB,CAAC,EACtG,GAAG,EAAE,OAAO,EACZ,IAAI,GAAE,sBAA2B,GAC/B,OAAO,CAAC,eAAe,CAAC,CAI1B","sourcesContent":["import {\n\ttype Context,\n\ttype Draft,\n\tdefineService,\n\ttype MutableReplicatedState,\n\ttype ReplicatedState,\n} from \"@earendil-works/chord\";\nimport type { Op, Path, Seg } from \"@earendil-works/chord/delta\";\nimport type { ConversationHandle, Harness } from \"./harness.ts\";\nimport type {\n\tConversationSpec,\n\tConversationView,\n\tEntry,\n\tEntryScan,\n\tEnvelope,\n\tId,\n\tJsonObject,\n\tNewEntry,\n\tSendInput,\n\tViewEvent,\n} from \"./types.ts\";\nimport { WATCH_CAPACITY, type Watch } from \"./view.ts\";\n\nexport type PublishedConversationView = ConversationView & {\n\tcommit: { events: ViewEvent[] };\n};\n\nexport interface PicoConversationService {\n\treadonly view: ReplicatedState<PublishedConversationView>;\n\tsend(input: SendInput, ctx: Context): Promise<Id>;\n\twrite(entry: NewEntry, ctx: Context): Promise<Id>;\n\tinputAbort(id: Id, ctx: Context): Promise<\"aborted\" | \"already_placed\" | \"not_found\">;\n\tconfigSet(patch: JsonObject, ctx: Context): Promise<void>;\n\tabort(ctx: Context): Promise<void>;\n\treset(handoff: string | null, ctx: Context): Promise<void>;\n\tcollapse(instructions: string | null, ctx: Context): Promise<Id>;\n\tfork(at: Id | \"start\", spec: Omit<ConversationSpec, \"parent\">, ctx: Context): Promise<Id>;\n\tentries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n}\n\n/** Local registration/control plane and remote keyed conversation contract used by Chord facets. */\nexport const PicoHarnessService = defineService<Harness>(\"pi.harness\", { local: true });\nexport const PicoConversationService = defineService<PicoConversationService>(\"pi.conversation\");\n\nexport function createPicoConversationService<Cfg extends object>(\n\tharness: Pick<Harness, \"abortInput\" | \"entries\">,\n\tconversation: ConversationHandle<Cfg>,\n\tview: ReplicatedState<PublishedConversationView>,\n): PicoConversationService {\n\treturn {\n\t\tview,\n\t\tsend: (input, ctx) => conversation.send(input, ctx).then((handle) => handle.id),\n\t\twrite: (entry, ctx) => conversation.write(entry, ctx),\n\t\tinputAbort: (id, ctx) => harness.abortInput(id, ctx, conversation.id),\n\t\tconfigSet: (patch, ctx) => conversation.config.set(patch as never, ctx),\n\t\tabort: (ctx) => conversation.abort(ctx),\n\t\treset: (handoff, ctx) => conversation.reset(handoff ?? undefined, ctx),\n\t\tcollapse: (instructions, ctx) => conversation.collapse(instructions ?? undefined, ctx),\n\t\tfork: (at, spec, ctx) => conversation.fork(at, spec, ctx).then((child) => child.id),\n\t\tentries: (scan, ctx) => harness.entries({ ...scan, conversationId: conversation.id }, ctx),\n\t};\n}\n\nexport interface ChordViewBridge {\n\treadonly view: MutableReplicatedState<PublishedConversationView>;\n\treadonly closed: boolean;\n\tclose(): void;\n}\n\nexport interface ChordViewBridgeOptions {\n\tcapacity?: number;\n\t/** Called after the raw watch is closed. The owner should close and respawn its keyed service instance. */\n\tonFailure?: (error: Error) => void;\n}\n\n/**\n * Adapt Pico's commit-granular envelopes to one Chord publication per commit.\n * The raw listener only enqueues. Applying ops and publishing happen together,\n * off the Session line, with no await between them.\n */\nexport async function attachChordView(\n\tconversation: Pick<ConversationHandle, \"watch\">,\n\tcreateState: (initial: PublishedConversationView) => MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions = {},\n): Promise<ChordViewBridge> {\n\tconst watch = await conversation.watch(ctx);\n\tconst view = createState({ ...structuredClone(watch.view), commit: { events: [] } });\n\treturn bridgeWatch(watch, view, ctx, opts);\n}\n\nfunction bridgeWatch(\n\twatch: Watch,\n\tview: MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions,\n): ChordViewBridge {\n\tconst capacity = opts.capacity ?? WATCH_CAPACITY;\n\tif (!Number.isSafeInteger(capacity) || capacity < 1)\n\t\tthrow new RangeError(\"Chord view queue capacity must be positive\");\n\tconst queue: Envelope[] = [];\n\tlet scheduled = false;\n\tlet closed = false;\n\tconst fail = (cause: unknown) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tqueue.length = 0;\n\t\twatch.stop();\n\t\ttry {\n\t\t\topts.onFailure?.(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t} catch {}\n\t};\n\tconst drain = () => {\n\t\tscheduled = false;\n\t\twhile (!closed && queue.length > 0) {\n\t\t\tconst envelope = queue.shift()!;\n\t\t\ttry {\n\t\t\t\tview.change(ctx, (draft) => {\n\t\t\t\t\tapplyTracked(draft, envelope.ops);\n\t\t\t\t\tdraft.commit.events = envelope.events as Draft<ViewEvent[]>;\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t}\n\t};\n\twatch.start((envelope) => {\n\t\tif (closed) return;\n\t\tif (queue.length >= capacity) {\n\t\t\tfail(new Error(`Pico-to-Chord view queue exceeded ${capacity} envelopes`));\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(envelope);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tqueueMicrotask(drain);\n\t});\n\treturn {\n\t\tview,\n\t\tget closed() {\n\t\t\treturn closed;\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tqueue.length = 0;\n\t\t\twatch.stop();\n\t\t},\n\t};\n}\n\nfunction applyTracked(root: Draft<PublishedConversationView>, ops: readonly Op[]): void {\n\tfor (const op of ops) {\n\t\tif (op[0] === \"r\") throw new Error(\"live Pico envelope unexpectedly replaced the view root\");\n\t\tconst path = op[1];\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target)) throw new Error(`Pico splice path is not an array: ${path.join(\".\")}`);\n\t\t\t(target as unknown[]).splice(op[2], op[3], ...op[4]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (op[0] === \"m\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target) || target.length !== op[2].length) {\n\t\t\t\tthrow new Error(`Pico permutation path is not a matching array: ${path.join(\".\")}`);\n\t\t\t}\n\t\t\tconst array = target as unknown[];\n\t\t\tconst previous = array.slice();\n\t\t\tconst rank = new Map<unknown, number>();\n\t\t\tfor (let index = 0; index < op[2].length; index++) {\n\t\t\t\tconst value = previous[op[2][index]!]!;\n\t\t\t\tif (!rank.has(value)) rank.set(value, index);\n\t\t\t}\n\t\t\tarray.sort((left, right) => rank.get(left)! - rank.get(right)!);\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = resolve(root, path.slice(0, -1));\n\t\tif (parent === null || typeof parent !== \"object\")\n\t\t\tthrow new Error(`Pico operation parent is not an object: ${path.join(\".\")}`);\n\t\tconst key = path[path.length - 1]!;\n\t\tif (op[0] === \"d\") {\n\t\t\tif (Array.isArray(parent)) parent.splice(key as number, 1);\n\t\t\telse delete (parent as Record<PropertyKey, unknown>)[key];\n\t\t\tcontinue;\n\t\t}\n\t\tconst record = parent as Record<PropertyKey, unknown>;\n\t\tif (op[0] === \"s\") record[key] = op[2];\n\t\telse if (op[0] === \"a\") record[key] = `${String(record[key])}${op[2]}`;\n\t\telse record[key] = String(record[key]).slice(op[2]);\n\t}\n}\n\nfunction resolve(root: unknown, path: Path): unknown {\n\tlet value = root;\n\tfor (const segment of path) {\n\t\tif (value === null || typeof value !== \"object\") return undefined;\n\t\tvalue = (value as Record<Seg, unknown>)[segment];\n\t}\n\treturn value;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { defineService } from "@earendil-works/chord";
1
+ import { defineService, } from "@earendil-works/chord";
2
2
  import { WATCH_CAPACITY } from "./view.js";
3
3
  /** Local registration/control plane and remote keyed conversation contract used by Chord facets. */
4
4
  export const PicoHarnessService = defineService("pi.harness", { local: true });
@@ -50,9 +50,10 @@ function bridgeWatch(watch, view, ctx, opts) {
50
50
  while (!closed && queue.length > 0) {
51
51
  const envelope = queue.shift();
52
52
  try {
53
- applyTracked(view.state, envelope.ops);
54
- view.state.commit.events = structuredClone(envelope.events);
55
- view.publish(ctx);
53
+ view.change(ctx, (draft) => {
54
+ applyTracked(draft, envelope.ops);
55
+ draft.commit.events = envelope.events;
56
+ });
56
57
  }
57
58
  catch (error) {
58
59
  fail(error);
@@ -95,7 +96,23 @@ function applyTracked(root, ops) {
95
96
  const target = resolve(root, path);
96
97
  if (!Array.isArray(target))
97
98
  throw new Error(`Pico splice path is not an array: ${path.join(".")}`);
98
- target.splice(op[2], op[3], ...structuredClone(op[4]));
99
+ target.splice(op[2], op[3], ...op[4]);
100
+ continue;
101
+ }
102
+ if (op[0] === "m") {
103
+ const target = resolve(root, path);
104
+ if (!Array.isArray(target) || target.length !== op[2].length) {
105
+ throw new Error(`Pico permutation path is not a matching array: ${path.join(".")}`);
106
+ }
107
+ const array = target;
108
+ const previous = array.slice();
109
+ const rank = new Map();
110
+ for (let index = 0; index < op[2].length; index++) {
111
+ const value = previous[op[2][index]];
112
+ if (!rank.has(value))
113
+ rank.set(value, index);
114
+ }
115
+ array.sort((left, right) => rank.get(left) - rank.get(right));
99
116
  continue;
100
117
  }
101
118
  const parent = resolve(root, path.slice(0, -1));
@@ -111,7 +128,7 @@ function applyTracked(root, ops) {
111
128
  }
112
129
  const record = parent;
113
130
  if (op[0] === "s")
114
- record[key] = structuredClone(op[2]);
131
+ record[key] = op[2];
115
132
  else if (op[0] === "a")
116
133
  record[key] = `${String(record[key])}${op[2]}`;
117
134
  else
@@ -1 +1 @@
1
- {"version":3,"file":"chord.js","sourceRoot":"","sources":["../../../src/harness/pico3/chord.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,aAAa,EAAqD,MAAM,uBAAuB,CAAC;AAevH,OAAO,EAAE,cAAc,EAAc,MAAM,WAAW,CAAC;AAmBvD,oGAAoG;AACpG,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAU,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACxF,MAAM,CAAC,MAAM,uBAAuB,GAAG,aAAa,CAA0B,iBAAiB,CAAC,CAAC;AAEjG,MAAM,UAAU,6BAA6B,CAC5C,OAAgD,EAChD,YAAqC,EACrC,IAAgD,EACtB;IAC1B,OAAO;QACN,IAAI;QACJ,IAAI,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/E,KAAK,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC;QACrD,UAAU,EAAE,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,EAAE,YAAY,CAAC,EAAE,CAAC;QACrE,SAAS,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,KAAc,EAAE,GAAG,CAAC;QACvE,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,GAAG,CAAC;QACvC,KAAK,EAAE,CAAC,OAAO,EAAE,GAA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,IAAI,CAAC;IACjB,KAAK,MAAM,OAAO,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAC;QAClE,KAAK,GAAI,KAA8B,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import { type Context, defineService, type MutableReplicatedState, type ReplicatedState } from \"@earendil-works/chord\";\nimport type { Op, Path, Seg } from \"@earendil-works/chord/delta\";\nimport type { ConversationHandle, Harness } from \"./harness.ts\";\nimport type {\n\tConversationSpec,\n\tConversationView,\n\tEntry,\n\tEntryScan,\n\tEnvelope,\n\tId,\n\tJsonObject,\n\tNewEntry,\n\tSendInput,\n\tViewEvent,\n} from \"./types.ts\";\nimport { WATCH_CAPACITY, type Watch } from \"./view.ts\";\n\nexport type PublishedConversationView = ConversationView & {\n\tcommit: { events: ViewEvent[] };\n};\n\nexport interface PicoConversationService {\n\treadonly view: ReplicatedState<PublishedConversationView>;\n\tsend(input: SendInput, ctx: Context): Promise<Id>;\n\twrite(entry: NewEntry, ctx: Context): Promise<Id>;\n\tinputAbort(id: Id, ctx: Context): Promise<\"aborted\" | \"already_placed\" | \"not_found\">;\n\tconfigSet(patch: JsonObject, ctx: Context): Promise<void>;\n\tabort(ctx: Context): Promise<void>;\n\treset(handoff: string | null, ctx: Context): Promise<void>;\n\tcollapse(instructions: string | null, ctx: Context): Promise<Id>;\n\tfork(at: Id | \"start\", spec: Omit<ConversationSpec, \"parent\">, ctx: Context): Promise<Id>;\n\tentries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n}\n\n/** Local registration/control plane and remote keyed conversation contract used by Chord facets. */\nexport const PicoHarnessService = defineService<Harness>(\"pi.harness\", { local: true });\nexport const PicoConversationService = defineService<PicoConversationService>(\"pi.conversation\");\n\nexport function createPicoConversationService<Cfg extends object>(\n\tharness: Pick<Harness, \"abortInput\" | \"entries\">,\n\tconversation: ConversationHandle<Cfg>,\n\tview: ReplicatedState<PublishedConversationView>,\n): PicoConversationService {\n\treturn {\n\t\tview,\n\t\tsend: (input, ctx) => conversation.send(input, ctx).then((handle) => handle.id),\n\t\twrite: (entry, ctx) => conversation.write(entry, ctx),\n\t\tinputAbort: (id, ctx) => harness.abortInput(id, ctx, conversation.id),\n\t\tconfigSet: (patch, ctx) => conversation.config.set(patch as never, ctx),\n\t\tabort: (ctx) => conversation.abort(ctx),\n\t\treset: (handoff, ctx) => conversation.reset(handoff ?? undefined, ctx),\n\t\tcollapse: (instructions, ctx) => conversation.collapse(instructions ?? undefined, ctx),\n\t\tfork: (at, spec, ctx) => conversation.fork(at, spec, ctx).then((child) => child.id),\n\t\tentries: (scan, ctx) => harness.entries({ ...scan, conversationId: conversation.id }, ctx),\n\t};\n}\n\nexport interface ChordViewBridge {\n\treadonly view: MutableReplicatedState<PublishedConversationView>;\n\treadonly closed: boolean;\n\tclose(): void;\n}\n\nexport interface ChordViewBridgeOptions {\n\tcapacity?: number;\n\t/** Called after the raw watch is closed. The owner should close and respawn its keyed service instance. */\n\tonFailure?: (error: Error) => void;\n}\n\n/**\n * Adapt Pico's commit-granular envelopes to one Chord publication per commit.\n * The raw listener only enqueues. Applying ops and publishing happen together,\n * off the Session line, with no await between them.\n */\nexport async function attachChordView(\n\tconversation: Pick<ConversationHandle, \"watch\">,\n\tcreateState: (initial: PublishedConversationView) => MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions = {},\n): Promise<ChordViewBridge> {\n\tconst watch = await conversation.watch(ctx);\n\tconst view = createState({ ...structuredClone(watch.view), commit: { events: [] } });\n\treturn bridgeWatch(watch, view, ctx, opts);\n}\n\nfunction bridgeWatch(\n\twatch: Watch,\n\tview: MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions,\n): ChordViewBridge {\n\tconst capacity = opts.capacity ?? WATCH_CAPACITY;\n\tif (!Number.isSafeInteger(capacity) || capacity < 1)\n\t\tthrow new RangeError(\"Chord view queue capacity must be positive\");\n\tconst queue: Envelope[] = [];\n\tlet scheduled = false;\n\tlet closed = false;\n\tconst fail = (cause: unknown) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tqueue.length = 0;\n\t\twatch.stop();\n\t\ttry {\n\t\t\topts.onFailure?.(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t} catch {}\n\t};\n\tconst drain = () => {\n\t\tscheduled = false;\n\t\twhile (!closed && queue.length > 0) {\n\t\t\tconst envelope = queue.shift()!;\n\t\t\ttry {\n\t\t\t\tapplyTracked(view.state, envelope.ops);\n\t\t\t\tview.state.commit.events = structuredClone(envelope.events);\n\t\t\t\tview.publish(ctx);\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t}\n\t};\n\twatch.start((envelope) => {\n\t\tif (closed) return;\n\t\tif (queue.length >= capacity) {\n\t\t\tfail(new Error(`Pico-to-Chord view queue exceeded ${capacity} envelopes`));\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(envelope);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tqueueMicrotask(drain);\n\t});\n\treturn {\n\t\tview,\n\t\tget closed() {\n\t\t\treturn closed;\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tqueue.length = 0;\n\t\t\twatch.stop();\n\t\t},\n\t};\n}\n\nfunction applyTracked(root: PublishedConversationView, ops: readonly Op[]): void {\n\tfor (const op of ops) {\n\t\tif (op[0] === \"r\") throw new Error(\"live Pico envelope unexpectedly replaced the view root\");\n\t\tconst path = op[1];\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target)) throw new Error(`Pico splice path is not an array: ${path.join(\".\")}`);\n\t\t\ttarget.splice(op[2], op[3], ...structuredClone(op[4]));\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = resolve(root, path.slice(0, -1));\n\t\tif (parent === null || typeof parent !== \"object\")\n\t\t\tthrow new Error(`Pico operation parent is not an object: ${path.join(\".\")}`);\n\t\tconst key = path[path.length - 1]!;\n\t\tif (op[0] === \"d\") {\n\t\t\tif (Array.isArray(parent)) parent.splice(key as number, 1);\n\t\t\telse delete (parent as Record<PropertyKey, unknown>)[key];\n\t\t\tcontinue;\n\t\t}\n\t\tconst record = parent as Record<PropertyKey, unknown>;\n\t\tif (op[0] === \"s\") record[key] = structuredClone(op[2]);\n\t\telse if (op[0] === \"a\") record[key] = `${String(record[key])}${op[2]}`;\n\t\telse record[key] = String(record[key]).slice(op[2]);\n\t}\n}\n\nfunction resolve(root: unknown, path: Path): unknown {\n\tlet value = root;\n\tfor (const segment of path) {\n\t\tif (value === null || typeof value !== \"object\") return undefined;\n\t\tvalue = (value as Record<Seg, unknown>)[segment];\n\t}\n\treturn value;\n}\n"]}
1
+ {"version":3,"file":"chord.js","sourceRoot":"","sources":["../../../src/harness/pico3/chord.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,aAAa,GAGb,MAAM,uBAAuB,CAAC;AAe/B,OAAO,EAAE,cAAc,EAAc,MAAM,WAAW,CAAC;AAmBvD,oGAAoG;AACpG,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAU,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACxF,MAAM,CAAC,MAAM,uBAAuB,GAAG,aAAa,CAA0B,iBAAiB,CAAC,CAAC;AAEjG,MAAM,UAAU,6BAA6B,CAC5C,OAAgD,EAChD,YAAqC,EACrC,IAAgD,EACtB;IAC1B,OAAO;QACN,IAAI;QACJ,IAAI,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/E,KAAK,EAAE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CAAC,EAAE,CAAC;;YAClE,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IACrD,CAAC;AAAA,CACD;AAED,SAAS,OAAO,CAAC,IAAa,EAAE,IAAU,EAAW;IACpD,IAAI,KAAK,GAAG,IAAI,CAAC;IACjB,KAAK,MAAM,OAAO,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;YAAE,OAAO,SAAS,CAAC;QAClE,KAAK,GAAI,KAA8B,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["import {\n\ttype Context,\n\ttype Draft,\n\tdefineService,\n\ttype MutableReplicatedState,\n\ttype ReplicatedState,\n} from \"@earendil-works/chord\";\nimport type { Op, Path, Seg } from \"@earendil-works/chord/delta\";\nimport type { ConversationHandle, Harness } from \"./harness.ts\";\nimport type {\n\tConversationSpec,\n\tConversationView,\n\tEntry,\n\tEntryScan,\n\tEnvelope,\n\tId,\n\tJsonObject,\n\tNewEntry,\n\tSendInput,\n\tViewEvent,\n} from \"./types.ts\";\nimport { WATCH_CAPACITY, type Watch } from \"./view.ts\";\n\nexport type PublishedConversationView = ConversationView & {\n\tcommit: { events: ViewEvent[] };\n};\n\nexport interface PicoConversationService {\n\treadonly view: ReplicatedState<PublishedConversationView>;\n\tsend(input: SendInput, ctx: Context): Promise<Id>;\n\twrite(entry: NewEntry, ctx: Context): Promise<Id>;\n\tinputAbort(id: Id, ctx: Context): Promise<\"aborted\" | \"already_placed\" | \"not_found\">;\n\tconfigSet(patch: JsonObject, ctx: Context): Promise<void>;\n\tabort(ctx: Context): Promise<void>;\n\treset(handoff: string | null, ctx: Context): Promise<void>;\n\tcollapse(instructions: string | null, ctx: Context): Promise<Id>;\n\tfork(at: Id | \"start\", spec: Omit<ConversationSpec, \"parent\">, ctx: Context): Promise<Id>;\n\tentries(scan: EntryScan, ctx: Context): Promise<Entry[]>;\n}\n\n/** Local registration/control plane and remote keyed conversation contract used by Chord facets. */\nexport const PicoHarnessService = defineService<Harness>(\"pi.harness\", { local: true });\nexport const PicoConversationService = defineService<PicoConversationService>(\"pi.conversation\");\n\nexport function createPicoConversationService<Cfg extends object>(\n\tharness: Pick<Harness, \"abortInput\" | \"entries\">,\n\tconversation: ConversationHandle<Cfg>,\n\tview: ReplicatedState<PublishedConversationView>,\n): PicoConversationService {\n\treturn {\n\t\tview,\n\t\tsend: (input, ctx) => conversation.send(input, ctx).then((handle) => handle.id),\n\t\twrite: (entry, ctx) => conversation.write(entry, ctx),\n\t\tinputAbort: (id, ctx) => harness.abortInput(id, ctx, conversation.id),\n\t\tconfigSet: (patch, ctx) => conversation.config.set(patch as never, ctx),\n\t\tabort: (ctx) => conversation.abort(ctx),\n\t\treset: (handoff, ctx) => conversation.reset(handoff ?? undefined, ctx),\n\t\tcollapse: (instructions, ctx) => conversation.collapse(instructions ?? undefined, ctx),\n\t\tfork: (at, spec, ctx) => conversation.fork(at, spec, ctx).then((child) => child.id),\n\t\tentries: (scan, ctx) => harness.entries({ ...scan, conversationId: conversation.id }, ctx),\n\t};\n}\n\nexport interface ChordViewBridge {\n\treadonly view: MutableReplicatedState<PublishedConversationView>;\n\treadonly closed: boolean;\n\tclose(): void;\n}\n\nexport interface ChordViewBridgeOptions {\n\tcapacity?: number;\n\t/** Called after the raw watch is closed. The owner should close and respawn its keyed service instance. */\n\tonFailure?: (error: Error) => void;\n}\n\n/**\n * Adapt Pico's commit-granular envelopes to one Chord publication per commit.\n * The raw listener only enqueues. Applying ops and publishing happen together,\n * off the Session line, with no await between them.\n */\nexport async function attachChordView(\n\tconversation: Pick<ConversationHandle, \"watch\">,\n\tcreateState: (initial: PublishedConversationView) => MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions = {},\n): Promise<ChordViewBridge> {\n\tconst watch = await conversation.watch(ctx);\n\tconst view = createState({ ...structuredClone(watch.view), commit: { events: [] } });\n\treturn bridgeWatch(watch, view, ctx, opts);\n}\n\nfunction bridgeWatch(\n\twatch: Watch,\n\tview: MutableReplicatedState<PublishedConversationView>,\n\tctx: Context,\n\topts: ChordViewBridgeOptions,\n): ChordViewBridge {\n\tconst capacity = opts.capacity ?? WATCH_CAPACITY;\n\tif (!Number.isSafeInteger(capacity) || capacity < 1)\n\t\tthrow new RangeError(\"Chord view queue capacity must be positive\");\n\tconst queue: Envelope[] = [];\n\tlet scheduled = false;\n\tlet closed = false;\n\tconst fail = (cause: unknown) => {\n\t\tif (closed) return;\n\t\tclosed = true;\n\t\tqueue.length = 0;\n\t\twatch.stop();\n\t\ttry {\n\t\t\topts.onFailure?.(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t} catch {}\n\t};\n\tconst drain = () => {\n\t\tscheduled = false;\n\t\twhile (!closed && queue.length > 0) {\n\t\t\tconst envelope = queue.shift()!;\n\t\t\ttry {\n\t\t\t\tview.change(ctx, (draft) => {\n\t\t\t\t\tapplyTracked(draft, envelope.ops);\n\t\t\t\t\tdraft.commit.events = envelope.events as Draft<ViewEvent[]>;\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t}\n\t\t}\n\t};\n\twatch.start((envelope) => {\n\t\tif (closed) return;\n\t\tif (queue.length >= capacity) {\n\t\t\tfail(new Error(`Pico-to-Chord view queue exceeded ${capacity} envelopes`));\n\t\t\treturn;\n\t\t}\n\t\tqueue.push(envelope);\n\t\tif (scheduled) return;\n\t\tscheduled = true;\n\t\tqueueMicrotask(drain);\n\t});\n\treturn {\n\t\tview,\n\t\tget closed() {\n\t\t\treturn closed;\n\t\t},\n\t\tclose() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tqueue.length = 0;\n\t\t\twatch.stop();\n\t\t},\n\t};\n}\n\nfunction applyTracked(root: Draft<PublishedConversationView>, ops: readonly Op[]): void {\n\tfor (const op of ops) {\n\t\tif (op[0] === \"r\") throw new Error(\"live Pico envelope unexpectedly replaced the view root\");\n\t\tconst path = op[1];\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target)) throw new Error(`Pico splice path is not an array: ${path.join(\".\")}`);\n\t\t\t(target as unknown[]).splice(op[2], op[3], ...op[4]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (op[0] === \"m\") {\n\t\t\tconst target = resolve(root, path);\n\t\t\tif (!Array.isArray(target) || target.length !== op[2].length) {\n\t\t\t\tthrow new Error(`Pico permutation path is not a matching array: ${path.join(\".\")}`);\n\t\t\t}\n\t\t\tconst array = target as unknown[];\n\t\t\tconst previous = array.slice();\n\t\t\tconst rank = new Map<unknown, number>();\n\t\t\tfor (let index = 0; index < op[2].length; index++) {\n\t\t\t\tconst value = previous[op[2][index]!]!;\n\t\t\t\tif (!rank.has(value)) rank.set(value, index);\n\t\t\t}\n\t\t\tarray.sort((left, right) => rank.get(left)! - rank.get(right)!);\n\t\t\tcontinue;\n\t\t}\n\t\tconst parent = resolve(root, path.slice(0, -1));\n\t\tif (parent === null || typeof parent !== \"object\")\n\t\t\tthrow new Error(`Pico operation parent is not an object: ${path.join(\".\")}`);\n\t\tconst key = path[path.length - 1]!;\n\t\tif (op[0] === \"d\") {\n\t\t\tif (Array.isArray(parent)) parent.splice(key as number, 1);\n\t\t\telse delete (parent as Record<PropertyKey, unknown>)[key];\n\t\t\tcontinue;\n\t\t}\n\t\tconst record = parent as Record<PropertyKey, unknown>;\n\t\tif (op[0] === \"s\") record[key] = op[2];\n\t\telse if (op[0] === \"a\") record[key] = `${String(record[key])}${op[2]}`;\n\t\telse record[key] = String(record[key]).slice(op[2]);\n\t}\n}\n\nfunction resolve(root: unknown, path: Path): unknown {\n\tlet value = root;\n\tfor (const segment of path) {\n\t\tif (value === null || typeof value !== \"object\") return undefined;\n\t\tvalue = (value as Record<Seg, unknown>)[segment];\n\t}\n\treturn value;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/image.ts"],"names":[],"mappings":"AAEA,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAOnF;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAatD","sourcesContent":["const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\nexport function detectSupportedImageMimeType(buffer: Uint8Array): string | undefined {\n\tif (startsWith(buffer, [0xff, 0xd8, 0xff])) return buffer[3] === 0xf7 ? undefined : \"image/jpeg\";\n\tif (startsWith(buffer, PNG_SIGNATURE)) return isPng(buffer) && !isAnimatedPng(buffer) ? \"image/png\" : undefined;\n\tif (startsWithAscii(buffer, 0, \"GIF\")) return \"image/gif\";\n\tif (startsWithAscii(buffer, 0, \"RIFF\") && startsWithAscii(buffer, 8, \"WEBP\")) return \"image/webp\";\n\tif (startsWithAscii(buffer, 0, \"BM\") && isBmp(buffer)) return \"image/bmp\";\n\treturn undefined;\n}\n\nexport function encodeBase64(bytes: Uint8Array): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\tlet output = \"\";\n\tfor (let index = 0; index < bytes.length; index += 3) {\n\t\tconst first = bytes[index] ?? 0;\n\t\tconst second = bytes[index + 1];\n\t\tconst third = bytes[index + 2];\n\t\toutput += alphabet[first >> 2];\n\t\toutput += alphabet[((first & 0x03) << 4) | ((second ?? 0) >> 4)];\n\t\toutput += second === undefined ? \"=\" : alphabet[((second & 0x0f) << 2) | ((third ?? 0) >> 6)];\n\t\toutput += third === undefined ? \"=\" : alphabet[third & 0x3f];\n\t}\n\treturn output;\n}\n\nfunction isPng(buffer: Uint8Array): boolean {\n\treturn (\n\t\tbuffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, \"IHDR\")\n\t);\n}\n\nfunction isAnimatedPng(buffer: Uint8Array): boolean {\n\tlet offset = PNG_SIGNATURE.length;\n\twhile (offset + 8 <= buffer.length) {\n\t\tconst chunkLength = readUint32BE(buffer, offset);\n\t\tconst chunkTypeOffset = offset + 4;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"acTL\")) return true;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"IDAT\")) return false;\n\t\tconst nextOffset = offset + 8 + chunkLength + 4;\n\t\tif (nextOffset <= offset || nextOffset > buffer.length) return false;\n\t\toffset = nextOffset;\n\t}\n\treturn false;\n}\n\nfunction isBmp(buffer: Uint8Array): boolean {\n\tif (buffer.length < 26) return false;\n\tconst declaredFileSize = readUint32LE(buffer, 2);\n\tconst pixelDataOffset = readUint32LE(buffer, 10);\n\tconst dibHeaderSize = readUint32LE(buffer, 14);\n\tif (declaredFileSize !== 0 && declaredFileSize < 26) return false;\n\tif (pixelDataOffset < 14 + dibHeaderSize) return false;\n\tif (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) return false;\n\n\tlet colorPlanes: number;\n\tlet bitsPerPixel: number;\n\tif (dibHeaderSize === 12) {\n\t\tcolorPlanes = readUint16LE(buffer, 22);\n\t\tbitsPerPixel = readUint16LE(buffer, 24);\n\t} else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {\n\t\tif (buffer.length < 30) return false;\n\t\tcolorPlanes = readUint16LE(buffer, 26);\n\t\tbitsPerPixel = readUint16LE(buffer, 28);\n\t} else {\n\t\treturn false;\n\t}\n\treturn colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);\n}\n\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n\treturn (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);\n}\n\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) * 0x1000000 +\n\t\t((buffer[offset + 1] ?? 0) << 16) +\n\t\t((buffer[offset + 2] ?? 0) << 8) +\n\t\t(buffer[offset + 3] ?? 0)\n\t);\n}\n\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) +\n\t\t((buffer[offset + 1] ?? 0) << 8) +\n\t\t((buffer[offset + 2] ?? 0) << 16) +\n\t\t(buffer[offset + 3] ?? 0) * 0x1000000\n\t);\n}\n\nfunction startsWith(buffer: Uint8Array, bytes: number[]): boolean {\n\tif (buffer.length < bytes.length) return false;\n\treturn bytes.every((byte, index) => buffer[index] === byte);\n}\n\nfunction startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {\n\tif (buffer.length < offset + text.length) return false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tif (buffer[offset + index] !== text.charCodeAt(index)) return false;\n\t}\n\treturn true;\n}\n"]}
1
+ {"version":3,"file":"image.d.ts","sourceRoot":"","sources":["../../../src/harness/tools/image.ts"],"names":[],"mappings":"AAEA,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAOnF;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAatD","sourcesContent":["const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n\nexport function detectSupportedImageMimeType(buffer: Uint8Array): string | undefined {\n\tif (startsWith(buffer, [0xff, 0xd8, 0xff])) return buffer[3] === 0xf7 ? undefined : \"image/jpeg\";\n\tif (startsWith(buffer, PNG_SIGNATURE)) return isPng(buffer) && !isAnimatedPng(buffer) ? \"image/png\" : undefined;\n\tif (startsWithAscii(buffer, 0, \"GIF87a\") || startsWithAscii(buffer, 0, \"GIF89a\")) return \"image/gif\";\n\tif (startsWithAscii(buffer, 0, \"RIFF\") && startsWithAscii(buffer, 8, \"WEBP\")) return \"image/webp\";\n\tif (startsWithAscii(buffer, 0, \"BM\") && isBmp(buffer)) return \"image/bmp\";\n\treturn undefined;\n}\n\nexport function encodeBase64(bytes: Uint8Array): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\tlet output = \"\";\n\tfor (let index = 0; index < bytes.length; index += 3) {\n\t\tconst first = bytes[index] ?? 0;\n\t\tconst second = bytes[index + 1];\n\t\tconst third = bytes[index + 2];\n\t\toutput += alphabet[first >> 2];\n\t\toutput += alphabet[((first & 0x03) << 4) | ((second ?? 0) >> 4)];\n\t\toutput += second === undefined ? \"=\" : alphabet[((second & 0x0f) << 2) | ((third ?? 0) >> 6)];\n\t\toutput += third === undefined ? \"=\" : alphabet[third & 0x3f];\n\t}\n\treturn output;\n}\n\nfunction isPng(buffer: Uint8Array): boolean {\n\treturn (\n\t\tbuffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, \"IHDR\")\n\t);\n}\n\nfunction isAnimatedPng(buffer: Uint8Array): boolean {\n\tlet offset = PNG_SIGNATURE.length;\n\twhile (offset + 8 <= buffer.length) {\n\t\tconst chunkLength = readUint32BE(buffer, offset);\n\t\tconst chunkTypeOffset = offset + 4;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"acTL\")) return true;\n\t\tif (startsWithAscii(buffer, chunkTypeOffset, \"IDAT\")) return false;\n\t\tconst nextOffset = offset + 8 + chunkLength + 4;\n\t\tif (nextOffset <= offset || nextOffset > buffer.length) return false;\n\t\toffset = nextOffset;\n\t}\n\treturn false;\n}\n\nfunction isBmp(buffer: Uint8Array): boolean {\n\tif (buffer.length < 26) return false;\n\tconst declaredFileSize = readUint32LE(buffer, 2);\n\tconst pixelDataOffset = readUint32LE(buffer, 10);\n\tconst dibHeaderSize = readUint32LE(buffer, 14);\n\tif (declaredFileSize !== 0 && declaredFileSize < 26) return false;\n\tif (pixelDataOffset < 14 + dibHeaderSize) return false;\n\tif (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize) return false;\n\n\tlet colorPlanes: number;\n\tlet bitsPerPixel: number;\n\tif (dibHeaderSize === 12) {\n\t\tcolorPlanes = readUint16LE(buffer, 22);\n\t\tbitsPerPixel = readUint16LE(buffer, 24);\n\t} else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {\n\t\tif (buffer.length < 30) return false;\n\t\tcolorPlanes = readUint16LE(buffer, 26);\n\t\tbitsPerPixel = readUint16LE(buffer, 28);\n\t} else {\n\t\treturn false;\n\t}\n\treturn colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);\n}\n\nfunction readUint16LE(buffer: Uint8Array, offset: number): number {\n\treturn (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);\n}\n\nfunction readUint32BE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) * 0x1000000 +\n\t\t((buffer[offset + 1] ?? 0) << 16) +\n\t\t((buffer[offset + 2] ?? 0) << 8) +\n\t\t(buffer[offset + 3] ?? 0)\n\t);\n}\n\nfunction readUint32LE(buffer: Uint8Array, offset: number): number {\n\treturn (\n\t\t(buffer[offset] ?? 0) +\n\t\t((buffer[offset + 1] ?? 0) << 8) +\n\t\t((buffer[offset + 2] ?? 0) << 16) +\n\t\t(buffer[offset + 3] ?? 0) * 0x1000000\n\t);\n}\n\nfunction startsWith(buffer: Uint8Array, bytes: number[]): boolean {\n\tif (buffer.length < bytes.length) return false;\n\treturn bytes.every((byte, index) => buffer[index] === byte);\n}\n\nfunction startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {\n\tif (buffer.length < offset + text.length) return false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tif (buffer[offset + index] !== text.charCodeAt(index)) return false;\n\t}\n\treturn true;\n}\n"]}