@providerprotocol/agents 0.0.4 → 0.0.5

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.
@@ -1,3 +1,5 @@
1
+ import { generateUUID } from './chunk-EKRXMSDX.js';
2
+
1
3
  // src/execution/loop.ts
2
4
  var DEFAULT_LOOP_OPTIONS = {
3
5
  maxIterations: Infinity
@@ -197,6 +199,39 @@ function loop(options = {}) {
197
199
  };
198
200
  }
199
201
 
200
- export { loop };
201
- //# sourceMappingURL=chunk-4ESYN66B.js.map
202
- //# sourceMappingURL=chunk-4ESYN66B.js.map
202
+ // src/execution/tool-context.ts
203
+ function injectToolContext(tools, context, options = {}) {
204
+ return tools.map((tool) => wrapToolWithContext(tool, context, options));
205
+ }
206
+ function wrapToolWithContext(tool, context, options) {
207
+ const originalRun = tool.run;
208
+ return {
209
+ ...tool,
210
+ run: async (params) => {
211
+ const toolContext = {
212
+ agentId: context.agent.id,
213
+ stateId: context.state.id,
214
+ toolCallId: generateUUID(),
215
+ // Generate unique ID for this call
216
+ onSubagentEvent: options.onSubagentEvent
217
+ };
218
+ if (originalRun.length > 1) {
219
+ return originalRun(params, toolContext);
220
+ }
221
+ return originalRun(params);
222
+ }
223
+ };
224
+ }
225
+ function isContextAwareTool(tool) {
226
+ return tool.run.length > 1;
227
+ }
228
+ function withToolContext(tool, handler) {
229
+ return {
230
+ ...tool,
231
+ run: handler
232
+ };
233
+ }
234
+
235
+ export { injectToolContext, isContextAwareTool, loop, withToolContext };
236
+ //# sourceMappingURL=chunk-CEHXAE4Z.js.map
237
+ //# sourceMappingURL=chunk-CEHXAE4Z.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/execution/loop.ts","../src/execution/tool-context.ts"],"names":[],"mappings":";;;AAUA,IAAM,oBAAA,GAA8C;AAAA,EAClD,aAAA,EAAe;AACjB,CAAA;AAeO,SAAS,IAAA,CAAK,OAAA,GAAuB,EAAC,EAAsB;AACjE,EAAA,M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O,CAAC,CAAA;AACxE;AAKA,SAAS,mBAAA,CACP,IAAA,EACA,OAAA,EACA,OAAA,EACM;AACN,EAAA,MAAM,cAAc,IAAA,CAAK,GAAA;AAEzB,EAAA,OAAO;AAAA,IACL,GAAG,IAAA;AAAA,IACH,GAAA,EAAK,OAAO,MAAA,KAAsD;AAEhE,MAAA,MAAM,WAAA,GAAoC;AAAA,QACxC,OAAA,EAAS,QAAQ,KAAA,CAAM,EAAA;AAAA,QACvB,OAAA,EAAS,QAAQ,KAAA,CAAM,EAAA;AAAA,QACvB,YAAY,YAAA,EAAa;AAAA;AAAA,QACzB,iBAAiB,OAAA,CAAQ;AAAA,OAC3B;AAIA,MAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AAE1B,QAAA,OAAQ,WAAA,CAAoC,QAAQ,WAAW,CAAA;AAAA,MACjE;AAGA,MAAA,OAAO,YAAY,MAAM,CAAA;AAAA,IAC3B;AAAA,GACF;AACF;AAQO,SAAS,mBAAmB,IAAA,EAAqB;AACtD,EAAA,OAAO,IAAA,CAAK,IAAI,MAAA,GAAS,CAAA;AAC3B;AAsBO,SAAS,eAAA,CACd,MACA,OAAA,EACM;AACN,EAAA,OAAO;AAAA,IACL,GAAG,IAAA;AAAA,IACH,GAAA,EAAK;AAAA,GACP;AACF","file":"chunk-CEHXAE4Z.js","sourcesContent":["import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n LoopOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_LOOP_OPTIONS: Required<LoopOptions> = {\n maxIterations: Infinity,\n};\n\n/**\n * Create a loop execution strategy.\n * The simplest strategy - equivalent to UPP's tool loop behavior.\n *\n * Behavior:\n * 1. Send input to LLM\n * 2. If response has tool calls, execute tools and loop\n * 3. Continue until no tool calls or maxIterations reached\n * 4. Return final response as UPP Turn\n *\n * @param options - Loop configuration options\n * @returns ExecutionStrategy\n */\nexport function loop(options: LoopOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_LOOP_OPTIONS, ...options };\n\n return {\n name: 'loop',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let iteration = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const inputMessages = [...currentState.messages];\n\n while (true) {\n iteration++;\n currentState = currentState.withStep(iteration);\n\n // Check abort signal\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n // Call strategy hooks\n strategy.onStepStart?.(iteration, currentState);\n\n // Generate response - llm.generate uses rest params, pass messages array\n const turn = await llm.generate(inputMessages);\n finalTurn = turn;\n\n // Update state with messages from this turn\n currentState = currentState.withMessages(turn.messages);\n\n // Call action hook if there were tool calls\n if (turn.response.hasToolCalls) {\n strategy.onAct?.(iteration, turn.response.toolCalls ?? []);\n }\n\n // Call observe hook if there were tool executions\n if (turn.toolExecutions && turn.toolExecutions.length > 0) {\n strategy.onObserve?.(iteration, turn.toolExecutions);\n }\n\n // Call step end hook\n strategy.onStepEnd?.(iteration, { turn, state: currentState });\n\n // Save checkpoint after step completes (fire-and-forget, log errors)\n if (context.checkpoints && context.sessionId) {\n context.checkpoints.save(context.sessionId, currentState.toJSON()).catch((err) => {\n console.error('[UAP] Checkpoint save failed:', err);\n });\n }\n\n // Check stop condition\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n // Check if there are more tool calls to process\n // UPP's llm.generate handles the tool loop internally,\n // so we only need one iteration unless we're doing multi-step\n if (!turn.response.hasToolCalls) {\n break;\n }\n\n // Check iteration limit\n if (opts.maxIterations !== Infinity && iteration >= opts.maxIterations) {\n break;\n }\n\n // For next iteration, use the updated messages\n inputMessages.length = 0;\n inputMessages.push(...currentState.messages);\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n // Per UAP spec Section 3.4: sessionId MUST be included in state.metadata\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n // Combine signals if one was provided\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let iteration = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const inputMessages = [...currentState.messages];\n\n try {\n while (!aborted) {\n iteration++;\n currentState = currentState.withStep(iteration);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(iteration, currentState);\n\n // Emit step start event\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step: iteration,\n agentId,\n data: { iteration },\n },\n };\n\n // Stream the LLM response\n const streamResult = llm.stream(inputMessages);\n\n for await (const event of streamResult as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n // Yield UPP events\n yield {\n source: 'upp',\n upp: event,\n };\n }\n\n // Get the final turn from the stream\n const turn = await streamResult.turn;\n finalTurn = turn;\n\n currentState = currentState.withMessages(turn.messages);\n\n if (turn.response.hasToolCalls) {\n strategy.onAct?.(iteration, turn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step: iteration,\n agentId,\n data: { toolCalls: turn.response.toolCalls },\n },\n };\n }\n\n if (turn.toolExecutions && turn.toolExecutions.length > 0) {\n strategy.onObserve?.(iteration, turn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step: iteration,\n agentId,\n data: { observations: turn.toolExecutions },\n },\n };\n }\n\n strategy.onStepEnd?.(iteration, { turn, state: currentState });\n\n // Save checkpoint after step completes (fire-and-forget, log errors)\n if (context.checkpoints && context.sessionId) {\n context.checkpoints.save(context.sessionId, currentState.toJSON()).catch((err) => {\n console.error('[UAP] Checkpoint save failed:', err);\n });\n }\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step: iteration,\n agentId,\n data: { iteration },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n if (!turn.response.hasToolCalls) {\n break;\n }\n\n if (opts.maxIterations !== Infinity && iteration >= opts.maxIterations) {\n break;\n }\n\n inputMessages.length = 0;\n inputMessages.push(...currentState.messages);\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n // Per UAP spec Section 3.4: sessionId MUST be included in state.metadata\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Tool } from '@providerprotocol/ai';\nimport type {\n ExecutionContext,\n ToolExecutionContext,\n OnSubagentEvent,\n ContextAwareToolRun,\n} from './types.ts';\nimport { generateUUID } from '../utils/uuid.ts';\n\n/**\n * Options for tool context injection.\n */\nexport interface InjectToolContextOptions {\n /** Callback for sub-agent events from tools */\n onSubagentEvent?: OnSubagentEvent;\n}\n\n/**\n * Wrap tools to inject execution context when they support it.\n *\n * Per UAP-1.0 Section 8.4, tools that accept a second parameter\n * should receive execution context including agentId, stateId,\n * and sub-agent event callbacks.\n *\n * This enables:\n * - Sub-agent model/config inheritance\n * - Execution hierarchy tracking\n * - Sub-agent event propagation\n *\n * @param tools - Original tool array\n * @param context - Execution context from the agent\n * @param options - Additional options like event callbacks\n * @returns Wrapped tools with context injection\n *\n * @example\n * ```typescript\n * // In execution strategy\n * const wrappedTools = injectToolContext(tools, context, {\n * onSubagentEvent: (event) => {\n * // Handle sub-agent events\n * yield { source: 'uap', uap: { type: event.type, ... } };\n * },\n * });\n *\n * // Pass wrapped tools to LLM\n * const llmWithContext = llm({ model, tools: wrappedTools });\n * ```\n */\nexport function injectToolContext(\n tools: Tool[],\n context: ExecutionContext,\n options: InjectToolContextOptions = {},\n): Tool[] {\n return tools.map((tool) => wrapToolWithContext(tool, context, options));\n}\n\n/**\n * Wrap a single tool with context injection.\n */\nfunction wrapToolWithContext(\n tool: Tool,\n context: ExecutionContext,\n options: InjectToolContextOptions,\n): Tool {\n const originalRun = tool.run;\n\n return {\n ...tool,\n run: async (params: Record<string, unknown>): Promise<unknown> => {\n // Build execution context for this tool call\n const toolContext: ToolExecutionContext = {\n agentId: context.agent.id,\n stateId: context.state.id,\n toolCallId: generateUUID(), // Generate unique ID for this call\n onSubagentEvent: options.onSubagentEvent,\n };\n\n // Check if tool accepts context (function has arity > 1)\n // We detect this by checking if the function expects more than 1 parameter\n if (originalRun.length > 1) {\n // Tool expects context as second argument\n return (originalRun as ContextAwareToolRun)(params, toolContext);\n }\n\n // Standard tool - just pass params\n return originalRun(params);\n },\n };\n}\n\n/**\n * Check if a tool is context-aware (accepts second parameter).\n *\n * @param tool - Tool to check\n * @returns true if tool.run accepts more than one parameter\n */\nexport function isContextAwareTool(tool: Tool): boolean {\n return tool.run.length > 1;\n}\n\n/**\n * Create a context-aware tool wrapper for existing tools.\n * This is useful when you want to add context support to a tool\n * that doesn't natively support it.\n *\n * @param tool - Original tool\n * @param handler - Function that receives params and context, returns result\n * @returns New tool with context support\n *\n * @example\n * ```typescript\n * const originalTool = { name: 'my_tool', run: async (p) => 'result', ... };\n *\n * const contextAware = withToolContext(originalTool, async (params, context) => {\n * console.log('Agent ID:', context?.agentId);\n * // Call original or do something with context\n * return originalTool.run(params);\n * });\n * ```\n */\nexport function withToolContext(\n tool: Tool,\n handler: ContextAwareToolRun,\n): Tool {\n return {\n ...tool,\n run: handler as Tool['run'],\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
- import { L as LoopOptions, E as ExecutionStrategy, R as ReactOptions, P as PlanOptions } from '../types-D1egxttz.js';
2
- export { A as AgentStrategy, b as AgentStreamEvent, a as AgentStreamResult, h as ExecutionContext, i as ExecutionResult, G as GenerateResult, O as OnSubagentEvent, k as OrderedToolCall, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, T as ToolDependencyOptions, j as ToolWithDependencies, U as UAPEventType } from '../types-D1egxttz.js';
1
+ import { L as LoopOptions, E as ExecutionStrategy, R as ReactOptions, P as PlanOptions } from '../types-DC8XeoaI.js';
2
+ export { A as AgentStrategy, b as AgentStreamEvent, a as AgentStreamResult, C as ContextAwareToolRun, h as ExecutionContext, i as ExecutionResult, G as GenerateResult, O as OnSubagentEvent, l as OrderedToolCall, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, j as ToolDependencyOptions, T as ToolExecutionContext, k as ToolWithDependencies, U as UAPEventType } from '../types-DC8XeoaI.js';
3
3
  import { ToolCall, Tool } from '@providerprotocol/ai';
