@providerprotocol/agents 0.0.1 → 0.0.3
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 +333 -6
- package/dist/checkpoint/index.d.ts +43 -0
- package/dist/checkpoint/index.js +64 -0
- package/dist/checkpoint/index.js.map +1 -0
- package/{src/execution/loop.ts → dist/chunk-4ESYN66B.js} +54 -162
- package/dist/chunk-4ESYN66B.js.map +1 -0
- package/dist/chunk-EKRXMSDX.js +8 -0
- package/dist/chunk-EKRXMSDX.js.map +1 -0
- package/dist/chunk-PHI5ULBV.js +427 -0
- package/dist/chunk-PHI5ULBV.js.map +1 -0
- package/dist/execution/index.d.ts +105 -0
- package/dist/execution/index.js +679 -0
- package/dist/execution/index.js.map +1 -0
- package/dist/index-qsPwbY86.d.ts +65 -0
- package/dist/index.d.ts +101 -0
- package/dist/index.js +218 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/index.d.ts +23 -0
- package/dist/middleware/index.js +82 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/thread-tree/index.d.ts +115 -0
- package/dist/thread-tree/index.js +4 -0
- package/dist/thread-tree/index.js.map +1 -0
- package/dist/types-2Vsthzyu.d.ts +163 -0
- package/dist/types-BhX9uD_d.d.ts +91 -0
- package/dist/types-DR02gtFv.d.ts +270 -0
- package/dist/types-NGQMdnaD.d.ts +65 -0
- package/package.json +40 -8
- package/.claude/settings.local.json +0 -27
- package/AGENTS.md +0 -681
- package/CLAUDE.md +0 -681
- package/bun.lock +0 -472
- package/eslint.config.js +0 -75
- package/index.ts +0 -1
- package/llms.md +0 -796
- package/specs/UAP-1.0.md +0 -2355
- package/src/agent/index.ts +0 -384
- package/src/agent/types.ts +0 -91
- package/src/checkpoint/file.ts +0 -126
- package/src/checkpoint/index.ts +0 -40
- package/src/checkpoint/types.ts +0 -95
- package/src/execution/index.ts +0 -37
- package/src/execution/plan.ts +0 -497
- package/src/execution/react.ts +0 -340
- package/src/execution/tool-ordering.ts +0 -186
- package/src/execution/types.ts +0 -315
- package/src/index.ts +0 -80
- package/src/middleware/index.ts +0 -7
- package/src/middleware/logging.ts +0 -123
- package/src/middleware/types.ts +0 -69
- package/src/state/index.ts +0 -301
- package/src/state/types.ts +0 -173
- package/src/thread-tree/index.ts +0 -249
- package/src/thread-tree/types.ts +0 -29
- package/src/utils/uuid.ts +0 -7
- package/tests/live/agent-anthropic.test.ts +0 -288
- package/tests/live/agent-strategy-hooks.test.ts +0 -268
- package/tests/live/checkpoint.test.ts +0 -243
- package/tests/live/execution-strategies.test.ts +0 -255
- package/tests/live/plan-strategy.test.ts +0 -160
- package/tests/live/subagent-events.live.test.ts +0 -249
- package/tests/live/thread-tree.test.ts +0 -186
- package/tests/unit/agent.test.ts +0 -703
- package/tests/unit/checkpoint.test.ts +0 -232
- package/tests/unit/execution/equivalence.test.ts +0 -402
- package/tests/unit/execution/loop.test.ts +0 -437
- package/tests/unit/execution/plan.test.ts +0 -590
- package/tests/unit/execution/react.test.ts +0 -604
- package/tests/unit/execution/subagent-events.test.ts +0 -235
- package/tests/unit/execution/tool-ordering.test.ts +0 -310
- package/tests/unit/middleware/logging.test.ts +0 -276
- package/tests/unit/state.test.ts +0 -573
- package/tests/unit/thread-tree.test.ts +0 -249
- package/tsconfig.json +0 -29
|
@@ -0,0 +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,E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B,IAAA,MAAM,OAAA,GAAU,IAAA;AAChB,IAAA,IAAI,OAAA,CAAQ,KAAA,IAAS,OAAA,CAAQ,KAAA,CAAM,SAAS,CAAA,EAAG;AAC7C,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n ReactOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_REACT_OPTIONS: Required<ReactOptions> = {\n maxSteps: Infinity,\n reasoningPrompt: 'Think step by step about what you need to do next. Consider the current state, what tools are available, and what action would be most helpful.',\n};\n\n/**\n * Create a ReAct (Reason-Act-Observe) execution strategy.\n *\n * Behavior:\n * 1. Reason: LLM outputs reasoning about what to do next\n * 2. Act: LLM selects and executes tool(s)\n * 3. Observe: Tool results are formatted as observations\n * 4. Repeat until stop condition, no more actions, or maxSteps\n *\n * @param options - ReAct configuration options\n * @returns ExecutionStrategy\n */\nexport function react(options: ReactOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_REACT_OPTIONS, ...options };\n\n return {\n name: 'react',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n while (true) {\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // REASON PHASE: Ask LLM to think about what to do\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningTurn = await llm.generate(reasoningMessages);\n\n const reasoning = reasoningTurn.response.text;\n currentState = currentState.withReasoning(reasoning);\n strategy.onReason?.(step, reasoning);\n\n // Add reasoning to conversation\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE: Execute with tools\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionTurn = await llm.generate(messages);\n finalTurn = actionTurn;\n\n // Update messages with action response\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n // Handle tool calls\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n }\n\n // OBSERVE PHASE: Process tool results\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n // Check stop conditions\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n // No more tool calls means we're done\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n // Check step limit\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n while (!aborted) {\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'reasoning' },\n },\n };\n\n // REASON PHASE\n const reasoningMessages = [\n ...messages,\n new UserMessage(opts.reasoningPrompt),\n ];\n\n const reasoningStream = llm.stream(reasoningMessages);\n let reasoningText = '';\n\n for await (const event of reasoningStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n\n if (event.type === 'text_delta' && event.delta.text) {\n reasoningText += event.delta.text;\n }\n }\n\n const reasoningTurn = await reasoningStream.turn;\n currentState = currentState.withReasoning(reasoningText || reasoningTurn.response.text);\n strategy.onReason?.(step, reasoningText || reasoningTurn.response.text);\n\n yield {\n source: 'uap',\n uap: {\n type: 'reasoning',\n step,\n agentId,\n data: { reasoning: reasoningText || reasoningTurn.response.text },\n },\n };\n\n messages.push(...reasoningTurn.messages);\n\n // ACT PHASE\n const actionPrompt = new UserMessage(\n 'Based on your reasoning, take the appropriate action. Use tools if needed, or provide a final answer.',\n );\n messages.push(actionPrompt);\n\n const actionStream = llm.stream(messages);\n\n for await (const event of actionStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const actionTurn = await actionStream.turn;\n finalTurn = actionTurn;\n\n messages.push(...actionTurn.messages);\n currentState = currentState.withMessages(actionTurn.messages);\n\n if (actionTurn.response.hasToolCalls) {\n strategy.onAct?.(step, actionTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: actionTurn.response.toolCalls },\n },\n };\n }\n\n if (actionTurn.toolExecutions && actionTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, actionTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: actionTurn.toolExecutions },\n },\n };\n }\n\n strategy.onStepEnd?.(step, { turn: actionTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'complete' },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n\n if (!actionTurn.response.hasToolCalls) {\n break;\n }\n\n if (opts.maxSteps !== Infinity && step >= opts.maxSteps) {\n break;\n }\n }\n\n if (!finalTurn) {\n throw new Error('No turn generated');\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Turn, StreamEvent } from '@providerprotocol/ai';\nimport { UserMessage } from '@providerprotocol/ai';\nimport type { PlanStep } from '../state/index.ts';\nimport { generateUUID } from '../utils/uuid.ts';\nimport type {\n ExecutionStrategy,\n ExecutionContext,\n ExecutionResult,\n PlanOptions,\n AgentStreamResult,\n AgentStreamEvent,\n} from './types.ts';\n\nconst DEFAULT_PLAN_OPTIONS: Required<PlanOptions> = {\n maxPlanSteps: Infinity,\n allowReplan: true,\n planSchema: {\n type: 'object',\n properties: {\n steps: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Unique step identifier' },\n description: { type: 'string', description: 'What this step does' },\n tool: { type: 'string', description: 'Tool to use (if applicable)' },\n dependsOn: {\n type: 'array',\n items: { type: 'string' },\n description: 'IDs of steps this depends on',\n },\n },\n required: ['id', 'description', 'dependsOn'],\n },\n },\n },\n required: ['steps'],\n },\n};\n\nconst PLAN_PROMPT = `Create a detailed execution plan to accomplish the task.\nBreak it down into clear steps, specifying which tool to use for each step if applicable.\nInclude dependencies between steps (which steps must complete before others can start).\nReturn your plan as a JSON object with a \"steps\" array.`;\n\n/**\n * Create a plan-then-execute strategy.\n *\n * Behavior:\n * 1. Plan: LLM generates structured plan with steps and dependencies\n * 2. Execute: Execute each plan step respecting dependency order\n * 3. Replan: If a step fails and allowReplan is true, generate new plan\n *\n * @param options - Plan configuration options\n * @returns ExecutionStrategy\n */\nexport function plan(options: PlanOptions = {}): ExecutionStrategy {\n const opts = { ...DEFAULT_PLAN_OPTIONS, ...options };\n\n return {\n name: 'plan',\n\n async execute(context: ExecutionContext): Promise<ExecutionResult> {\n const { llm, input, state, strategy, signal } = context;\n\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Generate the plan\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planTurn = await llm.generate(planMessages);\n\n // Parse the plan from the response\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n // Try to parse from text\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Convert to PlanStep format\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n // Apply maxPlanSteps limit\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n // Execute steps in topological order\n while (planSteps.some((s) => s.status === 'pending')) {\n // Find next executable step (all dependencies completed)\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n // No step can be executed - either done or cyclic dependency\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (signal?.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n // Update step status to in_progress\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n // Execute the step\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n try {\n const stepTurn = await llm.generate(messages);\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n }\n\n // Mark step as completed\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n } catch (err) {\n nextStep.status = 'failed';\n currentState = currentState.withPlan([...planSteps]);\n\n if (opts.allowReplan) {\n // Could implement replanning here\n // For now, just continue and let the error propagate\n }\n\n throw err;\n }\n\n // Check stop condition\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn; // Use plan turn if no execution happened\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n\n return result;\n },\n\n stream(context: ExecutionContext): AgentStreamResult {\n const { llm, input, state, strategy, signal } = context;\n const agentId = context.agent.id;\n\n let aborted = false;\n const abortController = new AbortController();\n\n if (signal) {\n signal.addEventListener('abort', () => abortController.abort());\n }\n\n let resolveResult: (result: ExecutionResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<ExecutionResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n async function* generateEvents(): AsyncGenerator<AgentStreamEvent> {\n // Add input message to state and set agentId in metadata\n // This ensures checkpoints include the full conversation\n let currentState = state\n .withMessage(input)\n .withMetadata('agentId', context.agent.id);\n let step = 0;\n let finalTurn: Turn | undefined;\n\n // Messages for LLM generation (includes input we just added)\n const messages = [...currentState.messages];\n\n try {\n // PLANNING PHASE\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_start',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n const planMessages = [\n ...messages,\n new UserMessage(PLAN_PROMPT),\n ];\n\n const planStream = llm.stream(planMessages);\n\n for await (const event of planStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const planTurn = await planStream.turn;\n\n let planData: { steps: Array<{ id: string; description: string; tool?: string; dependsOn: string[] }> };\n\n try {\n if (planTurn.data) {\n planData = planTurn.data as typeof planData;\n } else {\n const jsonMatch = planTurn.response.text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n planData = JSON.parse(jsonMatch[0]) as typeof planData;\n } else {\n throw new Error('Could not parse plan from response');\n }\n }\n } catch (err) {\n throw new Error(`Failed to parse execution plan: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n let planSteps: PlanStep[] = planData.steps.map((s) => ({\n id: s.id || generateUUID(),\n description: s.description,\n tool: s.tool,\n dependsOn: s.dependsOn || [],\n status: 'pending' as const,\n }));\n\n if (opts.maxPlanSteps !== Infinity && planSteps.length > opts.maxPlanSteps) {\n planSteps = planSteps.slice(0, opts.maxPlanSteps);\n }\n\n currentState = currentState.withPlan(planSteps);\n messages.push(...planTurn.messages);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_created',\n step,\n agentId,\n data: { plan: planSteps },\n },\n };\n\n strategy.onStepEnd?.(step, { turn: planTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'step_end',\n step,\n agentId,\n data: { phase: 'planning' },\n },\n };\n\n // EXECUTION PHASE\n const completedSteps = new Set<string>();\n\n while (planSteps.some((s) => s.status === 'pending') && !aborted) {\n const nextStep = planSteps.find(\n (s) => s.status === 'pending'\n && s.dependsOn.every((depId) => completedSteps.has(depId)),\n );\n\n if (!nextStep) {\n break;\n }\n\n step++;\n currentState = currentState.withStep(step);\n\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n strategy.onStepStart?.(step, currentState);\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_start',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n nextStep.status = 'in_progress';\n currentState = currentState.withPlan([...planSteps]);\n\n const stepPrompt = new UserMessage(\n `Execute step \"${nextStep.id}\": ${nextStep.description}${nextStep.tool ? ` using the ${nextStep.tool} tool` : ''}`,\n );\n messages.push(stepPrompt);\n\n const stepStream = llm.stream(messages);\n\n for await (const event of stepStream as AsyncIterable<StreamEvent>) {\n if (abortController.signal.aborted) {\n throw new Error('Execution aborted');\n }\n\n yield { source: 'upp', upp: event };\n }\n\n const stepTurn = await stepStream.turn;\n finalTurn = stepTurn;\n\n messages.push(...stepTurn.messages);\n currentState = currentState.withMessages(stepTurn.messages);\n\n if (stepTurn.response.hasToolCalls) {\n strategy.onAct?.(step, stepTurn.response.toolCalls ?? []);\n\n yield {\n source: 'uap',\n uap: {\n type: 'action',\n step,\n agentId,\n data: { toolCalls: stepTurn.response.toolCalls },\n },\n };\n }\n\n if (stepTurn.toolExecutions && stepTurn.toolExecutions.length > 0) {\n strategy.onObserve?.(step, stepTurn.toolExecutions);\n\n yield {\n source: 'uap',\n uap: {\n type: 'observation',\n step,\n agentId,\n data: { observations: stepTurn.toolExecutions },\n },\n };\n }\n\n nextStep.status = 'completed';\n completedSteps.add(nextStep.id);\n currentState = currentState.withPlan([...planSteps]);\n\n strategy.onStepEnd?.(step, { turn: stepTurn, state: currentState });\n\n yield {\n source: 'uap',\n uap: {\n type: 'plan_step_end',\n step,\n agentId,\n data: { planStep: nextStep },\n },\n };\n\n const shouldStop = await strategy.stopCondition?.(currentState);\n if (shouldStop) {\n break;\n }\n }\n\n if (!finalTurn) {\n finalTurn = planTurn;\n }\n\n // Include sessionId in state metadata if checkpointing is enabled\n let finalState = currentState;\n if (context.sessionId) {\n finalState = currentState.withMetadata('sessionId', context.sessionId);\n }\n\n const result: ExecutionResult = {\n turn: finalTurn,\n state: finalState,\n };\n\n strategy.onComplete?.(result);\n resolveResult(result);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n strategy.onError?.(err, currentState);\n rejectResult(err);\n throw err;\n }\n }\n\n const iterator = generateEvents();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n };\n}\n","import type { Tool, ToolCall } from '@providerprotocol/ai';\nimport type { ToolWithDependencies, OrderedToolCall } from './types.ts';\n\n/**\n * Execution group - a set of tool calls that can execute in parallel.\n */\nexport interface ExecutionGroup {\n /** Tool calls in this group */\n calls: ToolCall[];\n /** Whether this group contains a sequential tool (acts as barrier) */\n isBarrier: boolean;\n}\n\n/**\n * Build a map of tool definitions by name for quick lookup.\n */\nfunction buildToolMap(tools: Tool[]): Map<string, ToolWithDependencies> {\n const map = new Map<string, ToolWithDependencies>();\n for (const tool of tools) {\n map.set(tool.name, tool as ToolWithDependencies);\n }\n return map;\n}\n\n/**\n * Check if a tool call has an explicit dependency via model hint.\n */\nfunction getModelDependencies(call: ToolCall): string[] {\n const orderedCall = call as OrderedToolCall;\n return orderedCall.after ?? [];\n}\n\n/**\n * Order tool calls into execution groups respecting dependencies.\n *\n * This function takes a list of tool calls and the available tools,\n * then groups them for execution while respecting:\n * 1. Tool-level `sequential` flag (creates execution barriers)\n * 2. Tool-level `dependsOn` array (tool must wait for named tools)\n * 3. Model-driven `after` array on tool calls (call must wait for specific calls)\n *\n * @param toolCalls - Tool calls from the model response\n * @param tools - Tool definitions (may include dependency options)\n * @returns Ordered array of execution groups\n *\n * @example\n * ```typescript\n * const groups = orderToolCalls(turn.response.toolCalls, agent.tools);\n *\n * for (const group of groups) {\n * if (group.isBarrier) {\n * // Execute sequentially\n * for (const call of group.calls) {\n * await executeTool(call);\n * }\n * } else {\n * // Execute in parallel\n * await Promise.all(group.calls.map(executeTool));\n * }\n * }\n * ```\n */\nexport function orderToolCalls(\n toolCalls: ToolCall[],\n tools: Tool[],\n): ExecutionGroup[] {\n if (toolCalls.length === 0) {\n return [];\n }\n\n const toolMap = buildToolMap(tools);\n const groups: ExecutionGroup[] = [];\n\n // Track completed tool calls and tool names\n const completedCallIds = new Set<string>();\n const completedToolNames = new Set<string>();\n\n // Create a queue of pending calls\n const pending = [...toolCalls];\n\n while (pending.length > 0) {\n const readyForExecution: ToolCall[] = [];\n let hasSequential = false;\n\n // Find all calls that can execute now\n const stillPending: ToolCall[] = [];\n\n for (const call of pending) {\n const tool = toolMap.get(call.toolName);\n const toolDependsOn = tool?.dependsOn ?? [];\n const modelDependsOn = getModelDependencies(call);\n\n // Check if tool-level dependencies are satisfied\n const toolDepsOk = toolDependsOn.every(\n (depName) => completedToolNames.has(depName),\n );\n\n // Check if model-level dependencies are satisfied\n const modelDepsOk = modelDependsOn.every(\n (depId) => completedCallIds.has(depId),\n );\n\n if (toolDepsOk && modelDepsOk) {\n readyForExecution.push(call);\n if (tool?.sequential) {\n hasSequential = true;\n }\n } else {\n stillPending.push(call);\n }\n }\n\n // If nothing is ready but we have pending items, there's a cycle\n if (readyForExecution.length === 0 && stillPending.length > 0) {\n // Break the cycle by executing remaining items\n // This is a fallback - ideally dependencies should be acyclic\n groups.push({\n calls: stillPending,\n isBarrier: false,\n });\n break;\n }\n\n // If we have sequential tools, they form a barrier\n // Process them one at a time\n if (hasSequential) {\n for (const call of readyForExecution) {\n const tool = toolMap.get(call.toolName);\n groups.push({\n calls: [call],\n isBarrier: tool?.sequential ?? false,\n });\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n } else {\n // Non-sequential tools can be grouped for parallel execution\n groups.push({\n calls: readyForExecution,\n isBarrier: false,\n });\n for (const call of readyForExecution) {\n completedCallIds.add(call.toolCallId);\n completedToolNames.add(call.toolName);\n }\n }\n\n // Update pending list\n pending.length = 0;\n pending.push(...stillPending);\n }\n\n return groups;\n}\n\n/**\n * Check if any tools have execution dependencies defined.\n *\n * @param tools - Tool definitions to check\n * @returns true if any tool has sequential or dependsOn set\n */\nexport function hasToolDependencies(tools: Tool[]): boolean {\n for (const tool of tools) {\n const t = tool as ToolWithDependencies;\n if (t.sequential || (t.dependsOn && t.dependsOn.length > 0)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if any tool calls have model-driven dependencies.\n *\n * @param toolCalls - Tool calls to check\n * @returns true if any call has the `after` field set\n */\nexport function hasCallDependencies(toolCalls: ToolCall[]): boolean {\n for (const call of toolCalls) {\n const ordered = call as OrderedToolCall;\n if (ordered.after && ordered.after.length > 0) {\n return true;\n }\n }\n return false;\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Message } from '@providerprotocol/ai';
|
|
2
|
+
import { A as AgentStateInterface, P as PlanStep, S as SubagentExecutionTrace, a as AgentStateJSON } from './types-2Vsthzyu.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Immutable agent state snapshot.
|
|
6
|
+
* All operations return new instances - the original state is never mutated.
|
|
7
|
+
*/
|
|
8
|
+
declare class AgentState implements AgentStateInterface {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly messages: readonly Message[];
|
|
11
|
+
readonly step: number;
|
|
12
|
+
readonly metadata: Readonly<Record<string, unknown>>;
|
|
13
|
+
readonly reasoning: readonly string[];
|
|
14
|
+
readonly plan: readonly PlanStep[] | undefined;
|
|
15
|
+
readonly subagentTraces: readonly SubagentExecutionTrace[];
|
|
16
|
+
private constructor();
|
|
17
|
+
/**
|
|
18
|
+
* Create an initial empty state.
|
|
19
|
+
*/
|
|
20
|
+
static initial(): AgentState;
|
|
21
|
+
/**
|
|
22
|
+
* Return new state with a message added.
|
|
23
|
+
*/
|
|
24
|
+
withMessage(message: Message): AgentState;
|
|
25
|
+
/**
|
|
26
|
+
* Return new state with messages added.
|
|
27
|
+
*/
|
|
28
|
+
withMessages(messages: Message[]): AgentState;
|
|
29
|
+
/**
|
|
30
|
+
* Return new state with context replaced (all messages).
|
|
31
|
+
* Use for context window management (pruning, summarization).
|
|
32
|
+
*/
|
|
33
|
+
withContext(messages: Message[]): AgentState;
|
|
34
|
+
/**
|
|
35
|
+
* Return new state with updated step number.
|
|
36
|
+
*/
|
|
37
|
+
withStep(step: number): AgentState;
|
|
38
|
+
/**
|
|
39
|
+
* Return new state with metadata entry added/updated.
|
|
40
|
+
*/
|
|
41
|
+
withMetadata(key: string, value: unknown): AgentState;
|
|
42
|
+
/**
|
|
43
|
+
* Return new state with reasoning trace added.
|
|
44
|
+
*/
|
|
45
|
+
withReasoning(reasoning: string): AgentState;
|
|
46
|
+
/**
|
|
47
|
+
* Return new state with plan set.
|
|
48
|
+
*/
|
|
49
|
+
withPlan(plan: PlanStep[]): AgentState;
|
|
50
|
+
/**
|
|
51
|
+
* Return new state with sub-agent trace added.
|
|
52
|
+
* Per UAP spec Section 8.8.
|
|
53
|
+
*/
|
|
54
|
+
withSubagentTrace(trace: SubagentExecutionTrace): AgentState;
|
|
55
|
+
/**
|
|
56
|
+
* Serialize state to JSON for persistence.
|
|
57
|
+
*/
|
|
58
|
+
toJSON(): AgentStateJSON;
|
|
59
|
+
/**
|
|
60
|
+
* Deserialize state from JSON.
|
|
61
|
+
*/
|
|
62
|
+
static fromJSON(json: AgentStateJSON): AgentState;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export { AgentState as A };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { LLMOptions, ModelReference, LLMInstance, Tool, Message, Turn } from '@providerprotocol/ai';
|
|
2
|
+
import { A as AgentState } from './index-qsPwbY86.js';
|
|
3
|
+
import { E as ExecutionStrategy, A as AgentStrategy, G as GenerateResult, a as AgentStreamResult } from './types-DR02gtFv.js';
|
|
4
|
+
export { b as AgentStreamEvent, O as OnSubagentEvent, f as SubagentEndEvent, g as SubagentEvent, c as SubagentEventBase, S as SubagentEventType, e as SubagentInnerEvent, d as SubagentStartEvent, U as UAPEventType } from './types-DR02gtFv.js';
|
|
5
|
+
import { M as Middleware } from './types-NGQMdnaD.js';
|
|
6
|
+
import { C as CheckpointStore } from './types-BhX9uD_d.js';
|
|
7
|
+
export { b as CheckpointData, a as CheckpointMetadata, F as FileCheckpointOptions } from './types-BhX9uD_d.js';
|
|
8
|
+
export { ThreadNode, ThreadNodeJSON, ThreadTree, ThreadTreeJSON } from './thread-tree/index.js';
|
|
9
|
+
export { A as AgentStateInterface, a as AgentStateJSON, P as PlanStep, b as PlanStepStatus, S as SubagentExecutionTrace, c as SubagentExecutionTraceJSON, T as ToolExecutionTrace } from './types-2Vsthzyu.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Options for creating an agent.
|
|
13
|
+
* Extends LLMOptions for full UPP passthrough.
|
|
14
|
+
*/
|
|
15
|
+
interface AgentOptions extends Partial<Omit<LLMOptions, 'model'>> {
|
|
16
|
+
/** Model reference from a UPP provider factory */
|
|
17
|
+
model: ModelReference;
|
|
18
|
+
/** Execution strategy. Default: loop() */
|
|
19
|
+
execution?: ExecutionStrategy;
|
|
20
|
+
/** Ordered middleware pipeline */
|
|
21
|
+
middleware?: Middleware[];
|
|
22
|
+
/** Agent lifecycle hooks */
|
|
23
|
+
strategy?: AgentStrategy;
|
|
24
|
+
/** Checkpoint store for step-level persistence */
|
|
25
|
+
checkpoints?: CheckpointStore;
|
|
26
|
+
/** Session identifier for checkpointing (auto-generated if not provided) */
|
|
27
|
+
sessionId?: string;
|
|
28
|
+
/** @internal Pre-created LLM instance for testing */
|
|
29
|
+
_llmInstance?: LLMInstance;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Agent interface.
|
|
33
|
+
*/
|
|
34
|
+
interface Agent {
|
|
35
|
+
/** Unique agent identifier (UUIDv4) */
|
|
36
|
+
readonly id: string;
|
|
37
|
+
/** The bound model */
|
|
38
|
+
readonly model: ModelReference;
|
|
39
|
+
/** Available tools */
|
|
40
|
+
readonly tools: Tool[];
|
|
41
|
+
/** System prompt */
|
|
42
|
+
readonly system?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Execute agent and return Turn with new state.
|
|
45
|
+
*
|
|
46
|
+
* @param input - User input (string or Message)
|
|
47
|
+
* @param state - Current immutable state
|
|
48
|
+
* @returns Promise resolving to { turn, state }
|
|
49
|
+
*/
|
|
50
|
+
generate(input: string | Message, state: AgentState): Promise<GenerateResult>;
|
|
51
|
+
/**
|
|
52
|
+
* Execute agent with streaming.
|
|
53
|
+
*
|
|
54
|
+
* @param input - User input (string or Message)
|
|
55
|
+
* @param state - Current immutable state
|
|
56
|
+
* @returns AgentStreamResult with async iterator and result promise
|
|
57
|
+
*/
|
|
58
|
+
stream(input: string | Message, state: AgentState): AgentStreamResult;
|
|
59
|
+
/**
|
|
60
|
+
* Multi-turn execution with automatic history management.
|
|
61
|
+
* Appends input to state, calls generate(), appends response to returned state.
|
|
62
|
+
*
|
|
63
|
+
* @param input - User input (string or Message)
|
|
64
|
+
* @param state - Current immutable state
|
|
65
|
+
* @returns Promise resolving to { turn, state }
|
|
66
|
+
*/
|
|
67
|
+
ask(input: string | Message, state: AgentState): Promise<GenerateResult>;
|
|
68
|
+
/**
|
|
69
|
+
* Stateless single-turn execution.
|
|
70
|
+
* Creates ephemeral state, executes, and discards state.
|
|
71
|
+
*
|
|
72
|
+
* @param input - User input (string or Message)
|
|
73
|
+
* @returns Promise resolving to Turn
|
|
74
|
+
*/
|
|
75
|
+
query(input: string | Message): Promise<Turn>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Create an agent instance.
|
|
80
|
+
*
|
|
81
|
+
* @param options - Agent configuration
|
|
82
|
+
* @returns Agent instance
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```typescript
|
|
86
|
+
* import { agent, AgentState } from '@providerprotocol/agents';
|
|
87
|
+
* import { anthropic } from '@providerprotocol/ai/anthropic';
|
|
88
|
+
*
|
|
89
|
+
* const coder = agent({
|
|
90
|
+
* model: anthropic('claude-sonnet-4-20250514'),
|
|
91
|
+
* tools: [Bash, Read, Write],
|
|
92
|
+
* system: 'You are a coding assistant.',
|
|
93
|
+
* });
|
|
94
|
+
*
|
|
95
|
+
* const state = AgentState.initial();
|
|
96
|
+
* const { turn, state: newState } = await coder.generate('Hello', state);
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
declare function agent(options: AgentOptions): Agent;
|
|
100
|
+
|
|
101
|
+
export { type Agent, type AgentOptions, AgentState, AgentStrategy, AgentStreamResult, CheckpointStore, GenerateResult, agent };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { loop } from './chunk-4ESYN66B.js';
|
|
2
|
+
import { AgentState } from './chunk-PHI5ULBV.js';
|
|
3
|
+
export { AgentState, ThreadNode, ThreadTree } from './chunk-PHI5ULBV.js';
|
|
4
|
+
import { generateUUID } from './chunk-EKRXMSDX.js';
|
|
5
|
+
import { llm, UserMessage } from '@providerprotocol/ai';
|
|
6
|
+
|
|
7
|
+
function agent(options) {
|
|
8
|
+
const {
|
|
9
|
+
// UAP-specific options
|
|
10
|
+
execution = loop(),
|
|
11
|
+
middleware = [],
|
|
12
|
+
strategy = {},
|
|
13
|
+
checkpoints,
|
|
14
|
+
sessionId: providedSessionId,
|
|
15
|
+
_llmInstance,
|
|
16
|
+
// LLM options (passthrough to UPP)
|
|
17
|
+
model,
|
|
18
|
+
params = {},
|
|
19
|
+
config,
|
|
20
|
+
tools = [],
|
|
21
|
+
system,
|
|
22
|
+
structure,
|
|
23
|
+
toolStrategy
|
|
24
|
+
} = options;
|
|
25
|
+
const agentId = generateUUID();
|
|
26
|
+
const sessionId = checkpoints ? providedSessionId ?? generateUUID() : providedSessionId;
|
|
27
|
+
const llmInstance = _llmInstance ?? llm({
|
|
28
|
+
model,
|
|
29
|
+
params,
|
|
30
|
+
config,
|
|
31
|
+
system,
|
|
32
|
+
structure,
|
|
33
|
+
tools,
|
|
34
|
+
toolStrategy
|
|
35
|
+
});
|
|
36
|
+
function normalizeInput(input) {
|
|
37
|
+
if (typeof input === "string") {
|
|
38
|
+
return new UserMessage(input);
|
|
39
|
+
}
|
|
40
|
+
return input;
|
|
41
|
+
}
|
|
42
|
+
async function runBeforeMiddleware(middlewares, context) {
|
|
43
|
+
let currentContext = context;
|
|
44
|
+
for (const mw of middlewares) {
|
|
45
|
+
if (mw.before) {
|
|
46
|
+
const result = await mw.before(currentContext);
|
|
47
|
+
if (result) {
|
|
48
|
+
currentContext = result;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return currentContext;
|
|
53
|
+
}
|
|
54
|
+
async function runAfterMiddleware(middlewares, context, result) {
|
|
55
|
+
let currentResult = result;
|
|
56
|
+
for (let i = middlewares.length - 1; i >= 0; i--) {
|
|
57
|
+
const mw = middlewares[i];
|
|
58
|
+
if (mw?.after) {
|
|
59
|
+
currentResult = await mw.after(context, currentResult);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return currentResult;
|
|
63
|
+
}
|
|
64
|
+
async function runErrorMiddleware(middlewares, context, error) {
|
|
65
|
+
for (let i = middlewares.length - 1; i >= 0; i--) {
|
|
66
|
+
const mw = middlewares[i];
|
|
67
|
+
if (mw?.onError) {
|
|
68
|
+
const result = await mw.onError(context, error);
|
|
69
|
+
if (result) {
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return void 0;
|
|
75
|
+
}
|
|
76
|
+
function buildExecutionContext(input, state, resolvedStrategy, signal) {
|
|
77
|
+
return {
|
|
78
|
+
agent: { id: agentId, system },
|
|
79
|
+
llm: llmInstance,
|
|
80
|
+
input,
|
|
81
|
+
state,
|
|
82
|
+
tools,
|
|
83
|
+
strategy: resolvedStrategy,
|
|
84
|
+
signal,
|
|
85
|
+
checkpoints,
|
|
86
|
+
sessionId
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const agentInstance = {
|
|
90
|
+
id: agentId,
|
|
91
|
+
model,
|
|
92
|
+
tools,
|
|
93
|
+
system,
|
|
94
|
+
async generate(input, state) {
|
|
95
|
+
const normalizedInput = normalizeInput(input);
|
|
96
|
+
const middlewareContext = {
|
|
97
|
+
agent: { id: agentId, system },
|
|
98
|
+
input: normalizedInput,
|
|
99
|
+
state,
|
|
100
|
+
metadata: /* @__PURE__ */ new Map()
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
const processedContext = await runBeforeMiddleware(middleware, middlewareContext);
|
|
104
|
+
const executionContext = buildExecutionContext(
|
|
105
|
+
processedContext.input,
|
|
106
|
+
processedContext.state,
|
|
107
|
+
strategy
|
|
108
|
+
);
|
|
109
|
+
const result = await execution.execute(executionContext);
|
|
110
|
+
const finalResult = await runAfterMiddleware(
|
|
111
|
+
middleware,
|
|
112
|
+
processedContext,
|
|
113
|
+
result
|
|
114
|
+
);
|
|
115
|
+
return finalResult;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
118
|
+
const recovered = await runErrorMiddleware(middleware, middlewareContext, err);
|
|
119
|
+
if (recovered) {
|
|
120
|
+
return recovered;
|
|
121
|
+
}
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
stream(input, state) {
|
|
126
|
+
const normalizedInput = normalizeInput(input);
|
|
127
|
+
const middlewareContext = {
|
|
128
|
+
agent: { id: agentId, system },
|
|
129
|
+
input: normalizedInput,
|
|
130
|
+
state,
|
|
131
|
+
metadata: /* @__PURE__ */ new Map()
|
|
132
|
+
};
|
|
133
|
+
let aborted = false;
|
|
134
|
+
const abortController = new AbortController();
|
|
135
|
+
let resolveResult;
|
|
136
|
+
let rejectResult;
|
|
137
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
138
|
+
resolveResult = resolve;
|
|
139
|
+
rejectResult = reject;
|
|
140
|
+
});
|
|
141
|
+
const createStream = async function* () {
|
|
142
|
+
try {
|
|
143
|
+
const processedContext = await runBeforeMiddleware(middleware, middlewareContext);
|
|
144
|
+
const executionContext = buildExecutionContext(
|
|
145
|
+
processedContext.input,
|
|
146
|
+
processedContext.state,
|
|
147
|
+
strategy,
|
|
148
|
+
abortController.signal
|
|
149
|
+
);
|
|
150
|
+
const streamResult = execution.stream(executionContext);
|
|
151
|
+
for await (const event of streamResult) {
|
|
152
|
+
if (aborted) {
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
yield event;
|
|
156
|
+
}
|
|
157
|
+
const result = await streamResult.result;
|
|
158
|
+
const finalResult = await runAfterMiddleware(
|
|
159
|
+
middleware,
|
|
160
|
+
processedContext,
|
|
161
|
+
result
|
|
162
|
+
);
|
|
163
|
+
resolveResult(finalResult);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
166
|
+
const recovered = await runErrorMiddleware(middleware, middlewareContext, err);
|
|
167
|
+
if (recovered) {
|
|
168
|
+
resolveResult(recovered);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
rejectResult(err);
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const iterator = createStream();
|
|
176
|
+
return {
|
|
177
|
+
[Symbol.asyncIterator]() {
|
|
178
|
+
return iterator;
|
|
179
|
+
},
|
|
180
|
+
result: resultPromise,
|
|
181
|
+
abort() {
|
|
182
|
+
aborted = true;
|
|
183
|
+
abortController.abort();
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
},
|
|
187
|
+
async ask(input, state) {
|
|
188
|
+
const normalizedInput = normalizeInput(input);
|
|
189
|
+
const result = await agentInstance.generate(normalizedInput, state);
|
|
190
|
+
const responseMessages = result.state.messages.slice(state.messages.length);
|
|
191
|
+
const finalState = state.withMessage(normalizedInput).withMessages(responseMessages).withStep(result.state.step);
|
|
192
|
+
let stateWithMetadata = finalState;
|
|
193
|
+
for (const [key, value] of Object.entries(result.state.metadata)) {
|
|
194
|
+
stateWithMetadata = stateWithMetadata.withMetadata(key, value);
|
|
195
|
+
}
|
|
196
|
+
for (const reasoning of result.state.reasoning) {
|
|
197
|
+
stateWithMetadata = stateWithMetadata.withReasoning(reasoning);
|
|
198
|
+
}
|
|
199
|
+
if (result.state.plan) {
|
|
200
|
+
stateWithMetadata = stateWithMetadata.withPlan([...result.state.plan]);
|
|
201
|
+
}
|
|
202
|
+
return {
|
|
203
|
+
turn: result.turn,
|
|
204
|
+
state: stateWithMetadata
|
|
205
|
+
};
|
|
206
|
+
},
|
|
207
|
+
async query(input) {
|
|
208
|
+
const initialState = AgentState.initial();
|
|
209
|
+
const result = await agentInstance.generate(input, initialState);
|
|
210
|
+
return result.turn;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
return agentInstance;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export { agent };
|
|
217
|
+
//# sourceMappingURL=index.js.map
|
|
218
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agent/index.ts"],"names":[],"mappings":";;;;;;AA0CO,SAAS,MAAM,OAAA,EAA8B;AAClD,EAAA,MAAM;AAAA;AAAA,IAEJ,YAAY,IAAA,EAAK;AAAA,IACjB,aAAa,EAAC;AAAA,IACd,WAAW,EAAC;AAAA,IACZ,WAAA;AAAA,IACA,SAAA,EAAW,iBAAA;AAAA,IACX,YAAA;AAAA;AAAA,IAEA,KAAA;AAAA,IACA,SAAS,EAAC;AAAA,IACV,MAAA;AAAA,IACA,QAAQ,EAAC;AAAA,IACT,MAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAEJ,EAAA,MAAM,UAAU,YAAA,EAAa;AAG7B,EAAA,MAAM,SAAA,GAAY,WAAA,GAAe,iBAAA,IAAqB,YAAA,EAAa,GAAK,iBAAA;AAGxE,EAAA,MAAM,WAAA,GAA2B,gBAAgB,GAAA,CA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MAAM,YAAA,GAAe,WAAW,OAAA,EAAQ;AACxC,MAAA,MAAM,MAAA,GAAS,MAAM,aAAA,CAAc,QAAA,CAAS,OAAO,YAAY,CAAA;AAC/D,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB;AAAA,GACF;AAEA,EAAA,OAAO,aAAA;AACT","file":"index.js","sourcesContent":["import {\n llm,\n UserMessage,\n} from '@providerprotocol/ai';\nimport type {\n LLMInstance,\n Message,\n Turn,\n} from '@providerprotocol/ai';\nimport { generateUUID } from '../utils/uuid.ts';\nimport { AgentState } from '../state/index.ts';\nimport { loop } from '../execution/loop.ts';\nimport type {\n ExecutionContext,\n GenerateResult,\n AgentStreamResult,\n AgentStrategy,\n} from '../execution/types.ts';\nimport type { Middleware, MiddlewareContext } from '../middleware/types.ts';\nimport type { Agent, AgentOptions } from './types.ts';\n\n/**\n * Create an agent instance.\n *\n * @param options - Agent configuration\n * @returns Agent instance\n *\n * @example\n * ```typescript\n * import { agent, AgentState } from '@providerprotocol/agents';\n * import { anthropic } from '@providerprotocol/ai/anthropic';\n *\n * const coder = agent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * tools: [Bash, Read, Write],\n * system: 'You are a coding assistant.',\n * });\n *\n * const state = AgentState.initial();\n * const { turn, state: newState } = await coder.generate('Hello', state);\n * ```\n */\nexport function agent(options: AgentOptions): Agent {\n const {\n // UAP-specific options\n execution = loop(),\n middleware = [],\n strategy = {},\n checkpoints,\n sessionId: providedSessionId,\n _llmInstance,\n // LLM options (passthrough to UPP)\n model,\n params = {},\n config,\n tools = [],\n system,\n structure,\n toolStrategy,\n } = options;\n\n const agentId = generateUUID();\n // Generate sessionId (UUIDv4) if checkpoints provided but no sessionId\n // Per UAP spec Section 3.4: Session IDs MUST be UUIDv4\n const sessionId = checkpoints ? (providedSessionId ?? generateUUID()) : providedSessionId;\n\n // Create the LLM instance with full UPP passthrough (or use injected instance for testing)\n const llmInstance: LLMInstance = _llmInstance ?? llm({\n model,\n params,\n config,\n system,\n structure,\n tools,\n toolStrategy,\n });\n\n /**\n * Normalize input to a Message.\n */\n function normalizeInput(input: string | Message): Message {\n if (typeof input === 'string') {\n return new UserMessage(input);\n }\n return input;\n }\n\n /**\n * Run middleware before hooks.\n */\n async function runBeforeMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n ): Promise<MiddlewareContext> {\n let currentContext = context;\n\n for (const mw of middlewares) {\n if (mw.before) {\n const result = await mw.before(currentContext);\n if (result) {\n currentContext = result;\n }\n }\n }\n\n return currentContext;\n }\n\n /**\n * Run middleware after hooks (in reverse order).\n */\n async function runAfterMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n result: GenerateResult,\n ): Promise<GenerateResult> {\n let currentResult = result;\n\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.after) {\n currentResult = await mw.after(context, currentResult);\n }\n }\n\n return currentResult;\n }\n\n /**\n * Run middleware error hooks (in reverse order).\n */\n async function runErrorMiddleware(\n middlewares: Middleware[],\n context: MiddlewareContext,\n error: Error,\n ): Promise<GenerateResult | undefined> {\n // Run in reverse order\n for (let i = middlewares.length - 1; i >= 0; i--) {\n const mw = middlewares[i];\n if (mw?.onError) {\n const result = await mw.onError(context, error);\n if (result) {\n return result;\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Build execution context.\n */\n function buildExecutionContext(\n input: Message,\n state: AgentState,\n resolvedStrategy: AgentStrategy,\n signal?: AbortSignal,\n ): ExecutionContext {\n return {\n agent: { id: agentId, system },\n llm: llmInstance,\n input,\n state,\n tools,\n strategy: resolvedStrategy,\n signal,\n checkpoints,\n sessionId,\n };\n }\n\n const agentInstance: Agent = {\n id: agentId,\n model,\n tools,\n system,\n\n async generate(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n );\n\n // Execute strategy\n const result = await execution.execute(executionContext);\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n return finalResult;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n return recovered;\n }\n\n throw err;\n }\n },\n\n stream(\n input: string | Message,\n state: AgentState,\n ): AgentStreamResult {\n const normalizedInput = normalizeInput(input);\n\n // Create middleware context\n const middlewareContext: MiddlewareContext = {\n agent: { id: agentId, system },\n input: normalizedInput,\n state,\n metadata: new Map(),\n };\n\n // We need to run before middleware synchronously enough to get the context\n // but streaming is inherently async. We'll handle this by wrapping the stream.\n let aborted = false;\n const abortController = new AbortController();\n\n let resolveResult: (result: GenerateResult) => void;\n let rejectResult: (error: Error) => void;\n\n const resultPromise = new Promise<GenerateResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const createStream = async function* () {\n try {\n // Run before middleware\n const processedContext = await runBeforeMiddleware(middleware, middlewareContext);\n\n // Build execution context\n const executionContext = buildExecutionContext(\n processedContext.input,\n processedContext.state,\n strategy,\n abortController.signal,\n );\n\n // Get the stream from the execution strategy\n const streamResult = execution.stream(executionContext);\n\n // Yield events from the stream\n for await (const event of streamResult) {\n if (aborted) {\n break;\n }\n yield event;\n }\n\n // Get the final result\n const result = await streamResult.result;\n\n // Run after middleware\n const finalResult = await runAfterMiddleware(\n middleware,\n processedContext,\n result,\n );\n\n resolveResult(finalResult);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n // Try to recover with error middleware\n const recovered = await runErrorMiddleware(middleware, middlewareContext, err);\n if (recovered) {\n resolveResult(recovered);\n return;\n }\n\n rejectResult(err);\n throw err;\n }\n };\n\n const iterator = createStream();\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n result: resultPromise,\n abort() {\n aborted = true;\n abortController.abort();\n },\n };\n },\n\n async ask(\n input: string | Message,\n state: AgentState,\n ): Promise<GenerateResult> {\n const normalizedInput = normalizeInput(input);\n\n // Generate with original state - execution strategy adds input to LLM call\n const result = await agentInstance.generate(normalizedInput, state);\n\n // Build final state with correct message order:\n // original messages + input + response messages from this turn\n const responseMessages = result.state.messages.slice(state.messages.length);\n const finalState = state\n .withMessage(normalizedInput)\n .withMessages(responseMessages)\n .withStep(result.state.step);\n\n // Preserve metadata from execution\n let stateWithMetadata = finalState;\n for (const [key, value] of Object.entries(result.state.metadata)) {\n stateWithMetadata = stateWithMetadata.withMetadata(key, value);\n }\n\n // Preserve reasoning traces\n for (const reasoning of result.state.reasoning) {\n stateWithMetadata = stateWithMetadata.withReasoning(reasoning);\n }\n\n // Preserve plan if present\n if (result.state.plan) {\n stateWithMetadata = stateWithMetadata.withPlan([...result.state.plan]);\n }\n\n return {\n turn: result.turn,\n state: stateWithMetadata,\n };\n },\n\n async query(input: string | Message): Promise<Turn> {\n const initialState = AgentState.initial();\n const result = await agentInstance.generate(input, initialState);\n return result.turn;\n },\n };\n\n return agentInstance;\n}\n\nexport type { Agent, AgentOptions } from './types.ts';\nexport type {\n GenerateResult,\n AgentStreamResult,\n AgentStreamEvent,\n UAPEventType,\n AgentStrategy,\n // Sub-agent event types (Section 8.7)\n SubagentEventType,\n SubagentEventBase,\n SubagentStartEvent,\n SubagentInnerEvent,\n SubagentEndEvent,\n SubagentEvent,\n OnSubagentEvent,\n} from '../execution/types.ts';\n"]}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { L as LoggingOptions, M as Middleware } from '../types-NGQMdnaD.js';
|
|
2
|
+
export { a as MiddlewareContext } from '../types-NGQMdnaD.js';
|
|
3
|
+
import '@providerprotocol/ai';
|
|
4
|
+
import '../index-qsPwbY86.js';
|
|
5
|
+
import '../types-2Vsthzyu.js';
|
|
6
|
+
import '../types-DR02gtFv.js';
|
|
7
|
+
import '../types-BhX9uD_d.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Create a logging middleware.
|
|
11
|
+
*
|
|
12
|
+
* Logs agent execution with configurable detail level:
|
|
13
|
+
* - Execution start/end
|
|
14
|
+
* - Timing information (if enabled)
|
|
15
|
+
* - Message content (if enabled)
|
|
16
|
+
* - Errors
|
|
17
|
+
*
|
|
18
|
+
* @param options - Logging configuration options
|
|
19
|
+
* @returns Middleware
|
|
20
|
+
*/
|
|
21
|
+
declare function logging(options?: LoggingOptions): Middleware;
|
|
22
|
+
|
|
23
|
+
export { LoggingOptions, Middleware, logging };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// src/middleware/logging.ts
|
|
2
|
+
var DEFAULT_LOGGING_OPTIONS = {
|
|
3
|
+
level: "info",
|
|
4
|
+
logger: console.log,
|
|
5
|
+
includeMessages: false,
|
|
6
|
+
includeTiming: true
|
|
7
|
+
};
|
|
8
|
+
var LOG_LEVELS = {
|
|
9
|
+
debug: 0,
|
|
10
|
+
info: 1,
|
|
11
|
+
warn: 2,
|
|
12
|
+
error: 3
|
|
13
|
+
};
|
|
14
|
+
function logging(options = {}) {
|
|
15
|
+
const opts = { ...DEFAULT_LOGGING_OPTIONS, ...options };
|
|
16
|
+
const currentLevel = LOG_LEVELS[opts.level];
|
|
17
|
+
function shouldLog(level) {
|
|
18
|
+
return LOG_LEVELS[level] >= currentLevel;
|
|
19
|
+
}
|
|
20
|
+
function log(level, message) {
|
|
21
|
+
if (shouldLog(level)) {
|
|
22
|
+
const prefix = `[UAP:${level.toUpperCase()}]`;
|
|
23
|
+
opts.logger(`${prefix} ${message}`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function formatContext(context) {
|
|
27
|
+
const parts = [`agent=${context.agent.id}`];
|
|
28
|
+
if (opts.includeMessages) {
|
|
29
|
+
parts.push(`messages=${context.state.messages.length}`);
|
|
30
|
+
}
|
|
31
|
+
return parts.join(" ");
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
name: "logging",
|
|
35
|
+
async before(context) {
|
|
36
|
+
log("info", `Execution started: ${formatContext(context)}`);
|
|
37
|
+
if (opts.includeTiming) {
|
|
38
|
+
context.metadata.set("_logging_startTime", Date.now());
|
|
39
|
+
}
|
|
40
|
+
if (opts.includeMessages && shouldLog("debug")) {
|
|
41
|
+
log("debug", `Input: ${JSON.stringify(context.input)}`);
|
|
42
|
+
}
|
|
43
|
+
return context;
|
|
44
|
+
},
|
|
45
|
+
async after(context, result) {
|
|
46
|
+
let message = "Execution completed";
|
|
47
|
+
if (opts.includeTiming) {
|
|
48
|
+
const startTime = context.metadata.get("_logging_startTime");
|
|
49
|
+
if (startTime) {
|
|
50
|
+
const duration = Date.now() - startTime;
|
|
51
|
+
message += ` in ${duration}ms`;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
message += `: ${formatContext(context)}`;
|
|
55
|
+
if (result.turn.usage) {
|
|
56
|
+
message += ` tokens=${result.turn.usage.totalTokens}`;
|
|
57
|
+
}
|
|
58
|
+
log("info", message);
|
|
59
|
+
if (opts.includeMessages && shouldLog("debug")) {
|
|
60
|
+
log("debug", `Response: ${result.turn.response.text.substring(0, 200)}...`);
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
},
|
|
64
|
+
async onError(context, error) {
|
|
65
|
+
let message = `Execution failed: ${error.message}`;
|
|
66
|
+
if (opts.includeTiming) {
|
|
67
|
+
const startTime = context.metadata.get("_logging_startTime");
|
|
68
|
+
if (startTime) {
|
|
69
|
+
const duration = Date.now() - startTime;
|
|
70
|
+
message += ` after ${duration}ms`;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
message += `: ${formatContext(context)}`;
|
|
74
|
+
log("error", message);
|
|
75
|
+
return void 0;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export { logging };
|
|
81
|
+
//# sourceMappingURL=index.js.map
|
|
82
|
+
//# sourceMappingURL=index.js.map
|