@providerprotocol/agents 0.0.5 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/{chunk-CEHXAE4Z.js → chunk-72YPNBK3.js} +167 -3
- package/dist/chunk-72YPNBK3.js.map +1 -0
- package/dist/execution/index.d.ts +5 -122
- package/dist/execution/index.js +2 -166
- package/dist/execution/index.js.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +2 -2
- package/dist/middleware/index.d.ts +3 -3
- package/dist/tool-ordering-BQCRKVKf.d.ts +189 -0
- package/dist/{types-DC8XeoaI.d.ts → types-ClFW1Bjr.d.ts} +9 -1
- package/dist/{types-B9VuAOo6.d.ts → types-DLqkZUjz.d.ts} +1 -8
- package/package.json +1 -1
- package/dist/chunk-CEHXAE4Z.js.map +0 -1
- package/dist/tool-context-Cc_qNVud.d.ts +0 -72
package/README.md
CHANGED
|
@@ -11,6 +11,9 @@ A powerful, flexible agent framework implementing the Unified Agent Protocol (UA
|
|
|
11
11
|
- **Streaming** - Full streaming support with UAP and UPP events
|
|
12
12
|
- **Checkpointing** - Built-in session persistence and recovery
|
|
13
13
|
- **Thread Trees** - Branching conversation support
|
|
14
|
+
- **Sub-Agent Tools** - Helper utilities for creating tools that spawn sub-agents with event propagation
|
|
15
|
+
- **Tool Context Injection** - Pass execution context (agentId, stateId, toolCallId) to tools
|
|
16
|
+
- **Tool Ordering** - Execute tool calls respecting dependencies and sequential barriers
|
|
14
17
|
- **Type-Safe** - 100% TypeScript with full type inference
|
|
15
18
|
|
|
16
19
|
## Installation
|
|
@@ -232,6 +232,170 @@ function withToolContext(tool, handler) {
|
|
|
232
232
|
};
|
|
233
233
|
}
|
|
234
234
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
235
|
+
// src/execution/tool-ordering.ts
|
|
236
|
+
function buildToolMap(tools) {
|
|
237
|
+
const map = /* @__PURE__ */ new Map();
|
|
238
|
+
for (const tool of tools) {
|
|
239
|
+
map.set(tool.name, tool);
|
|
240
|
+
}
|
|
241
|
+
return map;
|
|
242
|
+
}
|
|
243
|
+
function getModelDependencies(call) {
|
|
244
|
+
const orderedCall = call;
|
|
245
|
+
return orderedCall.after ?? [];
|
|
246
|
+
}
|
|
247
|
+
function orderToolCalls(toolCalls, tools) {
|
|
248
|
+
if (toolCalls.length === 0) {
|
|
249
|
+
return [];
|
|
250
|
+
}
|
|
251
|
+
const toolMap = buildToolMap(tools);
|
|
252
|
+
const groups = [];
|
|
253
|
+
const completedCallIds = /* @__PURE__ */ new Set();
|
|
254
|
+
const completedToolNames = /* @__PURE__ */ new Set();
|
|
255
|
+
const pending = [...toolCalls];
|
|
256
|
+
while (pending.length > 0) {
|
|
257
|
+
const readyForExecution = [];
|
|
258
|
+
let hasSequential = false;
|
|
259
|
+
const stillPending = [];
|
|
260
|
+
for (const call of pending) {
|
|
261
|
+
const tool = toolMap.get(call.toolName);
|
|
262
|
+
const toolDependsOn = tool?.dependsOn ?? [];
|
|
263
|
+
const modelDependsOn = getModelDependencies(call);
|
|
264
|
+
const toolDepsOk = toolDependsOn.every(
|
|
265
|
+
(depName) => completedToolNames.has(depName)
|
|
266
|
+
);
|
|
267
|
+
const modelDepsOk = modelDependsOn.every(
|
|
268
|
+
(depId) => completedCallIds.has(depId)
|
|
269
|
+
);
|
|
270
|
+
if (toolDepsOk && modelDepsOk) {
|
|
271
|
+
readyForExecution.push(call);
|
|
272
|
+
if (tool?.sequential) {
|
|
273
|
+
hasSequential = true;
|
|
274
|
+
}
|
|
275
|
+
} else {
|
|
276
|
+
stillPending.push(call);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (readyForExecution.length === 0 && stillPending.length > 0) {
|
|
280
|
+
groups.push({
|
|
281
|
+
calls: stillPending,
|
|
282
|
+
isBarrier: false
|
|
283
|
+
});
|
|
284
|
+
break;
|
|
285
|
+
}
|
|
286
|
+
if (hasSequential) {
|
|
287
|
+
for (const call of readyForExecution) {
|
|
288
|
+
const tool = toolMap.get(call.toolName);
|
|
289
|
+
groups.push({
|
|
290
|
+
calls: [call],
|
|
291
|
+
isBarrier: tool?.sequential ?? false
|
|
292
|
+
});
|
|
293
|
+
completedCallIds.add(call.toolCallId);
|
|
294
|
+
completedToolNames.add(call.toolName);
|
|
295
|
+
}
|
|
296
|
+
} else {
|
|
297
|
+
groups.push({
|
|
298
|
+
calls: readyForExecution,
|
|
299
|
+
isBarrier: false
|
|
300
|
+
});
|
|
301
|
+
for (const call of readyForExecution) {
|
|
302
|
+
completedCallIds.add(call.toolCallId);
|
|
303
|
+
completedToolNames.add(call.toolName);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
pending.length = 0;
|
|
307
|
+
pending.push(...stillPending);
|
|
308
|
+
}
|
|
309
|
+
return groups;
|
|
310
|
+
}
|
|
311
|
+
function hasToolDependencies(tools) {
|
|
312
|
+
for (const tool of tools) {
|
|
313
|
+
const t = tool;
|
|
314
|
+
if (t.sequential || t.dependsOn && t.dependsOn.length > 0) {
|
|
315
|
+
return true;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
function hasCallDependencies(toolCalls) {
|
|
321
|
+
for (const call of toolCalls) {
|
|
322
|
+
const ordered = call;
|
|
323
|
+
if (ordered.after && ordered.after.length > 0) {
|
|
324
|
+
return true;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
async function executeOrderedToolCalls(toolCalls, tools, executor) {
|
|
330
|
+
if (toolCalls.length === 0) {
|
|
331
|
+
return [];
|
|
332
|
+
}
|
|
333
|
+
const toolMap = /* @__PURE__ */ new Map();
|
|
334
|
+
for (const tool of tools) {
|
|
335
|
+
toolMap.set(tool.name, tool);
|
|
336
|
+
}
|
|
337
|
+
const groups = orderToolCalls(toolCalls, tools);
|
|
338
|
+
const results = [];
|
|
339
|
+
for (const group of groups) {
|
|
340
|
+
if (group.isBarrier) {
|
|
341
|
+
for (const call of group.calls) {
|
|
342
|
+
const tool = toolMap.get(call.toolName);
|
|
343
|
+
if (!tool) {
|
|
344
|
+
results.push({
|
|
345
|
+
call,
|
|
346
|
+
result: null,
|
|
347
|
+
isError: true,
|
|
348
|
+
error: `Tool not found: ${call.toolName}`,
|
|
349
|
+
duration: 0
|
|
350
|
+
});
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const result = await executeOne(call, tool, executor);
|
|
354
|
+
results.push(result);
|
|
355
|
+
}
|
|
356
|
+
} else {
|
|
357
|
+
const groupResults = await Promise.all(
|
|
358
|
+
group.calls.map(async (call) => {
|
|
359
|
+
const tool = toolMap.get(call.toolName);
|
|
360
|
+
if (!tool) {
|
|
361
|
+
return {
|
|
362
|
+
call,
|
|
363
|
+
result: null,
|
|
364
|
+
isError: true,
|
|
365
|
+
error: `Tool not found: ${call.toolName}`,
|
|
366
|
+
duration: 0
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
return executeOne(call, tool, executor);
|
|
370
|
+
})
|
|
371
|
+
);
|
|
372
|
+
results.push(...groupResults);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return results;
|
|
376
|
+
}
|
|
377
|
+
async function executeOne(call, tool, executor) {
|
|
378
|
+
const startTime = Date.now();
|
|
379
|
+
try {
|
|
380
|
+
const result = await executor(call, tool);
|
|
381
|
+
return {
|
|
382
|
+
call,
|
|
383
|
+
result,
|
|
384
|
+
isError: false,
|
|
385
|
+
duration: Date.now() - startTime
|
|
386
|
+
};
|
|
387
|
+
} catch (error) {
|
|
388
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
389
|
+
return {
|
|
390
|
+
call,
|
|
391
|
+
result: null,
|
|
392
|
+
isError: true,
|
|
393
|
+
error: err.message,
|
|
394
|
+
duration: Date.now() - startTime
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export { executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, injectToolContext, isContextAwareTool, loop, orderToolCalls, withToolContext };
|
|
400
|
+
//# sourceMappingURL=chunk-72YPNBK3.js.map
|
|
401
|
+
//# sourceMappingURL=chunk-72YPNBK3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/execution/loop.ts","../src/execution/tool-context.ts","../src/execution/tool-ordering.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,WAAW,YAAY,CAAA;AAG9C,QAAA,MAAM,IAAA,GAAO,MAAM,GAAA,CAAI,QAAA,CAAS,aAAa,CA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EA,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":"chunk-72YPNBK3.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","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"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { L as LoopOptions, E as ExecutionStrategy, R as ReactOptions, P as PlanOptions } from '../types-
|
|
2
|
-
export { A as AgentStrategy, b as AgentStreamEvent, a as AgentStreamResult, C as ContextAwareToolRun,
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { L as LoopOptions, E as ExecutionStrategy, R as ReactOptions, P as PlanOptions } from '../types-ClFW1Bjr.js';
|
|
2
|
+
export { A as AgentStrategy, b as AgentStreamEvent, a as AgentStreamResult, C as ContextAwareToolRun, i as ExecutionContext, k 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, m as ToolDependencyOptions, T as ToolExecutionContext, n as ToolWithDependencies, U as UAPEventType } from '../types-ClFW1Bjr.js';
|
|
3
|
+
export { E as ExecutionGroup, I as InjectToolContextOptions, T as ToolExecutionResult, c as ToolExecutor, e as executeOrderedToolCalls, h as hasCallDependencies, b as hasToolDependencies, i as injectToolContext, a as isContextAwareTool, o as orderToolCalls, w as withToolContext } from '../tool-ordering-BQCRKVKf.js';
|
|
4
|
+
import '@providerprotocol/ai';
|
|
5
5
|
import '../index-qsPwbY86.js';
|
|
6
6
|
import '../types-2Vsthzyu.js';
|
|
7
7
|
import '../types-DChRdQoX.js';
|
|
@@ -48,121 +48,4 @@ declare function react(options?: ReactOptions): ExecutionStrategy;
|
|
|
48
48
|
*/
|
|
49
49
|
declare function plan(options?: PlanOptions): ExecutionStrategy;
|
|
50
50
|
|
|
51
|
-
|
|
52
|
-
* Execution group - a set of tool calls that can execute in parallel.
|
|
53
|
-
*/
|
|
54
|
-
interface ExecutionGroup {
|
|
55
|
-
/** Tool calls in this group */
|
|
56
|
-
calls: ToolCall[];
|
|
57
|
-
/** Whether this group contains a sequential tool (acts as barrier) */
|
|
58
|
-
isBarrier: boolean;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Order tool calls into execution groups respecting dependencies.
|
|
62
|
-
*
|
|
63
|
-
* This function takes a list of tool calls and the available tools,
|
|
64
|
-
* then groups them for execution while respecting:
|
|
65
|
-
* 1. Tool-level `sequential` flag (creates execution barriers)
|
|
66
|
-
* 2. Tool-level `dependsOn` array (tool must wait for named tools)
|
|
67
|
-
* 3. Model-driven `after` array on tool calls (call must wait for specific calls)
|
|
68
|
-
*
|
|
69
|
-
* @param toolCalls - Tool calls from the model response
|
|
70
|
-
* @param tools - Tool definitions (may include dependency options)
|
|
71
|
-
* @returns Ordered array of execution groups
|
|
72
|
-
*
|
|
73
|
-
* @example
|
|
74
|
-
* ```typescript
|
|
75
|
-
* const groups = orderToolCalls(turn.response.toolCalls, agent.tools);
|
|
76
|
-
*
|
|
77
|
-
* for (const group of groups) {
|
|
78
|
-
* if (group.isBarrier) {
|
|
79
|
-
* // Execute sequentially
|
|
80
|
-
* for (const call of group.calls) {
|
|
81
|
-
* await executeTool(call);
|
|
82
|
-
* }
|
|
83
|
-
* } else {
|
|
84
|
-
* // Execute in parallel
|
|
85
|
-
* await Promise.all(group.calls.map(executeTool));
|
|
86
|
-
* }
|
|
87
|
-
* }
|
|
88
|
-
* ```
|
|
89
|
-
*/
|
|
90
|
-
declare function orderToolCalls(toolCalls: ToolCall[], tools: Tool[]): ExecutionGroup[];
|
|
91
|
-
/**
|
|
92
|
-
* Check if any tools have execution dependencies defined.
|
|
93
|
-
*
|
|
94
|
-
* @param tools - Tool definitions to check
|
|
95
|
-
* @returns true if any tool has sequential or dependsOn set
|
|
96
|
-
*/
|
|
97
|
-
declare function hasToolDependencies(tools: Tool[]): boolean;
|
|
98
|
-
/**
|
|
99
|
-
* Check if any tool calls have model-driven dependencies.
|
|
100
|
-
*
|
|
101
|
-
* @param toolCalls - Tool calls to check
|
|
102
|
-
* @returns true if any call has the `after` field set
|
|
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[]>;
|
|
167
|
-
|
|
168
|
-
export { type ExecutionGroup, ExecutionStrategy, LoopOptions, PlanOptions, ReactOptions, type ToolExecutionResult, type ToolExecutor, executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, loop, orderToolCalls, plan, react };
|
|
51
|
+
export { ExecutionStrategy, LoopOptions, PlanOptions, ReactOptions, loop, plan, react };
|
package/dist/execution/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { injectToolContext, isContextAwareTool, loop, withToolContext } from '../chunk-
|
|
1
|
+
export { executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, injectToolContext, isContextAwareTool, loop, orderToolCalls, withToolContext } from '../chunk-72YPNBK3.js';
|
|
2
2
|
import { generateUUID } from '../chunk-EKRXMSDX.js';
|
|
3
3
|
import { UserMessage } from '@providerprotocol/ai';
|
|
4
4
|
|
|
@@ -579,170 +579,6 @@ function plan(options = {}) {
|
|
|
579
579
|
};
|
|
580
580
|
}
|
|
581
581
|
|
|
582
|
-
|
|
583
|
-
function buildToolMap(tools) {
|
|
584
|
-
const map = /* @__PURE__ */ new Map();
|
|
585
|
-
for (const tool of tools) {
|
|
586
|
-
map.set(tool.name, tool);
|
|
587
|
-
}
|
|
588
|
-
return map;
|
|
589
|
-
}
|
|
590
|
-
function getModelDependencies(call) {
|
|
591
|
-
const orderedCall = call;
|
|
592
|
-
return orderedCall.after ?? [];
|
|
593
|
-
}
|
|
594
|
-
function orderToolCalls(toolCalls, tools) {
|
|
595
|
-
if (toolCalls.length === 0) {
|
|
596
|
-
return [];
|
|
597
|
-
}
|
|
598
|
-
const toolMap = buildToolMap(tools);
|
|
599
|
-
const groups = [];
|
|
600
|
-
const completedCallIds = /* @__PURE__ */ new Set();
|
|
601
|
-
const completedToolNames = /* @__PURE__ */ new Set();
|
|
602
|
-
const pending = [...toolCalls];
|
|
603
|
-
while (pending.length > 0) {
|
|
604
|
-
const readyForExecution = [];
|
|
605
|
-
let hasSequential = false;
|
|
606
|
-
const stillPending = [];
|
|
607
|
-
for (const call of pending) {
|
|
608
|
-
const tool = toolMap.get(call.toolName);
|
|
609
|
-
const toolDependsOn = tool?.dependsOn ?? [];
|
|
610
|
-
const modelDependsOn = getModelDependencies(call);
|
|
611
|
-
const toolDepsOk = toolDependsOn.every(
|
|
612
|
-
(depName) => completedToolNames.has(depName)
|
|
613
|
-
);
|
|
614
|
-
const modelDepsOk = modelDependsOn.every(
|
|
615
|
-
(depId) => completedCallIds.has(depId)
|
|
616
|
-
);
|
|
617
|
-
if (toolDepsOk && modelDepsOk) {
|
|
618
|
-
readyForExecution.push(call);
|
|
619
|
-
if (tool?.sequential) {
|
|
620
|
-
hasSequential = true;
|
|
621
|
-
}
|
|
622
|
-
} else {
|
|
623
|
-
stillPending.push(call);
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
if (readyForExecution.length === 0 && stillPending.length > 0) {
|
|
627
|
-
groups.push({
|
|
628
|
-
calls: stillPending,
|
|
629
|
-
isBarrier: false
|
|
630
|
-
});
|
|
631
|
-
break;
|
|
632
|
-
}
|
|
633
|
-
if (hasSequential) {
|
|
634
|
-
for (const call of readyForExecution) {
|
|
635
|
-
const tool = toolMap.get(call.toolName);
|
|
636
|
-
groups.push({
|
|
637
|
-
calls: [call],
|
|
638
|
-
isBarrier: tool?.sequential ?? false
|
|
639
|
-
});
|
|
640
|
-
completedCallIds.add(call.toolCallId);
|
|
641
|
-
completedToolNames.add(call.toolName);
|
|
642
|
-
}
|
|
643
|
-
} else {
|
|
644
|
-
groups.push({
|
|
645
|
-
calls: readyForExecution,
|
|
646
|
-
isBarrier: false
|
|
647
|
-
});
|
|
648
|
-
for (const call of readyForExecution) {
|
|
649
|
-
completedCallIds.add(call.toolCallId);
|
|
650
|
-
completedToolNames.add(call.toolName);
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
pending.length = 0;
|
|
654
|
-
pending.push(...stillPending);
|
|
655
|
-
}
|
|
656
|
-
return groups;
|
|
657
|
-
}
|
|
658
|
-
function hasToolDependencies(tools) {
|
|
659
|
-
for (const tool of tools) {
|
|
660
|
-
const t = tool;
|
|
661
|
-
if (t.sequential || t.dependsOn && t.dependsOn.length > 0) {
|
|
662
|
-
return true;
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
return false;
|
|
666
|
-
}
|
|
667
|
-
function hasCallDependencies(toolCalls) {
|
|
668
|
-
for (const call of toolCalls) {
|
|
669
|
-
const ordered = call;
|
|
670
|
-
if (ordered.after && ordered.after.length > 0) {
|
|
671
|
-
return true;
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
return false;
|
|
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
|
-
}
|
|
745
|
-
|
|
746
|
-
export { executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, orderToolCalls, plan, react };
|
|
582
|
+
export { plan, react };
|
|
747
583
|
//# sourceMappingURL=index.js.map
|
|
748
584
|
//# 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,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,QACrC;AAEA,QAAA,QAAA,CAAS,WAAA,GAAc,MAAM,YAAY,CAAA;AAGzC,QAAA,MAAM,iBAAA,GAAoB;AAAA,UACxB,GAAG,QAAA;AAAA,UACH,IAAI,WAAA,CAAY,IAAA,CAAK,eAAe;AAAA,SACtC;AAEA,QAAA,MAAM,aAAA,GAAgB,MAAM,GAAA,CAAI,QAAA,CAAS,iBAAiB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AK,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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/execution/react.ts","../../src/execution/plan.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,QACrC;AAEA,QAAA,QAAA,CAAS,WAAA,GAAc,MAAM,YAAY,C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AAA,EAAM;AAAA,QACxB;AAAA,OACF;AAAA,IACF;AAAA,GACF;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"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
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, T as ToolExecutionContext } from './types-
|
|
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-
|
|
5
|
-
import { M as Middleware } from './types-
|
|
3
|
+
import { E as ExecutionStrategy, A as AgentStrategy, G as GenerateResult, a as AgentStreamResult, T as ToolExecutionContext } from './types-ClFW1Bjr.js';
|
|
4
|
+
export { h as AgentRef, b as AgentStreamEvent, C as ContextAwareToolRun, i as ExecutionContext, j as ExecutionPlan, k as ExecutionResult, L as LoopOptions, O as OnSubagentEvent, l as OrderedToolCall, P as PlanOptions, R as ReactOptions, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, m as ToolDependencyOptions, n as ToolWithDependencies, U as UAPEventType } from './types-ClFW1Bjr.js';
|
|
5
|
+
import { M as Middleware } from './types-DLqkZUjz.js';
|
|
6
|
+
export { L as LoggingOptions, a as MiddlewareContext } from './types-DLqkZUjz.js';
|
|
6
7
|
import { C as CheckpointStore } from './types-DChRdQoX.js';
|
|
7
8
|
export { b as CheckpointData, a as CheckpointMetadata, F as FileCheckpointOptions } from './types-DChRdQoX.js';
|
|
8
9
|
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-
|
|
10
|
+
export { E as ExecutionGroup, I as InjectToolContextOptions, T as ToolExecutionResult, c as ToolExecutor, e as executeOrderedToolCalls, h as hasCallDependencies, b as hasToolDependencies, i as injectToolContext, a as isContextAwareTool, o as orderToolCalls, w as withToolContext } from './tool-ordering-BQCRKVKf.js';
|
|
10
11
|
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';
|
|
11
12
|
|
|
12
13
|
/**
|
|
@@ -216,4 +217,4 @@ declare function createSubAgentTool(options: CreateSubAgentToolOptions): Tool;
|
|
|
216
217
|
*/
|
|
217
218
|
type SubAgentToolRun = (params: Record<string, unknown>, context?: ToolExecutionContext) => Promise<string>;
|
|
218
219
|
|
|
219
|
-
export { type Agent, type AgentOptions, AgentState, AgentStrategy, AgentStreamResult, CheckpointStore, type CreateSubAgentToolOptions, GenerateResult, type SubAgentToolRun, ToolExecutionContext, agent, createSubAgentTool };
|
|
220
|
+
export { type Agent, type AgentOptions, AgentState, AgentStrategy, AgentStreamResult, CheckpointStore, type CreateSubAgentToolOptions, ExecutionStrategy, GenerateResult, Middleware, type SubAgentToolRun, ToolExecutionContext, agent, createSubAgentTool };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { loop } from './chunk-
|
|
2
|
-
export { injectToolContext, isContextAwareTool, withToolContext } from './chunk-
|
|
1
|
+
import { loop } from './chunk-72YPNBK3.js';
|
|
2
|
+
export { executeOrderedToolCalls, hasCallDependencies, hasToolDependencies, injectToolContext, isContextAwareTool, orderToolCalls, withToolContext } from './chunk-72YPNBK3.js';
|
|
3
3
|
import { AgentState } from './chunk-T47B3VAF.js';
|
|
4
4
|
export { AgentState, ThreadNode, ThreadTree } from './chunk-T47B3VAF.js';
|
|
5
5
|
import { generateUUID } from './chunk-EKRXMSDX.js';
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { L as LoggingOptions, M as Middleware } from '../types-
|
|
2
|
-
export { a as MiddlewareContext } from '../types-
|
|
1
|
+
import { L as LoggingOptions, M as Middleware } from '../types-DLqkZUjz.js';
|
|
2
|
+
export { a as MiddlewareContext } from '../types-DLqkZUjz.js';
|
|
3
3
|
import '@providerprotocol/ai';
|
|
4
4
|
import '../index-qsPwbY86.js';
|
|
5
5
|
import '../types-2Vsthzyu.js';
|
|
6
|
-
import '../types-
|
|
6
|
+
import '../types-ClFW1Bjr.js';
|
|
7
7
|
import '../types-DChRdQoX.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { Tool, ToolCall } from '@providerprotocol/ai';
|
|
2
|
+
import { i as ExecutionContext, O as OnSubagentEvent, C as ContextAwareToolRun } from './types-ClFW1Bjr.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
|
+
/**
|
|
73
|
+
* Execution group - a set of tool calls that can execute in parallel.
|
|
74
|
+
*/
|
|
75
|
+
interface ExecutionGroup {
|
|
76
|
+
/** Tool calls in this group */
|
|
77
|
+
calls: ToolCall[];
|
|
78
|
+
/** Whether this group contains a sequential tool (acts as barrier) */
|
|
79
|
+
isBarrier: boolean;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Order tool calls into execution groups respecting dependencies.
|
|
83
|
+
*
|
|
84
|
+
* This function takes a list of tool calls and the available tools,
|
|
85
|
+
* then groups them for execution while respecting:
|
|
86
|
+
* 1. Tool-level `sequential` flag (creates execution barriers)
|
|
87
|
+
* 2. Tool-level `dependsOn` array (tool must wait for named tools)
|
|
88
|
+
* 3. Model-driven `after` array on tool calls (call must wait for specific calls)
|
|
89
|
+
*
|
|
90
|
+
* @param toolCalls - Tool calls from the model response
|
|
91
|
+
* @param tools - Tool definitions (may include dependency options)
|
|
92
|
+
* @returns Ordered array of execution groups
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```typescript
|
|
96
|
+
* const groups = orderToolCalls(turn.response.toolCalls, agent.tools);
|
|
97
|
+
*
|
|
98
|
+
* for (const group of groups) {
|
|
99
|
+
* if (group.isBarrier) {
|
|
100
|
+
* // Execute sequentially
|
|
101
|
+
* for (const call of group.calls) {
|
|
102
|
+
* await executeTool(call);
|
|
103
|
+
* }
|
|
104
|
+
* } else {
|
|
105
|
+
* // Execute in parallel
|
|
106
|
+
* await Promise.all(group.calls.map(executeTool));
|
|
107
|
+
* }
|
|
108
|
+
* }
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
declare function orderToolCalls(toolCalls: ToolCall[], tools: Tool[]): ExecutionGroup[];
|
|
112
|
+
/**
|
|
113
|
+
* Check if any tools have execution dependencies defined.
|
|
114
|
+
*
|
|
115
|
+
* @param tools - Tool definitions to check
|
|
116
|
+
* @returns true if any tool has sequential or dependsOn set
|
|
117
|
+
*/
|
|
118
|
+
declare function hasToolDependencies(tools: Tool[]): boolean;
|
|
119
|
+
/**
|
|
120
|
+
* Check if any tool calls have model-driven dependencies.
|
|
121
|
+
*
|
|
122
|
+
* @param toolCalls - Tool calls to check
|
|
123
|
+
* @returns true if any call has the `after` field set
|
|
124
|
+
*/
|
|
125
|
+
declare function hasCallDependencies(toolCalls: ToolCall[]): boolean;
|
|
126
|
+
/**
|
|
127
|
+
* Result of executing a tool call.
|
|
128
|
+
*/
|
|
129
|
+
interface ToolExecutionResult {
|
|
130
|
+
/** The tool call that was executed */
|
|
131
|
+
call: ToolCall;
|
|
132
|
+
/** The result from the tool */
|
|
133
|
+
result: unknown;
|
|
134
|
+
/** Whether the tool threw an error */
|
|
135
|
+
isError: boolean;
|
|
136
|
+
/** Error message if isError is true */
|
|
137
|
+
error?: string;
|
|
138
|
+
/** Execution duration in milliseconds */
|
|
139
|
+
duration: number;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Function type for executing a single tool call.
|
|
143
|
+
*/
|
|
144
|
+
type ToolExecutor = (call: ToolCall, tool: Tool) => Promise<unknown>;
|
|
145
|
+
/**
|
|
146
|
+
* Execute tool calls respecting dependency ordering.
|
|
147
|
+
*
|
|
148
|
+
* This function takes tool calls, orders them using `orderToolCalls()`,
|
|
149
|
+
* and executes them respecting barriers (sequential tools) and
|
|
150
|
+
* dependencies (dependsOn, after).
|
|
151
|
+
*
|
|
152
|
+
* Per UAP-1.0 Sections 8.5 and 8.6:
|
|
153
|
+
* - Tools with `sequential: true` execute alone (barrier)
|
|
154
|
+
* - Tools with `dependsOn` wait for named tools to complete
|
|
155
|
+
* - Tool calls with `after` wait for specific call IDs to complete
|
|
156
|
+
*
|
|
157
|
+
* @param toolCalls - Tool calls from the model response
|
|
158
|
+
* @param tools - Tool definitions with potential dependencies
|
|
159
|
+
* @param executor - Function to execute a single tool call
|
|
160
|
+
* @returns Array of execution results in completion order
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```typescript
|
|
164
|
+
* import { executeOrderedToolCalls } from '@providerprotocol/agents/execution';
|
|
165
|
+
*
|
|
166
|
+
* // Define tools with dependencies
|
|
167
|
+
* const readTool: ToolWithDependencies = {
|
|
168
|
+
* name: 'read_file',
|
|
169
|
+
* sequential: true, // Must complete before others
|
|
170
|
+
* run: async (params) => readFile(params.path),
|
|
171
|
+
* };
|
|
172
|
+
*
|
|
173
|
+
* const processTool: ToolWithDependencies = {
|
|
174
|
+
* name: 'process',
|
|
175
|
+
* dependsOn: ['read_file'], // Wait for read_file
|
|
176
|
+
* run: async (params) => process(params.data),
|
|
177
|
+
* };
|
|
178
|
+
*
|
|
179
|
+
* // Execute with ordering
|
|
180
|
+
* const results = await executeOrderedToolCalls(
|
|
181
|
+
* turn.response.toolCalls,
|
|
182
|
+
* [readTool, processTool],
|
|
183
|
+
* async (call, tool) => tool.run(call.arguments),
|
|
184
|
+
* );
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
declare function executeOrderedToolCalls(toolCalls: ToolCall[], tools: Tool[], executor: ToolExecutor): Promise<ToolExecutionResult[]>;
|
|
188
|
+
|
|
189
|
+
export { type ExecutionGroup as E, type InjectToolContextOptions as I, type ToolExecutionResult as T, isContextAwareTool as a, hasToolDependencies as b, type ToolExecutor as c, executeOrderedToolCalls as e, hasCallDependencies as h, injectToolContext as i, orderToolCalls as o, withToolContext as w };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { LLMInstance, Message, Tool, ToolCall, ToolExecution, Turn, StreamEvent, TokenUsage } from '@providerprotocol/ai';
|
|
2
2
|
import { A as AgentState } from './index-qsPwbY86.js';
|
|
3
3
|
import { C as CheckpointStore } from './types-DChRdQoX.js';
|
|
4
|
+
import { P as PlanStep } from './types-2Vsthzyu.js';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Result of agent generation.
|
|
@@ -145,6 +146,13 @@ interface PlanOptions {
|
|
|
145
146
|
/** Schema for plan structure */
|
|
146
147
|
planSchema?: Record<string, unknown>;
|
|
147
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Internal plan structure used by plan() strategy.
|
|
151
|
+
*/
|
|
152
|
+
interface ExecutionPlan {
|
|
153
|
+
steps: PlanStep[];
|
|
154
|
+
currentStepIndex: number;
|
|
155
|
+
}
|
|
148
156
|
/**
|
|
149
157
|
* Tool dependency options for execution ordering.
|
|
150
158
|
* These extend the base UPP Tool interface with UAP-specific fields.
|
|
@@ -305,4 +313,4 @@ interface ToolExecutionContext {
|
|
|
305
313
|
*/
|
|
306
314
|
type ContextAwareToolRun = (params: Record<string, unknown>, context?: ToolExecutionContext) => Promise<unknown>;
|
|
307
315
|
|
|
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,
|
|
316
|
+
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, AgentRef as h, ExecutionContext as i, ExecutionPlan as j, ExecutionResult as k, OrderedToolCall as l, ToolDependencyOptions as m, ToolWithDependencies as n };
|
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { Message } from '@providerprotocol/ai';
|
|
2
2
|
import { A as AgentState } from './index-qsPwbY86.js';
|
|
3
|
-
import { G as GenerateResult } from './types-
|
|
3
|
+
import { h as AgentRef, G as GenerateResult } from './types-ClFW1Bjr.js';
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
* Forward declaration of Agent for use in MiddlewareContext.
|
|
7
|
-
*/
|
|
8
|
-
interface AgentRef {
|
|
9
|
-
id: string;
|
|
10
|
-
system?: string;
|
|
11
|
-
}
|
|
12
5
|
/**
|
|
13
6
|
* Context passed to middleware functions.
|
|
14
7
|
*/
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
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,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,WAAW,YAAY,CAAA;AAG9C,QAAA,MAAM,IAAA,GAAO,MAAM,GAAA,CAAI,QAAA,CAAS,a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unk-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,72 +0,0 @@
|
|
|
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 };
|