4
+ export { I as InjectToolContextOptions, i as injectToolContext, a as isContextAwareTool, w as withToolContext } from '../tool-context-Cc_qNVud.js';
4
5
  import '../index-qsPwbY86.js';
5
6
  import '../types-2Vsthzyu.js';
6
7
  import '../types-DChRdQoX.js';
@@ -101,5 +102,67 @@ declare function hasToolDependencies(tools: Tool[]): boolean;
101
102
  * @returns true if any call has the `after` field set
102
103
  */
103
104
  declare function hasCallDependencies(toolCalls: ToolCall[]): boolean;
105
+ /**
106
+ * Result of executing a tool call.
107
+ */
108
+ interface ToolExecutionResult {
109
+ /** The tool call that was executed */
110
+ call: ToolCall;
111
+ /** The result from the tool */
112
+ result: unknown;
113
+ /** Whether the tool threw an error */
114
+ isError: boolean;
115
+ /** Error message if isError is true */
116
+ error?: string;
117
+ /** Execution duration in milliseconds */
118
+ duration: number;
119
+ }
120
+ /**
121
+ * Function type for executing a single tool call.
122
+ */
123
+ type ToolExecutor = (call: ToolCall, tool: Tool) => Promise<unknown>;
124
+ /**
125
+ * Execute tool calls respecting dependency ordering.
126
+ *
127
+ * This function takes tool calls, orders them using `orderToolCalls()`,
128
+ * and executes them respecting barriers (sequential tools) and
129
+ * dependencies (dependsOn, after).
130
+ *
131
+ * Per UAP-1.0 Sections 8.5 and 8.6:
132
+ * - Tools with `sequential: true` execute alone (barrier)
133
+ * - Tools with `dependsOn` wait for named tools to complete
134
+ * - Tool calls with `after` wait for specific call IDs to complete
135
+ *
136
+ * @param toolCalls - Tool calls from the model response
137
+ * @param tools - Tool definitions with potential dependencies
138
+ * @param executor - Function to execute a single tool call
139
+ * @returns Array of execution results in completion order
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * import { executeOrderedToolCalls } from '@providerprotocol/agents/execution';
144
+ *
145
+ * // Define tools with dependencies
146
+ * const readTool: ToolWithDependencies = {
147
+ * name: 'read_file',
148
+ * sequential: true, // Must complete before others
149
+ * run: async (params) => readFile(params.path),
150
+ * };
151
+ *
152
+ * const processTool: ToolWithDependencies = {
153
+ * name: 'process',
154
+ * dependsOn: ['read_file'], // Wait for read_file
155
+ * run: async (params) => process(params.data),
156
+ * };
157
+ *
158
+ * // Execute with ordering
159
+ * const results = await executeOrderedToolCalls(
160
+ * turn.response.toolCalls,
161
+ * [readTool, processTool],
162
+ * async (call, tool) => tool.run(call.arguments),
163
+ * );
164
+ * ```
165
+ */
166
+ declare function executeOrderedToolCalls(toolCalls: ToolCall[], tools: Tool[], executor: ToolExecutor): Promise<ToolExecutionResult[]>;
104
167
 
105
- export { type ExecutionGroup, ExecutionStrategy, LoopOptions, PlanOptions, ReactOptions, hasCallDependencies, hasToolDependencies, loop, orderToolCalls, plan, react };
168
+ export { type ExecutionGroup, ExecutionStrategy, LoopOptions, PlanOptions, ReactOptions, type ToolExecutionResult, type ToolExecutor, executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, loop, orderToolCalls, plan, react };
@@ -1,4 +1,4 @@
1
- export { loop } from '../chunk-4ESYN66B.js';
1
+ export { injectToolContext, isContextAwareTool, loop, withToolContext } from '../chunk-CEHXAE4Z.js';
2
2
  import { generateUUID } from '../chunk-EKRXMSDX.js';
3
3
  import { UserMessage } from '@providerprotocol/ai';
4
4
 
@@ -673,7 +673,76 @@ function hasCallDependencies(toolCalls) {
673
673
  }
674
674
  return false;
675
675
  }
676
+ async function executeOrderedToolCalls(toolCalls, tools, executor) {
677
+ if (toolCalls.length === 0) {
678
+ return [];
679
+ }
680
+ const toolMap = /* @__PURE__ */ new Map();
681
+ for (const tool of tools) {
682
+ toolMap.set(tool.name, tool);
683
+ }
684
+ const groups = orderToolCalls(toolCalls, tools);
685
+ const results = [];
686
+ for (const group of groups) {
687
+ if (group.isBarrier) {
688
+ for (const call of group.calls) {
689
+ const tool = toolMap.get(call.toolName);
690
+ if (!tool) {
691
+ results.push({
692
+ call,
693
+ result: null,
694
+ isError: true,
695
+ error: `Tool not found: ${call.toolName}`,
696
+ duration: 0
697
+ });
698
+ continue;
699
+ }
700
+ const result = await executeOne(call, tool, executor);
701
+ results.push(result);
702
+ }
703
+ } else {
704
+ const groupResults = await Promise.all(
705
+ group.calls.map(async (call) => {
706
+ const tool = toolMap.get(call.toolName);
707
+ if (!tool) {
708
+ return {
709
+ call,
710
+ result: null,
711
+ isError: true,
712
+ error: `Tool not found: ${call.toolName}`,
713
+ duration: 0
714
+ };
715
+ }
716
+ return executeOne(call, tool, executor);
717
+ })
718
+ );
719
+ results.push(...groupResults);
720
+ }
721
+ }
722
+ return results;
723
+ }
724
+ async function executeOne(call, tool, executor) {
725
+ const startTime = Date.now();
726
+ try {
727
+ const result = await executor(call, tool);
728
+ return {
729
+ call,
730
+ result,
731
+ isError: false,
732
+ duration: Date.now() - startTime
733
+ };
734
+ } catch (error) {
735
+ const err = error instanceof Error ? error : new Error(String(error));
736
+ return {
737
+ call,
738
+ result: null,
739
+ isError: true,
740
+ error: err.message,
741
+ duration: Date.now() - startTime
742
+ };
743
+ }
744
+ }
676
745
 
677
- export { hasCallDependencies, hasToolDependencies, orderToolCalls, plan, react };
746
+ export { executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, orderToolCalls, plan, react };
678
747
  //# sourceMappingURL=index.js.map
