@falai/agent 3.4.4 → 4.0.0-alpha.1
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 +41 -34
- package/dist/cjs/core/Agent.d.ts +22 -378
- package/dist/cjs/core/Agent.d.ts.map +1 -1
- package/dist/cjs/core/Agent.js +104 -1178
- package/dist/cjs/core/Agent.js.map +1 -1
- package/dist/cjs/core/CompactionEngine.d.ts.map +1 -1
- package/dist/cjs/core/CompactionEngine.js +5 -3
- package/dist/cjs/core/CompactionEngine.js.map +1 -1
- package/dist/cjs/core/FlowSpec.d.ts +136 -0
- package/dist/cjs/core/FlowSpec.d.ts.map +1 -0
- package/dist/cjs/core/FlowSpec.js +522 -0
- package/dist/cjs/core/FlowSpec.js.map +1 -0
- package/dist/cjs/core/Migrate.d.ts +38 -0
- package/dist/cjs/core/Migrate.d.ts.map +1 -0
- package/dist/cjs/core/Migrate.js +270 -0
- package/dist/cjs/core/Migrate.js.map +1 -0
- package/dist/cjs/core/Prompt.d.ts +54 -0
- package/dist/cjs/core/Prompt.d.ts.map +1 -0
- package/dist/cjs/core/Prompt.js +143 -0
- package/dist/cjs/core/Prompt.js.map +1 -0
- package/dist/cjs/core/Runner.d.ts +160 -0
- package/dist/cjs/core/Runner.d.ts.map +1 -0
- package/dist/cjs/core/Runner.js +1131 -0
- package/dist/cjs/core/Runner.js.map +1 -0
- package/dist/cjs/core/Speak.d.ts +37 -0
- package/dist/cjs/core/Speak.d.ts.map +1 -0
- package/dist/cjs/core/Speak.js +364 -0
- package/dist/cjs/core/Speak.js.map +1 -0
- package/dist/cjs/core/Understand.d.ts +28 -0
- package/dist/cjs/core/Understand.d.ts.map +1 -0
- package/dist/cjs/core/Understand.js +353 -0
- package/dist/cjs/core/Understand.js.map +1 -0
- package/dist/cjs/core/contracts.d.ts +122 -0
- package/dist/cjs/core/contracts.d.ts.map +1 -0
- package/dist/cjs/core/contracts.js +11 -0
- package/dist/cjs/core/contracts.js.map +1 -0
- package/dist/cjs/core/falai.d.ts +57 -0
- package/dist/cjs/core/falai.d.ts.map +1 -0
- package/dist/cjs/core/falai.js +43 -0
- package/dist/cjs/core/falai.js.map +1 -0
- package/dist/cjs/core/predicate.d.ts +9 -0
- package/dist/cjs/core/predicate.d.ts.map +1 -0
- package/dist/cjs/core/predicate.js +58 -0
- package/dist/cjs/core/predicate.js.map +1 -0
- package/dist/cjs/index.d.ts +26 -31
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +46 -68
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/persistence/MemoryStore.d.ts +15 -0
- package/dist/cjs/persistence/MemoryStore.d.ts.map +1 -0
- package/dist/cjs/persistence/MemoryStore.js +39 -0
- package/dist/cjs/persistence/MemoryStore.js.map +1 -0
- package/dist/cjs/persistence/MongoStore.d.ts +42 -0
- package/dist/cjs/persistence/MongoStore.d.ts.map +1 -0
- package/dist/cjs/persistence/MongoStore.js +60 -0
- package/dist/cjs/persistence/MongoStore.js.map +1 -0
- package/dist/cjs/persistence/OpenSearchStore.d.ts +86 -0
- package/dist/cjs/persistence/OpenSearchStore.d.ts.map +1 -0
- package/dist/cjs/persistence/OpenSearchStore.js +120 -0
- package/dist/cjs/persistence/OpenSearchStore.js.map +1 -0
- package/dist/cjs/persistence/PostgresStore.d.ts +41 -0
- package/dist/cjs/persistence/PostgresStore.d.ts.map +1 -0
- package/dist/cjs/persistence/PostgresStore.js +58 -0
- package/dist/cjs/persistence/PostgresStore.js.map +1 -0
- package/dist/cjs/persistence/PrismaStore.d.ts +65 -0
- package/dist/cjs/persistence/PrismaStore.d.ts.map +1 -0
- package/dist/cjs/persistence/PrismaStore.js +95 -0
- package/dist/cjs/persistence/PrismaStore.js.map +1 -0
- package/dist/cjs/persistence/RedisStore.d.ts +34 -0
- package/dist/cjs/persistence/RedisStore.d.ts.map +1 -0
- package/dist/cjs/persistence/RedisStore.js +61 -0
- package/dist/cjs/persistence/RedisStore.js.map +1 -0
- package/dist/cjs/persistence/SQLiteStore.d.ts +45 -0
- package/dist/cjs/persistence/SQLiteStore.d.ts.map +1 -0
- package/dist/cjs/persistence/SQLiteStore.js +74 -0
- package/dist/cjs/persistence/SQLiteStore.js.map +1 -0
- package/dist/cjs/persistence/sessionRow.d.ts +14 -0
- package/dist/cjs/persistence/sessionRow.d.ts.map +1 -0
- package/dist/cjs/persistence/sessionRow.js +50 -0
- package/dist/cjs/persistence/sessionRow.js.map +1 -0
- package/dist/cjs/providers/DeepSeekProvider.d.ts.map +1 -1
- package/dist/cjs/providers/DeepSeekProvider.js +8 -3
- package/dist/cjs/providers/DeepSeekProvider.js.map +1 -1
- package/dist/cjs/providers/GeminiProvider.d.ts +4 -3
- package/dist/cjs/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/cjs/providers/GeminiProvider.js +4 -3
- package/dist/cjs/providers/GeminiProvider.js.map +1 -1
- package/dist/cjs/providers/OpenAICompatibleProvider.d.ts +4 -0
- package/dist/cjs/providers/OpenAICompatibleProvider.d.ts.map +1 -1
- package/dist/cjs/providers/OpenAICompatibleProvider.js +2 -0
- package/dist/cjs/providers/OpenAICompatibleProvider.js.map +1 -1
- package/dist/cjs/providers/OpenRouterProvider.d.ts.map +1 -1
- package/dist/cjs/providers/OpenRouterProvider.js +2 -4
- package/dist/cjs/providers/OpenRouterProvider.js.map +1 -1
- package/dist/cjs/providers/ProviderAdapter.d.ts +1 -1
- package/dist/cjs/providers/ProviderAdapter.d.ts.map +1 -1
- package/dist/cjs/providers/ProviderAdapter.js +33 -10
- package/dist/cjs/providers/ProviderAdapter.js.map +1 -1
- package/dist/cjs/types/agent.d.ts +153 -383
- package/dist/cjs/types/agent.d.ts.map +1 -1
- package/dist/cjs/types/agent.js +1 -1
- package/dist/cjs/types/ai.d.ts +32 -1
- package/dist/cjs/types/ai.d.ts.map +1 -1
- package/dist/cjs/types/compaction.d.ts +3 -1
- package/dist/cjs/types/compaction.d.ts.map +1 -1
- package/dist/cjs/types/errors.d.ts +9 -12
- package/dist/cjs/types/errors.d.ts.map +1 -1
- package/dist/cjs/types/errors.js +14 -17
- package/dist/cjs/types/errors.js.map +1 -1
- package/dist/cjs/types/flow.d.ts +265 -513
- package/dist/cjs/types/flow.d.ts.map +1 -1
- package/dist/cjs/types/flow.js +7 -1
- package/dist/cjs/types/flow.js.map +1 -1
- package/dist/cjs/types/history.d.ts +7 -18
- package/dist/cjs/types/history.d.ts.map +1 -1
- package/dist/cjs/types/history.js.map +1 -1
- package/dist/cjs/types/index.d.ts +9 -15
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +4 -14
- package/dist/cjs/types/index.js.map +1 -1
- package/dist/cjs/types/session.d.ts +94 -64
- package/dist/cjs/types/session.d.ts.map +1 -1
- package/dist/cjs/types/session.js +5 -1
- package/dist/cjs/types/session.js.map +1 -1
- package/dist/cjs/types/tool.d.ts +37 -207
- package/dist/cjs/types/tool.d.ts.map +1 -1
- package/dist/cjs/types/tool.js +5 -14
- package/dist/cjs/types/tool.js.map +1 -1
- package/dist/cjs/utils/clock.d.ts +28 -0
- package/dist/cjs/utils/clock.d.ts.map +1 -0
- package/dist/cjs/utils/clock.js +64 -0
- package/dist/cjs/utils/clock.js.map +1 -0
- package/dist/cjs/utils/duration.d.ts +11 -0
- package/dist/cjs/utils/duration.d.ts.map +1 -0
- package/dist/cjs/utils/duration.js +31 -0
- package/dist/cjs/utils/duration.js.map +1 -0
- package/dist/cjs/utils/history.d.ts +4 -1
- package/dist/cjs/utils/history.d.ts.map +1 -1
- package/dist/cjs/utils/history.js +2 -2
- package/dist/cjs/utils/history.js.map +1 -1
- package/dist/cjs/utils/index.d.ts +4 -10
- package/dist/cjs/utils/index.d.ts.map +1 -1
- package/dist/cjs/utils/index.js +14 -61
- package/dist/cjs/utils/index.js.map +1 -1
- package/dist/cjs/utils/json.d.ts +2 -0
- package/dist/cjs/utils/json.d.ts.map +1 -1
- package/dist/cjs/utils/json.js +5 -0
- package/dist/cjs/utils/json.js.map +1 -1
- package/dist/cjs/utils/outcomes.d.ts +48 -0
- package/dist/cjs/utils/outcomes.d.ts.map +1 -0
- package/dist/cjs/utils/outcomes.js +51 -0
- package/dist/cjs/utils/outcomes.js.map +1 -0
- package/dist/cjs/utils/schema.d.ts +50 -0
- package/dist/cjs/utils/schema.d.ts.map +1 -0
- package/dist/cjs/utils/schema.js +138 -0
- package/dist/cjs/utils/schema.js.map +1 -0
- package/dist/cjs/utils/streamingMessage.d.ts +3 -2
- package/dist/cjs/utils/streamingMessage.d.ts.map +1 -1
- package/dist/cjs/utils/streamingMessage.js +38 -4
- package/dist/cjs/utils/streamingMessage.js.map +1 -1
- package/dist/cjs/utils/template.d.ts +13 -149
- package/dist/cjs/utils/template.d.ts.map +1 -1
- package/dist/cjs/utils/template.js +31 -363
- package/dist/cjs/utils/template.js.map +1 -1
- package/dist/cjs/utils/usage.d.ts +19 -0
- package/dist/cjs/utils/usage.d.ts.map +1 -0
- package/dist/cjs/utils/usage.js +35 -0
- package/dist/cjs/utils/usage.js.map +1 -0
- package/dist/core/Agent.d.ts +22 -378
- package/dist/core/Agent.d.ts.map +1 -1
- package/dist/core/Agent.js +107 -1181
- package/dist/core/Agent.js.map +1 -1
- package/dist/core/CompactionEngine.d.ts.map +1 -1
- package/dist/core/CompactionEngine.js +5 -3
- package/dist/core/CompactionEngine.js.map +1 -1
- package/dist/core/FlowSpec.d.ts +136 -0
- package/dist/core/FlowSpec.d.ts.map +1 -0
- package/dist/core/FlowSpec.js +516 -0
- package/dist/core/FlowSpec.js.map +1 -0
- package/dist/core/Migrate.d.ts +38 -0
- package/dist/core/Migrate.d.ts.map +1 -0
- package/dist/core/Migrate.js +264 -0
- package/dist/core/Migrate.js.map +1 -0
- package/dist/core/Prompt.d.ts +54 -0
- package/dist/core/Prompt.d.ts.map +1 -0
- package/dist/core/Prompt.js +133 -0
- package/dist/core/Prompt.js.map +1 -0
- package/dist/core/Runner.d.ts +160 -0
- package/dist/core/Runner.d.ts.map +1 -0
- package/dist/core/Runner.js +1127 -0
- package/dist/core/Runner.js.map +1 -0
- package/dist/core/Speak.d.ts +37 -0
- package/dist/core/Speak.d.ts.map +1 -0
- package/dist/core/Speak.js +360 -0
- package/dist/core/Speak.js.map +1 -0
- package/dist/core/Understand.d.ts +28 -0
- package/dist/core/Understand.d.ts.map +1 -0
- package/dist/core/Understand.js +349 -0
- package/dist/core/Understand.js.map +1 -0
- package/dist/core/contracts.d.ts +122 -0
- package/dist/core/contracts.d.ts.map +1 -0
- package/dist/core/contracts.js +10 -0
- package/dist/core/contracts.js.map +1 -0
- package/dist/core/falai.d.ts +57 -0
- package/dist/core/falai.d.ts.map +1 -0
- package/dist/core/falai.js +40 -0
- package/dist/core/falai.js.map +1 -0
- package/dist/core/predicate.d.ts +9 -0
- package/dist/core/predicate.d.ts.map +1 -0
- package/dist/core/predicate.js +54 -0
- package/dist/core/predicate.js.map +1 -0
- package/dist/index.d.ts +26 -31
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +19 -24
- package/dist/index.js.map +1 -1
- package/dist/persistence/MemoryStore.d.ts +15 -0
- package/dist/persistence/MemoryStore.d.ts.map +1 -0
- package/dist/persistence/MemoryStore.js +35 -0
- package/dist/persistence/MemoryStore.js.map +1 -0
- package/dist/persistence/MongoStore.d.ts +42 -0
- package/dist/persistence/MongoStore.d.ts.map +1 -0
- package/dist/persistence/MongoStore.js +56 -0
- package/dist/persistence/MongoStore.js.map +1 -0
- package/dist/persistence/OpenSearchStore.d.ts +86 -0
- package/dist/persistence/OpenSearchStore.d.ts.map +1 -0
- package/dist/persistence/OpenSearchStore.js +116 -0
- package/dist/persistence/OpenSearchStore.js.map +1 -0
- package/dist/persistence/PostgresStore.d.ts +41 -0
- package/dist/persistence/PostgresStore.d.ts.map +1 -0
- package/dist/persistence/PostgresStore.js +54 -0
- package/dist/persistence/PostgresStore.js.map +1 -0
- package/dist/persistence/PrismaStore.d.ts +65 -0
- package/dist/persistence/PrismaStore.d.ts.map +1 -0
- package/dist/persistence/PrismaStore.js +91 -0
- package/dist/persistence/PrismaStore.js.map +1 -0
- package/dist/persistence/RedisStore.d.ts +34 -0
- package/dist/persistence/RedisStore.d.ts.map +1 -0
- package/dist/persistence/RedisStore.js +57 -0
- package/dist/persistence/RedisStore.js.map +1 -0
- package/dist/persistence/SQLiteStore.d.ts +45 -0
- package/dist/persistence/SQLiteStore.d.ts.map +1 -0
- package/dist/persistence/SQLiteStore.js +70 -0
- package/dist/persistence/SQLiteStore.js.map +1 -0
- package/dist/persistence/sessionRow.d.ts +14 -0
- package/dist/persistence/sessionRow.d.ts.map +1 -0
- package/dist/persistence/sessionRow.js +45 -0
- package/dist/persistence/sessionRow.js.map +1 -0
- package/dist/providers/DeepSeekProvider.d.ts.map +1 -1
- package/dist/providers/DeepSeekProvider.js +8 -3
- package/dist/providers/DeepSeekProvider.js.map +1 -1
- package/dist/providers/GeminiProvider.d.ts +4 -3
- package/dist/providers/GeminiProvider.d.ts.map +1 -1
- package/dist/providers/GeminiProvider.js +4 -3
- package/dist/providers/GeminiProvider.js.map +1 -1
- package/dist/providers/OpenAICompatibleProvider.d.ts +4 -0
- package/dist/providers/OpenAICompatibleProvider.d.ts.map +1 -1
- package/dist/providers/OpenAICompatibleProvider.js +2 -0
- package/dist/providers/OpenAICompatibleProvider.js.map +1 -1
- package/dist/providers/OpenRouterProvider.d.ts.map +1 -1
- package/dist/providers/OpenRouterProvider.js +2 -4
- package/dist/providers/OpenRouterProvider.js.map +1 -1
- package/dist/providers/ProviderAdapter.d.ts +1 -1
- package/dist/providers/ProviderAdapter.d.ts.map +1 -1
- package/dist/providers/ProviderAdapter.js +34 -11
- package/dist/providers/ProviderAdapter.js.map +1 -1
- package/dist/types/agent.d.ts +153 -383
- package/dist/types/agent.d.ts.map +1 -1
- package/dist/types/agent.js +1 -1
- package/dist/types/ai.d.ts +32 -1
- package/dist/types/ai.d.ts.map +1 -1
- package/dist/types/compaction.d.ts +3 -1
- package/dist/types/compaction.d.ts.map +1 -1
- package/dist/types/errors.d.ts +9 -12
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +12 -15
- package/dist/types/errors.js.map +1 -1
- package/dist/types/flow.d.ts +265 -513
- package/dist/types/flow.d.ts.map +1 -1
- package/dist/types/flow.js +7 -1
- package/dist/types/flow.js.map +1 -1
- package/dist/types/history.d.ts +7 -18
- package/dist/types/history.d.ts.map +1 -1
- package/dist/types/history.js.map +1 -1
- package/dist/types/index.d.ts +9 -15
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +2 -7
- package/dist/types/index.js.map +1 -1
- package/dist/types/session.d.ts +94 -64
- package/dist/types/session.d.ts.map +1 -1
- package/dist/types/session.js +5 -1
- package/dist/types/session.js.map +1 -1
- package/dist/types/tool.d.ts +37 -207
- package/dist/types/tool.d.ts.map +1 -1
- package/dist/types/tool.js +6 -13
- package/dist/types/tool.js.map +1 -1
- package/dist/utils/clock.d.ts +28 -0
- package/dist/utils/clock.d.ts.map +1 -0
- package/dist/utils/clock.js +59 -0
- package/dist/utils/clock.js.map +1 -0
- package/dist/utils/duration.d.ts +11 -0
- package/dist/utils/duration.d.ts.map +1 -0
- package/dist/utils/duration.js +26 -0
- package/dist/utils/duration.js.map +1 -0
- package/dist/utils/history.d.ts +4 -1
- package/dist/utils/history.d.ts.map +1 -1
- package/dist/utils/history.js +2 -2
- package/dist/utils/history.js.map +1 -1
- package/dist/utils/index.d.ts +4 -10
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +4 -21
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/json.d.ts +2 -0
- package/dist/utils/json.d.ts.map +1 -1
- package/dist/utils/json.js +4 -0
- package/dist/utils/json.js.map +1 -1
- package/dist/utils/outcomes.d.ts +48 -0
- package/dist/utils/outcomes.d.ts.map +1 -0
- package/dist/utils/outcomes.js +48 -0
- package/dist/utils/outcomes.js.map +1 -0
- package/dist/utils/schema.d.ts +50 -0
- package/dist/utils/schema.d.ts.map +1 -0
- package/dist/utils/schema.js +129 -0
- package/dist/utils/schema.js.map +1 -0
- package/dist/utils/streamingMessage.d.ts +3 -2
- package/dist/utils/streamingMessage.d.ts.map +1 -1
- package/dist/utils/streamingMessage.js +38 -4
- package/dist/utils/streamingMessage.js.map +1 -1
- package/dist/utils/template.d.ts +13 -149
- package/dist/utils/template.d.ts.map +1 -1
- package/dist/utils/template.js +28 -355
- package/dist/utils/template.js.map +1 -1
- package/dist/utils/usage.d.ts +19 -0
- package/dist/utils/usage.d.ts.map +1 -0
- package/dist/utils/usage.js +31 -0
- package/dist/utils/usage.js.map +1 -0
- package/docs/README.md +37 -19
- package/docs/concepts/architecture.md +117 -239
- package/docs/concepts/collection.md +170 -0
- package/docs/concepts/pipeline.md +132 -378
- package/docs/concepts/runs-and-waits.md +192 -0
- package/docs/guides/actions-and-events.md +276 -0
- package/docs/guides/branching.md +119 -208
- package/docs/guides/compaction.md +63 -158
- package/docs/guides/conditions.md +164 -128
- package/docs/guides/error-handling.md +168 -164
- package/docs/guides/flow-control.md +210 -349
- package/docs/guides/flows-from-json.md +224 -0
- package/docs/guides/instructions.md +125 -161
- package/docs/guides/persistence.md +182 -206
- package/docs/guides/streaming.md +50 -114
- package/docs/guides/testing.md +284 -0
- package/docs/guides/triggers.md +401 -0
- package/docs/migration/README.md +8 -15
- package/docs/migration/v1-to-v2.md +1 -1
- package/docs/migration/v2-3-to-v2-4.md +2 -2
- package/docs/migration/v2-6-to-v2-7.md +4 -4
- package/docs/migration/v3-to-v4.md +452 -0
- package/docs/reference/actions-events-conditions.md +396 -0
- package/docs/reference/agent.md +244 -0
- package/docs/reference/branches.md +75 -203
- package/docs/reference/errors.md +188 -144
- package/docs/reference/fields.md +125 -0
- package/docs/reference/flow-spec.md +248 -0
- package/docs/reference/flow.md +104 -192
- package/docs/reference/instruction.md +83 -137
- package/docs/reference/outcomes.md +273 -0
- package/docs/reference/providers.md +525 -302
- package/docs/reference/session.md +210 -0
- package/docs/reference/step.md +194 -312
- package/docs/reference/stores.md +496 -0
- package/docs/reference/tool.md +162 -231
- package/docs/reference/trigger.md +180 -0
- package/docs/rfc/v4-one-flow.md +477 -0
- package/docs/start/01-install.md +59 -44
- package/docs/start/02-first-agent.md +97 -147
- package/docs/start/03-collect-data.md +78 -183
- package/docs/start/04-add-tools.md +159 -227
- package/docs/start/05-go-to-production.md +167 -164
- package/examples/01-quickstart.ts +26 -16
- package/examples/02-fields.ts +75 -0
- package/examples/03-tools.ts +79 -119
- package/examples/04-instructions.ts +60 -87
- package/examples/05-branches.ts +78 -0
- package/examples/06-triggers-and-waits.ts +148 -0
- package/examples/07-streaming.ts +34 -60
- package/examples/08-store-and-migration.ts +97 -0
- package/examples/09-flows-from-json.ts +107 -0
- package/package.json +9 -6
- package/src/core/Agent.ts +116 -1512
- package/src/core/CompactionEngine.ts +7 -4
- package/src/core/FlowSpec.ts +712 -0
- package/src/core/Migrate.ts +256 -0
- package/src/core/Prompt.ts +156 -0
- package/src/core/Runner.ts +1181 -0
- package/src/core/Speak.ts +451 -0
- package/src/core/Understand.ts +422 -0
- package/src/core/contracts.ts +111 -0
- package/src/core/falai.ts +86 -0
- package/src/core/predicate.ts +56 -0
- package/src/index.ts +119 -147
- package/src/persistence/MemoryStore.ts +37 -0
- package/src/persistence/MongoStore.ts +89 -0
- package/src/persistence/OpenSearchStore.ts +153 -0
- package/src/persistence/PostgresStore.ts +89 -0
- package/src/persistence/PrismaStore.ts +127 -0
- package/src/persistence/RedisStore.ts +90 -0
- package/src/persistence/SQLiteStore.ts +103 -0
- package/src/persistence/sessionRow.ts +45 -0
- package/src/providers/DeepSeekProvider.ts +8 -3
- package/src/providers/GeminiProvider.ts +4 -3
- package/src/providers/OpenAICompatibleProvider.ts +6 -0
- package/src/providers/OpenRouterProvider.ts +2 -4
- package/src/providers/ProviderAdapter.ts +36 -8
- package/src/types/agent.ts +124 -397
- package/src/types/ai.ts +33 -1
- package/src/types/compaction.ts +3 -1
- package/src/types/errors.ts +13 -16
- package/src/types/flow.ts +249 -550
- package/src/types/history.ts +7 -20
- package/src/types/index.ts +87 -139
- package/src/types/session.ts +135 -70
- package/src/types/tool.ts +42 -267
- package/src/utils/clock.ts +70 -0
- package/src/utils/duration.ts +33 -0
- package/src/utils/history.ts +3 -2
- package/src/utils/index.ts +8 -66
- package/src/utils/json.ts +5 -0
- package/src/utils/outcomes.ts +56 -0
- package/src/utils/schema.ts +145 -0
- package/src/utils/streamingMessage.ts +34 -4
- package/src/utils/template.ts +32 -423
- package/src/utils/usage.ts +37 -0
- package/dist/adapters/MemoryAdapter.d.ts +0 -47
- package/dist/adapters/MemoryAdapter.d.ts.map +0 -1
- package/dist/adapters/MemoryAdapter.js +0 -204
- package/dist/adapters/MemoryAdapter.js.map +0 -1
- package/dist/adapters/MongoAdapter.d.ts +0 -97
- package/dist/adapters/MongoAdapter.d.ts.map +0 -1
- package/dist/adapters/MongoAdapter.js +0 -196
- package/dist/adapters/MongoAdapter.js.map +0 -1
- package/dist/adapters/OpenSearchAdapter.d.ts +0 -169
- package/dist/adapters/OpenSearchAdapter.d.ts.map +0 -1
- package/dist/adapters/OpenSearchAdapter.js +0 -471
- package/dist/adapters/OpenSearchAdapter.js.map +0 -1
- package/dist/adapters/PostgreSQLAdapter.d.ts +0 -85
- package/dist/adapters/PostgreSQLAdapter.d.ts.map +0 -1
- package/dist/adapters/PostgreSQLAdapter.js +0 -308
- package/dist/adapters/PostgreSQLAdapter.js.map +0 -1
- package/dist/adapters/PrismaAdapter.d.ts +0 -115
- package/dist/adapters/PrismaAdapter.d.ts.map +0 -1
- package/dist/adapters/PrismaAdapter.js +0 -406
- package/dist/adapters/PrismaAdapter.js.map +0 -1
- package/dist/adapters/RedisAdapter.d.ts +0 -72
- package/dist/adapters/RedisAdapter.d.ts.map +0 -1
- package/dist/adapters/RedisAdapter.js +0 -286
- package/dist/adapters/RedisAdapter.js.map +0 -1
- package/dist/adapters/SQLiteAdapter.d.ts +0 -86
- package/dist/adapters/SQLiteAdapter.d.ts.map +0 -1
- package/dist/adapters/SQLiteAdapter.js +0 -337
- package/dist/adapters/SQLiteAdapter.js.map +0 -1
- package/dist/adapters/index.d.ts +0 -17
- package/dist/adapters/index.d.ts.map +0 -1
- package/dist/adapters/index.js +0 -11
- package/dist/adapters/index.js.map +0 -1
- package/dist/adapters/sessionRow.d.ts +0 -22
- package/dist/adapters/sessionRow.d.ts.map +0 -1
- package/dist/adapters/sessionRow.js +0 -48
- package/dist/adapters/sessionRow.js.map +0 -1
- package/dist/cjs/adapters/MemoryAdapter.d.ts +0 -47
- package/dist/cjs/adapters/MemoryAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/MemoryAdapter.js +0 -208
- package/dist/cjs/adapters/MemoryAdapter.js.map +0 -1
- package/dist/cjs/adapters/MongoAdapter.d.ts +0 -97
- package/dist/cjs/adapters/MongoAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/MongoAdapter.js +0 -200
- package/dist/cjs/adapters/MongoAdapter.js.map +0 -1
- package/dist/cjs/adapters/OpenSearchAdapter.d.ts +0 -169
- package/dist/cjs/adapters/OpenSearchAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/OpenSearchAdapter.js +0 -475
- package/dist/cjs/adapters/OpenSearchAdapter.js.map +0 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.d.ts +0 -85
- package/dist/cjs/adapters/PostgreSQLAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/PostgreSQLAdapter.js +0 -312
- package/dist/cjs/adapters/PostgreSQLAdapter.js.map +0 -1
- package/dist/cjs/adapters/PrismaAdapter.d.ts +0 -115
- package/dist/cjs/adapters/PrismaAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/PrismaAdapter.js +0 -410
- package/dist/cjs/adapters/PrismaAdapter.js.map +0 -1
- package/dist/cjs/adapters/RedisAdapter.d.ts +0 -72
- package/dist/cjs/adapters/RedisAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/RedisAdapter.js +0 -290
- package/dist/cjs/adapters/RedisAdapter.js.map +0 -1
- package/dist/cjs/adapters/SQLiteAdapter.d.ts +0 -86
- package/dist/cjs/adapters/SQLiteAdapter.d.ts.map +0 -1
- package/dist/cjs/adapters/SQLiteAdapter.js +0 -341
- package/dist/cjs/adapters/SQLiteAdapter.js.map +0 -1
- package/dist/cjs/adapters/index.d.ts +0 -17
- package/dist/cjs/adapters/index.d.ts.map +0 -1
- package/dist/cjs/adapters/index.js +0 -21
- package/dist/cjs/adapters/index.js.map +0 -1
- package/dist/cjs/adapters/sessionRow.d.ts +0 -22
- package/dist/cjs/adapters/sessionRow.d.ts.map +0 -1
- package/dist/cjs/adapters/sessionRow.js +0 -52
- package/dist/cjs/adapters/sessionRow.js.map +0 -1
- package/dist/cjs/constants/index.d.ts +0 -1
- package/dist/cjs/constants/index.d.ts.map +0 -1
- package/dist/cjs/constants/index.js +0 -4
- package/dist/cjs/constants/index.js.map +0 -1
- package/dist/cjs/core/AutoChainExecutor.d.ts +0 -97
- package/dist/cjs/core/AutoChainExecutor.d.ts.map +0 -1
- package/dist/cjs/core/AutoChainExecutor.js +0 -288
- package/dist/cjs/core/AutoChainExecutor.js.map +0 -1
- package/dist/cjs/core/BranchEvaluator.d.ts +0 -55
- package/dist/cjs/core/BranchEvaluator.d.ts.map +0 -1
- package/dist/cjs/core/BranchEvaluator.js +0 -125
- package/dist/cjs/core/BranchEvaluator.js.map +0 -1
- package/dist/cjs/core/DirectiveChainTracker.d.ts +0 -49
- package/dist/cjs/core/DirectiveChainTracker.d.ts.map +0 -1
- package/dist/cjs/core/DirectiveChainTracker.js +0 -121
- package/dist/cjs/core/DirectiveChainTracker.js.map +0 -1
- package/dist/cjs/core/Events.d.ts +0 -26
- package/dist/cjs/core/Events.d.ts.map +0 -1
- package/dist/cjs/core/Events.js +0 -144
- package/dist/cjs/core/Events.js.map +0 -1
- package/dist/cjs/core/Flow.d.ts +0 -183
- package/dist/cjs/core/Flow.d.ts.map +0 -1
- package/dist/cjs/core/Flow.js +0 -551
- package/dist/cjs/core/Flow.js.map +0 -1
- package/dist/cjs/core/FlowRouter.d.ts +0 -183
- package/dist/cjs/core/FlowRouter.d.ts.map +0 -1
- package/dist/cjs/core/FlowRouter.js +0 -1047
- package/dist/cjs/core/FlowRouter.js.map +0 -1
- package/dist/cjs/core/PersistenceManager.d.ts +0 -114
- package/dist/cjs/core/PersistenceManager.d.ts.map +0 -1
- package/dist/cjs/core/PersistenceManager.js +0 -336
- package/dist/cjs/core/PersistenceManager.js.map +0 -1
- package/dist/cjs/core/PromptComposer.d.ts +0 -47
- package/dist/cjs/core/PromptComposer.d.ts.map +0 -1
- package/dist/cjs/core/PromptComposer.js +0 -397
- package/dist/cjs/core/PromptComposer.js.map +0 -1
- package/dist/cjs/core/PromptSectionCache.d.ts +0 -48
- package/dist/cjs/core/PromptSectionCache.d.ts.map +0 -1
- package/dist/cjs/core/PromptSectionCache.js +0 -108
- package/dist/cjs/core/PromptSectionCache.js.map +0 -1
- package/dist/cjs/core/ResponseEngine.d.ts +0 -43
- package/dist/cjs/core/ResponseEngine.d.ts.map +0 -1
- package/dist/cjs/core/ResponseEngine.js +0 -235
- package/dist/cjs/core/ResponseEngine.js.map +0 -1
- package/dist/cjs/core/ResponseGenerationError.d.ts +0 -30
- package/dist/cjs/core/ResponseGenerationError.d.ts.map +0 -1
- package/dist/cjs/core/ResponseGenerationError.js +0 -35
- package/dist/cjs/core/ResponseGenerationError.js.map +0 -1
- package/dist/cjs/core/ResponseModal.d.ts +0 -305
- package/dist/cjs/core/ResponseModal.d.ts.map +0 -1
- package/dist/cjs/core/ResponseModal.js +0 -1414
- package/dist/cjs/core/ResponseModal.js.map +0 -1
- package/dist/cjs/core/ResponsePipeline.d.ts +0 -220
- package/dist/cjs/core/ResponsePipeline.d.ts.map +0 -1
- package/dist/cjs/core/ResponsePipeline.js +0 -1040
- package/dist/cjs/core/ResponsePipeline.js.map +0 -1
- package/dist/cjs/core/SessionFinalizer.d.ts +0 -34
- package/dist/cjs/core/SessionFinalizer.d.ts.map +0 -1
- package/dist/cjs/core/SessionFinalizer.js +0 -88
- package/dist/cjs/core/SessionFinalizer.js.map +0 -1
- package/dist/cjs/core/SessionManager.d.ts +0 -112
- package/dist/cjs/core/SessionManager.d.ts.map +0 -1
- package/dist/cjs/core/SessionManager.js +0 -308
- package/dist/cjs/core/SessionManager.js.map +0 -1
- package/dist/cjs/core/SignalCoordinator.d.ts +0 -103
- package/dist/cjs/core/SignalCoordinator.d.ts.map +0 -1
- package/dist/cjs/core/SignalCoordinator.js +0 -207
- package/dist/cjs/core/SignalCoordinator.js.map +0 -1
- package/dist/cjs/core/SignalEvaluator.d.ts +0 -86
- package/dist/cjs/core/SignalEvaluator.d.ts.map +0 -1
- package/dist/cjs/core/SignalEvaluator.js +0 -319
- package/dist/cjs/core/SignalEvaluator.js.map +0 -1
- package/dist/cjs/core/SignalProcessor.d.ts +0 -152
- package/dist/cjs/core/SignalProcessor.d.ts.map +0 -1
- package/dist/cjs/core/SignalProcessor.js +0 -505
- package/dist/cjs/core/SignalProcessor.js.map +0 -1
- package/dist/cjs/core/Step.d.ts +0 -184
- package/dist/cjs/core/Step.d.ts.map +0 -1
- package/dist/cjs/core/Step.js +0 -599
- package/dist/cjs/core/Step.js.map +0 -1
- package/dist/cjs/core/StepLifecycle.d.ts +0 -43
- package/dist/cjs/core/StepLifecycle.d.ts.map +0 -1
- package/dist/cjs/core/StepLifecycle.js +0 -180
- package/dist/cjs/core/StepLifecycle.js.map +0 -1
- package/dist/cjs/core/StreamingToolExecutor.d.ts +0 -142
- package/dist/cjs/core/StreamingToolExecutor.d.ts.map +0 -1
- package/dist/cjs/core/StreamingToolExecutor.js +0 -490
- package/dist/cjs/core/StreamingToolExecutor.js.map +0 -1
- package/dist/cjs/core/ToolLoopExecutor.d.ts +0 -133
- package/dist/cjs/core/ToolLoopExecutor.d.ts.map +0 -1
- package/dist/cjs/core/ToolLoopExecutor.js +0 -568
- package/dist/cjs/core/ToolLoopExecutor.js.map +0 -1
- package/dist/cjs/core/ToolManager.d.ts +0 -250
- package/dist/cjs/core/ToolManager.d.ts.map +0 -1
- package/dist/cjs/core/ToolManager.js +0 -1104
- package/dist/cjs/core/ToolManager.js.map +0 -1
- package/dist/cjs/core/createAgent.d.ts +0 -35
- package/dist/cjs/core/createAgent.d.ts.map +0 -1
- package/dist/cjs/core/createAgent.js +0 -39
- package/dist/cjs/core/createAgent.js.map +0 -1
- package/dist/cjs/core/flow-namespace.d.ts +0 -64
- package/dist/cjs/core/flow-namespace.d.ts.map +0 -1
- package/dist/cjs/core/flow-namespace.js +0 -182
- package/dist/cjs/core/flow-namespace.js.map +0 -1
- package/dist/cjs/core/toolGates.d.ts +0 -24
- package/dist/cjs/core/toolGates.d.ts.map +0 -1
- package/dist/cjs/core/toolGates.js +0 -52
- package/dist/cjs/core/toolGates.js.map +0 -1
- package/dist/cjs/types/persistence.d.ts +0 -254
- package/dist/cjs/types/persistence.d.ts.map +0 -1
- package/dist/cjs/types/persistence.js +0 -7
- package/dist/cjs/types/persistence.js.map +0 -1
- package/dist/cjs/types/prompt-cache.d.ts +0 -15
- package/dist/cjs/types/prompt-cache.d.ts.map +0 -1
- package/dist/cjs/types/prompt-cache.js +0 -6
- package/dist/cjs/types/prompt-cache.js.map +0 -1
- package/dist/cjs/types/signals.d.ts +0 -263
- package/dist/cjs/types/signals.d.ts.map +0 -1
- package/dist/cjs/types/signals.js +0 -11
- package/dist/cjs/types/signals.js.map +0 -1
- package/dist/cjs/types/template.d.ts +0 -84
- package/dist/cjs/types/template.d.ts.map +0 -1
- package/dist/cjs/types/template.js +0 -3
- package/dist/cjs/types/template.js.map +0 -1
- package/dist/cjs/utils/condition.d.ts +0 -63
- package/dist/cjs/utils/condition.d.ts.map +0 -1
- package/dist/cjs/utils/condition.js +0 -239
- package/dist/cjs/utils/condition.js.map +0 -1
- package/dist/cjs/utils/event.d.ts +0 -6
- package/dist/cjs/utils/event.d.ts.map +0 -1
- package/dist/cjs/utils/event.js +0 -20
- package/dist/cjs/utils/event.js.map +0 -1
- package/dist/cjs/utils/id.d.ts +0 -33
- package/dist/cjs/utils/id.d.ts.map +0 -1
- package/dist/cjs/utils/id.js +0 -84
- package/dist/cjs/utils/id.js.map +0 -1
- package/dist/cjs/utils/serialize.d.ts +0 -36
- package/dist/cjs/utils/serialize.d.ts.map +0 -1
- package/dist/cjs/utils/serialize.js +0 -77
- package/dist/cjs/utils/serialize.js.map +0 -1
- package/dist/cjs/utils/session.d.ts +0 -124
- package/dist/cjs/utils/session.d.ts.map +0 -1
- package/dist/cjs/utils/session.js +0 -396
- package/dist/cjs/utils/session.js.map +0 -1
- package/dist/constants/index.d.ts +0 -2
- package/dist/constants/index.d.ts.map +0 -1
- package/dist/constants/index.js +0 -4
- package/dist/constants/index.js.map +0 -1
- package/dist/core/AutoChainExecutor.d.ts +0 -97
- package/dist/core/AutoChainExecutor.d.ts.map +0 -1
- package/dist/core/AutoChainExecutor.js +0 -284
- package/dist/core/AutoChainExecutor.js.map +0 -1
- package/dist/core/BranchEvaluator.d.ts +0 -55
- package/dist/core/BranchEvaluator.d.ts.map +0 -1
- package/dist/core/BranchEvaluator.js +0 -121
- package/dist/core/BranchEvaluator.js.map +0 -1
- package/dist/core/DirectiveChainTracker.d.ts +0 -49
- package/dist/core/DirectiveChainTracker.d.ts.map +0 -1
- package/dist/core/DirectiveChainTracker.js +0 -117
- package/dist/core/DirectiveChainTracker.js.map +0 -1
- package/dist/core/Events.d.ts +0 -26
- package/dist/core/Events.d.ts.map +0 -1
- package/dist/core/Events.js +0 -137
- package/dist/core/Events.js.map +0 -1
- package/dist/core/Flow.d.ts +0 -183
- package/dist/core/Flow.d.ts.map +0 -1
- package/dist/core/Flow.js +0 -547
- package/dist/core/Flow.js.map +0 -1
- package/dist/core/FlowRouter.d.ts +0 -183
- package/dist/core/FlowRouter.d.ts.map +0 -1
- package/dist/core/FlowRouter.js +0 -1043
- package/dist/core/FlowRouter.js.map +0 -1
- package/dist/core/PersistenceManager.d.ts +0 -114
- package/dist/core/PersistenceManager.d.ts.map +0 -1
- package/dist/core/PersistenceManager.js +0 -332
- package/dist/core/PersistenceManager.js.map +0 -1
- package/dist/core/PromptComposer.d.ts +0 -47
- package/dist/core/PromptComposer.d.ts.map +0 -1
- package/dist/core/PromptComposer.js +0 -393
- package/dist/core/PromptComposer.js.map +0 -1
- package/dist/core/PromptSectionCache.d.ts +0 -48
- package/dist/core/PromptSectionCache.d.ts.map +0 -1
- package/dist/core/PromptSectionCache.js +0 -104
- package/dist/core/PromptSectionCache.js.map +0 -1
- package/dist/core/ResponseEngine.d.ts +0 -43
- package/dist/core/ResponseEngine.d.ts.map +0 -1
- package/dist/core/ResponseEngine.js +0 -231
- package/dist/core/ResponseEngine.js.map +0 -1
- package/dist/core/ResponseGenerationError.d.ts +0 -30
- package/dist/core/ResponseGenerationError.d.ts.map +0 -1
- package/dist/core/ResponseGenerationError.js +0 -31
- package/dist/core/ResponseGenerationError.js.map +0 -1
- package/dist/core/ResponseModal.d.ts +0 -305
- package/dist/core/ResponseModal.d.ts.map +0 -1
- package/dist/core/ResponseModal.js +0 -1410
- package/dist/core/ResponseModal.js.map +0 -1
- package/dist/core/ResponsePipeline.d.ts +0 -220
- package/dist/core/ResponsePipeline.d.ts.map +0 -1
- package/dist/core/ResponsePipeline.js +0 -1035
- package/dist/core/ResponsePipeline.js.map +0 -1
- package/dist/core/SessionFinalizer.d.ts +0 -34
- package/dist/core/SessionFinalizer.d.ts.map +0 -1
- package/dist/core/SessionFinalizer.js +0 -84
- package/dist/core/SessionFinalizer.js.map +0 -1
- package/dist/core/SessionManager.d.ts +0 -112
- package/dist/core/SessionManager.d.ts.map +0 -1
- package/dist/core/SessionManager.js +0 -301
- package/dist/core/SessionManager.js.map +0 -1
- package/dist/core/SignalCoordinator.d.ts +0 -103
- package/dist/core/SignalCoordinator.d.ts.map +0 -1
- package/dist/core/SignalCoordinator.js +0 -203
- package/dist/core/SignalCoordinator.js.map +0 -1
- package/dist/core/SignalEvaluator.d.ts +0 -86
- package/dist/core/SignalEvaluator.d.ts.map +0 -1
- package/dist/core/SignalEvaluator.js +0 -312
- package/dist/core/SignalEvaluator.js.map +0 -1
- package/dist/core/SignalProcessor.d.ts +0 -152
- package/dist/core/SignalProcessor.d.ts.map +0 -1
- package/dist/core/SignalProcessor.js +0 -498
- package/dist/core/SignalProcessor.js.map +0 -1
- package/dist/core/Step.d.ts +0 -184
- package/dist/core/Step.d.ts.map +0 -1
- package/dist/core/Step.js +0 -594
- package/dist/core/Step.js.map +0 -1
- package/dist/core/StepLifecycle.d.ts +0 -43
- package/dist/core/StepLifecycle.d.ts.map +0 -1
- package/dist/core/StepLifecycle.js +0 -176
- package/dist/core/StepLifecycle.js.map +0 -1
- package/dist/core/StreamingToolExecutor.d.ts +0 -142
- package/dist/core/StreamingToolExecutor.d.ts.map +0 -1
- package/dist/core/StreamingToolExecutor.js +0 -483
- package/dist/core/StreamingToolExecutor.js.map +0 -1
- package/dist/core/ToolLoopExecutor.d.ts +0 -133
- package/dist/core/ToolLoopExecutor.d.ts.map +0 -1
- package/dist/core/ToolLoopExecutor.js +0 -564
- package/dist/core/ToolLoopExecutor.js.map +0 -1
- package/dist/core/ToolManager.d.ts +0 -250
- package/dist/core/ToolManager.d.ts.map +0 -1
- package/dist/core/ToolManager.js +0 -1098
- package/dist/core/ToolManager.js.map +0 -1
- package/dist/core/createAgent.d.ts +0 -35
- package/dist/core/createAgent.d.ts.map +0 -1
- package/dist/core/createAgent.js +0 -36
- package/dist/core/createAgent.js.map +0 -1
- package/dist/core/flow-namespace.d.ts +0 -64
- package/dist/core/flow-namespace.d.ts.map +0 -1
- package/dist/core/flow-namespace.js +0 -179
- package/dist/core/flow-namespace.js.map +0 -1
- package/dist/core/toolGates.d.ts +0 -24
- package/dist/core/toolGates.d.ts.map +0 -1
- package/dist/core/toolGates.js +0 -49
- package/dist/core/toolGates.js.map +0 -1
- package/dist/types/persistence.d.ts +0 -254
- package/dist/types/persistence.d.ts.map +0 -1
- package/dist/types/persistence.js +0 -6
- package/dist/types/persistence.js.map +0 -1
- package/dist/types/prompt-cache.d.ts +0 -15
- package/dist/types/prompt-cache.d.ts.map +0 -1
- package/dist/types/prompt-cache.js +0 -5
- package/dist/types/prompt-cache.js.map +0 -1
- package/dist/types/signals.d.ts +0 -263
- package/dist/types/signals.d.ts.map +0 -1
- package/dist/types/signals.js +0 -10
- package/dist/types/signals.js.map +0 -1
- package/dist/types/template.d.ts +0 -84
- package/dist/types/template.d.ts.map +0 -1
- package/dist/types/template.js +0 -2
- package/dist/types/template.js.map +0 -1
- package/dist/utils/condition.d.ts +0 -63
- package/dist/utils/condition.d.ts.map +0 -1
- package/dist/utils/condition.js +0 -230
- package/dist/utils/condition.js.map +0 -1
- package/dist/utils/event.d.ts +0 -6
- package/dist/utils/event.d.ts.map +0 -1
- package/dist/utils/event.js +0 -17
- package/dist/utils/event.js.map +0 -1
- package/dist/utils/id.d.ts +0 -33
- package/dist/utils/id.d.ts.map +0 -1
- package/dist/utils/id.js +0 -77
- package/dist/utils/id.js.map +0 -1
- package/dist/utils/serialize.d.ts +0 -36
- package/dist/utils/serialize.d.ts.map +0 -1
- package/dist/utils/serialize.js +0 -72
- package/dist/utils/serialize.js.map +0 -1
- package/dist/utils/session.d.ts +0 -124
- package/dist/utils/session.d.ts.map +0 -1
- package/dist/utils/session.js +0 -379
- package/dist/utils/session.js.map +0 -1
- package/docs/concepts/directives.md +0 -369
- package/docs/reference/adapters.md +0 -543
- package/docs/reference/create-agent.md +0 -216
- package/docs/reference/directive.md +0 -242
- package/docs/reference/signals.md +0 -368
- package/examples/02-data-extraction.ts +0 -90
- package/examples/05-branching.ts +0 -140
- package/examples/06-flow-control.ts +0 -103
- package/examples/08-persistence.ts +0 -98
- package/examples/09-signals.ts +0 -144
- package/src/adapters/MemoryAdapter.ts +0 -281
- package/src/adapters/MongoAdapter.ts +0 -341
- package/src/adapters/OpenSearchAdapter.ts +0 -693
- package/src/adapters/PostgreSQLAdapter.ts +0 -487
- package/src/adapters/PrismaAdapter.ts +0 -617
- package/src/adapters/RedisAdapter.ts +0 -439
- package/src/adapters/SQLiteAdapter.ts +0 -496
- package/src/adapters/index.ts +0 -43
- package/src/adapters/sessionRow.ts +0 -57
- package/src/constants/index.ts +0 -2
- package/src/core/AutoChainExecutor.ts +0 -397
- package/src/core/BranchEvaluator.ts +0 -161
- package/src/core/DirectiveChainTracker.ts +0 -144
- package/src/core/Events.ts +0 -164
- package/src/core/Flow.ts +0 -665
- package/src/core/FlowRouter.ts +0 -1540
- package/src/core/PersistenceManager.ts +0 -446
- package/src/core/PromptComposer.ts +0 -448
- package/src/core/PromptSectionCache.ts +0 -125
- package/src/core/ResponseEngine.ts +0 -338
- package/src/core/ResponseGenerationError.ts +0 -53
- package/src/core/ResponseModal.ts +0 -1902
- package/src/core/ResponsePipeline.ts +0 -1404
- package/src/core/SessionFinalizer.ts +0 -108
- package/src/core/SessionManager.ts +0 -372
- package/src/core/SignalCoordinator.ts +0 -263
- package/src/core/SignalEvaluator.ts +0 -404
- package/src/core/SignalProcessor.ts +0 -663
- package/src/core/Step.ts +0 -782
- package/src/core/StepLifecycle.ts +0 -242
- package/src/core/StreamingToolExecutor.ts +0 -609
- package/src/core/ToolLoopExecutor.ts +0 -749
- package/src/core/ToolManager.ts +0 -1379
- package/src/core/createAgent.ts +0 -40
- package/src/core/flow-namespace.ts +0 -227
- package/src/core/toolGates.ts +0 -72
- package/src/types/persistence.ts +0 -303
- package/src/types/prompt-cache.ts +0 -17
- package/src/types/signals.ts +0 -338
- package/src/types/template.ts +0 -98
- package/src/utils/condition.ts +0 -296
- package/src/utils/event.ts +0 -16
- package/src/utils/id.ts +0 -91
- package/src/utils/serialize.ts +0 -86
- package/src/utils/session.ts +0 -501
package/dist/core/Agent.js
CHANGED
|
@@ -1,1194 +1,120 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Agent: immutable configuration plus one entry point, `turn`.
|
|
3
|
+
*
|
|
4
|
+
* One instance serves every session; context and history arrive per turn.
|
|
5
|
+
* A turn is the eight phases of docs/rfc/v4-one-flow.md §4 in one line each:
|
|
6
|
+
* Runner moves the runs by code, Understand and Speak spend at most one
|
|
7
|
+
* provider call apiece, and Runner settles what they returned.
|
|
3
8
|
*/
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { mergeCollected, dropUndeclaredFields, enterFlow, enterStep, completeCurrentFlow, logger, LoggerLevel, generateSignalId, } from "../utils/index.js";
|
|
8
|
-
import { Flow } from "./Flow.js";
|
|
9
|
-
import { FlowConfigurationError as StepFlowConfigurationError } from "./Step.js";
|
|
10
|
-
import { PersistenceManager } from "./PersistenceManager.js";
|
|
11
|
-
import { SessionManager } from "./SessionManager.js";
|
|
12
|
-
import { FlowRouter } from "./FlowRouter.js";
|
|
13
|
-
import { PromptSectionCache } from "./PromptSectionCache.js";
|
|
14
|
-
import { ResponseModal } from "./ResponseModal.js";
|
|
15
|
-
import { ToolManager } from "./ToolManager.js";
|
|
9
|
+
import { FlowConfigurationError } from "../types/errors.js";
|
|
10
|
+
import { logger, LoggerLevel } from "../utils/logger.js";
|
|
11
|
+
import { addUsage } from "../utils/usage.js";
|
|
16
12
|
import { CompactionEngine } from "./CompactionEngine.js";
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
constructor(errors, message) {
|
|
22
|
-
super(message || "Data validation failed");
|
|
23
|
-
this.errors = errors;
|
|
24
|
-
this.name = "DataValidationError";
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Error thrown when flow configuration is invalid
|
|
29
|
-
*/
|
|
30
|
-
class FlowConfigurationError extends Error {
|
|
31
|
-
constructor(flowTitle, invalidFields, message) {
|
|
32
|
-
super(message || `Flow configuration error in '${flowTitle}'`);
|
|
33
|
-
this.flowTitle = flowTitle;
|
|
34
|
-
this.invalidFields = invalidFields;
|
|
35
|
-
this.name = "FlowConfigurationError";
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Main Agent class with generic context and data support
|
|
40
|
-
*/
|
|
13
|
+
import { validateFlow } from "./FlowSpec.js";
|
|
14
|
+
import { Runner } from "./Runner.js";
|
|
15
|
+
import { Speak } from "./Speak.js";
|
|
16
|
+
import { Understand } from "./Understand.js";
|
|
41
17
|
export class Agent {
|
|
42
18
|
constructor(options) {
|
|
43
19
|
this.options = options;
|
|
44
|
-
|
|
45
|
-
this._instructions = [];
|
|
46
|
-
this._tools = [];
|
|
47
|
-
this._flows = [];
|
|
48
|
-
this._knowledgeBase = {};
|
|
49
|
-
/**
|
|
50
|
-
* Staging buffer for data set before any session exists (initialData and
|
|
51
|
-
* pre-session updateCollectedData calls). Consumed when a session is
|
|
52
|
-
* created; once a session exists, `session.data` is the single source of
|
|
53
|
-
* truth and this buffer stays empty.
|
|
54
|
-
*/
|
|
55
|
-
this._pendingData = {};
|
|
56
|
-
this.maxAutoStepsPerTurn = options.maxAutoStepsPerTurn ?? 10;
|
|
57
|
-
this.maxDirectiveChain = options.maxDirectiveChain ?? 10;
|
|
58
|
-
// Validate routerMode reservation — only 'ai' is supported in v2.0
|
|
59
|
-
if (options.routerMode !== undefined && options.routerMode !== 'ai') {
|
|
60
|
-
throw new NotImplementedError(`[NotImplementedError] routerMode "${String(options.routerMode)}" is not implemented: only "ai" is supported in v2.0. ` +
|
|
61
|
-
`Set routerMode to "ai" or omit the option.`);
|
|
62
|
-
}
|
|
63
|
-
// ─── Signal construction-time validation (Requirements 1.4, 1.5, 1.6, 1.9, 2.3) ───
|
|
64
|
-
const rawSignals = options.signals ?? [];
|
|
65
|
-
// Auto-generate stable ids for entries without `id`
|
|
66
|
-
for (let i = 0; i < rawSignals.length; i++) {
|
|
67
|
-
if (!rawSignals[i].id) {
|
|
68
|
-
rawSignals[i] = {
|
|
69
|
-
...rawSignals[i],
|
|
70
|
-
id: generateSignalId(rawSignals[i].title, rawSignals[i].description, i),
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
// Validate unique ids (Requirement 1.4)
|
|
75
|
-
const idCounts = new Map();
|
|
76
|
-
for (const signal of rawSignals) {
|
|
77
|
-
const id = signal.id;
|
|
78
|
-
idCounts.set(id, (idCounts.get(id) ?? 0) + 1);
|
|
79
|
-
}
|
|
80
|
-
const duplicateIds = [...idCounts.entries()]
|
|
81
|
-
.filter(([, count]) => count > 1)
|
|
82
|
-
.map(([id]) => id);
|
|
83
|
-
if (duplicateIds.length > 0) {
|
|
84
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Duplicate signal ids: ${duplicateIds.join(', ')}. ` +
|
|
85
|
-
`Each signal must have a unique id.`);
|
|
86
|
-
}
|
|
87
|
-
// Validate signalBatchSize (positive integer when set)
|
|
88
|
-
if (options.signalBatchSize !== undefined) {
|
|
89
|
-
if (!Number.isInteger(options.signalBatchSize) ||
|
|
90
|
-
options.signalBatchSize <= 0) {
|
|
91
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] signalBatchSize must be a positive integer, got: ${options.signalBatchSize}.`);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
// Validate each signal's configuration
|
|
95
|
-
for (const signal of rawSignals) {
|
|
96
|
-
// Requirement 1.5: cooldown without cooldownMs → debug warning, treat as 'always'
|
|
97
|
-
if (signal.behavior === 'cooldown' && signal.cooldownMs == null) {
|
|
98
|
-
logger.debug(`[Agent] Signal "${signal.id}" has behavior 'cooldown' but no cooldownMs. Treating as 'always'.`);
|
|
99
|
-
signal.behavior = 'always';
|
|
100
|
-
}
|
|
101
|
-
// Requirement 1.9: validate extract schema is a JSON Schema object
|
|
102
|
-
if (signal.extract !== undefined) {
|
|
103
|
-
if (signal.extract === null ||
|
|
104
|
-
typeof signal.extract !== 'object' ||
|
|
105
|
-
Array.isArray(signal.extract)) {
|
|
106
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Signal "${signal.id}" has an invalid extract schema. ` +
|
|
107
|
-
`Expected a JSON Schema object, got: ${typeof signal.extract}.`);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
this._signals = rawSignals;
|
|
112
|
-
// Requirement 2.3: Only instantiate SignalProcessor when signals are present
|
|
113
|
-
if (rawSignals.length > 0) {
|
|
114
|
-
const evaluator = new SignalEvaluator(options.provider);
|
|
115
|
-
this.signalProcessor = new SignalProcessor(rawSignals, options.provider, evaluator, { batchSize: options.signalBatchSize ?? 10 });
|
|
116
|
-
}
|
|
117
|
-
else {
|
|
118
|
-
this.signalProcessor = undefined;
|
|
119
|
-
}
|
|
120
|
-
// Set log level based on debug option. NOTE: loglevel's default logger is
|
|
121
|
-
// process-global — one agent enabling debug turns on DEBUG for every agent
|
|
122
|
-
// in the process. Warned so multi-tenant embedders aren't surprised.
|
|
123
|
-
if (options.debug) {
|
|
124
|
-
logger.warn(`[Agent] "${options.name}" enabled debug logging via the PROCESS-GLOBAL loglevel level. ` +
|
|
125
|
-
`Every agent in this process now logs at DEBUG. Scope logging in your host if needed.`);
|
|
20
|
+
if (options.debug)
|
|
126
21
|
logger.setLevel(LoggerLevel.DEBUG);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
this._persistenceManager = new PersistenceManager(options.persistence);
|
|
179
|
-
// Initialize the adapter if it has an initialize method
|
|
180
|
-
if (options.persistence.adapter.initialize) {
|
|
181
|
-
options.persistence.adapter.initialize().catch((error) => {
|
|
182
|
-
logger.error("[Agent] Persistence adapter initialization failed:", error instanceof Error ? error.message : String(error));
|
|
183
|
-
});
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
catch (error) {
|
|
187
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
188
|
-
logger.error("[Agent] Failed to initialize persistence:", errorMessage);
|
|
189
|
-
throw new Error(`Failed to initialize persistence: ${errorMessage}`);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
// Initialize from options - use create methods for consistency
|
|
193
|
-
if (options.terms) {
|
|
194
|
-
options.terms.forEach((term) => {
|
|
195
|
-
this.createTerm(term);
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
// Initialize instructions (new unified form)
|
|
199
|
-
if (options.instructions) {
|
|
200
|
-
options.instructions.forEach((instruction) => {
|
|
201
|
-
this.createInstruction(instruction);
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
if (options.tools) {
|
|
205
|
-
options.tools.forEach((tool) => {
|
|
206
|
-
this.addTool(tool);
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
if (options.flows) {
|
|
210
|
-
options.flows.forEach((flowOptions) => {
|
|
211
|
-
this.createFlow(flowOptions);
|
|
212
|
-
});
|
|
213
|
-
}
|
|
214
|
-
// Validate deferred branch `then` string references against the flow registry.
|
|
215
|
-
// This catches strings that don't match a local step id AND don't match any flow id/title.
|
|
216
|
-
this.validateBranchReferences();
|
|
217
|
-
// Initialize knowledge base
|
|
218
|
-
if (options.knowledgeBase) {
|
|
219
|
-
this._knowledgeBase = { ...options.knowledgeBase };
|
|
220
|
-
}
|
|
221
|
-
// Initialize compaction options if configured
|
|
222
|
-
if (options.compaction && options.compaction.enabled !== false) {
|
|
223
|
-
const compactionOptions = {
|
|
224
|
-
maxTokens: options.compaction.maxTokens,
|
|
225
|
-
compactionThreshold: options.compaction.compactionThreshold ?? 0.8,
|
|
226
|
-
preserveRecentCount: options.compaction.preserveRecentCount ?? 4,
|
|
227
|
-
maxToolResultChars: options.compaction.maxToolResultChars ?? 5000,
|
|
228
|
-
provider: options.provider,
|
|
229
|
-
};
|
|
230
|
-
CompactionEngine.validateOptions(compactionOptions);
|
|
231
|
-
this._compactionOptions = compactionOptions;
|
|
232
|
-
logger.debug("[Agent] Compaction options initialized and validated");
|
|
233
|
-
}
|
|
234
|
-
// Initialize session manager — the single owner of the live session
|
|
235
|
-
this.session = new SessionManager(this._persistenceManager, this);
|
|
236
|
-
// Adopt an explicitly provided session
|
|
237
|
-
if (options.session) {
|
|
238
|
-
this.session.syncSession(options.session);
|
|
239
|
-
}
|
|
240
|
-
// Store sessionId for later use in getOrCreate calls
|
|
241
|
-
if (options.sessionId) {
|
|
242
|
-
this.session.setDefaultSessionId(options.sessionId);
|
|
243
|
-
// The session will be loaded on first getOrCreate call; session.data
|
|
244
|
-
// is the source of truth, so no data sync is needed here
|
|
245
|
-
this.session.getOrCreate(options.sessionId).catch((err) => {
|
|
246
|
-
logger.error("Failed to start session", err);
|
|
247
|
-
});
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Drain the pre-session data staging buffer.
|
|
252
|
-
* @internal Called by SessionManager when a session is created or loaded.
|
|
253
|
-
*/
|
|
254
|
-
consumePendingData() {
|
|
255
|
-
const pending = this._pendingData;
|
|
256
|
-
this._pendingData = {};
|
|
257
|
-
return pending;
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Validate the agent-level schema structure
|
|
261
|
-
* @private
|
|
262
|
-
*/
|
|
263
|
-
validateSchema(schema) {
|
|
264
|
-
if (!schema || typeof schema !== 'object') {
|
|
265
|
-
throw new Error("Agent schema must be a valid JSON Schema object. " +
|
|
266
|
-
"Provide a schema with 'type': 'object' and 'properties' to define the data structure.");
|
|
267
|
-
}
|
|
268
|
-
if (schema.type !== 'object') {
|
|
269
|
-
throw new Error(`Agent schema must be of type 'object', but received '${String(schema.type)}'. ` +
|
|
270
|
-
"Agent-level schemas must define object structures for data collection.");
|
|
271
|
-
}
|
|
272
|
-
if (!schema.properties || typeof schema.properties !== 'object') {
|
|
273
|
-
throw new Error("Agent schema must have a 'properties' field defining the data fields. " +
|
|
274
|
-
"Example: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' } } }");
|
|
275
|
-
}
|
|
276
|
-
logger.debug("[Agent] Schema validation passed");
|
|
277
|
-
}
|
|
278
|
-
/**
|
|
279
|
-
* Walk every flow's steps and resolve deferred string `then` values in branches
|
|
280
|
-
* against the agent's flow registry. Strings that match neither a local step id
|
|
281
|
-
* nor any flow id/title throw FlowConfigurationError.
|
|
282
|
-
* @private
|
|
283
|
-
*/
|
|
284
|
-
validateBranchReferences() {
|
|
285
|
-
for (const flow of this._flows) {
|
|
286
|
-
this.validateFlowBranchReferences(flow);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
/**
|
|
290
|
-
* Validate branch `then` string references for a single flow against the agent's
|
|
291
|
-
* flow registry. Throws FlowConfigurationError for unresolved references.
|
|
292
|
-
* @private
|
|
293
|
-
*/
|
|
294
|
-
validateFlowBranchReferences(flow) {
|
|
295
|
-
const steps = flow.getAllSteps();
|
|
296
|
-
const localStepIds = new Set(steps.map(s => s.id));
|
|
297
|
-
for (const step of steps) {
|
|
298
|
-
if (!step.branches)
|
|
299
|
-
continue;
|
|
300
|
-
for (const entry of step.branches) {
|
|
301
|
-
if (typeof entry.then !== 'string')
|
|
302
|
-
continue;
|
|
303
|
-
// Already matches a local step id — no deferred resolution needed
|
|
304
|
-
if (localStepIds.has(entry.then))
|
|
305
|
-
continue;
|
|
306
|
-
// Check against the agent's flow registry (id or title)
|
|
307
|
-
const matchesFlow = this._flows.some(f => f.id === entry.then || f.title === entry.then);
|
|
308
|
-
if (!matchesFlow) {
|
|
309
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Unresolved branch target: "${entry.then}" in ${flow.id}.${step.id} does not match any step in the flow or any flow in the agent. ` +
|
|
310
|
-
`Fix the branch "then" value to reference a valid step id or flow id/title.`);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Validate that every step's `collect` fields in a flow reference valid keys
|
|
317
|
-
* from the agent-level schema. Throws FlowConfigurationError at construction
|
|
318
|
-
* time if any collect field is not a valid schema key.
|
|
319
|
-
*
|
|
320
|
-
* This enforces Requirement 14.5: generic inference is preserved AND every
|
|
321
|
-
* `collect` field reference is a valid key of the inferred TData.
|
|
322
|
-
* @private
|
|
323
|
-
*/
|
|
324
|
-
validateFlowCollectFields(flow) {
|
|
325
|
-
const schemaKeys = Object.keys(this._schema.properties);
|
|
326
|
-
const schemaKeySet = new Set(schemaKeys);
|
|
327
|
-
const steps = flow.getAllSteps();
|
|
328
|
-
for (const step of steps) {
|
|
329
|
-
if (!step.collect || step.collect.length === 0)
|
|
330
|
-
continue;
|
|
331
|
-
const invalidFields = step.collect.filter(field => !schemaKeySet.has(String(field)));
|
|
332
|
-
if (invalidFields.length > 0) {
|
|
333
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Step "${step.id}" in flow "${flow.title}" references invalid collect fields: ${invalidFields.map(f => String(f)).join(', ')}. ` +
|
|
334
|
-
`Must be valid keys from agent schema. Available fields: ${schemaKeys.join(', ')}.`);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
/**
|
|
339
|
-
* Validate data against the agent-level schema.
|
|
340
|
-
*
|
|
341
|
-
* A field the schema does not declare is a warning, not an error: a model
|
|
342
|
-
* can extract a key nobody asked for, and `updateCollectedData` drops it
|
|
343
|
-
* instead of failing the turn. `valid` is false only when `errors` is not empty.
|
|
344
|
-
*/
|
|
345
|
-
validateData(data) {
|
|
346
|
-
if (!this._schema) {
|
|
347
|
-
// No schema defined, consider all data valid
|
|
348
|
-
return { valid: true, errors: [], warnings: [] };
|
|
349
|
-
}
|
|
350
|
-
const errors = [];
|
|
351
|
-
const warnings = [];
|
|
352
|
-
// Undeclared fields are warnings — updateCollectedData drops them
|
|
353
|
-
if (this._schema.properties) {
|
|
354
|
-
for (const [key, value] of Object.entries(data)) {
|
|
355
|
-
if (!(key in this._schema.properties)) {
|
|
356
|
-
warnings.push({
|
|
357
|
-
field: key,
|
|
358
|
-
value,
|
|
359
|
-
message: `Field '${key}' is not defined in agent schema`,
|
|
360
|
-
schemaPath: `properties.${key}`
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
// Check required fields if specified
|
|
366
|
-
if (this._schema.required && Array.isArray(this._schema.required)) {
|
|
367
|
-
for (const requiredField of this._schema.required) {
|
|
368
|
-
if (!(requiredField in data) || data[requiredField] === undefined) {
|
|
369
|
-
warnings.push({
|
|
370
|
-
field: requiredField,
|
|
371
|
-
value: undefined,
|
|
372
|
-
message: `Required field '${requiredField}' is missing`,
|
|
373
|
-
schemaPath: `required`
|
|
374
|
-
});
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
return {
|
|
379
|
-
valid: errors.length === 0,
|
|
380
|
-
errors,
|
|
381
|
-
warnings
|
|
382
|
-
};
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* Check if a field is valid according to the agent schema
|
|
386
|
-
* @param field - The field key to validate
|
|
387
|
-
* @returns true if field exists in schema or no schema is defined, false otherwise
|
|
388
|
-
*/
|
|
389
|
-
isValidSchemaField(field) {
|
|
390
|
-
if (!this._schema || !this._schema.properties) {
|
|
391
|
-
// No schema defined, consider all fields valid
|
|
392
|
-
return true;
|
|
393
|
-
}
|
|
394
|
-
return field in this._schema.properties;
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* Get the current collected data.
|
|
398
|
-
* Reads from the live session when one exists; otherwise from the
|
|
399
|
-
* pre-session staging buffer.
|
|
400
|
-
*/
|
|
401
|
-
getCollectedData() {
|
|
402
|
-
const session = this.session.current;
|
|
403
|
-
return session ? { ...session.data } : { ...this._pendingData };
|
|
404
|
-
}
|
|
405
|
-
/**
|
|
406
|
-
* Update collected data with validation.
|
|
407
|
-
* Writes to the live session when one exists; otherwise stages the data
|
|
408
|
-
* for the session that will be created. Fields the agent schema does not
|
|
409
|
-
* declare are dropped with a warning, never stored.
|
|
410
|
-
*/
|
|
411
|
-
async updateCollectedData(updates) {
|
|
412
|
-
const declaredUpdates = dropUndeclaredFields(updates, this._schema);
|
|
413
|
-
// Validate the updates
|
|
414
|
-
const validation = this.validateData(declaredUpdates);
|
|
415
|
-
if (!validation.valid) {
|
|
416
|
-
const errorMessages = validation.errors.map(e => e.message).join(', ');
|
|
417
|
-
throw new DataValidationError(validation.errors, `[DataValidationError] Data validation failed: fields [${errorMessages}] did not pass schema validation. Fix the offending values to match the declared schema.`);
|
|
418
|
-
}
|
|
419
|
-
// Log warnings if any
|
|
420
|
-
if (validation.warnings.length > 0) {
|
|
421
|
-
const warningMessages = validation.warnings.map(w => w.message).join(', ');
|
|
422
|
-
logger.warn(`[Agent] Data validation warnings: ${warningMessages}`);
|
|
423
|
-
}
|
|
424
|
-
const session = this.session.current;
|
|
425
|
-
const previousData = session ? { ...session.data } : { ...this._pendingData };
|
|
426
|
-
let newData = {
|
|
427
|
-
...previousData,
|
|
428
|
-
...declaredUpdates
|
|
429
|
-
};
|
|
430
|
-
// Trigger agent-level lifecycle hook if configured
|
|
431
|
-
if (this.options.hooks?.onDataUpdate) {
|
|
432
|
-
newData = await this.options.hooks.onDataUpdate(newData, previousData);
|
|
433
|
-
}
|
|
434
|
-
if (session) {
|
|
435
|
-
session.data = newData;
|
|
436
|
-
session.metadata.lastUpdatedAt = new Date();
|
|
437
|
-
}
|
|
438
|
-
else {
|
|
439
|
-
this._pendingData = newData;
|
|
440
|
-
}
|
|
441
|
-
logger.debug("[Agent] Collected data updated:", declaredUpdates);
|
|
442
|
-
}
|
|
443
|
-
// ---------------------------------------------------------------------------
|
|
444
|
-
// Property accessors (get / set)
|
|
445
|
-
// ---------------------------------------------------------------------------
|
|
446
|
-
/**
|
|
447
|
-
* Get agent name
|
|
448
|
-
*/
|
|
449
|
-
get name() {
|
|
450
|
-
return this.options.name;
|
|
451
|
-
}
|
|
452
|
-
/**
|
|
453
|
-
* Set agent name
|
|
454
|
-
*/
|
|
455
|
-
set name(value) {
|
|
456
|
-
this.options.name = value;
|
|
457
|
-
}
|
|
458
|
-
/**
|
|
459
|
-
* Get agent persona
|
|
460
|
-
*/
|
|
461
|
-
get persona() {
|
|
462
|
-
return this.options.persona;
|
|
463
|
-
}
|
|
464
|
-
/**
|
|
465
|
-
* Set agent persona
|
|
466
|
-
*/
|
|
467
|
-
set persona(value) {
|
|
468
|
-
this.options.persona = value;
|
|
469
|
-
}
|
|
470
|
-
/**
|
|
471
|
-
* Get agent goal
|
|
472
|
-
*/
|
|
473
|
-
get goal() {
|
|
474
|
-
return this.options.goal;
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Set agent goal
|
|
478
|
-
*/
|
|
479
|
-
set goal(value) {
|
|
480
|
-
this.options.goal = value;
|
|
481
|
-
}
|
|
482
|
-
/**
|
|
483
|
-
* Get whether debug mode is enabled
|
|
484
|
-
*/
|
|
485
|
-
get debug() {
|
|
486
|
-
return this.options.debug ?? false;
|
|
487
|
-
}
|
|
488
|
-
/**
|
|
489
|
-
* Set debug mode (also updates logger level)
|
|
490
|
-
*/
|
|
491
|
-
set debug(value) {
|
|
492
|
-
this.options.debug = value;
|
|
493
|
-
logger.setLevel(value ? LoggerLevel.DEBUG : LoggerLevel.INFO);
|
|
494
|
-
}
|
|
495
|
-
/**
|
|
496
|
-
* Get the AI provider
|
|
497
|
-
*/
|
|
498
|
-
get provider() {
|
|
499
|
-
return this.options.provider;
|
|
500
|
-
}
|
|
501
|
-
/**
|
|
502
|
-
* Set the AI provider
|
|
503
|
-
*/
|
|
504
|
-
set provider(value) {
|
|
505
|
-
this.options.provider = value;
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Get the flow switch margin
|
|
509
|
-
* @default 15
|
|
510
|
-
*/
|
|
511
|
-
get flowSwitchMargin() {
|
|
512
|
-
return this.options.flowSwitchMargin ?? 15;
|
|
513
|
-
}
|
|
514
|
-
/**
|
|
515
|
-
* Set the flow switch margin
|
|
516
|
-
*/
|
|
517
|
-
set flowSwitchMargin(value) {
|
|
518
|
-
this.options.flowSwitchMargin = value;
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Get the prompt section cache instance
|
|
522
|
-
*/
|
|
523
|
-
get promptSectionCache() {
|
|
524
|
-
return this._promptSectionCache;
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Get all terms
|
|
528
|
-
*/
|
|
529
|
-
get terms() {
|
|
530
|
-
return [...this._terms];
|
|
531
|
-
}
|
|
532
|
-
/**
|
|
533
|
-
* Get all instructions
|
|
534
|
-
*/
|
|
535
|
-
get instructions() {
|
|
536
|
-
return [...this._instructions];
|
|
537
|
-
}
|
|
538
|
-
/**
|
|
539
|
-
* Get all tools
|
|
540
|
-
*/
|
|
541
|
-
get tools() {
|
|
542
|
-
return [...this._tools];
|
|
543
|
-
}
|
|
544
|
-
/**
|
|
545
|
-
* Get all flows
|
|
546
|
-
*/
|
|
547
|
-
get flows() {
|
|
548
|
-
return [...this._flows];
|
|
22
|
+
validate(options);
|
|
23
|
+
this.compaction = compactionOptions(options);
|
|
24
|
+
this.runner = new Runner(options);
|
|
25
|
+
this.understand = new Understand(options);
|
|
26
|
+
this.speak = new Speak(options);
|
|
27
|
+
}
|
|
28
|
+
/** Take whatever just happened and return the messages to send and the timers to set. */
|
|
29
|
+
async turn(input) {
|
|
30
|
+
const { turn, talk } = await this.open(input);
|
|
31
|
+
await this.runner.settle(turn, talk ? await this.speak.run(this.runner.speakRequest(turn, talk)) : null);
|
|
32
|
+
return this.runner.finish(turn);
|
|
33
|
+
}
|
|
34
|
+
/** `turn`, streaming the spoken text as it is generated; the last chunk carries the result. */
|
|
35
|
+
async *turnStream(input) {
|
|
36
|
+
const { turn, talk } = await this.open(input);
|
|
37
|
+
let outcome = null;
|
|
38
|
+
if (talk) {
|
|
39
|
+
for await (const chunk of this.speak.stream(this.runner.speakRequest(turn, talk))) {
|
|
40
|
+
if ("delta" in chunk)
|
|
41
|
+
yield { delta: chunk.delta };
|
|
42
|
+
else
|
|
43
|
+
outcome = chunk.outcome;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
await this.runner.settle(turn, outcome);
|
|
47
|
+
yield { done: true, result: this.runner.finish(turn) };
|
|
48
|
+
}
|
|
49
|
+
/** Load, Ingest, Understand, Decide and Run: everything before the one speaker is known. */
|
|
50
|
+
async open(input) {
|
|
51
|
+
const { runner } = this;
|
|
52
|
+
const compacted = await this.compacted(input);
|
|
53
|
+
const turn = runner.begin(compacted.input);
|
|
54
|
+
turn.llmCalls += compacted.llmCalls;
|
|
55
|
+
turn.usage = addUsage(turn.usage, compacted.usage);
|
|
56
|
+
const request = runner.understandRequest(turn);
|
|
57
|
+
runner.decide(turn, request ? await this.understand.run(request) : null);
|
|
58
|
+
return { turn, talk: await runner.advance(turn) };
|
|
59
|
+
}
|
|
60
|
+
/** With `compaction` set, the history both calls see is trimmed once per turn; a summarization is one model call. */
|
|
61
|
+
async compacted(input) {
|
|
62
|
+
const history = input.history ?? input.session?.history;
|
|
63
|
+
if (!this.compaction || !history?.length)
|
|
64
|
+
return { input, llmCalls: 0 };
|
|
65
|
+
const result = await CompactionEngine.checkAndCompact(history, this.compaction);
|
|
66
|
+
const llmCalls = result.strategy === "auto_compact" ? 1 : 0;
|
|
67
|
+
const usage = result.usage ? { usage: result.usage } : {};
|
|
68
|
+
if (result.history === history)
|
|
69
|
+
return { input, llmCalls, ...usage };
|
|
70
|
+
const trimmed = Object.assign({}, input);
|
|
71
|
+
trimmed.history = result.history;
|
|
72
|
+
return { input: trimmed, llmCalls, ...usage };
|
|
549
73
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
return
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
* Set the current session for convenience methods
|
|
593
|
-
* Set to undefined to clear the current session
|
|
594
|
-
*/
|
|
595
|
-
set currentSession(value) {
|
|
596
|
-
this.session.syncSession(value);
|
|
597
|
-
this._promptSectionCache.invalidateAll();
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Get all flows
|
|
601
|
-
*/
|
|
602
|
-
getFlows() {
|
|
603
|
-
return this.flows;
|
|
604
|
-
}
|
|
605
|
-
/**
|
|
606
|
-
* Get all terms
|
|
607
|
-
*/
|
|
608
|
-
getTerms() {
|
|
609
|
-
return this.terms;
|
|
610
|
-
}
|
|
611
|
-
/**
|
|
612
|
-
* Get all tools
|
|
613
|
-
*/
|
|
614
|
-
getTools() {
|
|
615
|
-
return this.tools;
|
|
616
|
-
}
|
|
617
|
-
/**
|
|
618
|
-
* Get all instructions
|
|
619
|
-
*/
|
|
620
|
-
getInstructions() {
|
|
621
|
-
return this.instructions;
|
|
622
|
-
}
|
|
623
|
-
/**
|
|
624
|
-
* Invalidate flow-dependent prompt cache sections.
|
|
625
|
-
* Called automatically when the active flow changes.
|
|
626
|
-
*/
|
|
627
|
-
invalidateFlowSections() {
|
|
628
|
-
this._promptSectionCache.invalidate('activeFlows');
|
|
629
|
-
this._promptSectionCache.invalidate('flowKnowledgeBase');
|
|
630
|
-
this._promptSectionCache.invalidate('instructionsFlow');
|
|
631
|
-
}
|
|
632
|
-
/**
|
|
633
|
-
* Get the persistence manager (if configured)
|
|
634
|
-
*/
|
|
635
|
-
getPersistenceManager() {
|
|
636
|
-
return this._persistenceManager;
|
|
637
|
-
}
|
|
638
|
-
/**
|
|
639
|
-
* Check if persistence is enabled
|
|
640
|
-
*/
|
|
641
|
-
hasPersistence() {
|
|
642
|
-
return this._persistenceManager !== undefined;
|
|
643
|
-
}
|
|
644
|
-
/**
|
|
645
|
-
* Get the resolved compaction options (if compaction is configured)
|
|
646
|
-
*/
|
|
647
|
-
getCompactionOptions() {
|
|
648
|
-
return this._compactionOptions;
|
|
649
|
-
}
|
|
650
|
-
// ---------------------------------------------------------------------------
|
|
651
|
-
// Core methods
|
|
652
|
-
// ---------------------------------------------------------------------------
|
|
653
|
-
/**
|
|
654
|
-
* Create a new flow (journey) using agent-level data type
|
|
655
|
-
*/
|
|
656
|
-
createFlow(options) {
|
|
657
|
-
// Validate that requiredFields exist in agent schema
|
|
658
|
-
if (options.requiredFields && this._schema?.properties) {
|
|
659
|
-
const invalidRequiredFields = options.requiredFields.filter(field => !(String(field) in this._schema.properties));
|
|
660
|
-
if (invalidRequiredFields.length > 0) {
|
|
661
|
-
throw new FlowConfigurationError(options.title, invalidRequiredFields.map(f => String(f)), `[FlowConfigurationError] Invalid required fields in flow "${options.title}": [${invalidRequiredFields.join(', ')}] are not declared in the agent schema. ` +
|
|
662
|
-
`Use valid schema keys. Available fields: ${Object.keys(this._schema.properties).join(', ')}.`);
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
// Validate that optionalFields exist in agent schema
|
|
666
|
-
if (options.optionalFields && this._schema?.properties) {
|
|
667
|
-
const invalidOptionalFields = options.optionalFields.filter(field => !(String(field) in this._schema.properties));
|
|
668
|
-
if (invalidOptionalFields.length > 0) {
|
|
669
|
-
throw new FlowConfigurationError(options.title, invalidOptionalFields.map(f => String(f)), `[FlowConfigurationError] Invalid optional fields in flow "${options.title}": [${invalidOptionalFields.join(', ')}] are not declared in the agent schema. ` +
|
|
670
|
-
`Use valid schema keys. Available fields: ${Object.keys(this._schema.properties).join(', ')}.`);
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
// Overlap detection: warn (don't throw) when the incoming flow's
|
|
674
|
-
// requiredFields intersect another registered flow's — the schema is
|
|
675
|
-
// agent-level, so both flows complete together and one is silently
|
|
676
|
-
// excluded from routing.
|
|
677
|
-
if (options.requiredFields && options.requiredFields.length > 0) {
|
|
678
|
-
const incoming = new Set(options.requiredFields.map(String));
|
|
679
|
-
for (const existing of this._flows) {
|
|
680
|
-
const shared = (existing.requiredFields ?? [])
|
|
681
|
-
.map(String)
|
|
682
|
-
.filter((f) => incoming.has(f));
|
|
683
|
-
if (shared.length > 0) {
|
|
684
|
-
logger.warn(`[FlowConfigurationError] Overlapping requiredFields: flows "${existing.title}" and "${options.title}" share [${shared.join(', ')}]. ` +
|
|
685
|
-
`The schema is agent-level, so data collected for one flow marks the other complete and excludes it from routing. ` +
|
|
686
|
-
`Give each flow distinct requiredFields, or set \`reentrant: true\` on flows that legitimately share fields.`);
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
const flow = new Flow(options, this);
|
|
691
|
-
// Validate that step collect fields reference valid schema keys
|
|
692
|
-
if (this._schema?.properties) {
|
|
693
|
-
this.validateFlowCollectFields(flow);
|
|
694
|
-
}
|
|
695
|
-
this._flows.push(flow);
|
|
696
|
-
return flow;
|
|
697
|
-
}
|
|
698
|
-
/**
|
|
699
|
-
* Create a domain term for the glossary
|
|
700
|
-
*/
|
|
701
|
-
createTerm(term) {
|
|
702
|
-
this._terms.push(term);
|
|
703
|
-
return this;
|
|
704
|
-
}
|
|
705
|
-
/**
|
|
706
|
-
* Create an instruction (unified behavioral primitive).
|
|
707
|
-
*/
|
|
708
|
-
createInstruction(instruction) {
|
|
709
|
-
const instructionWithId = {
|
|
710
|
-
...instruction,
|
|
711
|
-
kind: instruction.kind || 'should',
|
|
712
|
-
id: instruction.id || `instruction_${this._instructions.length}`,
|
|
713
|
-
enabled: instruction.enabled !== false, // Default to true
|
|
714
|
-
};
|
|
715
|
-
this._instructions.push(instructionWithId);
|
|
716
|
-
this._promptSectionCache.invalidate('instructionsGlobal');
|
|
717
|
-
return this;
|
|
718
|
-
}
|
|
719
|
-
/**
|
|
720
|
-
* Add a tool to the agent using the unified Tool interface
|
|
721
|
-
* Creates and adds the tool to agent scope in one operation
|
|
722
|
-
*/
|
|
723
|
-
addTool(tool) {
|
|
724
|
-
// Validate tool before adding
|
|
725
|
-
if (!tool || !tool.id || !tool.handler) {
|
|
726
|
-
throw new Error('Invalid tool: must have id and handler properties');
|
|
727
|
-
}
|
|
728
|
-
// Add directly to agent's tools array, preserving the TResult type
|
|
729
|
-
this._tools.push(tool);
|
|
730
|
-
logger.debug(`[Agent] Added tool to agent scope: ${tool.id}`);
|
|
731
|
-
return this;
|
|
732
|
-
}
|
|
733
|
-
/**
|
|
734
|
-
* Register multiple tools at the agent level
|
|
735
|
-
*/
|
|
736
|
-
registerTools(tools) {
|
|
737
|
-
tools.forEach((tool) => {
|
|
738
|
-
// Validate each tool before adding
|
|
739
|
-
if (!tool || !tool.id || !tool.handler) {
|
|
740
|
-
throw new Error(`Invalid tool in batch: must have id and handler properties (tool: ${tool?.id || 'unknown'})`);
|
|
741
|
-
}
|
|
742
|
-
this._tools.push(tool);
|
|
743
|
-
});
|
|
744
|
-
logger.debug(`[Agent] Registered ${tools.length} tools`);
|
|
745
|
-
return this;
|
|
746
|
-
}
|
|
747
|
-
/**
|
|
748
|
-
* Update the agent's context
|
|
749
|
-
* Triggers both agent-level and flow-specific onContextUpdate lifecycle hooks if configured
|
|
750
|
-
*/
|
|
751
|
-
async updateContext(updates) {
|
|
752
|
-
const previousContext = this._context;
|
|
753
|
-
// Merge updates with current context
|
|
754
|
-
this._context = {
|
|
755
|
-
...this._context,
|
|
756
|
-
...updates,
|
|
757
|
-
};
|
|
758
|
-
// Trigger flow-specific lifecycle hook if configured and session has current flow
|
|
759
|
-
const activeSession = this.session.current;
|
|
760
|
-
if (activeSession?.currentFlow) {
|
|
761
|
-
const currentFlow = this._flows.find((r) => r.id === activeSession.currentFlow?.id);
|
|
762
|
-
if (currentFlow?.hooks?.onContextUpdate &&
|
|
763
|
-
previousContext !== undefined) {
|
|
764
|
-
await currentFlow.handleContextUpdate(this._context, previousContext);
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
// Trigger agent-level lifecycle hook if configured
|
|
768
|
-
if (this.options.hooks?.onContextUpdate && previousContext !== undefined) {
|
|
769
|
-
await this.options.hooks.onContextUpdate(this._context, previousContext);
|
|
770
|
-
}
|
|
771
|
-
// Invalidate context-dependent prompt cache sections
|
|
772
|
-
this._promptSectionCache.invalidate('agentMeta');
|
|
773
|
-
this._promptSectionCache.invalidate('knowledgeBase');
|
|
774
|
-
this._promptSectionCache.invalidate('instructionsGlobal');
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* Update collected data in session with lifecycle hook support
|
|
778
|
-
* Triggers both agent-level and flow-specific onDataUpdate lifecycle hooks if configured
|
|
779
|
-
* @internal
|
|
780
|
-
*/
|
|
781
|
-
async updateData(session, dataUpdate) {
|
|
782
|
-
const previousCollected = { ...session.data };
|
|
783
|
-
// Merge new collected data
|
|
784
|
-
let newCollected = {
|
|
785
|
-
...session.data,
|
|
786
|
-
...dataUpdate,
|
|
787
|
-
};
|
|
788
|
-
// Trigger flow-specific lifecycle hook if configured and session has a current flow
|
|
789
|
-
if (session.currentFlow) {
|
|
790
|
-
const currentFlow = this._flows.find((r) => r.id === session.currentFlow?.id);
|
|
791
|
-
if (currentFlow?.hooks?.onDataUpdate) {
|
|
792
|
-
newCollected = await currentFlow.handleDataUpdate(newCollected, previousCollected);
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
// Trigger agent-level lifecycle hook if configured
|
|
796
|
-
if (this.options.hooks?.onDataUpdate) {
|
|
797
|
-
newCollected = (await this.options.hooks.onDataUpdate(newCollected, previousCollected));
|
|
798
|
-
}
|
|
799
|
-
// Return updated session — session.data is the single source of truth,
|
|
800
|
-
// so no agent-side copy is kept
|
|
801
|
-
return mergeCollected(session, newCollected);
|
|
802
|
-
}
|
|
803
|
-
/**
|
|
804
|
-
* Get current context (fetches from provider if configured)
|
|
805
|
-
*/
|
|
806
|
-
async getContext() {
|
|
807
|
-
// If context provider is configured, use it to fetch fresh context
|
|
808
|
-
if (this.options.contextProvider) {
|
|
809
|
-
return await this.options.contextProvider();
|
|
810
|
-
}
|
|
811
|
-
// Otherwise return the stored context
|
|
812
|
-
return this._context;
|
|
813
|
-
}
|
|
814
|
-
/**
|
|
815
|
-
* Generate a response based on history and context as a stream
|
|
816
|
-
*/
|
|
817
|
-
async *respondStream(params) {
|
|
818
|
-
// Delegate to ResponseModal
|
|
819
|
-
yield* this._responseModal.respondStream(params);
|
|
820
|
-
}
|
|
821
|
-
/**
|
|
822
|
-
* Generate a response based on history and context
|
|
823
|
-
*/
|
|
824
|
-
async respond(params) {
|
|
825
|
-
// Delegate to ResponseModal
|
|
826
|
-
return this._responseModal.respond(params);
|
|
827
|
-
}
|
|
828
|
-
/**
|
|
829
|
-
* Get agent options
|
|
830
|
-
* @internal Used by ResponseModal
|
|
831
|
-
*/
|
|
832
|
-
getAgentOptions() {
|
|
833
|
-
return this.options;
|
|
834
|
-
}
|
|
835
|
-
/**
|
|
836
|
-
* Get flow router
|
|
837
|
-
* @internal Used by ResponseModal
|
|
838
|
-
*/
|
|
839
|
-
getFlowRouter() {
|
|
840
|
-
return this._routingEngine;
|
|
841
|
-
}
|
|
842
|
-
/**
|
|
843
|
-
* Get the updateData method bound to this agent
|
|
844
|
-
* @internal Used by ResponseModal
|
|
845
|
-
*/
|
|
846
|
-
getUpdateDataMethod() {
|
|
847
|
-
return this.updateData.bind(this);
|
|
848
|
-
}
|
|
849
|
-
/**
|
|
850
|
-
* Execute a prepare or finalize function/tool
|
|
851
|
-
* @internal Used by ResponseModal
|
|
852
|
-
*/
|
|
853
|
-
async executePrepareFinalize(prepareOrFinalize, context, data, flow, step) {
|
|
854
|
-
if (!prepareOrFinalize)
|
|
855
|
-
return;
|
|
856
|
-
if (typeof prepareOrFinalize === "function") {
|
|
857
|
-
// It's a function - call it directly
|
|
858
|
-
await prepareOrFinalize(context, data);
|
|
859
|
-
}
|
|
860
|
-
else {
|
|
861
|
-
// It's a tool reference - find and execute the tool
|
|
862
|
-
let tool;
|
|
863
|
-
if (typeof prepareOrFinalize === "string") {
|
|
864
|
-
// Tool ID - use ToolManager to find it across all scopes
|
|
865
|
-
tool = this.tool.find(prepareOrFinalize, undefined, step, flow);
|
|
866
|
-
}
|
|
867
|
-
else {
|
|
868
|
-
// Tool object - validate it has required properties
|
|
869
|
-
if (prepareOrFinalize.id && typeof prepareOrFinalize.handler === 'function') {
|
|
870
|
-
tool = prepareOrFinalize;
|
|
871
|
-
}
|
|
872
|
-
else {
|
|
873
|
-
logger.error(`[Agent] Invalid tool object for prepare/finalize: missing id or invalid handler`);
|
|
874
|
-
return;
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
if (tool) {
|
|
878
|
-
// Use ToolManager for execution
|
|
879
|
-
const result = await this.tool.executeTool({
|
|
880
|
-
tool,
|
|
881
|
-
context,
|
|
882
|
-
updateContext: this.updateContext.bind(this),
|
|
883
|
-
updateData: this.updateCollectedData.bind(this),
|
|
884
|
-
history: [], // Empty history for prepare/finalize
|
|
885
|
-
data,
|
|
886
|
-
});
|
|
887
|
-
if (!result.success) {
|
|
888
|
-
logger.error(`[Agent] Tool execution failed in prepare/finalize: ${result.error}`);
|
|
889
|
-
throw new Error(`Tool execution failed: ${result.error}`);
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
else {
|
|
893
|
-
logger.warn(`[Agent] Tool not found for prepare/finalize: ${typeof prepareOrFinalize === "string"
|
|
894
|
-
? prepareOrFinalize
|
|
895
|
-
: "inline tool"}`);
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
/**
|
|
900
|
-
* Get collected data from the current session (or the pre-session staging
|
|
901
|
-
* buffer when no session exists yet). Alias of getCollectedData().
|
|
902
|
-
*/
|
|
903
|
-
getData() {
|
|
904
|
-
return this.getCollectedData();
|
|
905
|
-
}
|
|
906
|
-
/**
|
|
907
|
-
* Dispatch a directive (or a flow shorthand) into a session.
|
|
908
|
-
* Sets `pendingDirective` on the session without triggering a `respond()` call.
|
|
909
|
-
* The directive will be applied at the start of the next turn.
|
|
910
|
-
*
|
|
911
|
-
* String form desugars to `{ goTo: target }`.
|
|
912
|
-
*
|
|
913
|
-
* Durability: with a persistence adapter and autoSave configured (the
|
|
914
|
-
* defaults), the queued directive is persisted immediately — safe for
|
|
915
|
-
* out-of-process callers like webhooks or cron. Without an adapter it is
|
|
916
|
-
* memory-only, as is `persistence.autoSave: false` (then persisting before
|
|
917
|
-
* the next turn is the caller's job).
|
|
918
|
-
*
|
|
919
|
-
* @param target - Flow ID/title string (desugars to `{ goTo: target }`) or a full Directive
|
|
920
|
-
* @param session - Session to update (uses current session if not provided)
|
|
921
|
-
* @returns Updated session with `pendingDirective` set
|
|
922
|
-
*
|
|
923
|
-
* @throws FlowConfigurationError if the string target doesn't match any flow
|
|
924
|
-
* @throws FlowConfigurationError if the directive fails validation
|
|
925
|
-
* @throws SessionConflictError when persistence is enabled and another writer
|
|
926
|
-
* moved the stored session since this copy was loaded
|
|
927
|
-
*
|
|
928
|
-
* @example
|
|
929
|
-
* // String shorthand — desugars to { goTo: 'Feedback' }
|
|
930
|
-
* const updated = await agent.dispatch('Feedback', session);
|
|
931
|
-
*
|
|
932
|
-
* @example
|
|
933
|
-
* // Full directive
|
|
934
|
-
* const updated = await agent.dispatch({ goTo: 'Billing', reply: 'Transferring you now.' }, session);
|
|
935
|
-
*/
|
|
936
|
-
async dispatch(target, session) {
|
|
937
|
-
const targetSession = session || this.session.current;
|
|
938
|
-
if (!targetSession) {
|
|
939
|
-
throw new Error("No session provided and no current session available. Please provide a session to dispatch into.");
|
|
940
|
-
}
|
|
941
|
-
// Desugar string form to { goTo: target }
|
|
942
|
-
const directive = typeof target === 'string'
|
|
943
|
-
? { goTo: target }
|
|
944
|
-
: target;
|
|
945
|
-
// Validate the directive: check for multiple position fields, empty goTo, etc.
|
|
946
|
-
this.validateDirective(directive);
|
|
947
|
-
// If goTo is a string, validate it references a known flow
|
|
948
|
-
if (typeof directive.goTo === 'string') {
|
|
949
|
-
const flowTarget = directive.goTo;
|
|
950
|
-
const matchesFlow = this._flows.some(f => f.id === flowTarget || f.title === flowTarget);
|
|
951
|
-
if (!matchesFlow) {
|
|
952
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Unknown flow: "${flowTarget}" does not match any flow id or title. ` +
|
|
953
|
-
`Available flows: ${this._flows.map(f => f.title).join(', ')}.`);
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
else if (directive.goTo && typeof directive.goTo === 'object' && directive.goTo.flow) {
|
|
957
|
-
const flowTarget = directive.goTo.flow;
|
|
958
|
-
const matchesFlow = this._flows.some(f => f.id === flowTarget || f.title === flowTarget);
|
|
959
|
-
if (!matchesFlow) {
|
|
960
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Unknown flow: "${flowTarget}" does not match any flow id or title. ` +
|
|
961
|
-
`Available flows: ${this._flows.map(f => f.title).join(', ')}.`);
|
|
962
|
-
}
|
|
963
|
-
}
|
|
964
|
-
// Strip pre-LLM-only fields before storing
|
|
965
|
-
const stripped = this.stripPreDirectiveFields(directive);
|
|
966
|
-
// Set pendingDirective on the session without applying it
|
|
967
|
-
const updatedSession = {
|
|
968
|
-
...targetSession,
|
|
969
|
-
pendingDirective: stripped,
|
|
970
|
-
metadata: {
|
|
971
|
-
...targetSession.metadata,
|
|
972
|
-
lastUpdatedAt: new Date(),
|
|
973
|
-
},
|
|
974
|
-
};
|
|
975
|
-
// Durability: with an adapter + autoSave configured, dispatch persists
|
|
976
|
-
// immediately — webhooks/cron run out-of-process from the responder, and a
|
|
977
|
-
// memory-only queue would evaporate with this process. The save stamps the
|
|
978
|
-
// new version back onto updatedSession, so the next turn's auto-save CAS
|
|
979
|
-
// stays clean. Persisting BEFORE the in-memory sync keeps the existing
|
|
980
|
-
// invariant: a throwing dispatch leaves the session untouched.
|
|
981
|
-
if (this._persistenceManager && this.options.persistence?.autoSave !== false) {
|
|
982
|
-
await this._persistenceManager.saveSessionState(updatedSession.id, updatedSession);
|
|
983
|
-
logger.debug(`[Agent] Dispatched directive persisted to adapter for session ${updatedSession.id}`);
|
|
984
|
-
}
|
|
985
|
-
// Update current session in place if no explicit session was passed
|
|
986
|
-
if (!session && this.session.current) {
|
|
987
|
-
this.session.syncSession(updatedSession);
|
|
988
|
-
}
|
|
989
|
-
logger.debug(`[Agent] Dispatched directive: pendingDirective set on session ${updatedSession.id}`);
|
|
990
|
-
return updatedSession;
|
|
991
|
-
}
|
|
992
|
-
/**
|
|
993
|
-
* Apply a directive synchronously to a session without invoking `respond()`.
|
|
994
|
-
* Performs in-place application: updates flow/step position, merges state writes.
|
|
995
|
-
*
|
|
996
|
-
* This is the synchronous counterpart to `dispatch` — it applies immediately
|
|
997
|
-
* rather than deferring to the next turn.
|
|
998
|
-
*
|
|
999
|
-
* @param directive - The directive to apply
|
|
1000
|
-
* @param session - The session to apply the directive to
|
|
1001
|
-
* @returns The updated session with the directive applied
|
|
1002
|
-
*/
|
|
1003
|
-
applyDirective(directive, session) {
|
|
1004
|
-
// Validate the directive
|
|
1005
|
-
this.validateDirective(directive);
|
|
1006
|
-
let updatedSession = { ...session };
|
|
1007
|
-
const now = new Date();
|
|
1008
|
-
// Apply state writes
|
|
1009
|
-
if (directive.contextUpdate) {
|
|
1010
|
-
// Context updates are applied to the agent, not the session
|
|
1011
|
-
this._context = {
|
|
1012
|
-
...this._context,
|
|
1013
|
-
...directive.contextUpdate,
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
if (directive.dataUpdate) {
|
|
1017
|
-
updatedSession = {
|
|
1018
|
-
...updatedSession,
|
|
1019
|
-
data: {
|
|
1020
|
-
...updatedSession.data,
|
|
1021
|
-
...directive.dataUpdate,
|
|
1022
|
-
},
|
|
1023
|
-
};
|
|
1024
|
-
}
|
|
1025
|
-
// Apply position control
|
|
1026
|
-
if (directive.goTo) {
|
|
1027
|
-
const flowTarget = typeof directive.goTo === 'string'
|
|
1028
|
-
? directive.goTo
|
|
1029
|
-
: directive.goTo.flow;
|
|
1030
|
-
if (flowTarget) {
|
|
1031
|
-
const targetFlow = this._flows.find(f => f.id === flowTarget || f.title === flowTarget);
|
|
1032
|
-
if (targetFlow) {
|
|
1033
|
-
// Merge goTo.data if present
|
|
1034
|
-
if (typeof directive.goTo === 'object' && directive.goTo.data) {
|
|
1035
|
-
updatedSession = {
|
|
1036
|
-
...updatedSession,
|
|
1037
|
-
data: {
|
|
1038
|
-
...updatedSession.data,
|
|
1039
|
-
...directive.goTo.data,
|
|
1040
|
-
},
|
|
1041
|
-
};
|
|
1042
|
-
}
|
|
1043
|
-
updatedSession = enterFlow(updatedSession, targetFlow.id, targetFlow.title);
|
|
1044
|
-
// If a specific step is targeted
|
|
1045
|
-
if (typeof directive.goTo === 'object' && directive.goTo.step) {
|
|
1046
|
-
updatedSession = enterStep(updatedSession, directive.goTo.step);
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
}
|
|
1050
|
-
}
|
|
1051
|
-
else if (directive.goToStep) {
|
|
1052
|
-
const stepTarget = typeof directive.goToStep === 'string'
|
|
1053
|
-
? directive.goToStep
|
|
1054
|
-
: directive.goToStep.step;
|
|
1055
|
-
// Merge goToStep.data if present
|
|
1056
|
-
if (typeof directive.goToStep === 'object' && directive.goToStep.data) {
|
|
1057
|
-
updatedSession = {
|
|
1058
|
-
...updatedSession,
|
|
1059
|
-
data: {
|
|
1060
|
-
...updatedSession.data,
|
|
1061
|
-
...directive.goToStep.data,
|
|
1062
|
-
},
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
updatedSession = enterStep(updatedSession, stepTarget);
|
|
1066
|
-
}
|
|
1067
|
-
else if (directive.complete) {
|
|
1068
|
-
updatedSession = completeCurrentFlow(updatedSession);
|
|
1069
|
-
// If complete carries a chained directive, set it as pendingDirective
|
|
1070
|
-
if (typeof directive.complete === 'object' && directive.complete.next) {
|
|
1071
|
-
updatedSession = {
|
|
1072
|
-
...updatedSession,
|
|
1073
|
-
pendingDirective: directive.complete.next,
|
|
1074
|
-
};
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
else if (directive.abort) {
|
|
1078
|
-
const clearSession = typeof directive.abort === 'object'
|
|
1079
|
-
? directive.abort.clearSession !== false
|
|
1080
|
-
: true;
|
|
1081
|
-
if (clearSession) {
|
|
1082
|
-
updatedSession = {
|
|
1083
|
-
...updatedSession,
|
|
1084
|
-
currentFlow: undefined,
|
|
1085
|
-
currentStep: undefined,
|
|
1086
|
-
data: {},
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
else {
|
|
1090
|
-
updatedSession = {
|
|
1091
|
-
...updatedSession,
|
|
1092
|
-
currentFlow: undefined,
|
|
1093
|
-
currentStep: undefined,
|
|
1094
|
-
};
|
|
1095
|
-
}
|
|
1096
|
-
}
|
|
1097
|
-
else if (directive.reset) {
|
|
1098
|
-
const currentFlowId = updatedSession.currentFlow?.id;
|
|
1099
|
-
const currentFlowTitle = updatedSession.currentFlow?.title;
|
|
1100
|
-
if (currentFlowId && currentFlowTitle) {
|
|
1101
|
-
// Clear data if requested
|
|
1102
|
-
if (typeof directive.reset === 'object' && directive.reset.clearData) {
|
|
1103
|
-
const currentFlow = this._flows.find(f => f.id === currentFlowId);
|
|
1104
|
-
if (currentFlow) {
|
|
1105
|
-
const ownedFields = [
|
|
1106
|
-
...(currentFlow.requiredFields || []),
|
|
1107
|
-
...(currentFlow.optionalFields || []),
|
|
1108
|
-
];
|
|
1109
|
-
updatedSession = completeCurrentFlow(updatedSession, { clearOwnedFields: ownedFields });
|
|
1110
|
-
// Re-enter the same flow
|
|
1111
|
-
updatedSession = enterFlow(updatedSession, currentFlowId, currentFlowTitle);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
else {
|
|
1115
|
-
// Re-enter the flow from the beginning (or specified step)
|
|
1116
|
-
updatedSession = enterFlow(updatedSession, currentFlowId, currentFlowTitle);
|
|
1117
|
-
}
|
|
1118
|
-
// If a specific step is targeted for reset
|
|
1119
|
-
if (typeof directive.reset === 'object' && directive.reset.step) {
|
|
1120
|
-
updatedSession = enterStep(updatedSession, directive.reset.step);
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
// Update metadata
|
|
1125
|
-
updatedSession = {
|
|
1126
|
-
...updatedSession,
|
|
1127
|
-
metadata: {
|
|
1128
|
-
...updatedSession.metadata,
|
|
1129
|
-
lastUpdatedAt: now,
|
|
1130
|
-
},
|
|
1131
|
-
};
|
|
1132
|
-
return updatedSession;
|
|
1133
|
-
}
|
|
1134
|
-
/**
|
|
1135
|
-
* Validate a directive for structural correctness.
|
|
1136
|
-
* Throws FlowConfigurationError for invalid combinations.
|
|
1137
|
-
* @private
|
|
1138
|
-
*/
|
|
1139
|
-
validateDirective(directive) {
|
|
1140
|
-
// Check for multiple position fields
|
|
1141
|
-
const positionFields = ['goTo', 'goToStep', 'complete', 'abort', 'reset'];
|
|
1142
|
-
const setPositionFields = positionFields.filter(field => directive[field] !== undefined);
|
|
1143
|
-
if (setPositionFields.length > 1) {
|
|
1144
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Multiple position fields: a Directive may set at most one position field. ` +
|
|
1145
|
-
`Found: ${setPositionFields.join(', ')}. Remove all but one.`);
|
|
1146
|
-
}
|
|
1147
|
-
// Check for empty goTo object
|
|
1148
|
-
if (directive.goTo && typeof directive.goTo === 'object') {
|
|
1149
|
-
const goToObj = directive.goTo;
|
|
1150
|
-
if (!goToObj.flow && !goToObj.step) {
|
|
1151
|
-
throw new StepFlowConfigurationError(`[FlowConfigurationError] Empty goTo: "goTo" requires at least a "flow" field. ` +
|
|
1152
|
-
`Provide { goTo: { flow: '<id>' } } or use the string shorthand { goTo: '<id>' }.`);
|
|
74
|
+
}
|
|
75
|
+
function compactionOptions(options) {
|
|
76
|
+
const config = options.compaction;
|
|
77
|
+
if (!config || config.enabled === false)
|
|
78
|
+
return undefined;
|
|
79
|
+
const resolved = {
|
|
80
|
+
maxTokens: config.maxTokens,
|
|
81
|
+
compactionThreshold: config.compactionThreshold ?? 0.8,
|
|
82
|
+
preserveRecentCount: config.preserveRecentCount ?? 4,
|
|
83
|
+
maxToolResultChars: config.maxToolResultChars ?? 5000,
|
|
84
|
+
provider: options.provider,
|
|
85
|
+
};
|
|
86
|
+
CompactionEngine.validateOptions(resolved);
|
|
87
|
+
return resolved;
|
|
88
|
+
}
|
|
89
|
+
/** Every name a flow uses must resolve now, not on the turn that first reaches it. */
|
|
90
|
+
function validate(options) {
|
|
91
|
+
const ids = new Set();
|
|
92
|
+
for (const flow of options.flows ?? []) {
|
|
93
|
+
if (ids.has(flow.id)) {
|
|
94
|
+
throw new FlowConfigurationError(`[FlowConfigurationError] flow "${flow.id}" is declared twice: flow ids must be unique. Rename one of them.`);
|
|
95
|
+
}
|
|
96
|
+
ids.add(flow.id);
|
|
97
|
+
for (const warning of validateFlow(flow, options).warnings)
|
|
98
|
+
logger.warn(`[Agent] ${warning}`);
|
|
99
|
+
}
|
|
100
|
+
for (const tool of options.tools ?? []) {
|
|
101
|
+
// A function's parameters are a JSON Schema object, so anything else is a
|
|
102
|
+
// mistake — most often the action's `{ name: { type } }` map written in a
|
|
103
|
+
// tool. Only DeepSeek rejects it on the wire; everywhere else the tool is
|
|
104
|
+
// simply never callable, and nothing says so.
|
|
105
|
+
if (tool.parameters && tool.parameters.type !== "object") {
|
|
106
|
+
throw new FlowConfigurationError(`[FlowConfigurationError] tool "${tool.id}": parameters must be a JSON Schema object. ` +
|
|
107
|
+
`Write { type: "object", properties: { ... }, required: [...] }.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const { idle } = options;
|
|
111
|
+
if (idle && idle !== "silent") {
|
|
112
|
+
const known = new Set((options.tools ?? []).map((tool) => tool.id));
|
|
113
|
+
for (const name of idle.tools ?? []) {
|
|
114
|
+
if (!known.has(name)) {
|
|
115
|
+
throw new FlowConfigurationError(`[FlowConfigurationError] idle: unknown tool "${name}". Register it in the agent's tools or fix the name.`);
|
|
1153
116
|
}
|
|
1154
117
|
}
|
|
1155
118
|
}
|
|
1156
|
-
/**
|
|
1157
|
-
* Strip pre-LLM-only fields (appendPrompt, injectTools, halt) from a directive.
|
|
1158
|
-
* These fields are transient (one-turn lifetime) and must not be persisted.
|
|
1159
|
-
* @private
|
|
1160
|
-
*/
|
|
1161
|
-
stripPreDirectiveFields(directive) {
|
|
1162
|
-
const raw = directive;
|
|
1163
|
-
if (!raw.appendPrompt && !raw.injectTools && raw.halt === undefined) {
|
|
1164
|
-
return directive;
|
|
1165
|
-
}
|
|
1166
|
-
const { appendPrompt, injectTools, halt, ...rest } = raw;
|
|
1167
|
-
if (appendPrompt || injectTools || halt !== undefined) {
|
|
1168
|
-
logger.warn(`[Agent] Ignoring pre-LLM-only fields on pendingDirective (these only take effect in onEnter/prepare hooks): ` +
|
|
1169
|
-
`${[appendPrompt && 'appendPrompt', injectTools && 'injectTools', halt !== undefined && 'halt'].filter(Boolean).join(', ')}`);
|
|
1170
|
-
}
|
|
1171
|
-
return rest;
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Simplified respond method using SessionManager
|
|
1175
|
-
* Automatically manages conversation history through the session
|
|
1176
|
-
*/
|
|
1177
|
-
async chat(message, options) {
|
|
1178
|
-
// Delegate to ResponseModal.generate()
|
|
1179
|
-
return this._responseModal.generate(message, options);
|
|
1180
|
-
}
|
|
1181
|
-
/**
|
|
1182
|
-
* Modern streaming API - simple interface like chat() but returns a stream
|
|
1183
|
-
* Automatically manages conversation history through the session
|
|
1184
|
-
*/
|
|
1185
|
-
async *stream(message, options) {
|
|
1186
|
-
// Delegate to ResponseModal with the same options structure as chat()
|
|
1187
|
-
yield* this._responseModal.stream(message, {
|
|
1188
|
-
history: options?.history,
|
|
1189
|
-
contextOverride: options?.contextOverride,
|
|
1190
|
-
signal: options?.signal,
|
|
1191
|
-
});
|
|
1192
|
-
}
|
|
1193
119
|
}
|
|
1194
120
|
//# sourceMappingURL=Agent.js.map
|