@moureau/pipeflow 0.0.1 → 0.0.2
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 +245 -117
- package/dist/cjs/agents/agent.js +1 -1
- package/dist/cjs/agents/agent.js.map +3 -3
- package/dist/cjs/agents/tools/tools.js +1 -1
- package/dist/cjs/agents/tools/tools.js.map +3 -3
- package/dist/cjs/conversations/conversation/conversation.js +1 -1
- package/dist/cjs/conversations/conversation/conversation.js.map +3 -3
- package/dist/cjs/conversations/conversations.js +1 -1
- package/dist/cjs/conversations/conversations.js.map +3 -3
- package/dist/cjs/conversations/index.js +1 -1
- package/dist/cjs/conversations/index.js.map +3 -3
- package/dist/cjs/conversations/orchestration/coordination/coordination.js +10 -0
- package/dist/cjs/conversations/orchestration/coordination/coordination.js.map +7 -0
- package/dist/cjs/conversations/orchestration/coordination/index.js +2 -0
- package/dist/cjs/conversations/orchestration/coordination/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js +4 -0
- package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/generation/generation.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/generation/generation.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/generation/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/generation/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/history/history.js +4 -0
- package/dist/cjs/conversations/orchestration/orchestrator/history/history.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/history/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/history/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/index.js +1 -1
- package/dist/cjs/conversations/orchestration/orchestrator/index.js.map +3 -3
- package/dist/cjs/conversations/orchestration/orchestrator/orchestrator.js +1 -2
- package/dist/cjs/conversations/orchestration/orchestrator/orchestrator.js.map +3 -3
- package/dist/cjs/conversations/orchestration/orchestrator/routing/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/routing/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/routing/routing.js +23 -0
- package/dist/cjs/conversations/orchestration/orchestrator/routing/routing.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/speech/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/speech/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/speech/speech.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/speech/speech.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/tools/index.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/tools/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/orchestrator/tools/tools.js +2 -0
- package/dist/cjs/conversations/orchestration/orchestrator/tools/tools.js.map +7 -0
- package/dist/cjs/conversations/orchestration/test-harness.js +2 -0
- package/dist/cjs/conversations/orchestration/test-harness.js.map +7 -0
- package/dist/cjs/conversations/orchestration/text-chunker/index.js +2 -0
- package/dist/cjs/conversations/orchestration/text-chunker/index.js.map +7 -0
- package/dist/cjs/conversations/orchestration/text-chunker/text-chunker.js +3 -0
- package/dist/cjs/conversations/orchestration/text-chunker/text-chunker.js.map +7 -0
- package/dist/cjs/conversations/stream/conversation-stream.js +2 -0
- package/dist/cjs/conversations/stream/conversation-stream.js.map +7 -0
- package/dist/cjs/conversations/stream/index.js +2 -0
- package/dist/cjs/conversations/stream/index.js.map +7 -0
- package/dist/cjs/conversations/types.js +1 -1
- package/dist/cjs/conversations/types.js.map +2 -2
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +3 -3
- package/dist/cjs/persistence/adapters/sqlite/sqlite.js +18 -14
- package/dist/cjs/persistence/adapters/sqlite/sqlite.js.map +3 -3
- package/dist/cjs/pipeflow/index.js +2 -0
- package/dist/cjs/pipeflow/index.js.map +7 -0
- package/dist/cjs/pipeflow/pipeflow.js +2 -0
- package/dist/cjs/pipeflow/pipeflow.js.map +7 -0
- package/dist/cjs/providers/index.js +1 -1
- package/dist/cjs/providers/index.js.map +2 -2
- package/dist/cjs/providers/llm/adapters/claude/claude.js +5 -0
- package/dist/cjs/providers/llm/adapters/claude/claude.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/claude/index.js +2 -0
- package/dist/cjs/providers/llm/adapters/claude/index.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/deepseek/deepseek.js +1 -1
- package/dist/cjs/providers/llm/adapters/deepseek/deepseek.js.map +3 -3
- package/dist/cjs/providers/llm/adapters/index.js +1 -1
- package/dist/cjs/providers/llm/adapters/index.js.map +3 -3
- package/dist/cjs/providers/llm/adapters/openai/index.js +2 -0
- package/dist/cjs/providers/llm/adapters/openai/index.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/openai/openai.js +2 -0
- package/dist/cjs/providers/llm/adapters/openai/openai.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/openai-compatible.js +10 -0
- package/dist/cjs/providers/llm/adapters/openai-compatible.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/openrouter/index.js +2 -0
- package/dist/cjs/providers/llm/adapters/openrouter/index.js.map +7 -0
- package/dist/cjs/providers/llm/adapters/openrouter/openrouter.js +2 -0
- package/dist/cjs/providers/llm/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/cjs/providers/llm/index.js +1 -1
- package/dist/cjs/providers/llm/index.js.map +3 -3
- package/dist/cjs/providers/llm/toolmode/index.js +2 -0
- package/dist/cjs/providers/llm/toolmode/index.js.map +7 -0
- package/dist/cjs/providers/llm/toolmode/toolmode.js +2 -0
- package/dist/cjs/providers/llm/toolmode/toolmode.js.map +7 -0
- package/dist/cjs/providers/llm/types.js +1 -1
- package/dist/cjs/providers/llm/types.js.map +3 -3
- package/dist/cjs/providers/stt/adapters/deepgram/deepgram.js +1 -1
- package/dist/cjs/providers/stt/adapters/deepgram/deepgram.js.map +3 -3
- package/dist/cjs/providers/stt/adapters/index.js +1 -1
- package/dist/cjs/providers/stt/adapters/index.js.map +3 -3
- package/dist/cjs/providers/stt/adapters/openrouter/index.js +2 -0
- package/dist/cjs/providers/stt/adapters/openrouter/index.js.map +7 -0
- package/dist/cjs/providers/stt/adapters/openrouter/openrouter.js +2 -0
- package/dist/cjs/providers/stt/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/cjs/providers/tts/adapters/index.js +1 -1
- package/dist/cjs/providers/tts/adapters/index.js.map +3 -3
- package/dist/cjs/providers/tts/adapters/kokoro/kokoro.js +4 -1
- package/dist/cjs/providers/tts/adapters/kokoro/kokoro.js.map +3 -3
- package/dist/cjs/providers/tts/adapters/openrouter/index.js +2 -0
- package/dist/cjs/providers/tts/adapters/openrouter/index.js.map +7 -0
- package/dist/cjs/providers/tts/adapters/openrouter/openrouter.js +2 -0
- package/dist/cjs/providers/tts/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/cjs/transport/streamobject/field-stream/field-stream.js +2 -0
- package/dist/cjs/transport/streamobject/field-stream/field-stream.js.map +7 -0
- package/dist/cjs/transport/streamobject/field-stream/index.js +2 -0
- package/dist/cjs/transport/streamobject/field-stream/index.js.map +7 -0
- package/dist/cjs/transport/streamobject/index.js +2 -0
- package/dist/cjs/transport/streamobject/index.js.map +7 -0
- package/dist/cjs/transport/streamobject/json-adapter/index.js +2 -0
- package/dist/cjs/transport/streamobject/json-adapter/index.js.map +7 -0
- package/dist/cjs/transport/streamobject/json-adapter/json-adapter.js +4 -0
- package/dist/cjs/transport/streamobject/json-adapter/json-adapter.js.map +7 -0
- package/dist/cjs/transport/streamobject/reference/index.js +2 -0
- package/dist/cjs/transport/streamobject/reference/index.js.map +7 -0
- package/dist/cjs/transport/streamobject/reference/reference.js +2 -0
- package/dist/cjs/transport/streamobject/reference/reference.js.map +7 -0
- package/dist/cjs/transport/streamobject/stream-object/index.js +2 -0
- package/dist/cjs/transport/streamobject/stream-object/index.js.map +7 -0
- package/dist/cjs/transport/streamobject/stream-object/stream-object.js +2 -0
- package/dist/cjs/transport/streamobject/stream-object/stream-object.js.map +7 -0
- package/dist/esm/agents/agent.js +1 -1
- package/dist/esm/agents/agent.js.map +3 -3
- package/dist/esm/agents/tools/tools.js +1 -1
- package/dist/esm/agents/tools/tools.js.map +3 -3
- package/dist/esm/conversations/conversation/conversation.js +1 -1
- package/dist/esm/conversations/conversation/conversation.js.map +3 -3
- package/dist/esm/conversations/conversations.js +1 -1
- package/dist/esm/conversations/conversations.js.map +3 -3
- package/dist/esm/conversations/index.js +1 -1
- package/dist/esm/conversations/index.js.map +3 -3
- package/dist/esm/conversations/orchestration/coordination/coordination.js +10 -0
- package/dist/esm/conversations/orchestration/coordination/coordination.js.map +7 -0
- package/dist/esm/conversations/orchestration/coordination/index.js +2 -0
- package/dist/esm/conversations/orchestration/coordination/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js +4 -0
- package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/coordination-runner/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/generation/generation.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/generation/generation.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/generation/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/generation/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/history/history.js +4 -0
- package/dist/esm/conversations/orchestration/orchestrator/history/history.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/history/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/history/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/index.js +1 -1
- package/dist/esm/conversations/orchestration/orchestrator/index.js.map +3 -3
- package/dist/esm/conversations/orchestration/orchestrator/orchestrator.js +1 -2
- package/dist/esm/conversations/orchestration/orchestrator/orchestrator.js.map +3 -3
- package/dist/esm/conversations/orchestration/orchestrator/routing/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/routing/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/routing/routing.js +23 -0
- package/dist/esm/conversations/orchestration/orchestrator/routing/routing.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/speech/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/speech/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/speech/speech.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/speech/speech.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/tools/index.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/tools/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/orchestrator/tools/tools.js +2 -0
- package/dist/esm/conversations/orchestration/orchestrator/tools/tools.js.map +7 -0
- package/dist/esm/conversations/orchestration/test-harness.js +2 -0
- package/dist/esm/conversations/orchestration/test-harness.js.map +7 -0
- package/dist/esm/conversations/orchestration/text-chunker/index.js +2 -0
- package/dist/esm/conversations/orchestration/text-chunker/index.js.map +7 -0
- package/dist/esm/conversations/orchestration/text-chunker/text-chunker.js +3 -0
- package/dist/esm/conversations/orchestration/text-chunker/text-chunker.js.map +7 -0
- package/dist/esm/conversations/stream/conversation-stream.js +2 -0
- package/dist/esm/conversations/stream/conversation-stream.js.map +7 -0
- package/dist/esm/conversations/stream/index.js +2 -0
- package/dist/esm/conversations/stream/index.js.map +7 -0
- package/dist/esm/conversations/types.js +1 -1
- package/dist/esm/conversations/types.js.map +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +3 -3
- package/dist/esm/persistence/adapters/sqlite/sqlite.js +18 -14
- package/dist/esm/persistence/adapters/sqlite/sqlite.js.map +3 -3
- package/dist/esm/pipeflow/index.js +2 -0
- package/dist/esm/pipeflow/index.js.map +7 -0
- package/dist/esm/pipeflow/pipeflow.js +2 -0
- package/dist/esm/pipeflow/pipeflow.js.map +7 -0
- package/dist/esm/providers/index.js +1 -1
- package/dist/esm/providers/index.js.map +3 -3
- package/dist/esm/providers/llm/adapters/claude/claude.js +5 -0
- package/dist/esm/providers/llm/adapters/claude/claude.js.map +7 -0
- package/dist/esm/providers/llm/adapters/claude/index.js +2 -0
- package/dist/esm/providers/llm/adapters/claude/index.js.map +7 -0
- package/dist/esm/providers/llm/adapters/deepseek/deepseek.js +1 -1
- package/dist/esm/providers/llm/adapters/deepseek/deepseek.js.map +3 -3
- package/dist/esm/providers/llm/adapters/index.js +1 -1
- package/dist/esm/providers/llm/adapters/index.js.map +3 -3
- package/dist/esm/providers/llm/adapters/openai/index.js +2 -0
- package/dist/esm/providers/llm/adapters/openai/index.js.map +7 -0
- package/dist/esm/providers/llm/adapters/openai/openai.js +2 -0
- package/dist/esm/providers/llm/adapters/openai/openai.js.map +7 -0
- package/dist/esm/providers/llm/adapters/openai-compatible.js +10 -0
- package/dist/esm/providers/llm/adapters/openai-compatible.js.map +7 -0
- package/dist/esm/providers/llm/adapters/openrouter/index.js +2 -0
- package/dist/esm/providers/llm/adapters/openrouter/index.js.map +7 -0
- package/dist/esm/providers/llm/adapters/openrouter/openrouter.js +2 -0
- package/dist/esm/providers/llm/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/esm/providers/llm/index.js +1 -1
- package/dist/esm/providers/llm/index.js.map +3 -3
- package/dist/esm/providers/llm/toolmode/index.js +2 -0
- package/dist/esm/providers/llm/toolmode/index.js.map +7 -0
- package/dist/esm/providers/llm/toolmode/toolmode.js +2 -0
- package/dist/esm/providers/llm/toolmode/toolmode.js.map +7 -0
- package/dist/esm/providers/llm/types.js +1 -0
- package/dist/esm/providers/llm/types.js.map +4 -4
- package/dist/esm/providers/stt/adapters/deepgram/deepgram.js +1 -1
- package/dist/esm/providers/stt/adapters/deepgram/deepgram.js.map +3 -3
- package/dist/esm/providers/stt/adapters/index.js +1 -1
- package/dist/esm/providers/stt/adapters/index.js.map +3 -3
- package/dist/esm/providers/stt/adapters/openrouter/index.js +2 -0
- package/dist/esm/providers/stt/adapters/openrouter/index.js.map +7 -0
- package/dist/esm/providers/stt/adapters/openrouter/openrouter.js +2 -0
- package/dist/esm/providers/stt/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/esm/providers/tts/adapters/index.js +1 -1
- package/dist/esm/providers/tts/adapters/index.js.map +3 -3
- package/dist/esm/providers/tts/adapters/kokoro/kokoro.js +4 -1
- package/dist/esm/providers/tts/adapters/kokoro/kokoro.js.map +3 -3
- package/dist/esm/providers/tts/adapters/openrouter/index.js +2 -0
- package/dist/esm/providers/tts/adapters/openrouter/index.js.map +7 -0
- package/dist/esm/providers/tts/adapters/openrouter/openrouter.js +2 -0
- package/dist/esm/providers/tts/adapters/openrouter/openrouter.js.map +7 -0
- package/dist/esm/transport/streamobject/field-stream/field-stream.js +2 -0
- package/dist/esm/transport/streamobject/field-stream/field-stream.js.map +7 -0
- package/dist/esm/transport/streamobject/field-stream/index.js +2 -0
- package/dist/esm/transport/streamobject/field-stream/index.js.map +7 -0
- package/dist/esm/transport/streamobject/index.js +2 -0
- package/dist/esm/transport/streamobject/index.js.map +7 -0
- package/dist/esm/transport/streamobject/json-adapter/index.js +2 -0
- package/dist/esm/transport/streamobject/json-adapter/index.js.map +7 -0
- package/dist/esm/transport/streamobject/json-adapter/json-adapter.js +4 -0
- package/dist/esm/transport/streamobject/json-adapter/json-adapter.js.map +7 -0
- package/dist/esm/transport/streamobject/reference/index.js +2 -0
- package/dist/esm/transport/streamobject/reference/index.js.map +7 -0
- package/dist/esm/transport/streamobject/reference/reference.js +2 -0
- package/dist/esm/transport/streamobject/reference/reference.js.map +7 -0
- package/dist/esm/transport/streamobject/stream-object/index.js +2 -0
- package/dist/esm/transport/streamobject/stream-object/index.js.map +7 -0
- package/dist/esm/transport/streamobject/stream-object/stream-object.js +2 -0
- package/dist/esm/transport/streamobject/stream-object/stream-object.js.map +7 -0
- package/dist/types/agents/agent.d.ts +3 -0
- package/dist/types/agents/tools/tools.d.ts +28 -6
- package/dist/types/conversations/conversation/conversation.d.ts +85 -6
- package/dist/types/conversations/conversations.d.ts +11 -1
- package/dist/types/conversations/index.d.ts +2 -1
- package/dist/types/conversations/orchestration/coordination/coordination.d.ts +192 -0
- package/dist/types/conversations/orchestration/coordination/index.d.ts +2 -0
- package/dist/types/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.d.ts +108 -0
- package/dist/types/conversations/orchestration/orchestrator/coordination-runner/index.d.ts +2 -0
- package/dist/types/conversations/orchestration/orchestrator/generation/generation.d.ts +43 -0
- package/dist/types/conversations/orchestration/orchestrator/generation/index.d.ts +2 -0
- package/dist/types/conversations/orchestration/orchestrator/history/history.d.ts +62 -0
- package/dist/types/conversations/orchestration/orchestrator/history/index.d.ts +1 -0
- package/dist/types/conversations/orchestration/orchestrator/index.d.ts +10 -0
- package/dist/types/conversations/orchestration/orchestrator/orchestrator.d.ts +45 -27
- package/dist/types/conversations/orchestration/orchestrator/routing/index.d.ts +1 -0
- package/dist/types/conversations/orchestration/orchestrator/routing/routing.d.ts +19 -0
- package/dist/types/conversations/orchestration/orchestrator/speech/index.d.ts +2 -0
- package/dist/types/conversations/orchestration/orchestrator/speech/speech.d.ts +49 -0
- package/dist/types/conversations/orchestration/orchestrator/tools/index.d.ts +2 -0
- package/dist/types/conversations/orchestration/orchestrator/tools/tools.d.ts +31 -0
- package/dist/types/conversations/orchestration/test-harness.d.ts +96 -0
- package/dist/types/conversations/orchestration/text-chunker/index.d.ts +1 -0
- package/dist/types/conversations/orchestration/text-chunker/text-chunker.d.ts +39 -0
- package/dist/types/conversations/stream/conversation-stream.d.ts +42 -0
- package/dist/types/conversations/stream/index.d.ts +1 -0
- package/dist/types/conversations/types.d.ts +32 -0
- package/dist/types/index.d.ts +5 -38
- package/dist/types/pipeflow/index.d.ts +2 -0
- package/dist/types/pipeflow/pipeflow.d.ts +35 -0
- package/dist/types/providers/index.d.ts +1 -1
- package/dist/types/providers/llm/adapters/claude/claude.d.ts +45 -0
- package/dist/types/providers/llm/adapters/claude/index.d.ts +2 -0
- package/dist/types/providers/llm/adapters/deepseek/deepseek.d.ts +23 -2
- package/dist/types/providers/llm/adapters/index.d.ts +3 -0
- package/dist/types/providers/llm/adapters/openai/index.d.ts +2 -0
- package/dist/types/providers/llm/adapters/openai/openai.d.ts +45 -0
- package/dist/types/providers/llm/adapters/openai-compatible.d.ts +44 -0
- package/dist/types/providers/llm/adapters/openrouter/index.d.ts +2 -0
- package/dist/types/providers/llm/adapters/openrouter/openrouter.d.ts +60 -0
- package/dist/types/providers/llm/index.d.ts +5 -2
- package/dist/types/providers/llm/toolmode/index.d.ts +2 -0
- package/dist/types/providers/llm/toolmode/toolmode.d.ts +99 -0
- package/dist/types/providers/llm/types.d.ts +62 -0
- package/dist/types/providers/stt/adapters/deepgram/deepgram.d.ts +4 -1
- package/dist/types/providers/stt/adapters/index.d.ts +1 -0
- package/dist/types/providers/stt/adapters/openrouter/index.d.ts +2 -0
- package/dist/types/providers/stt/adapters/openrouter/openrouter.d.ts +94 -0
- package/dist/types/providers/tts/adapters/index.d.ts +1 -0
- package/dist/types/providers/tts/adapters/kokoro/kokoro.d.ts +17 -2
- package/dist/types/providers/tts/adapters/openrouter/index.d.ts +2 -0
- package/dist/types/providers/tts/adapters/openrouter/openrouter.d.ts +45 -0
- package/dist/types/transport/streamobject/field-stream/field-stream.d.ts +85 -0
- package/dist/types/transport/streamobject/field-stream/index.d.ts +2 -0
- package/dist/types/transport/streamobject/index.d.ts +8 -0
- package/dist/types/transport/streamobject/json-adapter/index.d.ts +2 -0
- package/dist/types/transport/streamobject/json-adapter/json-adapter.d.ts +65 -0
- package/dist/types/transport/streamobject/reference/index.d.ts +2 -0
- package/dist/types/transport/streamobject/reference/reference.d.ts +127 -0
- package/dist/types/transport/streamobject/stream-object/index.d.ts +2 -0
- package/dist/types/transport/streamobject/stream-object/stream-object.d.ts +31 -0
- package/package.json +23 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/agents/agent.ts"],
|
|
4
|
-
"sourcesContent": ["import { Tool } from \"./tools/tools\";\nimport type {\n LLM,\n LLMMessage,\n LLMToolCall,\n LLMToolDefinition,\n} from \"../providers/llm/types\";\n\nexport interface AgentOptions {\n name: string;\n context?: string;\n tools?: Tool<never, unknown>[];\n /** LLM provider used by `run()`. Injected by `Pipeflow.agent()`. */\n llm?: LLM;\n}\n\nexport interface AgentRunRequest {\n prompt: string;\n /** Prior messages to continue from, e.g. a previous `run()` result. */\n history?: LLMMessage[];\n temperature?: number;\n maxTokens?: number;\n /** Safety bound on the number of tool-call round trips. */\n maxToolIterations?: number;\n}\n\nexport interface ExecutedToolCall {\n id: string;\n name: string;\n /** Parsed arguments, or the raw JSON string if parsing failed. */\n arguments: unknown;\n /** The tool result, or `{ error }` when the tool failed or is unknown. */\n result: unknown;\n}\n\nexport interface AgentRunResult {\n /** The assistant's final text response. */\n text: string;\n /** The full message history including the response and tool results. */\n messages: LLMMessage[];\n /** Every tool call executed during the run, in order. */\n toolCalls: ExecutedToolCall[];\n}\n\n/**\n * An AI persona: a name, a system context, and a set of tools.\n *\n * An agent can participate in conversations or be invoked independently\n * with `run()`.\n */\nexport class Agent {\n readonly name: string;\n readonly context: string;\n private readonly toolRegistry = new Map<string, Tool<never, unknown>>();\n /** LLM provider used by `run()` and the orchestrator. */\n readonly llm: LLM | undefined;\n\n constructor(options: AgentOptions) {\n const name = options.name.trim();\n if (!name) {\n throw new Error(\"Agent requires a non-empty name\");\n }\n this.name = name;\n this.context = options.context?.trim() ?? \"\";\n this.llm = options.llm;\n for (const tool of options.tools ?? []) {\n this.addTool(tool);\n }\n }\n\n get tools(): Tool<never, unknown>[] {\n return [...this.toolRegistry.values()];\n }\n\n addTool(tool: Tool<never, unknown>): void {\n if (this.toolRegistry.has(tool.name)) {\n throw new Error(`Agent already has a tool named \"${tool.name}\"`);\n }\n this.toolRegistry.set(tool.name, tool);\n }\n\n hasTool(name: string): boolean {\n return this.toolRegistry.has(name);\n }\n\n getTool(name: string): Tool<never, unknown> | undefined {\n return this.toolRegistry.get(name);\n }\n\n /**\n * Run the agent against the LLM, executing any requested tools and\n * feeding their results back until the model responds without a tool\n * call.\n */\n async run(request: AgentRunRequest): Promise<AgentRunResult> {\n if (!this.llm) {\n throw new Error(\n `Agent \"${this.name}\" has no LLM provider configured. ` +\n \"Pass an LLM when constructing the agent or the Pipeflow instance.\",\n );\n }\n\n const messages: LLMMessage[] = [];\n if (this.context) {\n messages.push({ role: \"system\", content: this.context });\n }\n if (request.history) {\n messages.push(...request.history);\n }\n messages.push({ role: \"user\", content: request.prompt });\n\n const definitions: LLMToolDefinition[] = this.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters ?? { type: \"object\", properties: {} },\n }));\n\n const executed: ExecutedToolCall[] = [];\n const maxIterations = request.maxToolIterations ?? 10;\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n const { text, toolCalls } = await this.streamOnce({\n llm: this.llm,\n messages,\n definitions,\n temperature: request.temperature,\n maxTokens: request.maxTokens,\n });\n\n if (toolCalls.length === 0) {\n return { text, messages, toolCalls: executed };\n }\n\n messages.push({ role: \"assistant\", content: text, toolCalls });\n
|
|
5
|
-
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,WAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAqB,
|
|
6
|
-
"names": ["agent_exports", "__export", "Agent", "__toCommonJS", "import_tools", "Agent", "__name", "options", "name", "tool", "request", "messages", "definitions", "executed", "maxIterations", "iteration", "text", "toolCalls", "call", "executedCall", "llm", "temperature", "maxTokens", "event", "args", "result", "error"]
|
|
4
|
+
"sourcesContent": ["import { Tool } from \"./tools/tools\";\nimport type {\n LLM,\n LLMMessage,\n LLMToolCall,\n LLMToolDefinition,\n} from \"../providers/llm/types\";\n\nexport interface AgentOptions {\n name: string;\n /** Names a participant might use to address this agent. */\n aliases?: string[];\n context?: string;\n tools?: Tool<never, unknown>[];\n /** LLM provider used by `run()`. Injected by `Pipeflow.agent()`. */\n llm?: LLM;\n}\n\nexport interface AgentRunRequest {\n prompt: string;\n /** Prior messages to continue from, e.g. a previous `run()` result. */\n history?: LLMMessage[];\n temperature?: number;\n maxTokens?: number;\n /** Safety bound on the number of tool-call round trips. */\n maxToolIterations?: number;\n}\n\nexport interface ExecutedToolCall {\n id: string;\n name: string;\n /** Parsed arguments, or the raw JSON string if parsing failed. */\n arguments: unknown;\n /** The tool result, or `{ error }` when the tool failed or is unknown. */\n result: unknown;\n}\n\nexport interface AgentRunResult {\n /** The assistant's final text response. */\n text: string;\n /** The full message history including the response and tool results. */\n messages: LLMMessage[];\n /** Every tool call executed during the run, in order. */\n toolCalls: ExecutedToolCall[];\n}\n\n/**\n * An AI persona: a name, a system context, and a set of tools.\n *\n * An agent can participate in conversations or be invoked independently\n * with `run()`.\n */\nexport class Agent {\n readonly name: string;\n readonly aliases: string[];\n readonly context: string;\n private readonly toolRegistry = new Map<string, Tool<never, unknown>>();\n /** LLM provider used by `run()` and the orchestrator. */\n readonly llm: LLM | undefined;\n\n constructor(options: AgentOptions) {\n const name = options.name.trim();\n if (!name) {\n throw new Error(\"Agent requires a non-empty name\");\n }\n this.name = name;\n this.aliases = [...(options.aliases ?? [])];\n this.context = options.context?.trim() ?? \"\";\n this.llm = options.llm;\n for (const tool of options.tools ?? []) {\n this.addTool(tool);\n }\n }\n\n get tools(): Tool<never, unknown>[] {\n return [...this.toolRegistry.values()];\n }\n\n addTool(tool: Tool<never, unknown>): void {\n if (this.toolRegistry.has(tool.name)) {\n throw new Error(`Agent already has a tool named \"${tool.name}\"`);\n }\n this.toolRegistry.set(tool.name, tool);\n }\n\n hasTool(name: string): boolean {\n return this.toolRegistry.has(name);\n }\n\n getTool(name: string): Tool<never, unknown> | undefined {\n return this.toolRegistry.get(name);\n }\n\n /**\n * Run the agent against the LLM, executing any requested tools and\n * feeding their results back until the model responds without a tool\n * call.\n */\n async run(request: AgentRunRequest): Promise<AgentRunResult> {\n if (!this.llm) {\n throw new Error(\n `Agent \"${this.name}\" has no LLM provider configured. ` +\n \"Pass an LLM when constructing the agent or the Pipeflow instance.\",\n );\n }\n\n const messages: LLMMessage[] = [];\n if (this.context) {\n messages.push({ role: \"system\", content: this.context });\n }\n if (request.history) {\n messages.push(...request.history);\n }\n messages.push({ role: \"user\", content: request.prompt });\n\n const definitions: LLMToolDefinition[] = this.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters ?? { type: \"object\", properties: {} },\n }));\n\n const executed: ExecutedToolCall[] = [];\n const maxIterations = request.maxToolIterations ?? 10;\n\n for (let iteration = 0; iteration < maxIterations; iteration++) {\n const { text, toolCalls } = await this.streamOnce({\n llm: this.llm,\n messages,\n definitions,\n temperature: request.temperature,\n maxTokens: request.maxTokens,\n });\n\n if (toolCalls.length === 0) {\n return { text, messages, toolCalls: executed };\n }\n\n messages.push({ role: \"assistant\", content: text, toolCalls });\n // Execute the batch concurrently: the model issued these calls\n // together, so they are independent. Results keep call order.\n const executedBatch = await Promise.all(\n toolCalls.map((call) => this.executeToolCall(call)),\n );\n for (const executedCall of executedBatch) {\n executed.push(executedCall);\n messages.push({\n role: \"tool\",\n toolCallId: executedCall.id,\n name: executedCall.name,\n content: JSON.stringify(executedCall.result),\n });\n }\n }\n\n throw new Error(\n `Agent \"${this.name}\" exceeded ${maxIterations} tool iterations`,\n );\n }\n\n private async streamOnce(options: {\n llm: LLM;\n messages: LLMMessage[];\n definitions: LLMToolDefinition[];\n temperature?: number;\n maxTokens?: number;\n }): Promise<{ text: string; toolCalls: LLMToolCall[] }> {\n const { llm, messages, definitions, temperature, maxTokens } = options;\n let text = \"\";\n const toolCalls: LLMToolCall[] = [];\n\n for await (const event of llm.stream({\n messages,\n tools: definitions,\n temperature,\n maxTokens,\n })) {\n switch (event.type) {\n case \"delta\":\n text += event.content;\n break;\n case \"tool_call\":\n toolCalls.push({ id: event.id, name: event.name, arguments: event.arguments });\n break;\n case \"done\":\n return { text, toolCalls };\n case \"error\":\n throw event.error;\n }\n }\n\n return { text, toolCalls };\n }\n\n private async executeToolCall(call: LLMToolCall): Promise<ExecutedToolCall> {\n const tool = this.toolRegistry.get(call.name);\n\n let args: unknown;\n try {\n args = JSON.parse(call.arguments);\n } catch {\n args = call.arguments;\n }\n\n if (!tool) {\n return {\n id: call.id,\n name: call.name,\n arguments: args,\n result: { error: `Unknown tool \"${call.name}\"` },\n };\n }\n\n try {\n const result = await tool.execute(args as never);\n return { id: call.id, name: call.name, arguments: args, result };\n } catch (error) {\n return {\n id: call.id,\n name: call.name,\n arguments: args,\n result: { error: error instanceof Error ? error.message : String(error) },\n };\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,WAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAqB,yBAoDd,MAAMC,CAAM,CApDnB,MAoDmB,CAAAC,EAAA,cACR,KACA,QACA,QACQ,aAAe,IAAI,IAE3B,IAET,YAAYC,EAAuB,CACjC,MAAMC,EAAOD,EAAQ,KAAK,KAAK,EAC/B,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,iCAAiC,EAEnD,KAAK,KAAOA,EACZ,KAAK,QAAU,CAAC,GAAID,EAAQ,SAAW,CAAC,CAAE,EAC1C,KAAK,QAAUA,EAAQ,SAAS,KAAK,GAAK,GAC1C,KAAK,IAAMA,EAAQ,IACnB,UAAWE,KAAQF,EAAQ,OAAS,CAAC,EACnC,KAAK,QAAQE,CAAI,CAErB,CAEA,IAAI,OAAgC,CAClC,MAAO,CAAC,GAAG,KAAK,aAAa,OAAO,CAAC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Aa,EAC/C,MAAO,CAAE,GAAIN,EAAK,GAAI,KAAMA,EAAK,KAAM,UAAWM,EAAM,OAAAC,CAAO,CACjE,OAASC,EAAO,CACd,MAAO,CACL,GAAIR,EAAK,GACT,KAAMA,EAAK,KACX,UAAWM,EACX,OAAQ,CAAE,MAAOE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAE,CAC1E,CACF,CACF,CACF",
|
|
6
|
+
"names": ["agent_exports", "__export", "Agent", "__toCommonJS", "import_tools", "Agent", "__name", "options", "name", "tool", "request", "messages", "definitions", "executed", "maxIterations", "iteration", "text", "toolCalls", "executedBatch", "call", "executedCall", "llm", "temperature", "maxTokens", "event", "args", "result", "error"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var o=Object.defineProperty;var
|
|
1
|
+
"use strict";var o=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var u=(r,e)=>o(r,"name",{value:e,configurable:!0});var w=(r,e)=>{for(var n in e)o(r,n,{get:e[n],enumerable:!0})},f=(r,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of l(e))!p.call(r,t)&&t!==n&&o(r,t,{get:()=>e[t],enumerable:!(s=T(e,t))||s.enumerable});return r};var g=r=>f(o({},"__esModule",{value:!0}),r);var R={};w(R,{Tool:()=>O});module.exports=g(R);var c=require("zod");class O{static{u(this,"Tool")}name;description;parameters;parse;executor;constructor(e){const n=e.name.trim();if(!n)throw new Error("Tool requires a non-empty name");const s=e.description.trim();if(!s)throw new Error("Tool requires a non-empty description");if(e.schema!==void 0&&e.parameters!==void 0)throw new Error(`${n}: pass either schema or parameters, not both \u2014 schema derives the LLM schema`);if(this.name=n,this.description=s,e.schema!==void 0){const t=c.z.toJSONSchema(e.schema.in);delete t.$schema,this.parameters=t;const m=e.schema.out??e.schema.in;this.parse=d=>{const i=m.safeParse(d);if(!i.success){const h=i.error.issues.map(a=>a.path.length>0?`${a.path.join(".")}: ${a.message}`:a.message).join("; ");throw new Error(`${n}: invalid arguments: ${h}`)}return i.data}}else this.parameters=e.parameters,this.parse=void 0;this.executor=e.execute}async execute(e){const n=this.parse!==void 0?this.parse(e):e;return this.executor(n)}}
|
|
2
2
|
//# sourceMappingURL=tools.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/agents/tools/tools.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["tools_exports", "__export", "Tool", "__toCommonJS", "Tool", "__name", "options", "name", "description", "args"]
|
|
4
|
+
"sourcesContent": ["import { z } from \"zod\";\n\n/**\n * Zod schemas for a tool's arguments. `in` shapes what the model sends (and\n * derives the LLM-facing JSON schema); `out` is what `execute` receives after\n * validation. Keeping them separate means `in` stays plain JSON-schema-able\n * while `out` may transform, normalize, or narrow.\n */\nexport interface ToolSchema<TOut, TIn> {\n /** What the model sends \u2014 derives the LLM-facing JSON schema. */\n in: z.ZodType<TIn>;\n /** What `execute` receives, validated at run time. Defaults to `in`. */\n out?: z.ZodType<TOut>;\n}\n\nexport interface ToolOptions<TOut, TResult, TIn> {\n name: string;\n description: string;\n /**\n * Zod schemas for the tool arguments \u2014 the single source of truth: `in`\n * derives the LLM-facing JSON schema (`parameters`), and `out` (defaulting\n * to `in`) validates the arguments at `execute()` time, so a model sending\n * garbage surfaces a clear tool error instead of a crash inside the tool.\n * Mutually exclusive with `parameters`.\n */\n schema?: ToolSchema<TOut, TIn>;\n /** JSON schema describing the arguments for the LLM (no runtime validation). */\n parameters?: Record<string, unknown>;\n execute: (args: TOut) => TResult | Promise<TResult>;\n}\n\n/**\n * A capability exposed by the application to an agent.\n *\n * Tools execute in the application's backend: Pipeflow never runs\n * application code directly.\n */\nexport class Tool<TOut = Record<string, unknown>, TResult = unknown, TIn = TOut> {\n readonly name: string;\n readonly description: string;\n readonly parameters: Record<string, unknown> | undefined;\n // Widened to a generic-free parse function: holding `z.ZodType<...>` typed\n // against the class generics directly would make Tool invariant in its type\n // parameters and break the `Tool<{ city }, string>` \u2192 `Tool<never, unknown>`\n // assignability agents rely on.\n private readonly parse: ((args: unknown) => unknown) | undefined;\n private readonly executor: (args: TOut) => TResult | Promise<TResult>;\n\n constructor(options: ToolOptions<TOut, TResult, TIn>) {\n const name = options.name.trim();\n if (!name) {\n throw new Error(\"Tool requires a non-empty name\");\n }\n const description = options.description.trim();\n if (!description) {\n throw new Error(\"Tool requires a non-empty description\");\n }\n if (options.schema !== undefined && options.parameters !== undefined) {\n throw new Error(\n `${name}: pass either schema or parameters, not both \u2014 schema derives the LLM schema`,\n );\n }\n this.name = name;\n this.description = description;\n if (options.schema !== undefined) {\n // Single source of truth: the LLM sees exactly what execute validates.\n // `in` is always plain (transforms live on `out`), so this never throws.\n const jsonSchema = z.toJSONSchema(options.schema.in) as Record<string, unknown>;\n delete jsonSchema.$schema;\n this.parameters = jsonSchema;\n const schema = options.schema.out ?? options.schema.in;\n this.parse = (args: unknown): unknown => {\n const result = schema.safeParse(args as TIn);\n if (!result.success) {\n const details = result.error.issues\n .map((issue) =>\n issue.path.length > 0\n ? `${issue.path.join(\".\")}: ${issue.message}`\n : issue.message,\n )\n .join(\"; \");\n throw new Error(`${name}: invalid arguments: ${details}`);\n }\n return result.data;\n };\n } else {\n this.parameters = options.parameters;\n this.parse = undefined;\n }\n this.executor = options.execute;\n }\n\n /** Execute the tool. Sync throws and rejections both surface as rejections. */\n async execute(args: TIn): Promise<TResult> {\n const parsed = this.parse !== undefined ? this.parse(args) : args;\n return this.executor(parsed as TOut);\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB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", "description", "jsonSchema", "schema", "args", "result", "details", "issue", "parsed"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var d=Object.defineProperty;var l=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var c=(s,t)=>d(s,"name",{value:t,configurable:!0});var I=(s,t)=>{for(var e in t)d(s,e,{get:t[e],enumerable:!0})},f=(s,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of v(t))!m.call(s,n)&&n!==e&&d(s,n,{get:()=>t[n],enumerable:!(i=l(t,n))||i.enumerable});return s};var g=s=>f(d({},"__esModule",{value:!0}),s);var y={};I(y,{Conversation:()=>C});module.exports=g(y);var p=require("../orchestration/orchestrator/orchestrator.js"),h=require("../types.js"),u=require("../transcription/transcription.js");function a(s){return s.timing??={startedAt:s.startedAt}}c(a,"initTiming");const T={firstToken:"firstTokenAt",firstTtsText:"firstTtsTextAt",firstTtsRequest:"firstTtsRequestAt",firstTtsAudio:"firstTtsAudioAt"};class C{static{c(this,"Conversation")}id;agents;transcription;state;persistence;stt;tts;listeners=new Map;pendingToolCallsById=new Map;subGenerations=new Map;nextAudioSequence=0;constructor(t){this.id=t.id,this.agents=t.agents??[],this.persistence=t.persistence,this.stt=t.stt,this.tts=t.tts,this.transcription=new u.Transcription(this.id),this.state=(0,h.createConversationState)()}get status(){return this.state.status}get participants(){return[...this.state.participants.values()]}async start(){if(this.state.status==="stopped")throw new Error(`Conversation "${this.id}" has already been stopped`);if(this.state.status==="started")return;const t=this.buildRealtime();this.state.status="started",this.emit("start",{conversationId:this.id}),this.emitState(),await t?.start()}async stop(){if(this.state.status==="stopped")return;this.state.status="stopped",this.pendingToolCallsById.clear();const t=this.cancelCurrentGeneration();t&&await this.persistence?.appendGeneration(this.id,t);for(const e of[...this.subGenerations.values()])e.status==="streaming"&&(e.status="cancelled",e.endedAt=Date.now(),await this.persistence?.appendGeneration(this.id,e));await this.persistence?.finalizeConversation(this.id,Date.now()),this.emit("stop",{conversationId:this.id}),this.emitState()}async participate(t){if(this.state.status==="stopped")throw new Error(`Conversation "${this.id}" has already been stopped`);const e=Array.isArray(t)?t:[t],i=new Set;for(const r of e){if(i.has(r.userId))throw new Error(`Duplicate participant "${r.userId}" in batch`);if(i.add(r.userId),this.state.participants.has(r.userId))throw new Error(`Participant "${r.userId}" already exists`)}const n=[];for(const r of e){const o={userId:r.userId,aliases:[...r.aliases??[]],joinedAt:Date.now()};this.state.participants.set(o.userId,o),await this.persistence?.addParticipant(this.id,o),n.push(o),this.emit("participant",{conversationId:this.id,participant:o})}return this.emitState(),n}listen(t){if(this.state.status!=="started")throw new Error(`Conversation "${this.id}" is not started`);if(!this.state.participants.has(t.userId))throw new Error(`Unknown participant "${t.userId}"`);const e={data:t.audio,timestamp:Date.now(),sequence:this.nextAudioSequence++};this.emit("audio-in",{conversationId:this.id,userId:t.userId,audio:e})}send(t){if(this.state.status!=="started")throw new Error(`Conversation "${this.id}" is not started`);if(!this.state.participants.has(t.userId))throw new Error(`Unknown participant "${t.userId}"`);this.emit("text-in",{conversationId:this.id,userId:t.userId,text:t.text})}interrupt(){const t=this.cancelCurrentGeneration();t&&this.persistence?.appendGeneration(this.id,t).catch(()=>{}),this.emit("interrupt",{conversationId:this.id}),this.emitState()}on(t,e){let i=this.listeners.get(t);return i||(i=new Set,this.listeners.set(t,i)),i.add(e),()=>{i.delete(e)}}emit(t,e){const i=this.listeners.get(t);if(i)for(const n of[...i])n(e)}pushAudio(t){const e=this.state.currentGeneration;if(e&&e.status==="streaming"){const i=a(e);i.firstAudioAt===void 0&&(i.firstAudioAt=Date.now(),this.persistence?.appendGeneration(this.id,e).catch(()=>{}),this.emitState())}this.emit("audio",{conversationId:this.id,audio:t})}async pushTurn(t){this.state.currentTurn=t,this.emit("turn",{conversationId:this.id,turn:t}),await this.persistence?.appendTurn(this.id,t),this.emitState()}async pushTranscript(t){const e=this.transcription.append({...t});return this.state.transcriptCount++,this.emit("transcript",{conversationId:this.id,entry:e}),await this.persistence?.appendTranscript(this.id,e),this.emitState(),e}pushTextDelta(t){const e=this.state.currentGeneration?.agentName;this.emit("text-delta",{conversationId:this.id,text:t,agentName:e})}async pushGeneration(t){a(t),this.state.currentGeneration=t,this.emit("generation",{conversationId:this.id,generation:t}),await this.persistence?.appendGeneration(this.id,t),this.emitState()}noteTiming(t,e){const i=e?this.subGenerations.get(e):this.state.currentGeneration;if(!i||i.status!=="streaming")return;const n=a(i),r=T[t];n[r]===void 0&&(n[r]=Date.now(),this.persistence?.appendGeneration(this.id,i).catch(()=>{}),this.emitState())}get pendingToolCalls(){return[...this.pendingToolCallsById.values()]}requestToolCall(t){this.pendingToolCallsById.set(t.id,t),this.emit("tool-call",{conversationId:this.id,call:t}),this.emitState()}resolveToolCall(t){if(!this.pendingToolCallsById.has(t.id))throw new Error(`No pending tool call "${t.id}"`);this.pendingToolCallsById.delete(t.id),this.emit("tool-call-result",{conversationId:this.id,result:t}),this.emitState()}async completeGeneration(t){const e=this.state.currentGeneration;e&&e.status==="streaming"&&(t!==void 0&&(e.text=t),e.status="completed",e.endedAt=Date.now(),a(e).completedAt=Date.now(),await this.persistence?.appendGeneration(this.id,e),this.emitState(),this.emit("generation-complete",{conversationId:this.id,generation:e}))}async pushSubGeneration(t){a(t),this.subGenerations.set(t.id,t),this.emit("generation",{conversationId:this.id,generation:t}),await this.persistence?.appendGeneration(this.id,t),this.emitState()}async completeSubGeneration(t,e){const i=this.subGenerations.get(t);!i||i.status!=="streaming"||(e!==void 0&&(i.text=e),i.status="completed",i.endedAt=Date.now(),a(i).completedAt=Date.now(),await this.persistence?.appendGeneration(this.id,i),this.emitState())}async cancelSubGeneration(t){const e=this.subGenerations.get(t);!e||e.status!=="streaming"||(e.status="cancelled",e.endedAt=Date.now(),await this.persistence?.appendGeneration(this.id,e),this.emitState())}transcript(){return this.transcription.list()}cancelCurrentGeneration(){const t=this.state.currentGeneration;return t&&t.status==="streaming"&&(t.status="cancelled",t.endedAt=Date.now()),this.state.currentGeneration=null,t??null}buildRealtime(){if(!this.stt&&!this.agents.some(e=>e.llm))return null;const t={conversation:this,stt:this.stt,persistence:this.persistence};return this.agents.length>0?new p.Orchestrator({...t,agents:[...this.agents],tts:this.tts}):new p.Orchestrator(t)}emitState(){this.emit("state",{conversationId:this.id,state:this.state})}}
|
|
2
2
|
//# sourceMappingURL=conversation.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/conversations/conversation/conversation.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Agent } from \"../../agents/agent\";\nimport type { Persistence } from \"../../persistence/persistence\";\nimport type {\n AudioChunk,\n ConversationId,\n ConversationState,\n ConversationStatus,\n Generation,\n Participant,\n ParticipantInput,\n Turn,\n UserId,\n} from \"../types\";\nimport { createConversationState } from \"../types\";\nimport {\n Transcription,\n type TranscriptEntry,\n type TranscriptEntryInput,\n} from \"../transcription/transcription\";\nimport type { ToolCall, ToolCallResult } from \"../types\";\n\nexport interface ConversationOptions {\n id: ConversationId;\n agents?: Agent[];\n persistence?: Persistence;\n}\n\nexport interface ConversationEvents {\n start: { conversationId: ConversationId };\n stop: { conversationId: ConversationId };\n participant: { conversationId: ConversationId; participant: Participant };\n /** Raw audio fed in via `listen()`. Consumed by the orchestrator. */\n \"audio-in\": { conversationId: ConversationId; userId: UserId; audio: AudioChunk };\n /** Generated audio to be played by the application. */\n audio: { conversationId: ConversationId; audio: AudioChunk };\n turn: { conversationId: ConversationId; turn: Turn };\n transcript: { conversationId: ConversationId; entry: TranscriptEntry };\n generation: { conversationId: ConversationId; generation: Generation };\n /** Live STT partials, for captions and fast UX. Not persisted. */\n \"partial-transcript\": {\n conversationId: ConversationId;\n userId: UserId;\n text: string;\n };\n /** The model requested a tool call. Resolve it with `resolveToolCall()`. */\n \"tool-call\": { conversationId: ConversationId; call: ToolCall };\n /** A pending tool call was resolved by the application. */\n \"tool-call-result\": { conversationId: ConversationId; result: ToolCallResult };\n interrupt: { conversationId: ConversationId };\n /** A provider failure (STT, LLM, or TTS). */\n error: { conversationId: ConversationId; error: Error };\n state: { conversationId: ConversationId; state: ConversationState };\n}\n\n/**\n * The public realtime conversation API.\n *\n * A `Conversation` is a runtime handle to a persistent conversation:\n * lifecycle (`start`/`stop`), participants, audio intake (`listen`), and\n * events. The orchestrator (added later) subscribes to `audio-in` and\n * pushes generated audio, turns, transcripts, and tool calls back through\n * the `push*`/`requestToolCall` methods.\n */\nexport class Conversation {\n readonly id: ConversationId;\n readonly agents: readonly Agent[];\n readonly transcription: Transcription;\n readonly state: ConversationState;\n private readonly persistence: Persistence | undefined;\n private readonly listeners = new Map<\n keyof ConversationEvents,\n Set<(payload: never) => void>\n >();\n private readonly pendingToolCallsById = new Map<string, ToolCall>();\n private nextAudioSequence = 0;\n\n constructor(options: ConversationOptions) {\n this.id = options.id;\n this.agents = options.agents ?? [];\n this.persistence = options.persistence;\n this.transcription = new Transcription(this.id);\n this.state = createConversationState();\n }\n\n get status(): ConversationStatus {\n return this.state.status;\n }\n\n get participants(): Participant[] {\n return [...this.state.participants.values()];\n }\n\n start(): void {\n if (this.state.status === \"stopped\") {\n throw new Error(`Conversation \"${this.id}\" has already been stopped`);\n }\n if (this.state.status === \"started\") return;\n this.state.status = \"started\";\n this.emit(\"start\", { conversationId: this.id });\n this.emitState();\n }\n\n async stop(): Promise<void> {\n if (this.state.status === \"stopped\") return;\n this.state.status = \"stopped\";\n this.pendingToolCallsById.clear();\n const cancelled = this.cancelCurrentGeneration();\n if (cancelled) {\n await this.persistence?.appendGeneration(this.id, cancelled);\n }\n await this.persistence?.finalizeConversation(this.id, Date.now());\n this.emit(\"stop\", { conversationId: this.id });\n this.emitState();\n }\n\n async participate(\n input: ParticipantInput | ParticipantInput[],\n ): Promise<Participant[]> {\n if (this.state.status === \"stopped\") {\n throw new Error(`Conversation \"${this.id}\" has already been stopped`);\n }\n\n const inputs = Array.isArray(input) ? input : [input];\n\n // Validate the whole batch before mutating any state.\n const seen = new Set<UserId>();\n for (const item of inputs) {\n if (seen.has(item.userId)) {\n throw new Error(`Duplicate participant \"${item.userId}\" in batch`);\n }\n seen.add(item.userId);\n if (this.state.participants.has(item.userId)) {\n throw new Error(`Participant \"${item.userId}\" already exists`);\n }\n }\n\n const added: Participant[] = [];\n for (const item of inputs) {\n const participant: Participant = {\n userId: item.userId,\n aliases: [...(item.aliases ?? [])],\n joinedAt: Date.now(),\n };\n this.state.participants.set(participant.userId, participant);\n await this.persistence?.addParticipant(this.id, participant);\n added.push(participant);\n this.emit(\"participant\", { conversationId: this.id, participant });\n }\n this.emitState();\n return added;\n }\n\n /**\n * Send an audio packet. Intentionally synchronous: it means \"send this\n * packet\", not \"wait for this utterance to finish\".\n */\n listen(input: { userId: UserId; audio: Uint8Array }): void {\n if (this.state.status !== \"started\") {\n throw new Error(`Conversation \"${this.id}\" is not started`);\n }\n if (!this.state.participants.has(input.userId)) {\n throw new Error(`Unknown participant \"${input.userId}\"`);\n }\n const chunk: AudioChunk = {\n data: input.audio,\n timestamp: Date.now(),\n sequence: this.nextAudioSequence++,\n };\n this.emit(\"audio-in\", { conversationId: this.id, userId: input.userId, audio: chunk });\n }\n\n /** Interrupt the current agent output (stop TTS, cancel the generation). */\n interrupt(): void {\n const cancelled = this.cancelCurrentGeneration();\n // Persist asynchronously: interruption must stay synchronous for the\n // realtime path.\n if (cancelled) {\n void this.persistence?.appendGeneration(this.id, cancelled).catch(() => {});\n }\n this.emit(\"interrupt\", { conversationId: this.id });\n this.emitState();\n }\n\n on<K extends keyof ConversationEvents>(\n event: K,\n listener: (payload: ConversationEvents[K]) => void,\n ): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener as (payload: never) => void);\n return () => {\n set!.delete(listener as (payload: never) => void);\n };\n }\n\n /**\n * Emit an event. Primarily used by the orchestrator to push output\n * (audio, turns, transcripts) into the conversation.\n */\n emit<K extends keyof ConversationEvents>(\n event: K,\n payload: ConversationEvents[K],\n ): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n listener(payload as never);\n }\n }\n\n // -------------------------------------------------------------------------\n // Orchestrator-facing output\n // -------------------------------------------------------------------------\n\n /** Push a chunk of generated audio to the application. */\n pushAudio(audio: AudioChunk): void {\n this.emit(\"audio\", { conversationId: this.id, audio });\n }\n\n /** Push a completed participant turn into the conversation. */\n async pushTurn(turn: Turn): Promise<void> {\n this.state.currentTurn = turn;\n this.emit(\"turn\", { conversationId: this.id, turn });\n await this.persistence?.appendTurn(this.id, turn);\n this.emitState();\n }\n\n /** Append a transcript entry and notify listeners. */\n async pushTranscript(\n input: Omit<TranscriptEntryInput, \"conversationId\">,\n ): Promise<TranscriptEntry> {\n const entry = this.transcription.append({ ...input });\n this.state.transcriptCount++;\n this.emit(\"transcript\", { conversationId: this.id, entry });\n await this.persistence?.appendTranscript(this.id, entry);\n this.emitState();\n return entry;\n }\n\n /** Push an agent generation into the conversation. */\n async pushGeneration(generation: Generation): Promise<void> {\n this.state.currentGeneration = generation;\n this.emit(\"generation\", { conversationId: this.id, generation });\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n\n // -------------------------------------------------------------------------\n // Orchestrator-facing tool calls\n // -------------------------------------------------------------------------\n\n /** Tool calls requested by the model that are awaiting resolution. */\n get pendingToolCalls(): ToolCall[] {\n return [...this.pendingToolCallsById.values()];\n }\n\n /**\n * Track and emit a tool call requested by the model. The application\n * listens for `tool-call` events, executes the tool in its own backend,\n * and reports back through `resolveToolCall()`.\n */\n requestToolCall(call: ToolCall): void {\n this.pendingToolCallsById.set(call.id, call);\n this.emit(\"tool-call\", { conversationId: this.id, call });\n this.emitState();\n }\n\n /** Resolve a pending tool call with a result or an error. */\n resolveToolCall(result: ToolCallResult): void {\n if (!this.pendingToolCallsById.has(result.id)) {\n throw new Error(`No pending tool call \"${result.id}\"`);\n }\n this.pendingToolCallsById.delete(result.id);\n this.emit(\"tool-call-result\", { conversationId: this.id, result });\n this.emitState();\n }\n\n /** Mark the current generation as completed, recording its final text. */\n async completeGeneration(text?: string): Promise<void> {\n const generation = this.state.currentGeneration;\n if (generation && generation.status === \"streaming\") {\n if (text !== undefined) generation.text = text;\n generation.status = \"completed\";\n generation.endedAt = Date.now();\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n }\n\n /** The live in-memory transcript. */\n transcript(): TranscriptEntry[] {\n return this.transcription.list();\n }\n\n private cancelCurrentGeneration(): Generation | null {\n const generation = this.state.currentGeneration;\n if (generation && generation.status === \"streaming\") {\n generation.status = \"cancelled\";\n generation.endedAt = Date.now();\n }\n this.state.currentGeneration = null;\n return generation ?? null;\n }\n\n private emitState(): void {\n this.emit(\"state\", { conversationId: this.id, state: this.state });\n }\n}\n"],
|
|
5
|
-
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["conversation_exports", "__export", "Conversation", "__toCommonJS", "import_types", "import_transcription", "
|
|
4
|
+
"sourcesContent": ["import type { Agent } from \"../../agents/agent\";\nimport type { Persistence } from \"../../persistence/persistence\";\nimport { Orchestrator } from \"../orchestration/orchestrator/orchestrator\";\nimport type { STT } from \"../../providers/stt/types\";\nimport type { TTS } from \"../../providers/tts/types\";\nimport type {\n AudioChunk,\n ConversationId,\n ConversationState,\n ConversationStatus,\n Generation,\n GenerationTiming,\n Participant,\n ParticipantInput,\n Turn,\n UserId,\n} from \"../types\";\nimport { createConversationState } from \"../types\";\nimport {\n Transcription,\n type TranscriptEntry,\n type TranscriptEntryInput,\n} from \"../transcription/transcription\";\nimport type { ToolCall, ToolCallResult } from \"../types\";\n\n/** Ensure a generation carries a timing record, initialized from its start. */\nfunction initTiming(generation: Generation): GenerationTiming {\n return (generation.timing ??= { startedAt: generation.startedAt });\n}\n\n/** Timing points a generation can record, keyed by the stream event. */\ntype TimingPoint = \"firstToken\" | \"firstTtsText\" | \"firstTtsRequest\" | \"firstTtsAudio\";\n\nconst timingField: Record<TimingPoint, keyof GenerationTiming> = {\n firstToken: \"firstTokenAt\",\n firstTtsText: \"firstTtsTextAt\",\n firstTtsRequest: \"firstTtsRequestAt\",\n firstTtsAudio: \"firstTtsAudioAt\",\n};\n\nexport interface ConversationOptions {\n id: ConversationId;\n agents?: Agent[];\n persistence?: Persistence;\n /**\n * STT provider used to attach realtime processing automatically on\n * `start()`.\n */\n stt?: STT;\n tts?: TTS;\n}\n\nexport interface ConversationEvents {\n start: { conversationId: ConversationId };\n stop: { conversationId: ConversationId };\n participant: { conversationId: ConversationId; participant: Participant };\n /** Raw audio fed in via `listen()`. Consumed by the orchestrator. */\n \"audio-in\": { conversationId: ConversationId; userId: UserId; audio: AudioChunk };\n /** A finalized text turn via `send()`. Consumed by the orchestrator. */\n \"text-in\": { conversationId: ConversationId; userId: UserId; text: string };\n /** Generated audio to be played by the application. */\n audio: { conversationId: ConversationId; audio: AudioChunk };\n turn: { conversationId: ConversationId; turn: Turn };\n transcript: { conversationId: ConversationId; entry: TranscriptEntry };\n generation: { conversationId: ConversationId; generation: Generation };\n /**\n * The current generation's text, streamed as LLM deltas arrive. Emitted by\n * the orchestrator; the agent name is included when the generation is known.\n */\n \"text-delta\": {\n conversationId: ConversationId;\n text: string;\n agentName?: string;\n };\n /** The current (top-level) generation finished generating. */\n \"generation-complete\": {\n conversationId: ConversationId;\n generation: Generation;\n };\n /** Live STT partials, for captions and fast UX. Not persisted. */\n \"partial-transcript\": {\n conversationId: ConversationId;\n userId: UserId;\n text: string;\n };\n /** The model requested a tool call. Resolve it with `resolveToolCall()`. */\n \"tool-call\": { conversationId: ConversationId; call: ToolCall };\n /** A pending tool call was resolved by the application. */\n \"tool-call-result\": { conversationId: ConversationId; result: ToolCallResult };\n interrupt: { conversationId: ConversationId };\n /** A provider failure (STT, LLM, or TTS). */\n error: { conversationId: ConversationId; error: Error };\n state: { conversationId: ConversationId; state: ConversationState };\n}\n\n/**\n * The public realtime conversation API.\n *\n * A `Conversation` is a runtime handle to a persistent conversation:\n * lifecycle (`start`/`stop`), participants, audio intake (`listen`), text\n * turns (`send`), and events. When an STT provider or agents are configured,\n * `start()` automatically attaches the orchestrator, which runs the\n * STT/LLM/TTS pipeline (or routes text turns) and pushes generated audio,\n * turns, transcripts, and tool calls back through conversation events.\n */\nexport class Conversation {\n readonly id: ConversationId;\n readonly agents: readonly Agent[];\n readonly transcription: Transcription;\n readonly state: ConversationState;\n private readonly persistence: Persistence | undefined;\n private readonly stt: STT | undefined;\n private readonly tts: TTS | undefined;\n private readonly listeners = new Map<\n keyof ConversationEvents,\n Set<(payload: never) => void>\n >();\n private readonly pendingToolCallsById = new Map<string, ToolCall>();\n private readonly subGenerations = new Map<string, Generation>();\n private nextAudioSequence = 0;\n\n constructor(options: ConversationOptions) {\n this.id = options.id;\n this.agents = options.agents ?? [];\n this.persistence = options.persistence;\n this.stt = options.stt;\n this.tts = options.tts;\n this.transcription = new Transcription(this.id);\n this.state = createConversationState();\n }\n\n get status(): ConversationStatus {\n return this.state.status;\n }\n\n get participants(): Participant[] {\n return [...this.state.participants.values()];\n }\n\n /**\n * Move the conversation into the started state. This attaches the\n * orchestrator whenever there is realtime work: an STT provider (voice\n * pipeline) or agents to route text turns to (`send()`).\n */\n async start(): Promise<void> {\n if (this.state.status === \"stopped\") {\n throw new Error(`Conversation \"${this.id}\" has already been stopped`);\n }\n if (this.state.status === \"started\") return;\n\n // Validate the realtime configuration before mutating any state.\n const orchestrator = this.buildRealtime();\n\n this.state.status = \"started\";\n this.emit(\"start\", { conversationId: this.id });\n this.emitState();\n\n await orchestrator?.start();\n }\n\n async stop(): Promise<void> {\n if (this.state.status === \"stopped\") return;\n this.state.status = \"stopped\";\n this.pendingToolCallsById.clear();\n const cancelled = this.cancelCurrentGeneration();\n if (cancelled) {\n await this.persistence?.appendGeneration(this.id, cancelled);\n }\n for (const sub of [...this.subGenerations.values()]) {\n if (sub.status === \"streaming\") {\n sub.status = \"cancelled\";\n sub.endedAt = Date.now();\n await this.persistence?.appendGeneration(this.id, sub);\n }\n }\n await this.persistence?.finalizeConversation(this.id, Date.now());\n this.emit(\"stop\", { conversationId: this.id });\n this.emitState();\n }\n\n async participate(\n input: ParticipantInput | ParticipantInput[],\n ): Promise<Participant[]> {\n if (this.state.status === \"stopped\") {\n throw new Error(`Conversation \"${this.id}\" has already been stopped`);\n }\n\n const inputs = Array.isArray(input) ? input : [input];\n\n // Validate the whole batch before mutating any state.\n const seen = new Set<UserId>();\n for (const item of inputs) {\n if (seen.has(item.userId)) {\n throw new Error(`Duplicate participant \"${item.userId}\" in batch`);\n }\n seen.add(item.userId);\n if (this.state.participants.has(item.userId)) {\n throw new Error(`Participant \"${item.userId}\" already exists`);\n }\n }\n\n const added: Participant[] = [];\n for (const item of inputs) {\n const participant: Participant = {\n userId: item.userId,\n aliases: [...(item.aliases ?? [])],\n joinedAt: Date.now(),\n };\n this.state.participants.set(participant.userId, participant);\n await this.persistence?.addParticipant(this.id, participant);\n added.push(participant);\n this.emit(\"participant\", { conversationId: this.id, participant });\n }\n this.emitState();\n return added;\n }\n\n /**\n * Send an audio packet. Intentionally synchronous: it means \"send this\n * packet\", not \"wait for this utterance to finish\".\n */\n listen(input: { userId: UserId; audio: Uint8Array }): void {\n if (this.state.status !== \"started\") {\n throw new Error(`Conversation \"${this.id}\" is not started`);\n }\n if (!this.state.participants.has(input.userId)) {\n throw new Error(`Unknown participant \"${input.userId}\"`);\n }\n const chunk: AudioChunk = {\n data: input.audio,\n timestamp: Date.now(),\n sequence: this.nextAudioSequence++,\n };\n this.emit(\"audio-in\", { conversationId: this.id, userId: input.userId, audio: chunk });\n }\n\n /**\n * Send a finalized text turn, bypassing STT. Triggers the same pipeline as\n * a transcribed utterance (routing, coordination, generation, resume) \u2014\n * useful for text-first integrations such as chat or Discord text channels.\n */\n send(input: { userId: UserId; text: string }): void {\n if (this.state.status !== \"started\") {\n throw new Error(`Conversation \"${this.id}\" is not started`);\n }\n if (!this.state.participants.has(input.userId)) {\n throw new Error(`Unknown participant \"${input.userId}\"`);\n }\n this.emit(\"text-in\", {\n conversationId: this.id,\n userId: input.userId,\n text: input.text,\n });\n }\n\n /**\n * Stop the currently active generation and prevent any further generated\n * audio from reaching the conversation. The orchestrator cancels the LLM\n * and TTS streams, force-resolves pending tool calls, and discards queued\n * audio; the next participant turn starts fresh. Interrupt responsiveness\n * is a tested invariant \u2014 audio stops within ~100ms of this call.\n */\n interrupt(): void {\n const cancelled = this.cancelCurrentGeneration();\n // Persist asynchronously: interruption must stay synchronous for the\n // realtime path.\n if (cancelled) {\n void this.persistence?.appendGeneration(this.id, cancelled).catch(() => {});\n }\n this.emit(\"interrupt\", { conversationId: this.id });\n this.emitState();\n }\n\n on<K extends keyof ConversationEvents>(\n event: K,\n listener: (payload: ConversationEvents[K]) => void,\n ): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener as (payload: never) => void);\n return () => {\n set!.delete(listener as (payload: never) => void);\n };\n }\n\n /**\n * Emit an event. Primarily used by the orchestrator to push output\n * (audio, turns, transcripts) into the conversation.\n */\n emit<K extends keyof ConversationEvents>(\n event: K,\n payload: ConversationEvents[K],\n ): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n listener(payload as never);\n }\n }\n\n // -------------------------------------------------------------------------\n // Orchestrator-facing output\n // -------------------------------------------------------------------------\n\n /** Push a chunk of generated audio to the application. */\n pushAudio(audio: AudioChunk): void {\n // Record when the first synthesized chunk reached the application for the\n // in-flight generation (speech-to-delivery latency).\n const generation = this.state.currentGeneration;\n if (generation && generation.status === \"streaming\") {\n const timing = initTiming(generation);\n if (timing.firstAudioAt === undefined) {\n timing.firstAudioAt = Date.now();\n void this.persistence?.appendGeneration(this.id, generation).catch(() => {});\n this.emitState();\n }\n }\n this.emit(\"audio\", { conversationId: this.id, audio });\n }\n\n /** Push a completed participant turn into the conversation. */\n async pushTurn(turn: Turn): Promise<void> {\n this.state.currentTurn = turn;\n this.emit(\"turn\", { conversationId: this.id, turn });\n await this.persistence?.appendTurn(this.id, turn);\n this.emitState();\n }\n\n /** Append a transcript entry and notify listeners. */\n async pushTranscript(\n input: Omit<TranscriptEntryInput, \"conversationId\">,\n ): Promise<TranscriptEntry> {\n const entry = this.transcription.append({ ...input });\n this.state.transcriptCount++;\n this.emit(\"transcript\", { conversationId: this.id, entry });\n await this.persistence?.appendTranscript(this.id, entry);\n this.emitState();\n return entry;\n }\n\n /**\n * Stream the current generation's text, as produced by the orchestrator\n * from LLM deltas. Emits the `text-delta` event so applications can render\n * or act on partial replies.\n */\n pushTextDelta(text: string): void {\n const agentName = this.state.currentGeneration?.agentName;\n this.emit(\"text-delta\", { conversationId: this.id, text, agentName });\n }\n\n /** Push an agent generation into the conversation. */\n async pushGeneration(generation: Generation): Promise<void> {\n initTiming(generation);\n this.state.currentGeneration = generation;\n this.emit(\"generation\", { conversationId: this.id, generation });\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n\n /**\n * Record a timing point on a generation. Without an id this targets the\n * current generation; with one, a dispatched sub-generation. Each point is\n * recorded at most once.\n */\n noteTiming(point: TimingPoint, generationId?: string): void {\n const generation = generationId\n ? this.subGenerations.get(generationId)\n : this.state.currentGeneration;\n if (!generation || generation.status !== \"streaming\") return;\n const timing = initTiming(generation);\n const field = timingField[point];\n if (timing[field] !== undefined) return;\n timing[field] = Date.now();\n void this.persistence?.appendGeneration(this.id, generation).catch(() => {});\n this.emitState();\n }\n\n // -------------------------------------------------------------------------\n // Orchestrator-facing tool calls\n // -------------------------------------------------------------------------\n\n /** Tool calls requested by the model that are awaiting resolution. */\n get pendingToolCalls(): ToolCall[] {\n return [...this.pendingToolCallsById.values()];\n }\n\n /**\n * Track and emit a tool call requested by the model. The application\n * listens for `tool-call` events, executes the tool in its own backend,\n * and reports back through `resolveToolCall()`.\n */\n requestToolCall(call: ToolCall): void {\n this.pendingToolCallsById.set(call.id, call);\n this.emit(\"tool-call\", { conversationId: this.id, call });\n this.emitState();\n }\n\n /** Resolve a pending tool call with a result or an error. */\n resolveToolCall(result: ToolCallResult): void {\n if (!this.pendingToolCallsById.has(result.id)) {\n throw new Error(`No pending tool call \"${result.id}\"`);\n }\n this.pendingToolCallsById.delete(result.id);\n this.emit(\"tool-call-result\", { conversationId: this.id, result });\n this.emitState();\n }\n\n /** Mark the current generation as completed, recording its final text. */\n async completeGeneration(text?: string): Promise<void> {\n const generation = this.state.currentGeneration;\n if (generation && generation.status === \"streaming\") {\n if (text !== undefined) generation.text = text;\n generation.status = \"completed\";\n generation.endedAt = Date.now();\n initTiming(generation).completedAt = Date.now();\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n this.emit(\"generation-complete\", { conversationId: this.id, generation });\n }\n }\n\n // -------------------------------------------------------------------------\n // Dispatched sub-generations\n // -------------------------------------------------------------------------\n\n /**\n * Push a sub-generation: a task the coordinator dispatched to another\n * agent. Unlike `pushGeneration`, it does not become the conversation's\n * current generation, so parallel tasks don't clobber the coordinator's\n * own in-flight generation.\n */\n async pushSubGeneration(generation: Generation): Promise<void> {\n initTiming(generation);\n this.subGenerations.set(generation.id, generation);\n this.emit(\"generation\", { conversationId: this.id, generation });\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n\n /** Mark a dispatched sub-generation as completed with its final text. */\n async completeSubGeneration(id: string, text?: string): Promise<void> {\n const generation = this.subGenerations.get(id);\n if (!generation || generation.status !== \"streaming\") return;\n if (text !== undefined) generation.text = text;\n generation.status = \"completed\";\n generation.endedAt = Date.now();\n initTiming(generation).completedAt = Date.now();\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n\n /** Mark a dispatched sub-generation as cancelled (e.g. barge-in). */\n async cancelSubGeneration(id: string): Promise<void> {\n const generation = this.subGenerations.get(id);\n if (!generation || generation.status !== \"streaming\") return;\n generation.status = \"cancelled\";\n generation.endedAt = Date.now();\n await this.persistence?.appendGeneration(this.id, generation);\n this.emitState();\n }\n\n /** The live in-memory transcript. */\n transcript(): TranscriptEntry[] {\n return this.transcription.list();\n }\n\n private cancelCurrentGeneration(): Generation | null {\n const generation = this.state.currentGeneration;\n if (generation && generation.status === \"streaming\") {\n generation.status = \"cancelled\";\n generation.endedAt = Date.now();\n }\n this.state.currentGeneration = null;\n return generation ?? null;\n }\n\n private buildRealtime(): Orchestrator | null {\n // Attach the orchestrator whenever there is realtime work: an STT\n // provider for voice, or agents with an LLM to route text turns to\n // (`send()`). Agents without an LLM have nothing to generate.\n if (!this.stt && !this.agents.some((agent) => agent.llm)) return null;\n const common = {\n conversation: this,\n stt: this.stt,\n persistence: this.persistence,\n };\n // With agents the orchestrator coordinates the roster, routing each turn\n // to an agent by name/alias. Without agents it runs transcription-only.\n return this.agents.length > 0\n ? new Orchestrator({ ...common, agents: [...this.agents], tts: this.tts })\n : new Orchestrator(common);\n }\n\n private emitState(): void {\n this.emit(\"state\", { conversationId: this.id, state: this.state });\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAEA,IAAAI,EAA6B,sDAe7BC,EAAwC,oBACxCC,EAIO,0CAIP,SAASC,EAAWC,EAA0C,CAC5D,OAAQA,EAAW,SAAW,CAAE,UAAWA,EAAW,SAAU,CAClE,CAFSC,EAAAF,EAAA,cAOT,MAAMG,EAA2D,CAC/D,WAAY,eACZ,aAAc,iBACd,gBAAiB,oBACjB,cAAe,iBACjB,EAmEO,MAAMC,CAAa,CAzG1B,MAyG0B,CAAAF,EAAA,qBACf,GACA,OACA,cACA,MACQ,YACA,IACA,IACA,UAAY,IAAI,IAIhB,qBAAuB,IAAI,IAC3B,eAAiB,IAAI,IAC9B,kBAAoB,EAE5B,YAAYG,EAA8B,CACxC,KAAK,GAAKA,EAAQ,GAClB,KAAK,OAASA,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AAU,KAAK,IAAI,EAC9BD,EAAWC,CAAU,EAAE,YAAc,KAAK,IAAI,EAC9C,MAAM,KAAK,aAAa,iBAAiB,KAAK,GAAIA,CAAU,EAC5D,KAAK,UAAU,EACjB,CAGA,MAAM,oBAAoB8B,EAA2B,CACnD,MAAM9B,EAAa,KAAK,eAAe,IAAI8B,CAAE,EACzC,CAAC9B,GAAcA,EAAW,SAAW,cACzCA,EAAW,OAAS,YACpBA,EAAW,QAAU,KAAK,IAAI,EAC9B,MAAM,KAAK,aAAa,iBAAiB,KAAK,GAAIA,CAAU,EAC5D,KAAK,UAAU,EACjB,CAGA,YAAgC,CAC9B,OAAO,KAAK,cAAc,KAAK,CACjC,CAEQ,yBAA6C,CACnD,MAAMA,EAAa,KAAK,MAAM,kBAC9B,OAAIA,GAAcA,EAAW,SAAW,cACtCA,EAAW,OAAS,YACpBA,EAAW,QAAU,KAAK,IAAI,GAEhC,KAAK,MAAM,kBAAoB,KACxBA,GAAc,IACvB,CAEQ,eAAqC,CAI3C,GAAI,CAAC,KAAK,KAAO,CAAC,KAAK,OAAO,KAAM+B,GAAUA,EAAM,GAAG,EAAG,OAAO,KACjE,MAAMC,EAAS,CACb,aAAc,KACd,IAAK,KAAK,IACV,YAAa,KAAK,WACpB,EAGA,OAAO,KAAK,OAAO,OAAS,EACxB,IAAI,eAAa,CAAE,GAAGA,EAAQ,OAAQ,CAAC,GAAG,KAAK,MAAM,EAAG,IAAK,KAAK,GAAI,CAAC,EACvE,IAAI,eAAaA,CAAM,CAC7B,CAEQ,WAAkB,CACxB,KAAK,KAAK,QAAS,CAAE,eAAgB,KAAK,GAAI,MAAO,KAAK,KAAM,CAAC,CACnE,CACF",
|
|
6
|
+
"names": ["conversation_exports", "__export", "Conversation", "__toCommonJS", "import_orchestrator", "import_types", "import_transcription", "initTiming", "generation", "__name", "timingField", "Conversation", "options", "orchestrator", "cancelled", "sub", "input", "inputs", "seen", "item", "added", "participant", "chunk", "event", "listener", "set", "payload", "audio", "timing", "turn", "entry", "text", "agentName", "point", "generationId", "field", "call", "result", "id", "agent", "common"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var i=Object.defineProperty;var
|
|
1
|
+
"use strict";var i=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var a=(e,t)=>i(e,"name",{value:t,configurable:!0});var d=(e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})},m=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of c(t))!v.call(e,r)&&r!==s&&i(e,r,{get:()=>t[r],enumerable:!(n=p(t,r))||n.enumerable});return e};var C=e=>m(i({},"__esModule",{value:!0}),e);var T={};d(T,{Conversations:()=>y});module.exports=C(T);var o=require("./conversation/conversation.js");class y{static{a(this,"Conversations")}persistence;stt;tts;constructor(t){this.persistence=t.persistence,this.stt=t.stt,this.tts=t.tts}async create(t={}){const s=await this.persistence.createConversation({agentNames:(t.agents??[]).map(n=>n.name)});return new o.Conversation({id:s.id,agents:t.agents,persistence:this.persistence,stt:this.stt,tts:this.tts})}async transcript(t){return await this.requireConversation(t),this.persistence.listTranscript(t)}async get(t){const s=await this.persistence.getConversation(t);return s?new o.Conversation({id:s.id,persistence:this.persistence}):null}async requireConversation(t){if(!await this.persistence.getConversation(t))throw new Error(`Conversation "${t}" not found`)}}
|
|
2
2
|
//# sourceMappingURL=conversations.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/conversations/conversations.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Agent } from \"../agents/agent\";\nimport type { Persistence } from \"../persistence/persistence\";\nimport type { ConversationId } from \"./types\";\nimport type { TranscriptEntry } from \"./transcription/transcription\";\nimport { Conversation } from \"./conversation/conversation\";\n\nexport interface CreateConversationOptions {\n agents?: Agent[];\n}\n\n/**\n * The conversations API surface of a Pipeflow instance: create persistent\n * conversations and retrieve their transcripts.\n */\nexport class Conversations {\n
|
|
5
|
-
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["conversations_exports", "__export", "Conversations", "__toCommonJS", "import_conversation", "Conversations", "
|
|
4
|
+
"sourcesContent": ["import type { Agent } from \"../agents/agent\";\nimport type { Persistence } from \"../persistence/persistence\";\nimport type { STT } from \"../providers/stt/types\";\nimport type { TTS } from \"../providers/tts/types\";\nimport type { ConversationId } from \"./types\";\nimport type { TranscriptEntry } from \"./transcription/transcription\";\nimport { Conversation } from \"./conversation/conversation\";\n\nexport interface CreateConversationOptions {\n agents?: Agent[];\n}\n\nexport interface ConversationsOptions {\n persistence: Persistence;\n /** Passed to conversations so `start()` can attach realtime processing. */\n stt?: STT;\n tts?: TTS;\n}\n\n/**\n * The conversations API surface of a Pipeflow instance: create persistent\n * conversations and retrieve their transcripts.\n */\nexport class Conversations {\n private readonly persistence: Persistence;\n private readonly stt: STT | undefined;\n private readonly tts: TTS | undefined;\n\n constructor(options: ConversationsOptions) {\n this.persistence = options.persistence;\n this.stt = options.stt;\n this.tts = options.tts;\n }\n\n /** Create a persistent conversation. Realtime execution is separate. */\n async create(options: CreateConversationOptions = {}): Promise<Conversation> {\n const record = await this.persistence.createConversation({\n agentNames: (options.agents ?? []).map((agent) => agent.name),\n });\n return new Conversation({\n id: record.id,\n agents: options.agents,\n persistence: this.persistence,\n stt: this.stt,\n tts: this.tts,\n });\n }\n\n /** Retrieve the persisted transcript of a conversation. */\n async transcript(id: ConversationId): Promise<TranscriptEntry[]> {\n await this.requireConversation(id);\n return this.persistence.listTranscript(id);\n }\n\n /** Rehydrate a runtime handle for an existing conversation. */\n async get(id: ConversationId): Promise<Conversation | null> {\n const record = await this.persistence.getConversation(id);\n if (!record) return null;\n return new Conversation({ id: record.id, persistence: this.persistence });\n }\n\n private async requireConversation(id: ConversationId): Promise<void> {\n const record = await this.persistence.getConversation(id);\n if (!record) {\n throw new Error(`Conversation \"${id}\" not found`);\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GAMA,IAAAI,EAA6B,uCAiBtB,MAAMC,CAAc,CAvB3B,MAuB2B,CAAAC,EAAA,sBACR,YACA,IACA,IAEjB,YAAYC,EAA+B,CACzC,KAAK,YAAcA,EAAQ,YAC3B,KAAK,IAAMA,EAAQ,IACnB,KAAK,IAAMA,EAAQ,GACrB,CAGA,MAAM,OAAOA,EAAqC,CAAC,EAA0B,CAC3E,MAAMC,EAAS,MAAM,KAAK,YAAY,mBAAmB,CACvD,YAAaD,EAAQ,QAAU,CAAC,GAAG,IAAKE,GAAUA,EAAM,IAAI,CAC9D,CAAC,EACD,OAAO,IAAI,eAAa,CACtB,GAAID,EAAO,GACX,OAAQD,EAAQ,OAChB,YAAa,KAAK,YAClB,IAAK,KAAK,IACV,IAAK,KAAK,GACZ,CAAC,CACH,CAGA,MAAM,WAAWG,EAAgD,CAC/D,aAAM,KAAK,oBAAoBA,CAAE,EAC1B,KAAK,YAAY,eAAeA,CAAE,CAC3C,CAGA,MAAM,IAAIA,EAAkD,CAC1D,MAAMF,EAAS,MAAM,KAAK,YAAY,gBAAgBE,CAAE,EACxD,OAAKF,EACE,IAAI,eAAa,CAAE,GAAIA,EAAO,GAAI,YAAa,KAAK,WAAY,CAAC,EADpD,IAEtB,CAEA,MAAc,oBAAoBE,EAAmC,CAEnE,GAAI,CADW,MAAM,KAAK,YAAY,gBAAgBA,CAAE,EAEtD,MAAM,IAAI,MAAM,iBAAiBA,CAAE,aAAa,CAEpD,CACF",
|
|
6
|
+
"names": ["conversations_exports", "__export", "Conversations", "__toCommonJS", "import_conversation", "Conversations", "__name", "options", "record", "agent", "id"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var a=Object.defineProperty;var
|
|
1
|
+
"use strict";var a=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var u=(r,t)=>{for(var n in t)a(r,n,{get:t[n],enumerable:!0})},T=(r,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!f.call(r,o)&&o!==n&&a(r,o,{get:()=>t[o],enumerable:!(i=m(t,o))||i.enumerable});return r};var d=r=>T(a({},"__esModule",{value:!0}),r);var y={};u(y,{Conversation:()=>p.Conversation,ConversationStream:()=>C.ConversationStream,Conversations:()=>c.Conversations,Orchestrator:()=>x.Orchestrator,TranscriptEntry:()=>e.TranscriptEntry,Transcription:()=>e.Transcription,createConversationState:()=>s.createConversationState});module.exports=d(y);var s=require("./types.js"),p=require("./conversation/index.js"),c=require("./conversations.js"),x=require("./orchestration/orchestrator/index.js"),C=require("./stream/index.js"),e=require("./transcription/index.js");
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/conversations/index.ts"],
|
|
4
|
-
"sourcesContent": ["export type {\n AudioChunk,\n ConversationId,\n ConversationState,\n ConversationStatus,\n Generation,\n GenerationStatus,\n Participant,\n ParticipantInput,\n ToolCall,\n ToolCallResult,\n Turn,\n TurnId,\n UserId,\n} from \"./types\";\nexport { createConversationState } from \"./types\";\nexport { Conversation } from \"./conversation/index\";\nexport type {\n ConversationEvents,\n ConversationOptions,\n} from \"./conversation/index\";\nexport { Conversations } from \"./conversations\";\nexport type { CreateConversationOptions } from \"./conversations\";\nexport { Orchestrator } from \"./orchestration/orchestrator/index\";\nexport type { OrchestratorOptions } from \"./orchestration/orchestrator/index\";\nexport { Transcription, TranscriptEntry } from \"./transcription/index\";\nexport type {\n TranscriptEntryInput,\n TranscriptSpeakerKind,\n} from \"./transcription/index\";\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,
|
|
6
|
-
"names": ["conversations_exports", "__export", "__toCommonJS", "import_types", "import_conversation", "import_conversations", "import_orchestrator", "import_transcription"]
|
|
4
|
+
"sourcesContent": ["export type {\n AudioChunk,\n ConversationId,\n ConversationState,\n ConversationStatus,\n Generation,\n GenerationStatus,\n GenerationTiming,\n Participant,\n ParticipantInput,\n ToolCall,\n ToolCallResult,\n Turn,\n TurnId,\n UserId,\n} from \"./types\";\nexport { createConversationState } from \"./types\";\nexport { Conversation } from \"./conversation/index\";\nexport type {\n ConversationEvents,\n ConversationOptions,\n} from \"./conversation/index\";\nexport { Conversations } from \"./conversations\";\nexport type { CreateConversationOptions } from \"./conversations\";\nexport { Orchestrator } from \"./orchestration/orchestrator/index\";\nexport type { OrchestratorOptions } from \"./orchestration/orchestrator/index\";\nexport { ConversationStream } from \"./stream/index\";\nexport { Transcription, TranscriptEntry } from \"./transcription/index\";\nexport type {\n TranscriptEntryInput,\n TranscriptSpeakerKind,\n} from \"./transcription/index\";\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8RAAAE,EAAAF,GAgBA,IAAAG,EAAwC,mBACxCC,EAA6B,gCAK7BC,EAA8B,2BAE9BC,EAA6B,8CAE7BC,EAAmC,0BACnCC,EAA+C",
|
|
6
|
+
"names": ["conversations_exports", "__export", "__toCommonJS", "import_types", "import_conversation", "import_conversations", "import_orchestrator", "import_stream", "import_transcription"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";var u=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var d=(r,e)=>u(r,"name",{value:e,configurable:!0});var x=(r,e)=>{for(var n in e)u(r,n,{get:e[n],enumerable:!0})},D=(r,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of k(e))!C.call(r,a)&&a!==n&&u(r,a,{get:()=>e[a],enumerable:!(i=b(e,a))||i.enumerable});return r};var q=r=>D(u({},"__esModule",{value:!0}),r);var M={};x(M,{Coordination:()=>v,CoordinationBudgetExceeded:()=>g,CoordinationCancelled:()=>h,CoordinationSuspension:()=>y,buildClarifyPrompt:()=>T,delegateToolDefinition:()=>w,parseDelegateAction:()=>L,renderClarifyQuestion:()=>f});module.exports=q(M);var o=require("zod");function f(r){return`Before I continue, could you tell me: ${new Intl.ListFormat("en",{style:"long",type:"conjunction"}).format(r)}?`}d(f,"renderClarifyQuestion");function T(){return`You are the "clarify" coordination: a generic information-acquisition unit.
|
|
2
|
+
|
|
3
|
+
Your job is to turn an underspecified request into a sufficiently clear one by asking the user for whatever is missing. You know nothing about the request's domain \u2014 you only notice missing details and ask for them.
|
|
4
|
+
|
|
5
|
+
Use the delegate tool:
|
|
6
|
+
- action "clarify": list every missing detail in the "missing" array in one call \u2014 one round-trip covers all of them, never one question at a time, and never ask for anything that can be reasonably inferred.
|
|
7
|
+
- action "complete": finish once the request is clear enough to act on, restating it precisely including every answer the user gave.
|
|
8
|
+
|
|
9
|
+
You may ask the user questions at most twice per run. After each answer, reassess: is the request now clear enough to act on? If yes, complete. If not, call "clarify" again with the remaining missing details. After the second round, if anything is still missing, state reasonable assumptions and complete. Never delegate to agents \u2014 your job is only to gather information.`}d(T,"buildClarifyPrompt");class y extends Error{static{d(this,"CoordinationSuspension")}frames;question;constructor(e,n){super(`Coordination suspended: ${n}`),this.name="CoordinationSuspension",this.frames=e,this.question=n}}class h extends Error{static{d(this,"CoordinationCancelled")}constructor(){super("Coordination cancelled"),this.name="CoordinationCancelled"}}class g extends Error{static{d(this,"CoordinationBudgetExceeded")}constructor(e){super(`Coordination budget exceeded: ${e}`),this.name="CoordinationBudgetExceeded"}}const S="Decide what should happen next in order to produce the desired result. You may run one or more agents (each with a self-contained prompt), pass the work to another coordination, ask the user for missing information (batched into one call), or complete with the final spoken answer. Only ever take one action per call.";function m(r){return r.length>0?o.z.enum(r):o.z.string()}d(m,"targetsEnum");function p(r,e){const n=r.map(a=>[a.name,...a.aliases]).flat(),i=e.map(a=>a.name);return o.z.discriminatedUnion("action",[o.z.object({action:o.z.literal("agents"),tasks:o.z.array(o.z.object({agent:m(n).describe("Agent name or alias from the roster."),prompt:o.z.string().trim().min(1,"a prompt is required").describe("Self-contained instruction for that agent.")})).describe("Agents to run in parallel.").min(1,"at least one task is required")}),o.z.object({action:o.z.literal("coordination"),coordination:m(i).describe("The coordination to pass the work to."),input:o.z.unknown().describe("Input for the delegated coordination.").optional()}),o.z.object({action:o.z.literal("clarify"),missing:o.z.array(o.z.string().trim().min(1,"a missing detail is required")).min(1,"at least one missing detail is required").describe("The missing details to ask the user for, batched into one turn.")}),o.z.object({action:o.z.literal("user"),question:o.z.string().trim().min(1,"a question is required").describe("Clarifying question for the user.")}),o.z.object({action:o.z.literal("complete"),output:o.z.string().trim().min(1,"an output is required").describe("The final spoken answer.")})])}d(p,"delegateActionSchema");function w(r,e){const n=r.map(s=>[s.name,...s.aliases]).flat(),i=e.map(s=>s.name),a=o.z.object({action:o.z.enum(["agents","coordination","clarify","user","complete"]).describe("What to do next."),tasks:o.z.array(o.z.object({agent:m(n).describe("Agent name or alias from the roster."),prompt:o.z.string().trim().min(1,"a prompt is required").describe("Self-contained instruction for that agent.")})).describe("Agents to run in parallel (action 'agents').").optional(),coordination:m(i).describe("The coordination to pass the work to (action 'coordination').").optional(),input:o.z.unknown().describe("Input for the delegated coordination (action 'coordination').").optional(),missing:o.z.array(o.z.string().trim().min(1,"a missing detail is required")).min(1,"at least one missing detail is required").describe("The missing details to ask the user for (action 'clarify'), batched into one turn.").optional(),question:o.z.string().trim().min(1,"a question is required").describe("Clarifying question for the user (action 'user').").optional(),output:o.z.string().trim().min(1,"an output is required").describe("The final spoken answer (action 'complete').").optional()}),t=o.z.toJSONSchema(a);return delete t.$schema,{name:"delegate",description:S,parameters:t}}d(w,"delegateToolDefinition");function L(r,e,n){let i;try{i=JSON.parse(r)}catch{throw new Error("delegate arguments must be valid JSON")}const a=p(e,n).safeParse(i);if(!a.success){const t=a.error.issues.map(s=>s.path.length>0?`${s.path.join(".")}: ${s.message}`:s.message).join("; ");throw new Error(`invalid delegate arguments: ${t}`)}return a.data}d(L,"parseDelegateAction");class v{static{d(this,"Coordination")}name;prompt;maxTokens;maxDurationMs;maxQuestionRounds;runtime;llm;cachedToolDefinition=null;cachedSchema=null;constructor(e,n){if(!e.name.trim())throw new Error("Coordination requires a non-empty name");this.name=e.name.trim(),this.prompt=e.prompt?.trim()??"",this.maxTokens=e.maxTokens,this.maxDurationMs=e.maxDurationMs,this.maxQuestionRounds=e.maxQuestionRounds??2,this.runtime=n,this.llm=e.llm??n.llm}toolDefinition(){return this.cachedToolDefinition??=w(this.runtime.agents,this.runtime.coordinations),this.cachedToolDefinition}parseDelegate(e){this.cachedSchema??=p(this.runtime.agents,this.runtime.coordinations);let n;try{n=JSON.parse(e)}catch{throw new Error("delegate arguments must be valid JSON")}const i=this.cachedSchema.safeParse(n);if(!i.success){const a=i.error.issues.map(t=>t.path.length>0?`${t.path.join(".")}: ${t.message}`:t.message).join("; ");throw new Error(`invalid delegate arguments: ${a}`)}return i.data}async run(e){const n={messages:[],startedAt:Date.now(),narration:"",questionRounds:0};return this.prompt&&n.messages.push({role:"system",name:this.name,content:this.prompt}),n.messages.push(...this.runtime.history),e!==void 0&&n.messages.push({role:"user",content:typeof e=="string"?e:JSON.stringify(e)}),this.loop(n)}async resume(e,n){return e.narration="",e.messages.push({role:"user",content:n}),this.loop(e)}async continueWith(e,n){return e.narration="",e.messages.push(n),this.loop(e)}async loop(e){const n=e.startedAt;for(;;){if(this.runtime.checkBudget(),this.runtime.isCancelled())throw new h;if(this.maxDurationMs&&Date.now()-n>this.maxDurationMs)throw new g(`"${this.name}" exceeded ${this.maxDurationMs}ms`);const i=[];let a=!1;for await(const t of this.llm.stream({messages:e.messages,tools:[this.toolDefinition()],maxTokens:this.maxTokens})){if(this.runtime.isCancelled())throw new h;switch(t.type){case"delta":e.narration+=t.content,this.runtime.onDelta(t.content);break;case"tool_call":i.push({id:t.id,name:t.name,arguments:t.arguments});break;case"error":throw t.error;case"done":a=!0}}if(this.maxDurationMs&&Date.now()-n>this.maxDurationMs)throw new g(`"${this.name}" exceeded ${this.maxDurationMs}ms`);if(i.length>0){this.runtime.flushSpeech(),e.messages.push({role:"assistant",name:this.name,content:e.narration,toolCalls:i});for(const t of i){let s;try{s=this.parseDelegate(t.arguments)}catch(l){e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({error:l instanceof Error?l.message:String(l)})});continue}switch(s.action){case"agents":{const l=await this.runtime.delegateAgentTasks(s.tasks);e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify(l)});break}case"coordination":{const l=this.runtime.coordinations.find(c=>c.name===s.coordination);if(!l){e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({error:`Unknown coordination "${s.coordination}"`})});break}try{const c=await this.delegateToCoordination(l,s.input,e,t.id);e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify(c)})}catch(c){if(c instanceof g)e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({error:c.message})});else throw c}break}case"clarify":{if(e.questionRounds>=this.maxQuestionRounds){e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({error:`question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`})});continue}e.questionRounds++;const l=f(s.missing);throw this.runtime.speak(l),e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({action:"clarify",missing:s.missing})}),await this.runtime.askUser({coordination:this,state:e},l),new Error("unreachable")}case"user":{if(e.questionRounds>=this.maxQuestionRounds){e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({error:`question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`})});continue}throw e.questionRounds++,e.messages.push({role:"tool",toolCallId:t.id,name:"delegate",content:JSON.stringify({action:"user",question:s.question})}),await this.runtime.askUser({coordination:this,state:e},s.question),new Error("unreachable")}case"complete":return this.runtime.speak(s.output),this.completeOutput(e.narration,s.output)}}continue}if(a)return this.completeOutput(e.narration,"")}}async delegateToCoordination(e,n,i,a){i.pendingToolCallId=a;try{return await e.run(n)}catch(t){throw t instanceof y&&t.frames.unshift({coordination:this,state:i}),t}}completeOutput(e,n){const i=e.trim();return n?`${i?i+" ":""}${n}`:i}}
|
|
10
|
+
//# sourceMappingURL=coordination.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/conversations/orchestration/coordination/coordination.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Agent } from \"../../../agents/agent\";\nimport { z } from \"zod\";\nimport type { LLM, LLMMessage, LLMToolCall, LLMToolDefinition } from \"../../../providers/llm/types\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * One task delegated to an agent: a self-contained prompt for a roster member.\n */\nexport interface DelegatedTask {\n agent: string;\n prompt: string;\n}\n\n/**\n * The outcome of a delegated agent run (or sub-coordination, via `error`).\n */\nexport interface DelegationResult {\n agent: string;\n text: string;\n error?: string;\n}\n\n/** What a coordination's LLM may decide to do next. */\nexport type DelegateAction =\n | { action: \"agents\"; tasks: DelegatedTask[] }\n | { action: \"coordination\"; coordination: string; input?: unknown }\n | { action: \"clarify\"; missing: string[] }\n | { action: \"user\"; question: string }\n | { action: \"complete\"; output: string };\n\n/**\n * The runtime a coordination reasons against: the roster, every registered\n * coordination, and the primitives for delegating work. Supplied by the\n * orchestrator, so coordinations never couple to it directly.\n */\nexport interface CoordinationRuntime {\n readonly agents: readonly Agent[];\n readonly coordinations: readonly Coordination[];\n /** Shared LLM used for coordination reasoning. */\n readonly llm: LLM;\n /** Shared conversation history, seeded into fresh runs. */\n readonly history: readonly LLMMessage[];\n\n /** Run one or more agents in parallel (text-only) and return their outputs. */\n delegateAgentTasks(tasks: DelegatedTask[]): Promise<DelegationResult[]>;\n /**\n * Ask the user a question. Never returns: it throws `CoordinationSuspension`\n * carrying the innermost frame, which the orchestrator catches to park the\n * execution until the user answers.\n */\n askUser(frame: PendingFrame, question: string): Promise<never>;\n /** Stream a delta to speech (TTS narration). */\n onDelta(delta: string): void;\n /** Flush pending narration (e.g. before delegating or suspending). */\n flushSpeech(): void;\n /** Speak a standalone sentence (e.g. a `complete` output). */\n speak(sentence: string): void;\n /** True once an interrupt/stop has cancelled this run. */\n isCancelled(): boolean;\n /** Throw if the run exceeded the coordination step budget. */\n checkBudget(): void;\n}\n\nexport interface CoordinationOptions {\n name: string;\n /** System prompt describing the coordination's reasoning role. */\n prompt?: string;\n /** Overrides the runtime's shared LLM for this coordination. */\n llm?: LLM;\n maxTokens?: number;\n /** Hard wall-clock limit for a single run (including suspensions). */\n maxDurationMs?: number;\n /**\n * Deterministic cap on user-question rounds per run (both the structured\n * `clarify` action and open-ended `user` questions, across suspensions).\n * Once exhausted, the coordination is told to state reasonable\n * assumptions and complete. Defaults to 2.\n */\n maxQuestionRounds?: number;\n}\n\n/**\n * A coordination registered in the orchestrator by name \u2014 the registry key\n * is the coordination's name, so it is not repeated here.\n */\nexport type CoordinationRegistration = Omit<CoordinationOptions, \"name\">;\n\n/**\n * Render a batched clarification question from the missing details, so the\n * wording is deterministic regardless of how the model phrases the labels.\n */\nexport function renderClarifyQuestion(missing: string[]): string {\n const list = new Intl.ListFormat(\"en\", { style: \"long\", type: \"conjunction\" }).format(missing);\n return `Before I continue, could you tell me: ${list}?`;\n}\n\n/**\n * The system prompt for a `clarify` coordination: a generic,\n * domain-agnostic information-acquisition unit. It turns an underspecified\n * request into a clear one by asking the user for missing details via the\n * structured `clarify` action (batched), with a hard two-round cap enforced\n * by the runtime. Register it alongside `understand`:\n *\n * ```ts\n * coordinations: { clarify: { prompt: buildClarifyPrompt() } }\n * ```\n */\nexport function buildClarifyPrompt(): string {\n return `You are the \"clarify\" coordination: a generic information-acquisition unit.\n\nYour job is to turn an underspecified request into a sufficiently clear one by asking the user for whatever is missing. You know nothing about the request's domain \u2014 you only notice missing details and ask for them.\n\nUse the delegate tool:\n- action \"clarify\": list every missing detail in the \"missing\" array in one call \u2014 one round-trip covers all of them, never one question at a time, and never ask for anything that can be reasonably inferred.\n- action \"complete\": finish once the request is clear enough to act on, restating it precisely including every answer the user gave.\n\nYou may ask the user questions at most twice per run. After each answer, reassess: is the request now clear enough to act on? If yes, complete. If not, call \"clarify\" again with the remaining missing details. After the second round, if anything is still missing, state reasonable assumptions and complete. Never delegate to agents \u2014 your job is only to gather information.`;\n}\n\n/**\n * The resumable state of one coordination invocation. Plain data so it can be\n * parked in a `PendingExecution` while waiting for the user.\n */\nexport interface CoordinationState {\n messages: LLMMessage[];\n startedAt: number;\n /** Everything the coordination has spoken so far, for the final record. */\n narration: string;\n /** How many user-question rounds this run has used (across suspensions). */\n questionRounds: number;\n /** Tool call id awaiting a sub-coordination result, for resume replies. */\n pendingToolCallId?: string;\n}\n\n/** One frame of a suspended execution stack (outermost first). */\nexport interface PendingFrame {\n coordination: Coordination;\n state: CoordinationState;\n}\n\n/** Thrown when a coordination asks the user; carries the whole frame stack. */\nexport class CoordinationSuspension extends Error {\n readonly frames: PendingFrame[];\n readonly question: string;\n\n constructor(frames: PendingFrame[], question: string) {\n super(`Coordination suspended: ${question}`);\n this.name = \"CoordinationSuspension\";\n this.frames = frames;\n this.question = question;\n }\n}\n\n/** Thrown when a coordination run is cancelled (interrupt/stop). */\nexport class CoordinationCancelled extends Error {\n constructor() {\n super(\"Coordination cancelled\");\n this.name = \"CoordinationCancelled\";\n }\n}\n\n/** Thrown when a coordination exceeded its step or duration budget. */\nexport class CoordinationBudgetExceeded extends Error {\n constructor(detail: string) {\n super(`Coordination budget exceeded: ${detail}`);\n this.name = \"CoordinationBudgetExceeded\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Delegate tool\n// ---------------------------------------------------------------------------\n\nconst DELEGATE_DESCRIPTION =\n \"Decide what should happen next in order to produce the desired result. \" +\n \"You may run one or more agents (each with a self-contained prompt), pass the work to \" +\n \"another coordination, ask the user for missing information (batched into one call), or \" +\n \"complete with the final spoken answer. Only ever take one action per call.\";\n\n/** Non-empty zod enum, or a plain string when there are no targets. */\nfunction targetsEnum(targets: string[]): z.ZodType<string> {\n return targets.length > 0\n ? z.enum(targets as [string, ...string[]])\n : z.string();\n}\n\n/**\n * The strict schema a coordination's LLM output must satisfy. A discriminated\n * union on `action` \u2014 each variant carries exactly its own fields.\n */\nfunction delegateActionSchema(\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): z.ZodType<DelegateAction> {\n const agentTargets = agents.map((agent) => [agent.name, ...agent.aliases]).flat();\n const coordinationTargets = coordinations.map((coordination) => coordination.name);\n return z.discriminatedUnion(\"action\", [\n z.object({\n action: z.literal(\"agents\"),\n tasks: z\n .array(\n z.object({\n agent: targetsEnum(agentTargets).describe(\"Agent name or alias from the roster.\"),\n prompt: z.string().trim().min(1, \"a prompt is required\").describe(\"Self-contained instruction for that agent.\"),\n }),\n )\n .describe(\"Agents to run in parallel.\")\n .min(1, \"at least one task is required\"),\n }),\n z.object({\n action: z.literal(\"coordination\"),\n coordination: targetsEnum(coordinationTargets).describe(\n \"The coordination to pass the work to.\",\n ),\n input: z.unknown().describe(\"Input for the delegated coordination.\").optional(),\n }),\n z.object({\n action: z.literal(\"clarify\"),\n missing: z\n .array(z.string().trim().min(1, \"a missing detail is required\"))\n .min(1, \"at least one missing detail is required\")\n .describe(\"The missing details to ask the user for, batched into one turn.\"),\n }),\n z.object({\n action: z.literal(\"user\"),\n question: z.string().trim().min(1, \"a question is required\").describe(\"Clarifying question for the user.\"),\n }),\n z.object({\n action: z.literal(\"complete\"),\n output: z.string().trim().min(1, \"an output is required\").describe(\"The final spoken answer.\"),\n }),\n ]);\n}\n\n/**\n * The tool definition that lets a coordination's LLM choose the next execution\n * target: agents (one or more, in parallel), another coordination, the user,\n * or completion.\n *\n * The parameters are deliberately FLAT (action enum + optional fields) even\n * though the parser enforces a discriminated union per action. Why: Amazon\n * Bedrock (nova) ignores `oneOf` in tool input schemas, which makes the tool\n * effectively empty \u2014 the model stops calling it and answers directly instead\n * (measured: 0/2 tool calls and ~5k-token essays vs reliable ~1s calls with\n * the flat shape). The flat schema works across every provider tested; the\n * discriminated contract is enforced when the call is parsed, and an invalid\n * combination costs one bounded retry rather than a broken tool.\n */\nexport function delegateToolDefinition(\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): LLMToolDefinition {\n const agentTargets = agents.map((agent) => [agent.name, ...agent.aliases]).flat();\n const coordinationTargets = coordinations.map((coordination) => coordination.name);\n const parameters = z.object({\n action: z\n .enum([\"agents\", \"coordination\", \"clarify\", \"user\", \"complete\"])\n .describe(\"What to do next.\"),\n tasks: z\n .array(\n z.object({\n agent: targetsEnum(agentTargets).describe(\"Agent name or alias from the roster.\"),\n prompt: z.string().trim().min(1, \"a prompt is required\").describe(\"Self-contained instruction for that agent.\"),\n }),\n )\n .describe(\"Agents to run in parallel (action 'agents').\")\n .optional(),\n coordination: targetsEnum(coordinationTargets)\n .describe(\"The coordination to pass the work to (action 'coordination').\")\n .optional(),\n input: z\n .unknown()\n .describe(\"Input for the delegated coordination (action 'coordination').\")\n .optional(),\n missing: z\n .array(z.string().trim().min(1, \"a missing detail is required\"))\n .min(1, \"at least one missing detail is required\")\n .describe(\"The missing details to ask the user for (action 'clarify'), batched into one turn.\")\n .optional(),\n question: z\n .string()\n .trim()\n .min(1, \"a question is required\")\n .describe(\"Clarifying question for the user (action 'user').\")\n .optional(),\n output: z\n .string()\n .trim()\n .min(1, \"an output is required\")\n .describe(\"The final spoken answer (action 'complete').\")\n .optional(),\n });\n const jsonSchema = z.toJSONSchema(parameters) as Record<string, unknown>;\n delete jsonSchema.$schema;\n return { name: \"delegate\", description: DELEGATE_DESCRIPTION, parameters: jsonSchema };\n}\n\nexport function parseDelegateAction(\n argumentsJson: string,\n agents: readonly Agent[],\n coordinations: readonly Coordination[],\n): DelegateAction {\n let parsed: unknown;\n try {\n parsed = JSON.parse(argumentsJson);\n } catch {\n throw new Error(\"delegate arguments must be valid JSON\");\n }\n const result = delegateActionSchema(agents, coordinations).safeParse(parsed);\n if (!result.success) {\n const details = result.error.issues\n .map((issue) => (issue.path.length > 0 ? `${issue.path.join(\".\")}: ${issue.message}` : issue.message))\n .join(\"; \");\n throw new Error(`invalid delegate arguments: ${details}`);\n }\n return result.data;\n}\n\n// ---------------------------------------------------------------------------\n// Coordination\n// ---------------------------------------------------------------------------\n\n/**\n * A hardcoded reasoning/control-flow unit. Unlike an `Agent` (input \u2192 LLM \u2192\n * output), a coordination decides *what should happen next*: run agents, pass\n * work to another coordination, ask the user, or complete. Definitions are\n * stateless; each invocation carries its own `CoordinationState`, which can be\n * parked (suspended) while waiting for the user and resumed later.\n */\nexport class Coordination {\n readonly name: string;\n readonly prompt: string;\n readonly maxTokens: number | undefined;\n readonly maxDurationMs: number | undefined;\n readonly maxQuestionRounds: number;\n private readonly runtime: CoordinationRuntime;\n private readonly llm: LLM;\n private cachedToolDefinition: LLMToolDefinition | null = null;\n private cachedSchema: ReturnType<typeof delegateActionSchema> | null = null;\n\n constructor(options: CoordinationOptions, runtime: CoordinationRuntime) {\n if (!options.name.trim()) {\n throw new Error(\"Coordination requires a non-empty name\");\n }\n this.name = options.name.trim();\n this.prompt = options.prompt?.trim() ?? \"\";\n this.maxTokens = options.maxTokens;\n this.maxDurationMs = options.maxDurationMs;\n this.maxQuestionRounds = options.maxQuestionRounds ?? 2;\n this.runtime = runtime;\n this.llm = options.llm ?? runtime.llm;\n }\n\n /** The delegate tool definition, generated once from the roster. */\n private toolDefinition(): LLMToolDefinition {\n this.cachedToolDefinition ??= delegateToolDefinition(\n this.runtime.agents,\n this.runtime.coordinations,\n );\n return this.cachedToolDefinition;\n }\n\n /** Parse a `delegate` tool call against the roster's strict schema. */\n private parseDelegate(argumentsJson: string): DelegateAction {\n this.cachedSchema ??= delegateActionSchema(\n this.runtime.agents,\n this.runtime.coordinations,\n );\n let parsed: unknown;\n try {\n parsed = JSON.parse(argumentsJson);\n } catch {\n throw new Error(\"delegate arguments must be valid JSON\");\n }\n const result = this.cachedSchema.safeParse(parsed);\n if (!result.success) {\n const details = result.error.issues\n .map((issue) =>\n issue.path.length > 0\n ? `${issue.path.join(\".\")}: ${issue.message}`\n : issue.message,\n )\n .join(\"; \");\n throw new Error(`invalid delegate arguments: ${details}`);\n }\n return result.data;\n }\n\n /** Run the coordination with fresh state (seeded with the shared history). */\n async run(input?: unknown): Promise<unknown> {\n const state: CoordinationState = {\n messages: [],\n startedAt: Date.now(),\n narration: \"\",\n questionRounds: 0,\n };\n if (this.prompt) {\n state.messages.push({ role: \"system\", name: this.name, content: this.prompt });\n }\n state.messages.push(...this.runtime.history);\n if (input !== undefined) {\n state.messages.push({\n role: \"user\",\n content: typeof input === \"string\" ? input : JSON.stringify(input),\n });\n }\n return this.loop(state);\n }\n\n /** Resume a suspended state with the user's answer. */\n async resume(state: CoordinationState, answer: string): Promise<unknown> {\n // The pre-suspension narration was already recorded as the question.\n state.narration = \"\";\n state.messages.push({ role: \"user\", content: answer });\n return this.loop(state);\n }\n\n /** Continue a suspended state with an injected message (e.g. a sub-result). */\n async continueWith(state: CoordinationState, message: LLMMessage): Promise<unknown> {\n state.narration = \"\";\n state.messages.push(message);\n return this.loop(state);\n }\n\n /**\n * The coordination loop: one LLM round trip per iteration, choosing the next\n * execution target via the `delegate` tool. Throws `CoordinationSuspension`\n * when asking the user; the state carried in the suspension is resumable.\n */\n private async loop(state: CoordinationState): Promise<unknown> {\n const startedAt = state.startedAt;\n\n for (;;) {\n this.runtime.checkBudget();\n if (this.runtime.isCancelled()) throw new CoordinationCancelled();\n if (this.maxDurationMs && Date.now() - startedAt > this.maxDurationMs) {\n throw new CoordinationBudgetExceeded(`\"${this.name}\" exceeded ${this.maxDurationMs}ms`);\n }\n\n const toolCalls: LLMToolCall[] = [];\n let done = false;\n\n for await (const event of this.llm.stream({\n messages: state.messages,\n tools: [this.toolDefinition()],\n maxTokens: this.maxTokens,\n })) {\n if (this.runtime.isCancelled()) throw new CoordinationCancelled();\n switch (event.type) {\n case \"delta\":\n state.narration += event.content;\n this.runtime.onDelta(event.content);\n break;\n case \"tool_call\":\n toolCalls.push({ id: event.id, name: event.name, arguments: event.arguments });\n break;\n case \"error\":\n throw event.error;\n case \"done\":\n done = true;\n }\n }\n\n // Re-check the wall-clock limit after the round trip: a single slow\n // iteration must still count against maxDurationMs.\n if (this.maxDurationMs && Date.now() - startedAt > this.maxDurationMs) {\n throw new CoordinationBudgetExceeded(`\"${this.name}\" exceeded ${this.maxDurationMs}ms`);\n }\n\n if (toolCalls.length > 0) {\n this.runtime.flushSpeech();\n state.messages.push({\n role: \"assistant\",\n name: this.name,\n content: state.narration,\n toolCalls,\n });\n for (const call of toolCalls) {\n let action: DelegateAction;\n try {\n action = this.parseDelegate(call.arguments);\n } catch (error) {\n // Malformed arguments: report to the coordination's LLM so it can\n // recover instead of crashing the run.\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: error instanceof Error ? error.message : String(error),\n }),\n });\n continue;\n }\n switch (action.action) {\n case \"agents\": {\n const results = await this.runtime.delegateAgentTasks(action.tasks);\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify(results),\n });\n break;\n }\n case \"coordination\": {\n const target = this.runtime.coordinations.find(\n (coordination) => coordination.name === action.coordination,\n );\n if (!target) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `Unknown coordination \"${action.coordination}\"`,\n }),\n });\n break;\n }\n try {\n const result = await this.delegateToCoordination(\n target,\n action.input,\n state,\n call.id,\n );\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify(result),\n });\n } catch (error) {\n if (error instanceof CoordinationBudgetExceeded) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ error: error.message }),\n });\n } else {\n throw error; // suspension or cancellation propagates\n }\n }\n break;\n }\n case \"clarify\": {\n // Structured, batched clarification: the model declares which\n // details are missing; the framework renders and speaks the\n // question so batching and the round cap are deterministic.\n if (state.questionRounds >= this.maxQuestionRounds) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`,\n }),\n });\n continue;\n }\n state.questionRounds++;\n const question = renderClarifyQuestion(action.missing);\n this.runtime.speak(question);\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ action: \"clarify\", missing: action.missing }),\n });\n await this.runtime.askUser({ coordination: this, state }, question);\n throw new Error(\"unreachable\");\n }\n case \"user\": {\n // Open-ended questions count against the same deterministic\n // question-round budget as structured clarification.\n if (state.questionRounds >= this.maxQuestionRounds) {\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({\n error: `question budget exceeded (max ${this.maxQuestionRounds} rounds) \u2014 state reasonable assumptions and complete`,\n }),\n });\n continue;\n }\n state.questionRounds++;\n state.messages.push({\n role: \"tool\",\n toolCallId: call.id,\n name: \"delegate\",\n content: JSON.stringify({ action: \"user\", question: action.question }),\n });\n await this.runtime.askUser({ coordination: this, state }, action.question);\n throw new Error(\"unreachable\");\n }\n case \"complete\":\n this.runtime.speak(action.output);\n return this.completeOutput(state.narration, action.output);\n }\n }\n continue;\n }\n\n if (done) {\n // No delegate call: the coordination answered directly.\n return this.completeOutput(state.narration, \"\");\n }\n }\n }\n\n /** Delegate to a sub-coordination, attaching this frame on suspension. */\n private async delegateToCoordination(\n target: Coordination,\n input: unknown,\n state: CoordinationState,\n toolCallId: string,\n ): Promise<unknown> {\n state.pendingToolCallId = toolCallId;\n try {\n return await target.run(input);\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift({ coordination: this, state });\n throw error;\n }\n throw error;\n }\n }\n\n private completeOutput(narration: string, output: string): string {\n const trimmed = narration.trim();\n return output ? `${trimmed ? trimmed + \" \" : \"\"}${output}` : trimmed;\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,EAAA,+BAAAC,EAAA,0BAAAC,EAAA,2BAAAC,EAAA,uBAAAC,EAAA,2BAAAC,EAAA,wBAAAC,EAAA,0BAAAC,IAAA,eAAAC,EAAAV,GACA,IAAAW,EAAkB,eA6FX,SAASC,EAAsBC,EAA2B,CAE/D,MAAO,yCADM,IAAI,KAAK,WAAW,KAAM,CAAE,MAAO,OAAQ,KAAM,aAAc,CAAC,EAAE,OAAOA,CAAO,CACzC,GACtD,CAHgBC,EAAAF,EAAA,yBAgBT,SAASG,GAA6B,CAC3C,MAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0XAST,CAVgBD,EAAAC,EAAA,sBAkCT,MAAMC,UAA+B,KAAM,CAhJlD,MAgJkD,CAAAF,EAAA,+BACvC,OACA,SAET,YAAYG,EAAwBC,EAAkB,CACpD,MAAM,2BAA2BA,CAAQ,EAAE,EAC3C,KAAK,KAAO,yBACZ,KAAK,OAASD,EACd,KAAK,SAAWC,CAClB,CACF,CAGO,MAAMC,UAA8B,KAAM,CA7JjD,MA6JiD,CAAAL,EAAA,8BAC/C,aAAc,CACZ,MAAM,wBAAwB,EAC9B,KAAK,KAAO,uBACd,CACF,CAGO,MAAMM,UAAmC,KAAM,CArKtD,MAqKsD,CAAAN,EAAA,mCACpD,YAAYO,EAAgB,CAC1B,MAAM,iCAAiCA,CAAM,EAAE,EAC/C,KAAK,KAAO,4BACd,CACF,CAMA,MAAMC,EACJ,gUAM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ded", "CoordinationCancelled", "CoordinationSuspension", "buildClarifyPrompt", "delegateToolDefinition", "parseDelegateAction", "renderClarifyQuestion", "__toCommonJS", "import_zod", "renderClarifyQuestion", "missing", "__name", "buildClarifyPrompt", "CoordinationSuspension", "frames", "question", "CoordinationCancelled", "CoordinationBudgetExceeded", "detail", "DELEGATE_DESCRIPTION", "targetsEnum", "targets", "delegateActionSchema", "agents", "coordinations", "agentTargets", "agent", "coordinationTargets", "coordination", "delegateToolDefinition", "parameters", "jsonSchema", "parseDelegateAction", "argumentsJson", "parsed", "result", "details", "issue", "Coordination", "options", "runtime", "input", "state", "answer", "message", "startedAt", "toolCalls", "done", "event", "call", "action", "error", "results", "target", "toolCallId", "narration", "output", "trimmed"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var a=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var g=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},p=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of l(e))!C.call(n,i)&&i!==t&&a(n,i,{get:()=>e[i],enumerable:!(d=r(e,i))||d.enumerable});return n};var s=n=>p(a({},"__esModule",{value:!0}),n);var c={};g(c,{Coordination:()=>o.Coordination,CoordinationBudgetExceeded:()=>o.CoordinationBudgetExceeded,CoordinationCancelled:()=>o.CoordinationCancelled,CoordinationSuspension:()=>o.CoordinationSuspension,delegateToolDefinition:()=>o.delegateToolDefinition,parseDelegateAction:()=>o.parseDelegateAction});module.exports=s(c);var o=require("./coordination.js");
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/conversations/orchestration/coordination/index.ts"],
|
|
4
|
+
"sourcesContent": ["export {\n Coordination,\n CoordinationSuspension,\n CoordinationCancelled,\n CoordinationBudgetExceeded,\n delegateToolDefinition,\n parseDelegateAction,\n} from \"./coordination\";\nexport type {\n CoordinationOptions,\n CoordinationRuntime,\n CoordinationState,\n DelegateAction,\n DelegatedTask,\n DelegationResult,\n PendingFrame,\n} from \"./coordination\";\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sTAAAE,EAAAF,GAAA,IAAAG,EAOO",
|
|
6
|
+
"names": ["coordination_exports", "__export", "__toCommonJS", "import_coordination"]
|
|
7
|
+
}
|
package/dist/cjs/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"use strict";var p=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var a=(d,t)=>p(d,"name",{value:t,configurable:!0});var w=(d,t)=>{for(var n in t)p(d,n,{get:t[n],enumerable:!0})},x=(d,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of y(t))!C.call(d,e)&&e!==n&&p(d,e,{get:()=>t[e],enumerable:!(o=f(t,e))||o.enumerable});return d};var E=d=>x(p({},"__esModule",{value:!0}),d);var S={};w(S,{CoordinationRunner:()=>T});module.exports=E(S);var i=require("../../coordination/coordination.js"),g=require("../history/history.js"),l=require("../routing/routing.js");class T{static{a(this,"CoordinationRunner")}coordinations={};understand=null;conversation;agents;llm;history;historyWindow;speech;generation;tools;maxCoordinationSteps;maxToolIterations;temperature;maxTokens;currentEpoch;isCurrent;coordinationEpoch=0;coordinationStepCount=0;coordinationRunId="";pendingExecution=null;constructor(t){this.conversation=t.conversation,this.agents=t.agents,this.llm=t.llm,this.history=t.history,this.historyWindow=t.historyWindow,this.speech=t.speech,this.generation=t.generation,this.tools=t.tools,this.maxCoordinationSteps=t.maxCoordinationSteps,this.maxToolIterations=t.maxToolIterations,this.temperature=t.temperature,this.maxTokens=t.maxTokens,this.currentEpoch=t.currentEpoch,this.isCurrent=t.isCurrent}register(t,n){const o={...t};n.length>1&&!o.understand&&(o.understand={prompt:(0,l.buildUnderstandPrompt)(n)});for(const[e,s]of Object.entries(o))this.coordinations[e]=new i.Coordination({name:e,...s},this.runtime());this.understand=this.coordinations.understand??null}hasPending(){return this.pendingExecution!==null}cancel(){this.pendingExecution=null}async runDefault(t){const n=this.understand,o=this.llm();if(!(!n||!o)){this.coordinationEpoch=this.currentEpoch(),this.coordinationStepCount=0,this.coordinationRunId=crypto.randomUUID(),await this.conversation.pushGeneration({id:this.coordinationRunId,conversationId:this.conversation.id,agentName:this.agents()[0].name,text:"",status:"streaming",startedAt:Date.now()});try{const e=await n.run();await this.finalizeOutput(String(e))}catch(e){e instanceof i.CoordinationSuspension?await this.recordSuspension(e):e instanceof i.CoordinationCancelled||this.emitError(e)}}}async resume(t){const n=this.pendingExecution;if(!n)return;this.pendingExecution=null,this.coordinationEpoch=this.currentEpoch(),this.coordinationStepCount=n.stepCount,this.coordinationRunId=crypto.randomUUID(),await this.conversation.pushGeneration({id:this.coordinationRunId,conversationId:this.conversation.id,agentName:this.agents()[0].name,text:"",status:"streaming",startedAt:Date.now()});const o=[...n.frames],e=o.pop();if(!e)return;let s;try{s=await e.coordination.resume(e.state,t.text)}catch(r){r instanceof i.CoordinationSuspension?(r.frames.unshift(...o),await this.recordSuspension(r)):r instanceof i.CoordinationCancelled||this.emitError(r);return}for(;o.length>0;){const r=o.pop(),m=r.state.pendingToolCallId??crypto.randomUUID();try{s=await r.coordination.continueWith(r.state,{role:"tool",toolCallId:m,name:"delegate",content:JSON.stringify(s)})}catch(h){h instanceof i.CoordinationSuspension?(h.frames.unshift(...o),await this.recordSuspension(h)):h instanceof i.CoordinationCancelled||this.emitError(h);return}}await this.finalizeOutput(String(s))}runtime(){const t=this;return{get agents(){return t.agents()},get coordinations(){return Object.values(t.coordinations)},get llm(){return t.llm()},get history(){return t.history.windowed(t.historyWindow)},delegateAgentTasks:a(n=>this.delegateAgentTasks(n),"delegateAgentTasks"),askUser:a((n,o)=>this.askUser(n,o),"askUser"),onDelta:a(n=>this.speech.feed(n,this.currentEpoch()),"onDelta"),flushSpeech:a(()=>this.speech.flush(this.currentEpoch()),"flushSpeech"),speak:a(n=>this.speech.speak(n,this.currentEpoch()),"speak"),isCancelled:a(()=>this.currentEpoch()!==this.coordinationEpoch,"isCancelled"),checkBudget:a(()=>this.checkBudget(),"checkBudget")}}async finalizeOutput(t){this.speech.flush(this.currentEpoch()),await this.speech.waitForIdle(),this.currentEpoch()===this.coordinationEpoch&&(await this.conversation.completeGeneration(t),await this.conversation.pushTranscript({speaker:this.agents()[0].name,speakerKind:"agent",text:t}),this.history.addAssistant(this.agents()[0].name,t))}async recordSuspension(t){await this.conversation.completeGeneration(t.question),await this.conversation.pushTranscript({speaker:this.agents()[0].name,speakerKind:"agent",text:t.question}),this.history.addAssistant(this.agents()[0].name,t.question),this.pendingExecution={frames:t.frames,question:t.question,stepCount:this.coordinationStepCount}}askUser(t,n){throw new i.CoordinationSuspension([t],n)}checkBudget(){if(this.coordinationStepCount++,this.coordinationStepCount>this.maxCoordinationSteps)throw new i.CoordinationBudgetExceeded(`exceeded ${this.maxCoordinationSteps} coordination steps`)}emitError(t){this.conversation.emit("error",{conversationId:this.conversation.id,error:t instanceof Error?t:new Error(String(t))}),this.currentEpoch()===this.coordinationEpoch&&this.conversation.completeGeneration("")}async delegateAgentTasks(t){const n=await Promise.all(t.map(o=>this.runSubGeneration(this.coordinationEpoch,o,this.coordinationRunId)));if(!this.isCurrent(this.coordinationEpoch))return n.map(({agent:o,text:e,error:s})=>({agent:o,text:e,error:s}));for(const o of n)o.text&&!o.error&&await this.conversation.pushTranscript({speaker:o.agent,speakerKind:"agent",text:o.text});return n}async runSubGeneration(t,n,o){const e=(0,l.findAgentByName)(this.agents(),n.agent);if(!e)return{agent:n.agent,text:"",error:`Unknown agent "${n.agent}"`};const s=e.llm??this.llm();if(!s)return{agent:e.name,text:"",error:`Agent "${e.name}" has no LLM configured`};const r=crypto.randomUUID();await this.conversation.pushSubGeneration({id:r,conversationId:this.conversation.id,agentName:e.name,text:"",status:"streaming",startedAt:Date.now(),kind:"sub",parentGenerationId:o});const m=e.tools.map(u=>({name:u.name,description:u.description,parameters:u.parameters??{type:"object",properties:{}}})),h=[];e.context&&h.push({role:"system",name:e.name,content:e.context}),h.push(...this.history.windowed(this.historyWindow)),h.push({role:"user",content:`${n.prompt}
|
|
2
|
+
|
|
3
|
+
${(0,g.formatTimeContext)()}`});const c=await this.generation.run({agentName:e.name,llm:s,messages:h,tools:m,temperature:this.temperature,maxTokens:this.maxTokens,maxToolIterations:this.maxToolIterations,isCurrent:a(()=>this.isCurrent(t),"isCurrent"),onDelta:a((u,v)=>{v.length===0&&this.conversation.noteTiming("firstToken",r)},"onDelta"),resolveToolCalls:a(u=>this.tools.resolveCalls(u),"resolveToolCalls")});return!this.isCurrent(t)||c.status==="interrupted"?(await this.conversation.cancelSubGeneration(r),{agent:e.name,text:"",error:"interrupted"}):(await this.conversation.completeSubGeneration(r,c.text),c.status==="error"?(this.conversation.emit("error",{conversationId:this.conversation.id,error:c.error instanceof Error?c.error:new Error(String(c.error))}),{agent:e.name,text:c.text,error:c.error instanceof Error?c.error.message:String(c.error)}):{agent:e.name,text:c.text})}}
|
|
4
|
+
//# sourceMappingURL=coordination-runner.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/conversations/orchestration/orchestrator/coordination-runner/coordination-runner.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Agent } from \"../../../../agents/agent\";\nimport type { Conversation } from \"../../../conversation/conversation\";\nimport type { LLM, LLMMessage, LLMToolDefinition } from \"../../../../providers/llm/types\";\nimport type { Turn } from \"../../../types\";\nimport {\n Coordination,\n CoordinationBudgetExceeded,\n CoordinationCancelled,\n CoordinationSuspension,\n type CoordinationRegistration,\n type CoordinationRuntime,\n type DelegatedTask,\n type DelegationResult,\n type PendingFrame,\n} from \"../../coordination/coordination\";\nimport { ConversationHistory, formatTimeContext } from \"../history/history\";\nimport { buildUnderstandPrompt, findAgentByName } from \"../routing/routing\";\nimport type { GenerationRunner } from \"../generation/generation\";\nimport type { SpeechPipeline } from \"../speech/speech\";\nimport type { ToolCallManager } from \"../tools/tools\";\n\nexport interface CoordinationRunnerOptions {\n conversation: Conversation;\n /** Live roster accessor (read at coordination-run time). */\n agents(): Agent[];\n /** Live shared-LLM accessor (undefined in transcription-only mode). */\n llm(): LLM | undefined;\n /** The conversation's message log, seeded into fresh coordination runs. */\n history: ConversationHistory;\n historyWindow: Parameters<ConversationHistory[\"windowed\"]>[0];\n speech: SpeechPipeline;\n generation: GenerationRunner;\n tools: ToolCallManager;\n /** Safety bound on LLM reasoning steps per coordination execution. */\n maxCoordinationSteps: number;\n maxToolIterations: number;\n temperature?: number;\n maxTokens?: number;\n /** The orchestrator's current generation epoch (bumped on interrupt/stop). */\n currentEpoch(): number;\n /** True while the orchestrator is started and the epoch is current. */\n isCurrent(epoch: number): boolean;\n}\n\n/** A coordination execution parked while waiting for the user to answer. */\ninterface PendingExecution {\n /** Execution stack, outermost frame first. */\n frames: PendingFrame[];\n question: string;\n /** Coordination step count so the budget survives the suspension. */\n stepCount: number;\n}\n\n/**\n * The application-specific execution of coordinations: binds the generic\n * `Coordination` primitives to the orchestrator's machinery (roster, shared\n * LLM, history, speech, delegation, budgets, cancellation) and owns the\n * suspension/resume lifecycle \u2014 the parked frame stack, the step budget, and\n * the coordination generation records.\n */\nexport class CoordinationRunner {\n /** Coordinations registered by name (the key is the coordination's name). */\n readonly coordinations: Record<string, Coordination> = {};\n /** The built-in `understand` coordination, when one is active. */\n understand: Coordination | null = null;\n\n private readonly conversation: Conversation;\n private readonly agents: () => Agent[];\n private readonly llm: () => LLM | undefined;\n private readonly history: ConversationHistory;\n private readonly historyWindow: Parameters<ConversationHistory[\"windowed\"]>[0];\n private readonly speech: SpeechPipeline;\n private readonly generation: GenerationRunner;\n private readonly tools: ToolCallManager;\n private readonly maxCoordinationSteps: number;\n private readonly maxToolIterations: number;\n private readonly temperature: number | undefined;\n private readonly maxTokens: number | undefined;\n private readonly currentEpoch: () => number;\n private readonly isCurrent: (epoch: number) => boolean;\n\n private coordinationEpoch = 0;\n private coordinationStepCount = 0;\n private coordinationRunId = \"\";\n private pendingExecution: PendingExecution | null = null;\n\n constructor(options: CoordinationRunnerOptions) {\n this.conversation = options.conversation;\n this.agents = options.agents;\n this.llm = options.llm;\n this.history = options.history;\n this.historyWindow = options.historyWindow;\n this.speech = options.speech;\n this.generation = options.generation;\n this.tools = options.tools;\n this.maxCoordinationSteps = options.maxCoordinationSteps;\n this.maxToolIterations = options.maxToolIterations;\n this.temperature = options.temperature;\n this.maxTokens = options.maxTokens;\n this.currentEpoch = options.currentEpoch;\n this.isCurrent = options.isCurrent;\n }\n\n /**\n * Register coordinations by name. The built-in `understand` runs unaddressed\n * turns: it decides whether to delegate to agents, ask the user, or answer\n * directly. Apps can override it by registering their own \"understand\" key,\n * and add their own (e.g. clarify, review).\n */\n register(\n registrations: Record<string, CoordinationRegistration>,\n agents: readonly Agent[],\n ): void {\n const merged: Record<string, CoordinationRegistration> = {\n ...registrations,\n };\n if (agents.length > 1 && !merged.understand) {\n merged.understand = { prompt: buildUnderstandPrompt(agents) };\n }\n for (const [name, registration] of Object.entries(merged)) {\n this.coordinations[name] = new Coordination(\n { name, ...registration },\n this.runtime(),\n );\n }\n this.understand = this.coordinations[\"understand\"] ?? null;\n }\n\n /** True while a coordination is parked waiting for the user to answer. */\n hasPending(): boolean {\n return this.pendingExecution !== null;\n }\n\n /** Drop a parked execution (interrupt, stop). */\n cancel(): void {\n this.pendingExecution = null;\n }\n\n /**\n * Run the built-in `understand` coordination on an unaddressed turn. A\n * streaming generation is opened for the conversation's default agent; the\n * coordination's final answer (or question) completes it.\n */\n async runDefault(turn: Turn): Promise<void> {\n const understand = this.understand;\n const llm = this.llm();\n if (!understand || !llm) return;\n this.coordinationEpoch = this.currentEpoch();\n this.coordinationStepCount = 0;\n this.coordinationRunId = crypto.randomUUID();\n await this.conversation.pushGeneration({\n id: this.coordinationRunId,\n conversationId: this.conversation.id,\n agentName: this.agents()[0]!.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n });\n\n try {\n // The current turn is already in history, so no separate input message.\n const output = await understand.run();\n await this.finalizeOutput(String(output));\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n await this.recordSuspension(error);\n } else if (error instanceof CoordinationCancelled) {\n // Discarded by an interrupt \u2014 nothing to finalize.\n } else {\n this.emitError(error);\n }\n }\n }\n\n /**\n * Resume a parked coordination with the user's answer, propagating the\n * result back up the frame stack to the outermost coordination.\n */\n async resume(turn: Turn): Promise<void> {\n const pending = this.pendingExecution;\n if (!pending) return;\n this.pendingExecution = null;\n this.coordinationEpoch = this.currentEpoch();\n this.coordinationStepCount = pending.stepCount;\n this.coordinationRunId = crypto.randomUUID();\n await this.conversation.pushGeneration({\n id: this.coordinationRunId,\n conversationId: this.conversation.id,\n agentName: this.agents()[0]!.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n });\n\n const frames = [...pending.frames]; // outermost first\n const innermost = frames.pop();\n if (!innermost) return;\n\n let result: unknown;\n try {\n result = await innermost.coordination.resume(innermost.state, turn.text);\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift(...frames);\n await this.recordSuspension(error);\n } else if (!(error instanceof CoordinationCancelled)) {\n this.emitError(error);\n }\n return;\n }\n\n // Feed the result back into each remaining parent frame, innermost first.\n while (frames.length > 0) {\n const parent = frames.pop()!;\n const toolCallId = parent.state.pendingToolCallId ?? crypto.randomUUID();\n try {\n result = await parent.coordination.continueWith(parent.state, {\n role: \"tool\",\n toolCallId,\n name: \"delegate\",\n content: JSON.stringify(result),\n });\n } catch (error) {\n if (error instanceof CoordinationSuspension) {\n error.frames.unshift(...frames);\n await this.recordSuspension(error);\n } else if (!(error instanceof CoordinationCancelled)) {\n this.emitError(error);\n }\n return;\n }\n }\n\n await this.finalizeOutput(String(result));\n }\n\n /**\n * The runtime the coordinations reason against. Binds the coordination\n * primitives (delegate to agents, ask the user, speech, budget, cancellation)\n * to the runner's machinery without coupling `Coordination` to it.\n */\n runtime(): CoordinationRuntime {\n const runner = this;\n return {\n // Getters: read the current state at call time (the coordinations are\n // built after the runtime object is created).\n get agents() {\n return runner.agents();\n },\n get coordinations() {\n return Object.values(runner.coordinations);\n },\n get llm() {\n return runner.llm()!;\n },\n get history() {\n return runner.history.windowed(runner.historyWindow);\n },\n delegateAgentTasks: (tasks) => this.delegateAgentTasks(tasks),\n askUser: (frame, question) => this.askUser(frame, question),\n onDelta: (delta) => this.speech.feed(delta, this.currentEpoch()),\n flushSpeech: () => this.speech.flush(this.currentEpoch()),\n speak: (sentence) => this.speech.speak(sentence, this.currentEpoch()),\n isCancelled: () => this.currentEpoch() !== this.coordinationEpoch,\n checkBudget: () => this.checkBudget(),\n };\n }\n\n /** Complete the current generation and record the coordination's answer. */\n private async finalizeOutput(text: string): Promise<void> {\n this.speech.flush(this.currentEpoch());\n await this.speech.waitForIdle();\n if (this.currentEpoch() !== this.coordinationEpoch) return;\n await this.conversation.completeGeneration(text);\n await this.conversation.pushTranscript({\n speaker: this.agents()[0]!.name,\n speakerKind: \"agent\",\n text,\n });\n this.history.addAssistant(this.agents()[0]!.name, text);\n }\n\n /** Park a suspended coordination: record the question and store the stack. */\n private async recordSuspension(suspension: CoordinationSuspension): Promise<void> {\n await this.conversation.completeGeneration(suspension.question);\n await this.conversation.pushTranscript({\n speaker: this.agents()[0]!.name,\n speakerKind: \"agent\",\n text: suspension.question,\n });\n this.history.addAssistant(this.agents()[0]!.name, suspension.question);\n this.pendingExecution = {\n frames: suspension.frames,\n question: suspension.question,\n stepCount: this.coordinationStepCount,\n };\n }\n\n /** Throw the suspension that parks a coordination waiting for the user. */\n private askUser(frame: PendingFrame, question: string): never {\n // Recording (transcript, history, generation) happens when the suspension\n // is caught at the top of the stack, where the full frame set is known.\n throw new CoordinationSuspension([frame], question);\n }\n\n /** Enforce the per-execution reasoning step budget. */\n private checkBudget(): void {\n this.coordinationStepCount++;\n if (this.coordinationStepCount > this.maxCoordinationSteps) {\n throw new CoordinationBudgetExceeded(\n `exceeded ${this.maxCoordinationSteps} coordination steps`,\n );\n }\n }\n\n private emitError(error: unknown): void {\n this.conversation.emit(\"error\", {\n conversationId: this.conversation.id,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n // Finalize the current coordination generation so an errored run does not\n // leave a dangling \"streaming\" record. The narration was streamed to\n // speech; the failure surfaces through the error event.\n if (this.currentEpoch() === this.coordinationEpoch) {\n void this.conversation.completeGeneration(\"\");\n }\n }\n\n /** Run delegated agent tasks in parallel and surface their work. */\n private async delegateAgentTasks(tasks: DelegatedTask[]): Promise<DelegationResult[]> {\n const results = await Promise.all(\n tasks.map((task) =>\n this.runSubGeneration(this.coordinationEpoch, task, this.coordinationRunId),\n ),\n );\n\n if (!this.isCurrent(this.coordinationEpoch)) {\n return results.map(({ agent, text, error }) => ({ agent, text, error }));\n }\n\n // Surface each specialist's work in the transcript, in task order.\n for (const result of results) {\n if (result.text && !result.error) {\n await this.conversation.pushTranscript({\n speaker: result.agent,\n speakerKind: \"agent\",\n text: result.text,\n });\n }\n }\n return results;\n }\n\n /**\n * Execute one dispatched task as a sub-generation: the target agent's own\n * LLM, context, and tools, running text-only (no TTS). The final text is\n * returned so the coordinator can merge it into the spoken answer.\n */\n private async runSubGeneration(\n epoch: number,\n task: DelegatedTask,\n parentGenerationId: string,\n ): Promise<DelegationResult> {\n const agent = findAgentByName(this.agents(), task.agent);\n if (!agent) {\n return { agent: task.agent, text: \"\", error: `Unknown agent \"${task.agent}\"` };\n }\n const llm = agent.llm ?? this.llm();\n if (!llm) {\n return {\n agent: agent.name,\n text: \"\",\n error: `Agent \"${agent.name}\" has no LLM configured`,\n };\n }\n\n const id = crypto.randomUUID();\n await this.conversation.pushSubGeneration({\n id,\n conversationId: this.conversation.id,\n agentName: agent.name,\n text: \"\",\n status: \"streaming\",\n startedAt: Date.now(),\n kind: \"sub\",\n parentGenerationId,\n });\n\n const definitions: LLMToolDefinition[] = agent.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters ?? { type: \"object\", properties: {} },\n }));\n\n const messages: LLMMessage[] = [];\n if (agent.context) {\n messages.push({ role: \"system\", name: agent.name, content: agent.context });\n }\n messages.push(...this.history.windowed(this.historyWindow));\n // The prompt carries a time stamp so time-sensitive tasks (flights,\n // meetings, deadlines) don't reason about a stale \"now\".\n messages.push({ role: \"user\", content: `${task.prompt}\\n\\n${formatTimeContext()}` });\n\n const outcome = await this.generation.run({\n agentName: agent.name,\n llm,\n messages,\n tools: definitions,\n temperature: this.temperature,\n maxTokens: this.maxTokens,\n maxToolIterations: this.maxToolIterations,\n isCurrent: () => this.isCurrent(epoch),\n onDelta: (delta, textBefore) => {\n if (textBefore.length === 0) this.conversation.noteTiming(\"firstToken\", id);\n },\n resolveToolCalls: (calls) => this.tools.resolveCalls(calls),\n });\n\n if (!this.isCurrent(epoch) || outcome.status === \"interrupted\") {\n await this.conversation.cancelSubGeneration(id);\n return { agent: agent.name, text: \"\", error: \"interrupted\" };\n }\n\n await this.conversation.completeSubGeneration(id, outcome.text);\n if (outcome.status === \"error\") {\n this.conversation.emit(\"error\", {\n conversationId: this.conversation.id,\n error: outcome.error instanceof Error ? outcome.error : new Error(String(outcome.error)),\n });\n return {\n agent: agent.name,\n text: outcome.text,\n error: outcome.error instanceof Error ? outcome.error.message : String(outcome.error),\n };\n }\n return { agent: agent.name, text: outcome.text };\n }\n}\n"],
|
|
5
|
+
"mappings": "4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,IAAA,eAAAC,EAAAH,GAIA,IAAAI,EAUO,2CACPC,EAAuD,8BACvDC,EAAuD,8BA4ChD,MAAMC,CAAmB,CA5DhC,MA4DgC,CAAAC,EAAA,2BAErB,cAA8C,CAA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MAAM,KAAK,WAAW,IAAI,CACxC,UAAWP,EAAM,KACjB,IAAAnB,EACA,SAAAyB,EACA,MAAOF,EACP,YAAa,KAAK,YAClB,UAAW,KAAK,UAChB,kBAAmB,KAAK,kBACxB,UAAWhC,EAAA,IAAM,KAAK,UAAU6B,CAAK,EAA1B,aACX,QAAS7B,EAAA,CAACsB,EAAOc,IAAe,CAC1BA,EAAW,SAAW,GAAG,KAAK,aAAa,WAAW,aAAcL,CAAE,CAC5E,EAFS,WAGT,iBAAkB/B,EAACqC,GAAU,KAAK,MAAM,aAAaA,CAAK,EAAxC,mBACpB,CAAC,EAED,MAAI,CAAC,KAAK,UAAUR,CAAK,GAAKM,EAAQ,SAAW,eAC/C,MAAM,KAAK,aAAa,oBAAoBJ,CAAE,EACvC,CAAE,MAAOH,EAAM,KAAM,KAAM,GAAI,MAAO,aAAc,IAG7D,MAAM,KAAK,aAAa,sBAAsBG,EAAII,EAAQ,IAAI,EAC1DA,EAAQ,SAAW,SACrB,KAAK,aAAa,KAAK,QAAS,CAC9B,eAAgB,KAAK,aAAa,GAClC,MAAOA,EAAQ,iBAAiB,MAAQA,EAAQ,MAAQ,IAAI,MAAM,OAAOA,EAAQ,KAAK,CAAC,CACzF,CAAC,EACM,CACL,MAAOP,EAAM,KACb,KAAMO,EAAQ,KACd,MAAOA,EAAQ,iBAAiB,MAAQA,EAAQ,MAAM,QAAU,OAAOA,EAAQ,KAAK,CACtF,GAEK,CAAE,MAAOP,EAAM,KAAM,KAAMO,EAAQ,IAAK,EACjD,CACF",
|
|
6
|
+
"names": ["coordination_runner_exports", "__export", "CoordinationRunner", "__toCommonJS", "import_coordination", "import_history", "import_routing", "CoordinationRunner", "__name", "options", "registrations", "agents", "merged", "name", "registration", "turn", "understand", "llm", "output", "error", "pending", "frames", "innermost", "result", "parent", "toolCallId", "runner", "tasks", "frame", "question", "delta", "sentence", "text", "suspension", "results", "task", "agent", "epoch", "parentGenerationId", "id", "definitions", "tool", "messages", "outcome", "textBefore", "calls"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var t=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var f=(n,o)=>{for(var i in o)t(n,i,{get:o[i],enumerable:!0})},m=(n,o,i,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of d(o))!u.call(n,r)&&r!==i&&t(n,r,{get:()=>o[r],enumerable:!(e=a(o,r))||e.enumerable});return n};var x=n=>m(t({},"__esModule",{value:!0}),n);var C={};f(C,{CoordinationRunner:()=>p.CoordinationRunner});module.exports=x(C);var p=require("./coordination-runner.js");
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../../src/conversations/orchestration/orchestrator/coordination-runner/index.ts"],
|
|
4
|
+
"sourcesContent": ["export { CoordinationRunner } from \"./coordination-runner\";\nexport type { CoordinationRunnerOptions } from \"./coordination-runner\";\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8DAAAE,EAAAF,GAAA,IAAAG,EAAmC",
|
|
6
|
+
"names": ["coordination_runner_exports", "__export", "__toCommonJS", "import_coordination_runner"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var c=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var h=Object.prototype.hasOwnProperty;var p=(t,e)=>c(t,"name",{value:e,configurable:!0});var y=(t,e)=>{for(var a in e)c(t,a,{get:e[a],enumerable:!0})},v=(t,e,a,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of b(e))!h.call(t,o)&&o!==a&&c(t,o,{get:()=>e[o],enumerable:!(l=M(e,o))||l.enumerable});return t};var G=t=>v(c({},"__esModule",{value:!0}),t);var w={};y(w,{GenerationRunner:()=>k});module.exports=G(w);class k{static{p(this,"GenerationRunner")}async run(e){const{agentName:a,llm:l,messages:o,tools:d,temperature:L,maxTokens:g,maxToolIterations:T,isCurrent:i,onDelta:x,resolveToolCalls:C}=e;let n="";try{for(let u=0;u<T;u++){if(!i())return{text:n,status:"interrupted"};const m=[];let f=!1;for await(const r of l.stream({messages:o,tools:d,temperature:L,maxTokens:g})){if(!i())return{text:n,status:"interrupted"};switch(r.type){case"delta":{const s=n;n+=r.content,r.content.length>0&&x?.(r.content,s);break}case"tool_call":m.push({id:r.id,name:r.name,arguments:r.arguments});break;case"error":throw r.error;case"done":f=!0}}if(!i())return{text:n,status:"interrupted"};if(m.length>0){o.push({role:"assistant",name:a,content:n,toolCalls:m});const r=await C(m);if(!i())return{text:n,status:"interrupted"};for(const s of r)o.push({role:"tool",toolCallId:s.id,name:s.name,content:JSON.stringify(s.error!==void 0?{error:s.error}:s.result)});continue}if(f)break}return{text:n,status:"done"}}catch(u){return{text:n,status:"error",error:u}}}}
|
|
2
|
+
//# sourceMappingURL=generation.js.map
|