679
748
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/execution/react.ts","../../src/execution/plan.ts","../../src/execution/tool-ordering.ts"],"names":["UserMessage"],"mappings":";;;;AAWA,IAAM,qBAAA,GAAgD;AAAA,EACpD,QAAA,EAAU,QAAA;AAAA,EACV,eAAA,EAAiB;AACnB,CAAA;AAcO,SAAS,KAAA,CAAM,OAAA,GAAwB,EAAC,EAAsB;AACnE,EAAA,MAAM,IAAA,GAAO,EAAE,GAAG,qBAAA,EAAuB,GAAG,OAAA,EAAQ;AAEpD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IAEN,MAAM,QAAQ,OAAA,EAAqD;AACjE,MAAA,MAAM,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,QAAO,GAAI,OAAA;AAIhD,MAAA,IA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,EAAG;AAC7C,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n ReactOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_REACT_OPTIONS: Required<ReactOptions> = {\n maxSteps: Infinity,\n reasoningPrompt: 'Think step by step about what you need to do next. Consider the current state, what tools are available, and what action would be most helpful.',\n};\n\n/**\n * Create a ReAct (Reason-Act-Observe) execution strategy.\n *\n * Behavior:\n * 1. Reason: LLM outputs reasoning about what to do next\n * 2. Act: LLM selects and executes tool(s)\n * 3. Observe: Tool results are formatted as observations\n * 4. Repeat until stop condition, no more actions, or maxSteps\n *\n * @param options - ReAct configuration options\n * @returns ExecutionStrategy\n */\nexport function react(options: ReactOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n return {\n name: 'react',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n while (true) {\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // REASON PHASE: Ask LLM to think about what to do\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningTurn = await llm.generate(reasoningMessages);\n\n const reasoning = reasoningTurn.response.text;\n currentState = currentState.withReasoning(reasoning);\n strategy.onReason?.(step, reasoning);\n\n // Add reasoning to conversation\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE: Execute with tools\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionTurn = await llm.generate(messages);\n finalTurn = actionTurn;\n\n // Update messages with action response\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n // Handle tool calls\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n }\n\n // OBSERVE PHASE: Process tool results\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n // Check stop conditions\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n // No more tool calls means we're done\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n // Check step limit\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n while (!aborted) {\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'reasoning' },\n },\n };\n\n // REASON PHASE\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningStream = llm.stream(reasoningMessages);\n let reasoningText = '';\n\n for await (const event of reasoningStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n\n if (event.type === 'text_delta' && event.delta.text) {\n reasoningText += event.delta.text;\n }\n }\n\n const reasoningTurn = await reasoningStream.turn;\n currentState = currentState.withReasoning(reasoningText || reasoningTurn.response.text);\n strategy.onReason?.(step, reasoningText || reasoningTurn.response.text);\n\n yield {\n source: 'uap',\n uap: {\n type: 'reasoning',\n step,\n agentId,\n data: { reasoning: reasoningText || reasoningTurn.response.text },\n },\n };\n\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionStream = llm.stream(messages);\n\n for await (const event of actionStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const actionTurn = await actionStream.turn;\n finalTurn = actionTurn;\n\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: actionTurn.response.toolCalls },\n },\n };\n }\n\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: actionTurn.toolExecutions },\n },\n };\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'complete' },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type { PlanStep } from '../state/index.ts';\nimport { generateUUID } from '../utils/uuid.ts';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n PlanOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_PLAN_OPTIONS: Required<PlanOptions> = {\n maxPlanSteps: Infinity,\n allowReplan: true,\n planSchema: {\n type: 'object',\n properties: {\n steps: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique step identifier' },\n description: { type: 'string', description: 'What this step does' },\n tool: { type: 'string', description: 'Tool to use (if applicable)' },\n dependsOn: {\n type: 'array',\n items: { type: 'string' },\n description: 'IDs of steps this depends on',\n },\n },\n required: ['id', 'description', 'dependsOn'],\n },\n },\n },\n required: ['steps'],\n },\n};\n\nconst PLAN_PROMPT = `Create a detailed execution plan to accomplish the task.\nBreak it down into clear steps, specifying which tool to use for each step if applicable.\nInclude dependencies between steps (which steps must complete before others can start).\nReturn your plan as a JSON object with a \"steps\" array.`;\n\n/**\n * Create a plan-then-execute strategy.\n *\n * Behavior:\n * 1. Plan: LLM generates structured plan with steps and dependencies\n * 2. Execute: Execute each plan step respecting dependency order\n * 3. Replan: If a step fails and allowReplan is true, generate new plan\n *\n * @param options - Plan configuration options\n * @returns ExecutionStrategy\n */\nexport function plan(options: PlanOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_PLAN_OPTIONS, ...options };\n\n return {\n name: 'plan',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Generate the plan\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planTurn = await llm.generate(planMessages);\n\n // Parse the plan from the response\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n // Try to parse from text\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Convert to PlanStep format\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n // Apply maxPlanSteps limit\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n // Execute steps in topological order\n while (planSteps.some((s) => s.status === 'pending')) {\n // Find next executable step (all dependencies completed)\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n // No step can be executed - either done or cyclic dependency\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Update step status to in_progress\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n // Execute the step\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n try {\n const stepTurn = await llm.generate(messages);\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n }\n\n // Mark step as completed\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n } catch (err) {\n nextStep.status = 'failed';\n currentState = currentState.withPlan([...planSteps]);\n\n if (opts.allowReplan) {\n // Could implement replanning here\n // For now, just continue and let the error propagate\n }\n\n throw err;\n }\n\n // Check stop condition\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn; // Use plan turn if no execution happened\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planStream = llm.stream(planMessages);\n\n for await (const event of planStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const planTurn = await planStream.turn;\n\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_created',\n step,\n agentId,\n data: { plan: planSteps },\n },\n };\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n while (planSteps.some((s) => s.status === 'pending') && !aborted) {\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_start',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n const stepStream = llm.stream(messages);\n\n for await (const event of stepStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const stepTurn = await stepStream.turn;\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: stepTurn.response.toolCalls },\n },\n };\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: stepTurn.toolExecutions },\n },\n };\n }\n\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_end',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn;\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Tool, ToolCall } from '@providerprotocol/ai';\nimport type { ToolWithDependencies, OrderedToolCall } from './types.ts';\n\n/**\n * Execution group - a set of tool calls that can execute in parallel.\n */\nexport interface ExecutionGroup {\n /** Tool calls in this group */\n calls: ToolCall[];\n /** Whether this group contains a sequential tool (acts as barrier) */\n isBarrier: boolean;\n}\n\n/**\n * Build a map of tool definitions by name for quick lookup.\n */\nfunction buildToolMap(tools: Tool[]): Map<string, ToolWithDependencies> {\n const map = new Map<string, ToolWithDependencies>();\n for (const tool of tools) {\n map.set(tool.name, tool as ToolWithDependencies);\n }\n return map;\n}\n\n/**\n * Check if a tool call has an explicit dependency via model hint.\n */\nfunction getModelDependencies(call: ToolCall): string[] {\n const orderedCall = call as OrderedToolCall;\n return orderedCall.after ?? [];\n}\n\n/**\n * Order tool calls into execution groups respecting dependencies.\n *\n * This function takes a list of tool calls and the available tools,\n * then groups them for execution while respecting:\n * 1. Tool-level `sequential` flag (creates execution barriers)\n * 2. Tool-level `dependsOn` array (tool must wait for named tools)\n * 3. Model-driven `after` array on tool calls (call must wait for specific calls)\n *\n * @param toolCalls - Tool calls from the model response\n * @param tools - Tool definitions (may include dependency options)\n * @returns Ordered array of execution groups\n *\n * @example\n * ```typescript\n * const groups = orderToolCalls(turn.response.toolCalls, agent.tools);\n *\n * for (const group of groups) {\n * if (group.isBarrier) {\n * // Execute sequentially\n * for (const call of group.calls) {\n * await executeTool(call);\n * }\n * } else {\n * // Execute in parallel\n * await Promise.all(group.calls.map(executeTool));\n * }\n * }\n * ```\n */\nexport function orderToolCalls(\n toolCalls: ToolCall[],\n tools: Tool[],\n): ExecutionGroup[] {\n if (toolCalls.length === 0) {\n return [];\n }\n\n const toolMap = buildToolMap(tools);\n const groups: ExecutionGroup[] = [];\n\n // Track completed tool calls and tool names\n const completedCallIds = new Set<string>();\n const completedToolNames = new Set<string>();\n\n // Create a queue of pending calls\n const pending = [...toolCalls];\n\n while (pending.length > 0) {\n const readyForExecution: ToolCall[] = [];\n let hasSequential = false;\n\n // Find all calls that can execute now\n const stillPending: ToolCall[] = [];\n\n for (const call of pending) {\n const tool = toolMap.get(call.toolName);\n const toolDependsOn = tool?.dependsOn ?? [];\n const modelDependsOn = getModelDependencies(call);\n\n // Check if tool-level dependencies are satisfied\n const toolDepsOk = toolDependsOn.every(\n (depName) => completedToolNames.has(depName),\n );\n\n // Check if model-level dependencies are satisfied\n const modelDepsOk = modelDependsOn.every(\n (depId) => completedCallIds.has(depId),\n );\n\n if (toolDepsOk && modelDepsOk) {\n readyForExecution.push(call);\n if (tool?.sequential) {\n hasSequential = true;\n }\n } else {\n stillPending.push(call);\n }\n }\n\n // If nothing is ready but we have pending items, there's a cycle\n if (readyForExecution.length === 0 && stillPending.length > 0) {\n // Break the cycle by executing remaining items\n // This is a fallback - ideally dependencies should be acyclic\n groups.push({\n calls: stillPending,\n isBarrier: false,\n });\n break;\n }\n\n // If we have sequential tools, they form a barrier\n // Process them one at a time\n if (hasSequential) {\n for (const call of readyForExecution) {\n const tool = toolMap.get(call.toolName);\n groups.push({\n calls: [call],\n isBarrier: tool?.sequential ?? false,\n });\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n } else {\n // Non-sequential tools can be grouped for parallel execution\n groups.push({\n calls: readyForExecution,\n isBarrier: false,\n });\n for (const call of readyForExecution) {\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n }\n\n // Update pending list\n pending.length = 0;\n pending.push(...stillPending);\n }\n\n return groups;\n}\n\n/**\n * Check if any tools have execution dependencies defined.\n *\n * @param tools - Tool definitions to check\n * @returns true if any tool has sequential or dependsOn set\n */\nexport function hasToolDependencies(tools: Tool[]): boolean {\n for (const tool of tools) {\n const t = tool as ToolWithDependencies;\n if (t.sequential || (t.dependsOn && t.dependsOn.length > 0)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if any tool calls have model-driven dependencies.\n *\n * @param toolCalls - Tool calls to check\n * @returns true if any call has the `after` field set\n */\nexport function hasCallDependencies(toolCalls: ToolCall[]): boolean {\n for (const call of toolCalls) {\n const ordered = call as OrderedToolCall;\n if (ordered.after && ordered.after.length > 0) {\n return true;\n }\n }\n return false;\n}\n"]}
1
+ {"version":3,"sources":["../../src/execution/react.ts","../../src/execution/plan.ts","../../src/execution/tool-ordering.ts"],"names":["UserMessage"],"mappings":";;;;AAWA,IAAM,qBAAA,GAAgD;AAAA,EACpD,QAAA,EAAU,QAAA;AAAA,EACV,eAAA,EAAiB;AACnB,CAAA;AAcO,SAAS,KAAA,CAAM,OAAA,GAAwB,EAAC,EAAsB;AACnE,EAAA,MAAM,IAAA,GAAO,EAAE,GAAG,qBAAA,EAAuB,GAAG,OAAA,EAAQ;AAEpD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,OAAA;AAAA,IAEN,MAAM,QAAQ,OAAA,EAAqD;AACjE,MAAA,MAAM,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,QAAO,GAAI,OAAA;AAIhD,MAAA,IAAI,YAAA,GAAe,MAChB,WAAA,CAAY,KAAK,EACjB,YAAA,CAAa,SAAA,EAAW,OAAA,CAAQ,KAAA,CAAM,EAAE,CAAA;AAC3C,MAAA,IAAI,IAAA,GAAO,CAAA;AACX,MAAA,IAAI,SAAA;AAGJ,MAAA,MAAM,QAAA,GAAW,CAAC,GAAG,YAAA,CAAa,QAAQ,CAAA;AAE1C,MAAA,OAAO,IAAA,EAAM;AACX,QAAA,IAAA,EAAA;AACA,QAAA,YAAA,GAAe,YAAA,CAAa,SAAS,IAAI,CAAA;AAEzC,QAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,UAAA,MAAM,IAAI,MAAM,mBAAmB,CAAA;AAAA,QAC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M,QAAQ,CAAA;AAAA,QACxC,CAAC;AAAA,OACH;AACA,MAAA,OAAA,CAAQ,IAAA,CAAK,GAAG,YAAY,CAAA;AAAA,IAC9B;AAAA,EACF;AAEA,EAAA,OAAO,OAAA;AACT;AAKA,eAAe,UAAA,CACb,IAAA,EACA,IAAA,EACA,QAAA,EAC8B;AAC9B,EAAA,MAAM,SAAA,GAAY,KAAK,GAAA,EAAI;AAE3B,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,IAAA,EAAM,IAAI,CAAA;AACxC,IAAA,OAAO;AAAA,MACL,IAAA;AAAA,MACA,MAAA;AAAA,MACA,OAAA,EAAS,KAAA;AAAA,MACT,QAAA,EAAU,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KACzB;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,GAAA,GAAM,iBAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA;AACpE,IAAA,OAAO;AAAA,MACL,IAAA;AAAA,MACA,MAAA,EAAQ,IAAA;AAAA,MACR,OAAA,EAAS,IAAA;AAAA,MACT,OAAO,GAAA,CAAI,OAAA;AAAA,MACX,QAAA,EAAU,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KACzB;AAAA,EACF;AACF","file":"index.js","sourcesContent":["import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n ReactOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_REACT_OPTIONS: Required<ReactOptions> = {\n maxSteps: Infinity,\n reasoningPrompt: 'Think step by step about what you need to do next. Consider the current state, what tools are available, and what action would be most helpful.',\n};\n\n/**\n * Create a ReAct (Reason-Act-Observe) execution strategy.\n *\n * Behavior:\n * 1. Reason: LLM outputs reasoning about what to do next\n * 2. Act: LLM selects and executes tool(s)\n * 3. Observe: Tool results are formatted as observations\n * 4. Repeat until stop condition, no more actions, or maxSteps\n *\n * @param options - ReAct configuration options\n * @returns ExecutionStrategy\n */\nexport function react(options: ReactOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n return {\n name: 'react',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n while (true) {\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // REASON PHASE: Ask LLM to think about what to do\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningTurn = await llm.generate(reasoningMessages);\n\n const reasoning = reasoningTurn.response.text;\n currentState = currentState.withReasoning(reasoning);\n strategy.onReason?.(step, reasoning);\n\n // Add reasoning to conversation\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE: Execute with tools\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionTurn = await llm.generate(messages);\n finalTurn = actionTurn;\n\n // Update messages with action response\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n // Handle tool calls\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n }\n\n // OBSERVE PHASE: Process tool results\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n // Check stop conditions\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n // No more tool calls means we're done\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n // Check step limit\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n while (!aborted) {\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'reasoning' },\n },\n };\n\n // REASON PHASE\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningStream = llm.stream(reasoningMessages);\n let reasoningText = '';\n\n for await (const event of reasoningStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n\n if (event.type === 'text_delta' && event.delta.text) {\n reasoningText += event.delta.text;\n }\n }\n\n const reasoningTurn = await reasoningStream.turn;\n currentState = currentState.withReasoning(reasoningText || reasoningTurn.response.text);\n strategy.onReason?.(step, reasoningText || reasoningTurn.response.text);\n\n yield {\n source: 'uap',\n uap: {\n type: 'reasoning',\n step,\n agentId,\n data: { reasoning: reasoningText || reasoningTurn.response.text },\n },\n };\n\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionStream = llm.stream(messages);\n\n for await (const event of actionStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const actionTurn = await actionStream.turn;\n finalTurn = actionTurn;\n\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: actionTurn.response.toolCalls },\n },\n };\n }\n\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: actionTurn.toolExecutions },\n },\n };\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'complete' },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type { PlanStep } from '../state/index.ts';\nimport { generateUUID } from '../utils/uuid.ts';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n PlanOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_PLAN_OPTIONS: Required<PlanOptions> = {\n maxPlanSteps: Infinity,\n allowReplan: true,\n planSchema: {\n type: 'object',\n properties: {\n steps: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique step identifier' },\n description: { type: 'string', description: 'What this step does' },\n tool: { type: 'string', description: 'Tool to use (if applicable)' },\n dependsOn: {\n type: 'array',\n items: { type: 'string' },\n description: 'IDs of steps this depends on',\n },\n },\n required: ['id', 'description', 'dependsOn'],\n },\n },\n },\n required: ['steps'],\n },\n};\n\nconst PLAN_PROMPT = `Create a detailed execution plan to accomplish the task.\nBreak it down into clear steps, specifying which tool to use for each step if applicable.\nInclude dependencies between steps (which steps must complete before others can start).\nReturn your plan as a JSON object with a \"steps\" array.`;\n\n/**\n * Create a plan-then-execute strategy.\n *\n * Behavior:\n * 1. Plan: LLM generates structured plan with steps and dependencies\n * 2. Execute: Execute each plan step respecting dependency order\n * 3. Replan: If a step fails and allowReplan is true, generate new plan\n *\n * @param options - Plan configuration options\n * @returns ExecutionStrategy\n */\nexport function plan(options: PlanOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_PLAN_OPTIONS, ...options };\n\n return {\n name: 'plan',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Generate the plan\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planTurn = await llm.generate(planMessages);\n\n // Parse the plan from the response\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n // Try to parse from text\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Convert to PlanStep format\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n // Apply maxPlanSteps limit\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n // Execute steps in topological order\n while (planSteps.some((s) => s.status === 'pending')) {\n // Find next executable step (all dependencies completed)\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n // No step can be executed - either done or cyclic dependency\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Update step status to in_progress\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n // Execute the step\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n try {\n const stepTurn = await llm.generate(messages);\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n }\n\n // Mark step as completed\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n } catch (err) {\n nextStep.status = 'failed';\n currentState = currentState.withPlan([...planSteps]);\n\n if (opts.allowReplan) {\n // Could implement replanning here\n // For now, just continue and let the error propagate\n }\n\n throw err;\n }\n\n // Check stop condition\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn; // Use plan turn if no execution happened\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planStream = llm.stream(planMessages);\n\n for await (const event of planStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const planTurn = await planStream.turn;\n\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_created',\n step,\n agentId,\n data: { plan: planSteps },\n },\n };\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n while (planSteps.some((s) => s.status === 'pending') && !aborted) {\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_start',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n const stepStream = llm.stream(messages);\n\n for await (const event of stepStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const stepTurn = await stepStream.turn;\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: stepTurn.response.toolCalls },\n },\n };\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: stepTurn.toolExecutions },\n },\n };\n }\n\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_end',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn;\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Tool, ToolCall } from '@providerprotocol/ai';\nimport type { ToolWithDependencies, OrderedToolCall } from './types.ts';\n\n/**\n * Execution group - a set of tool calls that can execute in parallel.\n */\nexport interface ExecutionGroup {\n /** Tool calls in this group */\n calls: ToolCall[];\n /** Whether this group contains a sequential tool (acts as barrier) */\n isBarrier: boolean;\n}\n\n/**\n * Build a map of tool definitions by name for quick lookup.\n */\nfunction buildToolMap(tools: Tool[]): Map<string, ToolWithDependencies> {\n const map = new Map<string, ToolWithDependencies>();\n for (const tool of tools) {\n map.set(tool.name, tool as ToolWithDependencies);\n }\n return map;\n}\n\n/**\n * Check if a tool call has an explicit dependency via model hint.\n */\nfunction getModelDependencies(call: ToolCall): string[] {\n const orderedCall = call as OrderedToolCall;\n return orderedCall.after ?? [];\n}\n\n/**\n * Order tool calls into execution groups respecting dependencies.\n *\n * This function takes a list of tool calls and the available tools,\n * then groups them for execution while respecting:\n * 1. Tool-level `sequential` flag (creates execution barriers)\n * 2. Tool-level `dependsOn` array (tool must wait for named tools)\n * 3. Model-driven `after` array on tool calls (call must wait for specific calls)\n *\n * @param toolCalls - Tool calls from the model response\n * @param tools - Tool definitions (may include dependency options)\n * @returns Ordered array of execution groups\n *\n * @example\n * ```typescript\n * const groups = orderToolCalls(turn.response.toolCalls, agent.tools);\n *\n * for (const group of groups) {\n * if (group.isBarrier) {\n * // Execute sequentially\n * for (const call of group.calls) {\n * await executeTool(call);\n * }\n * } else {\n * // Execute in parallel\n * await Promise.all(group.calls.map(executeTool));\n * }\n * }\n * ```\n */\nexport function orderToolCalls(\n toolCalls: ToolCall[],\n tools: Tool[],\n): ExecutionGroup[] {\n if (toolCalls.length === 0) {\n return [];\n }\n\n const toolMap = buildToolMap(tools);\n const groups: ExecutionGroup[] = [];\n\n // Track completed tool calls and tool names\n const completedCallIds = new Set<string>();\n const completedToolNames = new Set<string>();\n\n // Create a queue of pending calls\n const pending = [...toolCalls];\n\n while (pending.length > 0) {\n const readyForExecution: ToolCall[] = [];\n let hasSequential = false;\n\n // Find all calls that can execute now\n const stillPending: ToolCall[] = [];\n\n for (const call of pending) {\n const tool = toolMap.get(call.toolName);\n const toolDependsOn = tool?.dependsOn ?? [];\n const modelDependsOn = getModelDependencies(call);\n\n // Check if tool-level dependencies are satisfied\n const toolDepsOk = toolDependsOn.every(\n (depName) => completedToolNames.has(depName),\n );\n\n // Check if model-level dependencies are satisfied\n const modelDepsOk = modelDependsOn.every(\n (depId) => completedCallIds.has(depId),\n );\n\n if (toolDepsOk && modelDepsOk) {\n readyForExecution.push(call);\n if (tool?.sequential) {\n hasSequential = true;\n }\n } else {\n stillPending.push(call);\n }\n }\n\n // If nothing is ready but we have pending items, there's a cycle\n if (readyForExecution.length === 0 && stillPending.length > 0) {\n // Break the cycle by executing remaining items\n // This is a fallback - ideally dependencies should be acyclic\n groups.push({\n calls: stillPending,\n isBarrier: false,\n });\n break;\n }\n\n // If we have sequential tools, they form a barrier\n // Process them one at a time\n if (hasSequential) {\n for (const call of readyForExecution) {\n const tool = toolMap.get(call.toolName);\n groups.push({\n calls: [call],\n isBarrier: tool?.sequential ?? false,\n });\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n } else {\n // Non-sequential tools can be grouped for parallel execution\n groups.push({\n calls: readyForExecution,\n isBarrier: false,\n });\n for (const call of readyForExecution) {\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n }\n\n // Update pending list\n pending.length = 0;\n pending.push(...stillPending);\n }\n\n return groups;\n}\n\n/**\n * Check if any tools have execution dependencies defined.\n *\n * @param tools - Tool definitions to check\n * @returns true if any tool has sequential or dependsOn set\n */\nexport function hasToolDependencies(tools: Tool[]): boolean {\n for (const tool of tools) {\n const t = tool as ToolWithDependencies;\n if (t.sequential || (t.dependsOn && t.dependsOn.length > 0)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if any tool calls have model-driven dependencies.\n *\n * @param toolCalls - Tool calls to check\n * @returns true if any call has the `after` field set\n */\nexport function hasCallDependencies(toolCalls: ToolCall[]): boolean {\n for (const call of toolCalls) {\n const ordered = call as OrderedToolCall;\n if (ordered.after && ordered.after.length > 0) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Result of executing a tool call.\n */\nexport interface ToolExecutionResult {\n /** The tool call that was executed */\n call: ToolCall;\n /** The result from the tool */\n result: unknown;\n /** Whether the tool threw an error */\n isError: boolean;\n /** Error message if isError is true */\n error?: string;\n /** Execution duration in milliseconds */\n duration: number;\n}\n\n/**\n * Function type for executing a single tool call.\n */\nexport type ToolExecutor = (call: ToolCall, tool: Tool) => Promise<unknown>;\n\n/**\n * Execute tool calls respecting dependency ordering.\n *\n * This function takes tool calls, orders them using `orderToolCalls()`,\n * and executes them respecting barriers (sequential tools) and\n * dependencies (dependsOn, after).\n *\n * Per UAP-1.0 Sections 8.5 and 8.6:\n * - Tools with `sequential: true` execute alone (barrier)\n * - Tools with `dependsOn` wait for named tools to complete\n * - Tool calls with `after` wait for specific call IDs to complete\n *\n * @param toolCalls - Tool calls from the model response\n * @param tools - Tool definitions with potential dependencies\n * @param executor - Function to execute a single tool call\n * @returns Array of execution results in completion order\n *\n * @example\n * ```typescript\n * import { executeOrderedToolCalls } from '@providerprotocol/agents/execution';\n *\n * // Define tools with dependencies\n * const readTool: ToolWithDependencies = {\n * name: 'read_file',\n * sequential: true, // Must complete before others\n * run: async (params) => readFile(params.path),\n * };\n *\n * const processTool: ToolWithDependencies = {\n * name: 'process',\n * dependsOn: ['read_file'], // Wait for read_file\n * run: async (params) => process(params.data),\n * };\n *\n * // Execute with ordering\n * const results = await executeOrderedToolCalls(\n * turn.response.toolCalls,\n * [readTool, processTool],\n * async (call, tool) => tool.run(call.arguments),\n * );\n * ```\n */\nexport async function executeOrderedToolCalls(\n toolCalls: ToolCall[],\n tools: Tool[],\n executor: ToolExecutor,\n): Promise<ToolExecutionResult[]> {\n if (toolCalls.length === 0) {\n return [];\n }\n\n const toolMap = new Map<string, Tool>();\n for (const tool of tools) {\n toolMap.set(tool.name, tool);\n }\n\n const groups = orderToolCalls(toolCalls, tools);\n const results: ToolExecutionResult[] = [];\n\n for (const group of groups) {\n if (group.isBarrier) {\n // Sequential execution - one at a time\n for (const call of group.calls) {\n const tool = toolMap.get(call.toolName);\n if (!tool) {\n results.push({\n call,\n result: null,\n isError: true,\n error: `Tool not found: ${call.toolName}`,\n duration: 0,\n });\n continue;\n }\n\n const result = await executeOne(call, tool, executor);\n results.push(result);\n }\n } else {\n // Parallel execution\n const groupResults = await Promise.all(\n group.calls.map(async (call) => {\n const tool = toolMap.get(call.toolName);\n if (!tool) {\n return {\n call,\n result: null,\n isError: true,\n error: `Tool not found: ${call.toolName}`,\n duration: 0,\n };\n }\n return executeOne(call, tool, executor);\n }),\n );\n results.push(...groupResults);\n }\n }\n\n return results;\n}\n\n/**\n * Execute a single tool call with timing and error handling.\n */\nasync function executeOne(\n call: ToolCall,\n tool: Tool,\n executor: ToolExecutor,\n): Promise<ToolExecutionResult> {\n const startTime = Date.now();\n\n try {\n const result = await executor(call, tool);\n return {\n call,\n result,\n isError: false,\n duration: Date.now() - startTime,\n };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return {\n call,\n result: null,\n isError: true,\n error: err.message,\n duration: Date.now() - startTime,\n };\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import { LLMOptions, ModelReference, LLMInstance, Tool, Message, Turn } from '@providerprotocol/ai';
1
+ import { LLMOptions, ModelReference, LLMInstance, Tool, Message, Turn, JSONSchema } from '@providerprotocol/ai';
2
2
  import { A as AgentState } from './index-qsPwbY86.js';
3
- import { E as ExecutionStrategy, A as AgentStrategy, G as GenerateResult, a as AgentStreamResult } from './types-D1egxttz.js';
4
- export { b as AgentStreamEvent, O as OnSubagentEvent, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, U as UAPEventType } from './types-D1egxttz.js';
5
- import { M as Middleware } from './types-BiyEVOnf.js';
3
+ import { E as ExecutionStrategy, A as AgentStrategy, G as GenerateResult, a as AgentStreamResult, T as ToolExecutionContext } from './types-DC8XeoaI.js';
4
+ export { b as AgentStreamEvent, C as ContextAwareToolRun, O as OnSubagentEvent, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, U as UAPEventType } from './types-DC8XeoaI.js';
5
+ import { M as Middleware } from './types-B9VuAOo6.js';
6
6
  import { C as CheckpointStore } from './types-DChRdQoX.js';
7
7
  export { b as CheckpointData, a as CheckpointMetadata, F as FileCheckpointOptions } from './types-DChRdQoX.js';
8
8
  export { ThreadNode, ThreadNodeJSON, ThreadTree, ThreadTreeJSON } from './thread-tree/index.js';
9
+ export { I as InjectToolContextOptions, i as injectToolContext, a as isContextAwareTool, w as withToolContext } from './tool-context-Cc_qNVud.js';
9
10
  export { A as AgentStateInterface, a as AgentStateJSON, P as PlanStep, b as PlanStepStatus, S as SubagentExecutionTrace, c as SubagentExecutionTraceJSON, T as ToolExecutionTrace } from './types-2Vsthzyu.js';
10
11
 
11
12
  /**
@@ -98,4 +99,121 @@ interface Agent {
98
99
  */
99
100
  declare function agent(options: AgentOptions): Agent;
100
101
 
101
- export { type Agent, type AgentOptions, AgentState, AgentStrategy, AgentStreamResult, CheckpointStore, GenerateResult, agent };
102
+ /**
103
+ * Sub-agent tool creation utilities.
104
+ *
105
+ * Per UAP-1.0 Section 8.7, implementations SHOULD provide helper utilities
106
+ * for creating sub-agent tools with event propagation.
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * import { agent } from '@providerprotocol/agents';
111
+ * import { createSubAgentTool } from '@providerprotocol/agents/subagent';
112
+ *
113
+ * // Create a sub-agent
114
+ * const explorer = agent({
115
+ * model: anthropic('claude-haiku-4-20250514'),
116
+ * tools: [Glob, Grep, Read],
117
+ * system: 'You explore codebases.',
118
+ * });
119
+ *
120
+ * // Wrap as a tool with event propagation
121
+ * const explorerTool = createSubAgentTool({
122
+ * agent: explorer,
123
+ * name: 'explore_codebase',
124
+ * description: 'Explore and find relevant code',
125
+ * parameters: {
126
+ * type: 'object',
127
+ * properties: {
128
+ * query: { type: 'string', description: 'What to find' },
129
+ * },
130
+ * required: ['query'],
131
+ * },
132
+ * buildPrompt: (params) => `Find: ${params.query}`,
133
+ * subagentType: 'explorer',
134
+ * });
135
+ *
136
+ * // Use in parent agent
137
+ * const coder = agent({
138
+ * model: anthropic('claude-sonnet-4-20250514'),
139
+ * tools: [Bash, Write, explorerTool],
140
+ * });
141
+ * ```
142
+ *
143
+ * @packageDocumentation
144
+ */
145
+
146
+ /**
147
+ * Options for creating a sub-agent tool.
148
+ */
149
+ interface CreateSubAgentToolOptions {
150
+ /** The sub-agent to expose as a tool */
151
+ agent: Agent;
152
+ /** Tool name (must be unique within parent agent's tools) */
153
+ name: string;
154
+ /** Tool description for the model */
155
+ description: string;
156
+ /** JSON Schema for tool parameters */
157
+ parameters: JSONSchema;
158
+ /** Convert tool parameters to a prompt for the sub-agent */
159
+ buildPrompt: (params: Record<string, unknown>) => string;
160
+ /**
161
+ * Identifier for the sub-agent type (used in events).
162
+ * Defaults to the tool name.
163
+ */
164
+ subagentType?: string;
165
+ /**
166
+ * Whether to stream the sub-agent execution.
167
+ * When true, inner events are forwarded to parent.
168
+ * Default: true
169
+ */
170
+ stream?: boolean;
171
+ }
172
+ /**
173
+ * Create a UPP Tool from a UAP Agent with full event propagation.
174
+ *
175
+ * Per UAP-1.0 Section 8.7, this helper:
176
+ * 1. Emits `subagent_start` before execution begins
177
+ * 2. Forwards inner events during streaming execution
178
+ * 3. Emits `subagent_end` after completion (success or failure)
179
+ * 4. Provides execution context to sub-agent for tracing
180
+ *
181
+ * The created tool accepts an optional `ToolExecutionContext` as a second
182
+ * parameter, which is injected by `injectToolContext()` during execution.
183
+ *
184
+ * @param options - Configuration for the sub-agent tool
185
+ * @returns A Tool that executes the sub-agent and propagates events
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * const summarizer = agent({
190
+ * model: anthropic('claude-haiku-4-20250514'),
191
+ * system: 'You summarize text concisely.',
192
+ * });
193
+ *
194
+ * const summarizerTool = createSubAgentTool({
195
+ * agent: summarizer,
196
+ * name: 'summarize',
197
+ * description: 'Summarize the given text',
198
+ * parameters: {
199
+ * type: 'object',
200
+ * properties: {
201
+ * text: { type: 'string', description: 'Text to summarize' },
202
+ * maxLength: { type: 'number', description: 'Max summary length' },
203
+ * },
204
+ * required: ['text'],
205
+ * },
206
+ * buildPrompt: (params) =>
207
+ * `Summarize this in ${params.maxLength ?? 100} words:\n\n${params.text}`,
208
+ * subagentType: 'summarizer',
209
+ * });
210
+ * ```
211
+ */
212
+ declare function createSubAgentTool(options: CreateSubAgentToolOptions): Tool;
213
+ /**
214
+ * Type for the run function of a sub-agent tool.
215
+ * Accepts params and optional execution context.
216
+ */
217
+ type SubAgentToolRun = (params: Record<string, unknown>, context?: ToolExecutionContext) => Promise<string>;
218
+
219
+ export { type Agent, type AgentOptions, AgentState, AgentStrategy, AgentStreamResult, CheckpointStore, type CreateSubAgentToolOptions, GenerateResult, type SubAgentToolRun, ToolExecutionContext, agent, createSubAgentTool };
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { loop } from './chunk-4ESYN66B.js';
1
+ import { loop } from './chunk-CEHXAE4Z.js';
2
+ export { injectToolContext, isContextAwareTool, withToolContext } from './chunk-CEHXAE4Z.js';
2
3
  import { AgentState } from './chunk-T47B3VAF.js';
3
4
  export { AgentState, ThreadNode, ThreadTree } from './chunk-T47B3VAF.js';
4
5
  import { generateUUID } from './chunk-EKRXMSDX.js';
@@ -185,24 +186,7 @@ function agent(options) {
185
186
  };
186
187
  },
187
188
  async ask(input, state) {
188
- const normalizedInput = normalizeInput(input);
189
- const result = await agentInstance.generate(normalizedInput, state);
190
- const responseMessages = result.state.messages.slice(state.messages.length);
191
- const finalState = state.withMessage(normalizedInput).withMessages(responseMessages).withStep(result.state.step);
192
- let stateWithMetadata = finalState;
193
- for (const [key, value] of Object.entries(result.state.metadata)) {
194
- stateWithMetadata = stateWithMetadata.withMetadata(key, value);
195
- }
196
- for (const reasoning of result.state.reasoning) {
197
- stateWithMetadata = stateWithMetadata.withReasoning(reasoning);
198
- }
199
- if (result.state.plan) {
200
- stateWithMetadata = stateWithMetadata.withPlan([...result.state.plan]);
201
- }
202
- return {
203
- turn: result.turn,
204
- state: stateWithMetadata
205
- };
189
+ return agentInstance.generate(input, state);
206
190
  },
207
191
  async query(input) {
208
192
  const initialState = AgentState.initial();
@@ -213,6 +197,123 @@ function agent(options) {
213
197
  return agentInstance;
214
198
  }
215
199
 
216
- export { agent };
200
+ // src/subagent/index.ts
201
+ function createSubAgentTool(options) {
202
+ const {
203
+ agent: agent2,
204
+ name,
205
+ description,
206
+ parameters,
207
+ buildPrompt,
208
+ subagentType = name,
209
+ stream: shouldStream = true
210
+ } = options;
211
+ return {
212
+ name,
213
+ description,
214
+ parameters,
215
+ run: async (params, context) => {
216
+ const subagentId = generateUUID();
217
+ const toolCallId = context?.toolCallId ?? generateUUID();
218
+ const emit = context?.onSubagentEvent;
219
+ const prompt = buildPrompt(params);
220
+ const startTime = Date.now();
221
+ const startEvent = {
222
+ type: "subagent_start",
223
+ subagentId,
224
+ subagentType,
225
+ parentToolCallId: toolCallId,
226
+ prompt,
227
+ timestamp: startTime
228
+ };
229
+ emit?.(startEvent);
230
+ try {
231
+ if (shouldStream) {
232
+ return await executeWithStreaming(
233
+ agent2,
234
+ prompt,
235
+ subagentId,
236
+ subagentType,
237
+ toolCallId,
238
+ emit
239
+ );
240
+ }
241
+ return await executeWithoutStreaming(
242
+ agent2,
243
+ prompt,
244
+ subagentId,
245
+ subagentType,
246
+ toolCallId,
247
+ emit
248
+ );
249
+ } catch (error) {
250
+ const err = error instanceof Error ? error : new Error(String(error));
251
+ const endEvent = {
252
+ type: "subagent_end",
253
+ subagentId,
254
+ subagentType,
255
+ parentToolCallId: toolCallId,
256
+ success: false,
257
+ error: err.message,
258
+ timestamp: Date.now()
259
+ };
260
+ emit?.(endEvent);
261
+ throw err;
262
+ }
263
+ }
264
+ };
265
+ }
266
+ async function executeWithStreaming(agent2, prompt, subagentId, subagentType, toolCallId, emit) {
267
+ const stream = agent2.stream(prompt, AgentState.initial());
268
+ for await (const event of stream) {
269
+ emit?.({
270
+ type: "subagent_event",
271
+ subagentId,
272
+ subagentType,
273
+ parentToolCallId: toolCallId,
274
+ innerEvent: event
275
+ });
276
+ }
277
+ const result = await stream.result;
278
+ const endEvent = {
279
+ type: "subagent_end",
280
+ subagentId,
281
+ subagentType,
282
+ parentToolCallId: toolCallId,
283
+ success: true,
284
+ result: result.turn.response.text,
285
+ timestamp: Date.now(),
286
+ toolExecutions: result.turn.toolExecutions?.map((te) => ({
287
+ toolName: te.toolName,
288
+ arguments: te.arguments,
289
+ result: String(te.result)
290
+ })),
291
+ usage: result.turn.usage
292
+ };
293
+ emit?.(endEvent);
294
+ return result.turn.response.text;
295
+ }
296
+ async function executeWithoutStreaming(agent2, prompt, subagentId, subagentType, toolCallId, emit) {
297
+ const result = await agent2.generate(prompt, AgentState.initial());
298
+ const endEvent = {
299
+ type: "subagent_end",
300
+ subagentId,
301
+ subagentType,
302
+ parentToolCallId: toolCallId,
303
+ success: true,
304
+ result: result.turn.response.text,
305
+ timestamp: Date.now(),
306
+ toolExecutions: result.turn.toolExecutions?.map((te) => ({
307
+ toolName: te.toolName,
308
+ arguments: te.arguments,
309
+ result: String(te.result)
310
+ })),
311
+ usage: result.turn.usage
312
+ };
313
+ emit?.(endEvent);
314
+ return result.turn.response.text;
315
+ }
316
+
317
+ export { agent, createSubAgentTool };
217
318
  //# sourceMappingURL=index.js.map
218
319
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/index.ts"],"names":[],"mappings":";;;;;;AA0CO,SAAS,MAAM,OAAA,EAA8B;AAClD,EAAA,MAAM;AAAA;AAAA,IAEJ,YAAY,IAAA,EAAK;AAAA,IACjB,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,WAAA;AAAA,IACA,SAAA,EAAW,iBAAA;AAAA,IACX,YAAA;AAAA;AAAA,IAEA,KAAA;AAAA,IACA,SAAS,EAAC;AAAA,IACV,MAAA;AAAA,IACA,QAAQ,EAAC;AAAA,IACT,MAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAEJ,EA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,MACvE;AAEA,MAAA,OAAO;AAAA,QACL,MAAM,MAAA,CAAO,IAAA;AAAA,QACb,KAAA,EAAO;AAAA,OACT;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,MAAM,KAAA,EAAwC;AAClD,MAAA,MAAM,YAAA,GAAe,WAAW,OAAA,EAAQ;AACxC,MAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAc,QAAA,CAAS,OAAO,YAAY,CAAA;AAC/D,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AAEA,EAAA,OAAO,aAAA;AACT","file":"index.js","sourcesContent":["import {\n llm,\n UserMessage,\n} from '@providerprotocol/ai';\nimport type {\n LLMInstance,\n Message,\n Turn,\n} from '@providerprotocol/ai';\nimport { generateUUID } from '../utils/uuid.ts';\nimport { AgentState } from '../state/index.ts';\nimport { loop } from '../execution/loop.ts';\nimport type {\n ExecutionContext,\n GenerateResult,\n AgentStreamResult,\n AgentStrategy,\n} from '../execution/types.ts';\nimport type { Middleware, MiddlewareContext } from '../middleware/types.ts';\nimport type { Agent, AgentOptions } from './types.ts';\n\n/**\n * Create an agent instance.\n *\n * @param options - Agent configuration\n * @returns Agent instance\n *\n * @example\n * ```typescript\n * import { agent, AgentState } from '@providerprotocol/agents';\n * import { anthropic } from '@providerprotocol/ai/anthropic';\n *\n * const coder = agent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * tools: [Bash, Read, Write],\n * system: 'You are a coding assistant.',\n * });\n *\n * const state = AgentState.initial();\n * const { turn, state: newState } = await coder.generate('Hello', state);\n * ```\n */\nexport function agent(options: AgentOptions): Agent {\n const {\n // UAP-specific options\n execution = loop(),\n middleware = [],\n strategy = {},\n checkpoints,\n sessionId: providedSessionId,\n _llmInstance,\n // LLM options (passthrough to UPP)\n model,\n params = {},\n config,\n tools = [],\n system,\n structure,\n toolStrategy,\n } = options;\n\n const agentId = generateUUID();\n // Generate sessionId (UUIDv4) if checkpoints provided but no sessionId\n // Per UAP spec Section 3.4: Session IDs MUST be UUIDv4\n const sessionId = checkpoints ? (providedSessionId ?? generateUUID()) : providedSessionId;\n\n // Create the LLM instance with full UPP passthrough (or use injected instance for testing)\n const llmInstance: LLMInstance = _llmInstance ?? llm({\n model,\n params,\n config,\n system,\n structure,\n tools,\n toolStrategy,\n });\n\n /**\n * Normalize input to a Message.\n */\n function normalizeInput(input: string | Message): Message {\n if (typeof input === 'string') {\n return new UserMessage(input);\n }\n return input;\n }\n\n /**\n * Run middleware before hooks.\n */\n async function runBeforeMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n ): Promise<MiddlewareContext> {\n let currentContext = context;\n\n for (const mw of middlewares) {\n if (mw.before) {\n const result = await mw.before(currentContext);\n if (result) {\n currentContext = result;\n }\n }\n }\n\n return currentContext;\n }\n\n /**\n * Run middleware after hooks (in reverse order).\n */\n async function runAfterMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n result: GenerateResult,\n ): Promise<GenerateResult> {\n let currentResult = result;\n\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.after) {\n currentResult = await mw.after(context, currentResult);\n }\n }\n\n return currentResult;\n }\n\n /**\n * Run middleware error hooks (in reverse order).\n */\n async function runErrorMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n error: Error,\n ): Promise<GenerateResult | undefined> {\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.onError) {\n const result = await mw.onError(context, error);\n if (result) {\n return result;\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Build execution context.\n */\n function buildExecutionContext(\n input: Message,\n state: AgentState,\n resolvedStrategy: AgentStrategy,\n signal?: AbortSignal,\n ): ExecutionContext {\n return {\n agent: { id: agentId, system },\n llm: llmInstance,\n input,\n state,\n tools,\n strategy: resolvedStrategy,\n signal,\n checkpoints,\n sessionId,\n };\n }\n\n const agentInstance: Agent = {\n id: agentId,\n model,\n tools,\n system,\n\n async generate(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n );\n\n // Execute strategy\n const result = await execution.execute(executionContext);\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n return finalResult;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n return recovered;\n }\n\n throw err;\n }\n },\n\n stream(\n input: string | Message,\n state: AgentState,\n ): AgentStreamResult {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n // We need to run before middleware synchronously enough to get the context\n // but streaming is inherently async. We'll handle this by wrapping the stream.\n let aborted = false;\n const abortController = new AbortController();\n\n let resolveResult: (result: GenerateResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<GenerateResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const createStream = async function* () {\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n abortController.signal,\n );\n\n // Get the stream from the execution strategy\n const streamResult = execution.stream(executionContext);\n\n // Yield events from the stream\n for await (const event of streamResult) {\n if (aborted) {\n break;\n }\n yield event;\n }\n\n // Get the final result\n const result = await streamResult.result;\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n resolveResult(finalResult);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n resolveResult(recovered);\n return;\n }\n\n rejectResult(err);\n throw err;\n }\n };\n\n const iterator = createStream();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n\n async ask(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n const normalizedInput = normalizeInput(input);\n\n // Generate with original state - execution strategy adds input to LLM call\n const result = await agentInstance.generate(normalizedInput, state);\n\n // Build final state with correct message order:\n // original messages + input + response messages from this turn\n const responseMessages = result.state.messages.slice(state.messages.length);\n const finalState = state\n .withMessage(normalizedInput)\n .withMessages(responseMessages)\n .withStep(result.state.step);\n\n // Preserve metadata from execution\n let stateWithMetadata = finalState;\n for (const [key, value] of Object.entries(result.state.metadata)) {\n stateWithMetadata = stateWithMetadata.withMetadata(key, value);\n }\n\n // Preserve reasoning traces\n for (const reasoning of result.state.reasoning) {\n stateWithMetadata = stateWithMetadata.withReasoning(reasoning);\n }\n\n // Preserve plan if present\n if (result.state.plan) {\n stateWithMetadata = stateWithMetadata.withPlan([...result.state.plan]);\n }\n\n return {\n turn: result.turn,\n state: stateWithMetadata,\n };\n },\n\n async query(input: string | Message): Promise<Turn> {\n const initialState = AgentState.initial();\n const result = await agentInstance.generate(input, initialState);\n return result.turn;\n },\n };\n\n return agentInstance;\n}\n\nexport type { Agent, AgentOptions } from './types.ts';\nexport type {\n GenerateResult,\n AgentStreamResult,\n AgentStreamEvent,\n UAPEventType,\n AgentStrategy,\n // Sub-agent event types (Section 8.7)\n SubagentEventType,\n SubagentEventBase,\n SubagentStartEvent,\n SubagentInnerEvent,\n SubagentEndEvent,\n SubagentEvent,\n OnSubagentEvent,\n} from '../execution/types.ts';\n"]}
1
+ {"version":3,"sources":["../src/agent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AAO,QAAQ,CAAA;AAEf,EAAA,OAAO,MAAA,CAAO,KAAK,QAAA,CAAS,IAAA;AAC9B;AAKA,eAAe,wBACbA,MAAAA,EACA,MAAA,EACA,UAAA,EACA,YAAA,EACA,YACA,IAAA,EACiB;AACjB,EAAA,MAAM,SAAS,MAAMA,MAAAA,CAAM,SAAS,MAAA,EAAQ,UAAA,CAAW,SAAS,CAAA;AAGhE,EAAA,MAAM,QAAA,GAA6B;AAAA,IACjC,IAAA,EAAM,cAAA;AAAA,IACN,UAAA;AAAA,IACA,YAAA;AAAA,IACA,gBAAA,EAAkB,UAAA;AAAA,IAClB,OAAA,EAAS,IAAA;AAAA,IACT,MAAA,EAAQ,MAAA,CAAO,IAAA,CAAK,QAAA,CAAS,IAAA;AAAA,IAC7B,SAAA,EAAW,KAAK,GAAA,EAAI;AAAA,IACpB,gBAAgB,MAAA,CAAO,IAAA,CAAK,cAAA,EAAgB,GAAA,CAAI,CAAC,EAAA,MAAQ;AAAA,MACvD,UAAU,EAAA,CAAG,QAAA;AAAA,MACb,WAAW,EAAA,CAAG,SAAA;AAAA,MACd,MAAA,EAAQ,MAAA,CAAO,EAAA,CAAG,MAAM;AAAA,KAC1B,CAAE,CAAA;AAAA,IACF,KAAA,EAAO,OAAO,IAAA,CAAK;AAAA,GACrB;AACA,EAAA,IAAA,GAAO,QAAQ,CAAA;AAEf,EAAA,OAAO,MAAA,CAAO,KAAK,QAAA,CAAS,IAAA;AAC9B","file":"index.js","sourcesContent":["import {\n llm,\n UserMessage,\n} from '@providerprotocol/ai';\nimport type {\n LLMInstance,\n Message,\n Turn,\n} from '@providerprotocol/ai';\nimport { generateUUID } from '../utils/uuid.ts';\nimport { AgentState } from '../state/index.ts';\nimport { loop } from '../execution/loop.ts';\nimport type {\n ExecutionContext,\n GenerateResult,\n AgentStreamResult,\n AgentStrategy,\n} from '../execution/types.ts';\nimport type { Middleware, MiddlewareContext } from '../middleware/types.ts';\nimport type { Agent, AgentOptions } from './types.ts';\n\n/**\n * Create an agent instance.\n *\n * @param options - Agent configuration\n * @returns Agent instance\n *\n * @example\n * ```typescript\n * import { agent, AgentState } from '@providerprotocol/agents';\n * import { anthropic } from '@providerprotocol/ai/anthropic';\n *\n * const coder = agent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * tools: [Bash, Read, Write],\n * system: 'You are a coding assistant.',\n * });\n *\n * const state = AgentState.initial();\n * const { turn, state: newState } = await coder.generate('Hello', state);\n * ```\n */\nexport function agent(options: AgentOptions): Agent {\n const {\n // UAP-specific options\n execution = loop(),\n middleware = [],\n strategy = {},\n checkpoints,\n sessionId: providedSessionId,\n _llmInstance,\n // LLM options (passthrough to UPP)\n model,\n params = {},\n config,\n tools = [],\n system,\n structure,\n toolStrategy,\n } = options;\n\n const agentId = generateUUID();\n // Generate sessionId (UUIDv4) if checkpoints provided but no sessionId\n // Per UAP spec Section 3.4: Session IDs MUST be UUIDv4\n const sessionId = checkpoints ? (providedSessionId ?? generateUUID()) : providedSessionId;\n\n // Create the LLM instance with full UPP passthrough (or use injected instance for testing)\n const llmInstance: LLMInstance = _llmInstance ?? llm({\n model,\n params,\n config,\n system,\n structure,\n tools,\n toolStrategy,\n });\n\n /**\n * Normalize input to a Message.\n */\n function normalizeInput(input: string | Message): Message {\n if (typeof input === 'string') {\n return new UserMessage(input);\n }\n return input;\n }\n\n /**\n * Run middleware before hooks.\n */\n async function runBeforeMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n ): Promise<MiddlewareContext> {\n let currentContext = context;\n\n for (const mw of middlewares) {\n if (mw.before) {\n const result = await mw.before(currentContext);\n if (result) {\n currentContext = result;\n }\n }\n }\n\n return currentContext;\n }\n\n /**\n * Run middleware after hooks (in reverse order).\n */\n async function runAfterMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n result: GenerateResult,\n ): Promise<GenerateResult> {\n let currentResult = result;\n\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.after) {\n currentResult = await mw.after(context, currentResult);\n }\n }\n\n return currentResult;\n }\n\n /**\n * Run middleware error hooks (in reverse order).\n */\n async function runErrorMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n error: Error,\n ): Promise<GenerateResult | undefined> {\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.onError) {\n const result = await mw.onError(context, error);\n if (result) {\n return result;\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Build execution context.\n */\n function buildExecutionContext(\n input: Message,\n state: AgentState,\n resolvedStrategy: AgentStrategy,\n signal?: AbortSignal,\n ): ExecutionContext {\n return {\n agent: { id: agentId, system },\n llm: llmInstance,\n input,\n state,\n tools,\n strategy: resolvedStrategy,\n signal,\n checkpoints,\n sessionId,\n };\n }\n\n const agentInstance: Agent = {\n id: agentId,\n model,\n tools,\n system,\n\n async generate(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n );\n\n // Execute strategy\n const result = await execution.execute(executionContext);\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n return finalResult;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n return recovered;\n }\n\n throw err;\n }\n },\n\n stream(\n input: string | Message,\n state: AgentState,\n ): AgentStreamResult {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n // We need to run before middleware synchronously enough to get the context\n // but streaming is inherently async. We'll handle this by wrapping the stream.\n let aborted = false;\n const abortController = new AbortController();\n\n let resolveResult: (result: GenerateResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<GenerateResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const createStream = async function* () {\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n abortController.signal,\n );\n\n // Get the stream from the execution strategy\n const streamResult = execution.stream(executionContext);\n\n // Yield events from the stream\n for await (const event of streamResult) {\n if (aborted) {\n break;\n }\n yield event;\n }\n\n // Get the final result\n const result = await streamResult.result;\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n resolveResult(finalResult);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n resolveResult(recovered);\n return;\n }\n\n rejectResult(err);\n throw err;\n }\n };\n\n const iterator = createStream();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n\n async ask(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n // Per UAP-1.0 Section 4.6: ask() is a convenience method for multi-turn execution.\n // The execution strategy handles adding input to state and appending response.\n // We delegate directly to generate() to:\n // 1. Preserve middleware before() modifications (e.g., context pruning via withContext)\n // 2. Preserve middleware after() modifications\n // 3. Avoid message duplication (strategy already adds input)\n // 4. Return the correctly built state from the execution pipeline\n return agentInstance.generate(input, state);\n },\n\n async query(input: string | Message): Promise<Turn> {\n const initialState = AgentState.initial();\n const result = await agentInstance.generate(input, initialState);\n return result.turn;\n },\n };\n\n return agentInstance;\n}\n\nexport type { Agent, AgentOptions } from './types.ts';\nexport type {\n GenerateResult,\n AgentStreamResult,\n AgentStreamEvent,\n UAPEventType,\n AgentStrategy,\n // Sub-agent event types (Section 8.7)\n SubagentEventType,\n SubagentEventBase,\n SubagentStartEvent,\n SubagentInnerEvent,\n SubagentEndEvent,\n SubagentEvent,\n OnSubagentEvent,\n} from '../execution/types.ts';\n","/**\n * Sub-agent tool creation utilities.\n *\n * Per UAP-1.0 Section 8.7, implementations SHOULD provide helper utilities\n * for creating sub-agent tools with event propagation.\n *\n * @example\n * ```typescript\n * import { agent } from '@providerprotocol/agents';\n * import { createSubAgentTool } from '@providerprotocol/agents/subagent';\n *\n * // Create a sub-agent\n * const explorer = agent({\n * model: anthropic('claude-haiku-4-20250514'),\n * tools: [Glob, Grep, Read],\n * system: 'You explore codebases.',\n * });\n *\n * // Wrap as a tool with event propagation\n * const explorerTool = createSubAgentTool({\n * agent: explorer,\n * name: 'explore_codebase',\n * description: 'Explore and find relevant code',\n * parameters: {\n * type: 'object',\n * properties: {\n * query: { type: 'string', description: 'What to find' },\n * },\n * required: ['query'],\n * },\n * buildPrompt: (params) => `Find: ${params.query}`,\n * subagentType: 'explorer',\n * });\n *\n * // Use in parent agent\n * const coder = agent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * tools: [Bash, Write, explorerTool],\n * });\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { Tool, JSONSchema } from '@providerprotocol/ai';\nimport type { Agent } from '../agent/types.ts';\nimport type {\n ToolExecutionContext,\n SubagentEvent,\n SubagentStartEvent,\n SubagentEndEvent,\n} from '../execution/types.ts';\nimport { AgentState } from '../state/index.ts';\nimport { generateUUID } from '../utils/uuid.ts';\n\n/**\n * Options for creating a sub-agent tool.\n */\nexport interface CreateSubAgentToolOptions {\n /** The sub-agent to expose as a tool */\n agent: Agent;\n /** Tool name (must be unique within parent agent's tools) */\n name: string;\n /** Tool description for the model */\n description: string;\n /** JSON Schema for tool parameters */\n parameters: JSONSchema;\n /** Convert tool parameters to a prompt for the sub-agent */\n buildPrompt: (params: Record<string, unknown>) => string;\n /**\n * Identifier for the sub-agent type (used in events).\n * Defaults to the tool name.\n */\n subagentType?: string;\n /**\n * Whether to stream the sub-agent execution.\n * When true, inner events are forwarded to parent.\n * Default: true\n */\n stream?: boolean;\n}\n\n/**\n * Create a UPP Tool from a UAP Agent with full event propagation.\n *\n * Per UAP-1.0 Section 8.7, this helper:\n * 1. Emits `subagent_start` before execution begins\n * 2. Forwards inner events during streaming execution\n * 3. Emits `subagent_end` after completion (success or failure)\n * 4. Provides execution context to sub-agent for tracing\n *\n * The created tool accepts an optional `ToolExecutionContext` as a second\n * parameter, which is injected by `injectToolContext()` during execution.\n *\n * @param options - Configuration for the sub-agent tool\n * @returns A Tool that executes the sub-agent and propagates events\n *\n * @example\n * ```typescript\n * const summarizer = agent({\n * model: anthropic('claude-haiku-4-20250514'),\n * system: 'You summarize text concisely.',\n * });\n *\n * const summarizerTool = createSubAgentTool({\n * agent: summarizer,\n * name: 'summarize',\n * description: 'Summarize the given text',\n * parameters: {\n * type: 'object',\n * properties: {\n * text: { type: 'string', description: 'Text to summarize' },\n * maxLength: { type: 'number', description: 'Max summary length' },\n * },\n * required: ['text'],\n * },\n * buildPrompt: (params) =>\n * `Summarize this in ${params.maxLength ?? 100} words:\\n\\n${params.text}`,\n * subagentType: 'summarizer',\n * });\n * ```\n */\nexport function createSubAgentTool(options: CreateSubAgentToolOptions): Tool {\n const {\n agent,\n name,\n description,\n parameters,\n buildPrompt,\n subagentType = name,\n stream: shouldStream = true,\n } = options;\n\n return {\n name,\n description,\n parameters,\n run: async (\n params: Record<string, unknown>,\n context?: ToolExecutionContext,\n ): Promise<string> => {\n const subagentId = generateUUID();\n const toolCallId = context?.toolCallId ?? generateUUID();\n const emit = context?.onSubagentEvent;\n const prompt = buildPrompt(params);\n const startTime = Date.now();\n\n // Emit start event\n const startEvent: SubagentStartEvent = {\n type: 'subagent_start',\n subagentId,\n subagentType,\n parentToolCallId: toolCallId,\n prompt,\n timestamp: startTime,\n };\n emit?.(startEvent);\n\n try {\n if (shouldStream) {\n return await executeWithStreaming(\n agent,\n prompt,\n subagentId,\n subagentType,\n toolCallId,\n emit,\n );\n }\n return await executeWithoutStreaming(\n agent,\n prompt,\n subagentId,\n subagentType,\n toolCallId,\n emit,\n );\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Emit end event with error\n const endEvent: SubagentEndEvent = {\n type: 'subagent_end',\n subagentId,\n subagentType,\n parentToolCallId: toolCallId,\n success: false,\n error: err.message,\n timestamp: Date.now(),\n };\n emit?.(endEvent);\n\n throw err;\n }\n },\n };\n}\n\n/**\n * Execute sub-agent with streaming and forward events.\n */\nasync function executeWithStreaming(\n agent: Agent,\n prompt: string,\n subagentId: string,\n subagentType: string,\n toolCallId: string,\n emit?: (event: SubagentEvent) => void,\n): Promise<string> {\n const stream = agent.stream(prompt, AgentState.initial());\n\n // Forward inner events\n for await (const event of stream) {\n emit?.({\n type: 'subagent_event',\n subagentId,\n subagentType,\n parentToolCallId: toolCallId,\n innerEvent: event,\n });\n }\n\n const result = await stream.result;\n\n // Emit end event\n const endEvent: SubagentEndEvent = {\n type: 'subagent_end',\n subagentId,\n subagentType,\n parentToolCallId: toolCallId,\n success: true,\n result: result.turn.response.text,\n timestamp: Date.now(),\n toolExecutions: result.turn.toolExecutions?.map((te) => ({\n toolName: te.toolName,\n arguments: te.arguments as Record<string, unknown>,\n result: String(te.result),\n })),\n usage: result.turn.usage,\n };\n emit?.(endEvent);\n\n return result.turn.response.text;\n}\n\n/**\n * Execute sub-agent without streaming (simpler, but no inner events).\n */\nasync function executeWithoutStreaming(\n agent: Agent,\n prompt: string,\n subagentId: string,\n subagentType: string,\n toolCallId: string,\n emit?: (event: SubagentEvent) => void,\n): Promise<string> {\n const result = await agent.generate(prompt, AgentState.initial());\n\n // Emit end event\n const endEvent: SubagentEndEvent = {\n type: 'subagent_end',\n subagentId,\n subagentType,\n parentToolCallId: toolCallId,\n success: true,\n result: result.turn.response.text,\n timestamp: Date.now(),\n toolExecutions: result.turn.toolExecutions?.map((te) => ({\n toolName: te.toolName,\n arguments: te.arguments as Record<string, unknown>,\n result: String(te.result),\n })),\n usage: result.turn.usage,\n };\n emit?.(endEvent);\n\n return result.turn.response.text;\n}\n\n/**\n * Type for the run function of a sub-agent tool.\n * Accepts params and optional execution context.\n */\nexport type SubAgentToolRun = (\n params: Record<string, unknown>,\n context?: ToolExecutionContext,\n) => Promise<string>;\n"]}
@@ -1,9 +1,9 @@
1
- import { L as LoggingOptions, M as Middleware } from '../types-BiyEVOnf.js';
2
- export { a as MiddlewareContext } from '../types-BiyEVOnf.js';
1
+ import { L as LoggingOptions, M as Middleware } from '../types-B9VuAOo6.js';
2
+ export { a as MiddlewareContext } from '../types-B9VuAOo6.js';
3
3
  import '@providerprotocol/ai';
4
4
  import '../index-qsPwbY86.js';
5
5
  import '../types-2Vsthzyu.js';
6
- import '../types-D1egxttz.js';
6
+ import '../types-DC8XeoaI.js';
7
7
  import '../types-DChRdQoX.js';
8
8
 
9
9
  /**
@@ -0,0 +1,72 @@
1
+ import { Tool } from '@providerprotocol/ai';
2
+ import { h as ExecutionContext, O as OnSubagentEvent, C as ContextAwareToolRun } from './types-DC8XeoaI.js';
3
+
4
+ /**
5
+ * Options for tool context injection.
6
+ */
7
+ interface InjectToolContextOptions {
8
+ /** Callback for sub-agent events from tools */
9
+ onSubagentEvent?: OnSubagentEvent;
10
+ }
11
+ /**
12
+ * Wrap tools to inject execution context when they support it.
13
+ *
14
+ * Per UAP-1.0 Section 8.4, tools that accept a second parameter
15
+ * should receive execution context including agentId, stateId,
16
+ * and sub-agent event callbacks.
17
+ *
18
+ * This enables:
19
+ * - Sub-agent model/config inheritance
20
+ * - Execution hierarchy tracking
21
+ * - Sub-agent event propagation
22
+ *
23
+ * @param tools - Original tool array
24
+ * @param context - Execution context from the agent
25
+ * @param options - Additional options like event callbacks
26
+ * @returns Wrapped tools with context injection
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * // In execution strategy
31
+ * const wrappedTools = injectToolContext(tools, context, {
32
+ * onSubagentEvent: (event) => {
33
+ * // Handle sub-agent events
34
+ * yield { source: 'uap', uap: { type: event.type, ... } };
35
+ * },
36
+ * });
37
+ *
38
+ * // Pass wrapped tools to LLM
39
+ * const llmWithContext = llm({ model, tools: wrappedTools });
40
+ * ```
41
+ */
42
+ declare function injectToolContext(tools: Tool[], context: ExecutionContext, options?: InjectToolContextOptions): Tool[];
43
+ /**
44
+ * Check if a tool is context-aware (accepts second parameter).
45
+ *
46
+ * @param tool - Tool to check
47
+ * @returns true if tool.run accepts more than one parameter
48
+ */
49
+ declare function isContextAwareTool(tool: Tool): boolean;
50
+ /**
51
+ * Create a context-aware tool wrapper for existing tools.
52
+ * This is useful when you want to add context support to a tool
53
+ * that doesn't natively support it.
54
+ *
55
+ * @param tool - Original tool
56
+ * @param handler - Function that receives params and context, returns result
57
+ * @returns New tool with context support
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const originalTool = { name: 'my_tool', run: async (p) => 'result', ... };
62
+ *
63
+ * const contextAware = withToolContext(originalTool, async (params, context) => {
64
+ * console.log('Agent ID:', context?.agentId);
65
+ * // Call original or do something with context
66
+ * return originalTool.run(params);
67
+ * });
68
+ * ```
69
+ */
70
+ declare function withToolContext(tool: Tool, handler: ContextAwareToolRun): Tool;
71
+
72
+ export { type InjectToolContextOptions as I, isContextAwareTool as a, injectToolContext as i, withToolContext as w };
@@ -1,6 +1,6 @@
1
1
  import { Message } from '@providerprotocol/ai';
2
2
  import { A as AgentState } from './index-qsPwbY86.js';
3
- import { G as GenerateResult } from './types-D1egxttz.js';
3
+ import { G as GenerateResult } from './types-DC8XeoaI.js';
4
4
 
5
5
  /**
6
6
  * Forward declaration of Agent for use in MiddlewareContext.
@@ -266,5 +266,43 @@ type SubagentEvent = SubagentStartEvent | SubagentInnerEvent | SubagentEndEvent;
266
266
  * Tools that spawn sub-agents SHOULD accept this callback.
267
267
  */
268
268
  type OnSubagentEvent = (event: SubagentEvent) => void;
269
+ /**
270
+ * Context injected into tools during execution.
271
+ * Per UAP-1.0 Section 8.4, ExecutionStrategy MUST inject this context
272
+ * when invoking tools that accept a second parameter.
273
+ *
274
+ * @see UAP-1.0 Spec Section 8.4
275
+ */
276
+ interface ToolExecutionContext {
277
+ /** Agent instance ID */
278
+ agentId: string;
279
+ /** Current state snapshot ID */
280
+ stateId: string;
281
+ /** Tool call ID from the model response */
282
+ toolCallId: string;
283
+ /** Callback for sub-agent events */
284
+ onSubagentEvent?: OnSubagentEvent;
285
+ }
286
+ /**
287
+ * Type for a tool that accepts execution context as a second parameter.
288
+ * Tools can optionally accept this context for sub-agent inheritance
289
+ * and event propagation.
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * const contextAwareTool: Tool = {
294
+ * name: 'my_tool',
295
+ * description: 'Tool that uses execution context',
296
+ * parameters: { ... },
297
+ * run: async (params, context?: ToolExecutionContext) => {
298
+ * if (context?.onSubagentEvent) {
299
+ * // Can propagate sub-agent events
300
+ * }
301
+ * return 'result';
302
+ * },
303
+ * };
304
+ * ```
305
+ */
306
+ type ContextAwareToolRun = (params: Record<string, unknown>, context?: ToolExecutionContext) => Promise<unknown>;
269
307
 
270
- export type { AgentStrategy as A, ExecutionStrategy as E, GenerateResult as G, LoopOptions as L, OnSubagentEvent as O, PlanOptions as P, ReactOptions as R, SubagentEventType as S, ToolDependencyOptions as T, UAPEventType as U, AgentStreamResult as a, AgentStreamEvent as b, SubagentEventBase as c, SubagentStartEvent as d, SubagentInnerEvent as e, SubagentEndEvent as f, SubagentEvent as g, ExecutionContext as h, ExecutionResult as i, ToolWithDependencies as j, OrderedToolCall as k };
308
+ export type { AgentStrategy as A, ContextAwareToolRun as C, ExecutionStrategy as E, GenerateResult as G, LoopOptions as L, OnSubagentEvent as O, PlanOptions as P, ReactOptions as R, SubagentEventType as S, ToolExecutionContext as T, UAPEventType as U, AgentStreamResult as a, AgentStreamEvent as b, SubagentEventBase as c, SubagentStartEvent as d, SubagentInnerEvent as e, SubagentEndEvent as f, SubagentEvent as g, ExecutionContext as h, ExecutionResult as i, ToolDependencyOptions as j, ToolWithDependencies as k, OrderedToolCall as l };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@providerprotocol/agents",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "Unified Agent Protocol (UAP) 1.0 implementation for @providerprotocol/ai",
5
5
  "type": "module",
6
6
  "author": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/execution/loop.ts"],"names":[],"mappings":";AAUA,IAAM,oBAAA,GAA8C;AAAA,EAClD,aAAA,EAAe;AACjB,CAAA;AAeO,SAAS,IAAA,CAAK,OAAA,GAAuB,EAAC,EAAsB;AACjE,EAAA,MAAM,IAAA,GAAO,EAAE,GAAG,oBAAA,EAAsB,GAAG,OAAA,EAAQ;AAEnD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,MAAA;AAAA,IAEN,MAAM,QAAQ,OAAA,EAAqD;AACjE,MAAA,MAAM,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,QAAA,EAAU,QAAO,GAAI,OAAA;AAIhD,MAAA,IAAI,YAAA,GAAe,MAChB,WAAA,CAAY,KAAK,EACjB,YAAA,CAAa,SAAA,EAAW,OAAA,CAAQ,KAAA,CAAM,EAAE,CAAA;AAC3C,MAAA,IAAI,SAAA,GAAY,CAAA;AAChB,MAAA,IAAI,SAAA;AAGJ,MAAA,MAAM,aAAA,GAAgB,CAAC,GAAG,YAAA,CAAa,QAAQ,CAAA;AAE/C,MAAA,OAAO,IAAA,EAAM;AACX,QAAA,SAAA,EAAA;AACA,QAAA,YAAA,GAAe,YAAA,CAAa,SAAS,SAAS,CAAA;AAG9C,QAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,UAAA,MAAM,IAAI,MAAM,mBAAmB,CAAA;AAAA,QACrC;AAGA,QAAA,QAAA,CAAS,WAAA,GAAc,WAA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AAA,QACR;AAAA,MACF;AAEA,MAAA,MAAM,WAAW,cAAA,EAAe;AAEhC,MAAA,OAAO;AAAA,QACL,CAAC,MAAA,CAAO,aAAa,CAAA,GAAI;AACvB,UAAA,OAAO,QAAA;AAAA,QACT,CAAA;AAAA,QACA,MAAA,EAAQ,aAAA;AAAA,QACR,KAAA,GAAQ;AACN,UAAA,OAAA,GAAU,IAAA;AACV,UAAA,eAAA,CAAgB,KAAA,EAAM;AAAA,QACxB;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-4ESYN66B.js","sourcesContent":["import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n LoopOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_LOOP_OPTIONS: Required<LoopOptions> = {\n maxIterations: Infinity,\n};\n\n/**\n * Create a loop execution strategy.\n * The simplest strategy - equivalent to UPP's tool loop behavior.\n *\n * Behavior:\n * 1. Send input to LLM\n * 2. If response has tool calls, execute tools and loop\n * 3. Continue until no tool calls or maxIterations reached\n * 4. Return final response as UPP Turn\n *\n * @param options - Loop configuration options\n * @returns ExecutionStrategy\n */\nexport function loop(options: LoopOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_LOOP_OPTIONS, ...options };\n\n return {\n name: 'loop',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let iteration = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const inputMessages = [...currentState.messages];\n\n while (true) {\n iteration++;\n currentState = currentState.withStep(iteration);\n\n // Check abort signal\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n // Call strategy hooks\n strategy.onStepStart?.(iteration, currentState);\n\n // Generate response - llm.generate uses rest params, pass messages array\n const turn = await llm.generate(inputMessages);\n finalTurn = turn;\n\n // Update state with messages from this turn\n currentState = currentState.withMessages(turn.messages);\n\n // Call action hook if there were tool calls\n if (turn.response.hasToolCalls) {\n strategy.onAct?.(iteration, turn.response.toolCalls ?? []);\n }\n\n // Call observe hook if there were tool executions\n if (turn.toolExecutions && turn.toolExecutions.length > 0) {\n strategy.onObserve?.(iteration, turn.toolExecutions);\n }\n\n // Call step end hook\n strategy.onStepEnd?.(iteration, { turn, state: currentState });\n\n // Save checkpoint after step completes (fire-and-forget, log errors)\n if (context.checkpoints && context.sessionId) {\n context.checkpoints.save(context.sessionId, currentState.toJSON()).catch((err) => {\n console.error('[UAP] Checkpoint save failed:', err);\n });\n }\n\n // Check stop condition\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n // Check if there are more tool calls to process\n // UPP's llm.generate handles the tool loop internally,\n // so we only need one iteration unless we're doing multi-step\n if (!turn.response.hasToolCalls) {\n break;\n }\n\n // Check iteration limit\n if (opts.maxIterations !== Infinity && iteration >= opts.maxIterations) {\n break;\n }\n\n // For next iteration, use the updated messages\n inputMessages.length = 0;\n inputMessages.push(...currentState.messages);\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n // Per UAP spec Section 3.4: sessionId MUST be included in state.metadata\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n // Combine signals if one was provided\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let iteration = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const inputMessages = [...currentState.messages];\n\n try {\n while (!aborted) {\n iteration++;\n currentState = currentState.withStep(iteration);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(iteration, currentState);\n\n // Emit step start event\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step: iteration,\n agentId,\n data: { iteration },\n },\n };\n\n // Stream the LLM response\n const streamResult = llm.stream(inputMessages);\n\n for await (const event of streamResult as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n // Yield UPP events\n yield {\n source: 'upp',\n upp: event,\n };\n }\n\n // Get the final turn from the stream\n const turn = await streamResult.turn;\n finalTurn = turn;\n\n currentState = currentState.withMessages(turn.messages);\n\n if (turn.response.hasToolCalls) {\n strategy.onAct?.(iteration, turn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step: iteration,\n agentId,\n data: { toolCalls: turn.response.toolCalls },\n },\n };\n }\n\n if (turn.toolExecutions && turn.toolExecutions.length > 0) {\n strategy.onObserve?.(iteration, turn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step: iteration,\n agentId,\n data: { observations: turn.toolExecutions },\n },\n };\n }\n\n strategy.onStepEnd?.(iteration, { turn, state: currentState });\n\n // Save checkpoint after step completes (fire-and-forget, log errors)\n if (context.checkpoints && context.sessionId) {\n context.checkpoints.save(context.sessionId, currentState.toJSON()).catch((err) => {\n console.error('[UAP] Checkpoint save failed:', err);\n });\n }\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step: iteration,\n agentId,\n data: { iteration },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n if (!turn.response.hasToolCalls) {\n break;\n }\n\n if (opts.maxIterations !== Infinity && iteration >= opts.maxIterations) {\n break;\n }\n\n inputMessages.length = 0;\n inputMessages.push(...currentState.messages);\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n // Per UAP spec Section 3.4: sessionId MUST be included in state.metadata\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n"]}