@providerprotocol/agents 0.0.4 → 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-4ESYN66B.js → chunk-72YPNBK3.js} +202 -3
- package/dist/chunk-72YPNBK3.js.map +1 -0
- package/dist/execution/index.d.ts +5 -59
- package/dist/execution/index.js +2 -97
- package/dist/execution/index.js.map +1 -1
- package/dist/index.d.ts +124 -5
- package/dist/index.js +121 -20
- package/dist/index.js.map +1 -1
- package/dist/middleware/index.d.ts +3 -3
- package/dist/tool-ordering-BQCRKVKf.d.ts +189 -0
- package/dist/{types-D1egxttz.d.ts → types-ClFW1Bjr.d.ts} +47 -1
- package/dist/{types-BiyEVOnf.d.ts → types-DLqkZUjz.d.ts} +1 -8
- package/package.json +1 -1
- package/dist/chunk-4ESYN66B.js.map +0 -1
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
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { generateUUID } from './chunk-EKRXMSDX.js';
|
|
2
|
+
|
|
1
3
|
// src/execution/loop.ts
|
|
2
4
|
var DEFAULT_LOOP_OPTIONS = {
|
|
3
5
|
maxIterations: Infinity
|
|
@@ -197,6 +199,203 @@ function loop(options = {}) {
|
|
|
197
199
|
};
|
|
198
200
|
}
|
|
199
201
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
202
|
+
// src/execution/tool-context.ts
|
|
203
|
+
function injectToolContext(tools, context, options = {}) {
|
|
204
|
+
return tools.map((tool) => wrapToolWithContext(tool, context, options));
|
|
205
|
+
}
|
|
206
|
+
function wrapToolWithContext(tool, context, options) {
|
|
207
|
+
const originalRun = tool.run;
|
|
208
|
+
return {
|
|
209
|
+
...tool,
|
|
210
|
+
run: async (params) => {
|
|
211
|
+
const toolContext = {
|
|
212
|
+
agentId: context.agent.id,
|
|
213
|
+
stateId: context.state.id,
|
|
214
|
+
toolCallId: generateUUID(),
|
|
215
|
+
// Generate unique ID for this call
|
|
216
|
+
onSubagentEvent: options.onSubagentEvent
|
|
217
|
+
};
|
|
218
|
+
if (originalRun.length > 1) {
|
|
219
|
+
return originalRun(params, toolContext);
|
|
220
|
+
}
|
|
221
|
+
return originalRun(params);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function isContextAwareTool(tool) {
|
|
226
|
+
return tool.run.length > 1;
|
|
227
|
+
}
|
|
228
|
+
function withToolContext(tool, handler) {
|
|
229
|
+
return {
|
|
230
|
+
...tool,
|
|
231
|
+
run: handler
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// 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,E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,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,6 +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,
|
|
3
|
-
|
|
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';
|
|
4
5
|
import '../index-qsPwbY86.js';
|
|
5
6
|
import '../types-2Vsthzyu.js';
|
|
6
7
|
import '../types-DChRdQoX.js';
|
|
@@ -47,59 +48,4 @@ declare function react(options?: ReactOptions): ExecutionStrategy;
|
|
|
47
48
|
*/
|
|
48
49
|
declare function plan(options?: PlanOptions): ExecutionStrategy;
|
|
49
50
|
|
|
50
|
-
|
|
51
|
-
* Execution group - a set of tool calls that can execute in parallel.
|
|
52
|
-
*/
|
|
53
|
-
interface ExecutionGroup {
|
|
54
|
-
/** Tool calls in this group */
|
|
55
|
-
calls: ToolCall[];
|
|
56
|
-
/** Whether this group contains a sequential tool (acts as barrier) */
|
|
57
|
-
isBarrier: boolean;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Order tool calls into execution groups respecting dependencies.
|
|
61
|
-
*
|
|
62
|
-
* This function takes a list of tool calls and the available tools,
|
|
63
|
-
* then groups them for execution while respecting:
|
|
64
|
-
* 1. Tool-level `sequential` flag (creates execution barriers)
|
|
65
|
-
* 2. Tool-level `dependsOn` array (tool must wait for named tools)
|
|
66
|
-
* 3. Model-driven `after` array on tool calls (call must wait for specific calls)
|
|
67
|
-
*
|
|
68
|
-
* @param toolCalls - Tool calls from the model response
|
|
69
|
-
* @param tools - Tool definitions (may include dependency options)
|
|
70
|
-
* @returns Ordered array of execution groups
|
|
71
|
-
*
|
|
72
|
-
* @example
|
|
73
|
-
* ```typescript
|
|
74
|
-
* const groups = orderToolCalls(turn.response.toolCalls, agent.tools);
|
|
75
|
-
*
|
|
76
|
-
* for (const group of groups) {
|
|
77
|
-
* if (group.isBarrier) {
|
|
78
|
-
* // Execute sequentially
|
|
79
|
-
* for (const call of group.calls) {
|
|
80
|
-
* await executeTool(call);
|
|
81
|
-
* }
|
|
82
|
-
* } else {
|
|
83
|
-
* // Execute in parallel
|
|
84
|
-
* await Promise.all(group.calls.map(executeTool));
|
|
85
|
-
* }
|
|
86
|
-
* }
|
|
87
|
-
* ```
|
|
88
|
-
*/
|
|
89
|
-
declare function orderToolCalls(toolCalls: ToolCall[], tools: Tool[]): ExecutionGroup[];
|
|
90
|
-
/**
|
|
91
|
-
* Check if any tools have execution dependencies defined.
|
|
92
|
-
*
|
|
93
|
-
* @param tools - Tool definitions to check
|
|
94
|
-
* @returns true if any tool has sequential or dependsOn set
|
|
95
|
-
*/
|
|
96
|
-
declare function hasToolDependencies(tools: Tool[]): boolean;
|
|
97
|
-
/**
|
|
98
|
-
* Check if any tool calls have model-driven dependencies.
|
|
99
|
-
*
|
|
100
|
-
* @param toolCalls - Tool calls to check
|
|
101
|
-
* @returns true if any call has the `after` field set
|
|
102
|
-
*/
|
|
103
|
-
declare function hasCallDependencies(toolCalls: ToolCall[]): boolean;
|
|
104
|
-
|
|
105
|
-
export { type ExecutionGroup, ExecutionStrategy, LoopOptions, PlanOptions, ReactOptions, 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 { loop } 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,101 +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
|
-
|
|
677
|
-
export { hasCallDependencies, hasToolDependencies, orderToolCalls, plan, react };
|
|
582
|
+
export { plan, react };
|
|
678
583
|
//# sourceMappingURL=index.js.map
|
|
679
584
|
//# sourceMappingURL=index.js.map
|