dotdo 0.0.1 → 0.1.0
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/LICENSE +1 -1
- package/README.md +446 -315
- package/cli/README.md +238 -0
- package/cli/agent.ts +72 -0
- package/cli/bin.js +44 -0
- package/cli/bin.ts +38 -0
- package/cli/build.ts +157 -0
- package/cli/commands/auth/login.ts +14 -0
- package/cli/commands/auth/logout.ts +6 -0
- package/cli/commands/auth/whoami.ts +16 -0
- package/cli/commands/deploy-multi.ts +245 -0
- package/cli/commands/dev/deploy.ts +100 -0
- package/cli/commands/dev/dev.ts +95 -0
- package/cli/commands/dev/logs.ts +91 -0
- package/cli/commands/dev-local.ts +88 -0
- package/cli/commands/do-ops.ts +314 -0
- package/cli/commands/index.ts +100 -0
- package/cli/commands/init.ts +247 -0
- package/cli/commands/introspect/emitter.ts +315 -0
- package/cli/commands/introspect/index.ts +193 -0
- package/cli/commands/link.ts +598 -0
- package/cli/commands/snippets.ts +415 -0
- package/cli/commands/tunnel.ts +239 -0
- package/cli/device-auth.ts +289 -0
- package/cli/fallback.ts +12 -0
- package/cli/index.ts +121 -0
- package/cli/main.ts +246 -0
- package/cli/mcp-stdio.ts +790 -0
- package/cli/package.json +62 -0
- package/cli/runtime/do-registry.ts +193 -0
- package/cli/runtime/embedded-db.ts +344 -0
- package/cli/runtime/index.ts +9 -0
- package/cli/runtime/miniflare-adapter.ts +162 -0
- package/cli/sandbox.ts +82 -0
- package/cli/src/args.ts +174 -0
- package/cli/src/auth.ts +55 -0
- package/cli/src/commands/call.ts +84 -0
- package/cli/src/commands/charge.ts +96 -0
- package/cli/src/commands/config.ts +115 -0
- package/cli/src/commands/email.ts +112 -0
- package/cli/src/commands/llm.ts +115 -0
- package/cli/src/commands/queue.ts +134 -0
- package/cli/src/commands/text.ts +86 -0
- package/cli/src/config.ts +185 -0
- package/cli/src/output.ts +246 -0
- package/cli/src/rpc.ts +192 -0
- package/cli/utils/config.ts +282 -0
- package/cli/utils/detect.ts +73 -0
- package/cli/utils/index.ts +15 -0
- package/cli/utils/logger.ts +232 -0
- package/dist/ai/index.js +19 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/ai/template-literals.js +852 -0
- package/dist/ai/template-literals.js.map +1 -0
- package/dist/api/middleware/auth-federation.js +573 -0
- package/dist/api/middleware/auth-federation.js.map +1 -0
- package/dist/api/middleware/auth.js +545 -0
- package/dist/api/middleware/auth.js.map +1 -0
- package/dist/db/actions.js +212 -0
- package/dist/db/actions.js.map +1 -0
- package/dist/db/auth.js +506 -0
- package/dist/db/auth.js.map +1 -0
- package/dist/db/branches.js +65 -0
- package/dist/db/branches.js.map +1 -0
- package/dist/db/clickhouse.js +1074 -0
- package/dist/db/clickhouse.js.map +1 -0
- package/dist/db/dlq.js +39 -0
- package/dist/db/dlq.js.map +1 -0
- package/dist/db/events.js +28 -0
- package/dist/db/events.js.map +1 -0
- package/dist/db/exec.js +64 -0
- package/dist/db/exec.js.map +1 -0
- package/dist/db/files.js +85 -0
- package/dist/db/files.js.map +1 -0
- package/dist/db/flags.js +24 -0
- package/dist/db/flags.js.map +1 -0
- package/dist/db/git.js +116 -0
- package/dist/db/git.js.map +1 -0
- package/dist/db/iceberg/inverted-index.js +862 -0
- package/dist/db/iceberg/inverted-index.js.map +1 -0
- package/dist/db/iceberg/puffin.js +878 -0
- package/dist/db/iceberg/puffin.js.map +1 -0
- package/dist/db/iceberg/search-manifest.js +422 -0
- package/dist/db/iceberg/search-manifest.js.map +1 -0
- package/dist/db/iceberg/types.js +8 -0
- package/dist/db/iceberg/types.js.map +1 -0
- package/dist/db/index.js +121 -0
- package/dist/db/index.js.map +1 -0
- package/dist/db/integrations.js +368 -0
- package/dist/db/integrations.js.map +1 -0
- package/dist/db/json-indexes.js +332 -0
- package/dist/db/json-indexes.js.map +1 -0
- package/dist/db/linked-accounts.js +287 -0
- package/dist/db/linked-accounts.js.map +1 -0
- package/dist/db/nouns.js +183 -0
- package/dist/db/nouns.js.map +1 -0
- package/dist/db/objects.js +170 -0
- package/dist/db/objects.js.map +1 -0
- package/dist/db/primitives/dag-scheduler/index.js +869 -0
- package/dist/db/primitives/dag-scheduler/index.js.map +1 -0
- package/dist/db/primitives/exactly-once-context.js +237 -0
- package/dist/db/primitives/exactly-once-context.js.map +1 -0
- package/dist/db/primitives/index.js +62 -0
- package/dist/db/primitives/index.js.map +1 -0
- package/dist/db/primitives/keyed-router.js +145 -0
- package/dist/db/primitives/keyed-router.js.map +1 -0
- package/dist/db/primitives/observability.js +162 -0
- package/dist/db/primitives/observability.js.map +1 -0
- package/dist/db/primitives/schema-evolution.js +643 -0
- package/dist/db/primitives/schema-evolution.js.map +1 -0
- package/dist/db/primitives/stateful-operator/index.js +770 -0
- package/dist/db/primitives/stateful-operator/index.js.map +1 -0
- package/dist/db/primitives/temporal-store.js +306 -0
- package/dist/db/primitives/temporal-store.js.map +1 -0
- package/dist/db/primitives/typed-column-store.js +1229 -0
- package/dist/db/primitives/typed-column-store.js.map +1 -0
- package/dist/db/primitives/utils/duration.js +162 -0
- package/dist/db/primitives/utils/duration.js.map +1 -0
- package/dist/db/primitives/utils/murmur3.js +116 -0
- package/dist/db/primitives/utils/murmur3.js.map +1 -0
- package/dist/db/primitives/watermark-service.js +136 -0
- package/dist/db/primitives/watermark-service.js.map +1 -0
- package/dist/db/primitives/window-manager.js +764 -0
- package/dist/db/primitives/window-manager.js.map +1 -0
- package/dist/db/relationships.js +66 -0
- package/dist/db/relationships.js.map +1 -0
- package/dist/db/schema-minimal.js +61 -0
- package/dist/db/schema-minimal.js.map +1 -0
- package/dist/db/search.js +28 -0
- package/dist/db/search.js.map +1 -0
- package/dist/db/stores.js +1665 -0
- package/dist/db/stores.js.map +1 -0
- package/dist/db/things.js +297 -0
- package/dist/db/things.js.map +1 -0
- package/dist/db/vault.js +171 -0
- package/dist/db/vault.js.map +1 -0
- package/dist/db/verbs.js +102 -0
- package/dist/db/verbs.js.map +1 -0
- package/dist/do/base.js +48 -0
- package/dist/do/base.js.map +1 -0
- package/dist/do/tiny.js +31 -0
- package/dist/do/tiny.js.map +1 -0
- package/dist/lib/DOAuth.js +261 -0
- package/dist/lib/DOAuth.js.map +1 -0
- package/dist/lib/DODispatcher.js +72 -0
- package/dist/lib/DODispatcher.js.map +1 -0
- package/dist/lib/Modifier.js +189 -0
- package/dist/lib/Modifier.js.map +1 -0
- package/dist/lib/StateStorage.js +403 -0
- package/dist/lib/StateStorage.js.map +1 -0
- package/dist/lib/TypeRegistry.js +122 -0
- package/dist/lib/TypeRegistry.js.map +1 -0
- package/dist/lib/ai/gateway.js +247 -0
- package/dist/lib/ai/gateway.js.map +1 -0
- package/dist/lib/ai/tool-loop-agent.js +591 -0
- package/dist/lib/ai/tool-loop-agent.js.map +1 -0
- package/dist/lib/auto-wiring.js +439 -0
- package/dist/lib/auto-wiring.js.map +1 -0
- package/dist/lib/browse/browserbase.js +163 -0
- package/dist/lib/browse/browserbase.js.map +1 -0
- package/dist/lib/browse/cloudflare.js +144 -0
- package/dist/lib/browse/cloudflare.js.map +1 -0
- package/dist/lib/browse/index.js +62 -0
- package/dist/lib/browse/index.js.map +1 -0
- package/dist/lib/browse/types.js +13 -0
- package/dist/lib/browse/types.js.map +1 -0
- package/dist/lib/cache/index.js +37 -0
- package/dist/lib/cache/index.js.map +1 -0
- package/dist/lib/cache/visibility.js +638 -0
- package/dist/lib/cache/visibility.js.map +1 -0
- package/dist/lib/capabilities.js +268 -0
- package/dist/lib/capabilities.js.map +1 -0
- package/dist/lib/channels/base.js +106 -0
- package/dist/lib/channels/base.js.map +1 -0
- package/dist/lib/channels/discord.js +94 -0
- package/dist/lib/channels/discord.js.map +1 -0
- package/dist/lib/channels/email.js +204 -0
- package/dist/lib/channels/email.js.map +1 -0
- package/dist/lib/channels/index.js +90 -0
- package/dist/lib/channels/index.js.map +1 -0
- package/dist/lib/channels/mdxui-chat.js +95 -0
- package/dist/lib/channels/mdxui-chat.js.map +1 -0
- package/dist/lib/channels/slack-blockkit.js +121 -0
- package/dist/lib/channels/slack-blockkit.js.map +1 -0
- package/dist/lib/channels/types.js +7 -0
- package/dist/lib/channels/types.js.map +1 -0
- package/dist/lib/cloudflare/ai.js +654 -0
- package/dist/lib/cloudflare/ai.js.map +1 -0
- package/dist/lib/cloudflare/index.js +88 -0
- package/dist/lib/cloudflare/index.js.map +1 -0
- package/dist/lib/cloudflare/kv.js +342 -0
- package/dist/lib/cloudflare/kv.js.map +1 -0
- package/dist/lib/cloudflare/queues.js +434 -0
- package/dist/lib/cloudflare/queues.js.map +1 -0
- package/dist/lib/cloudflare/r2.js +604 -0
- package/dist/lib/cloudflare/r2.js.map +1 -0
- package/dist/lib/cloudflare/vectorize.js +494 -0
- package/dist/lib/cloudflare/vectorize.js.map +1 -0
- package/dist/lib/cloudflare/workflows.js +569 -0
- package/dist/lib/cloudflare/workflows.js.map +1 -0
- package/dist/lib/colo/caching.js +196 -0
- package/dist/lib/colo/caching.js.map +1 -0
- package/dist/lib/colo/detection.js +194 -0
- package/dist/lib/colo/detection.js.map +1 -0
- package/dist/lib/colo/external-data.js +219 -0
- package/dist/lib/colo/external-data.js.map +1 -0
- package/dist/lib/colo/globe-data.js +179 -0
- package/dist/lib/colo/globe-data.js.map +1 -0
- package/dist/lib/colo/index.js +16 -0
- package/dist/lib/colo/index.js.map +1 -0
- package/dist/lib/decorators.js +37 -0
- package/dist/lib/decorators.js.map +1 -0
- package/dist/lib/discovery.js +81 -0
- package/dist/lib/discovery.js.map +1 -0
- package/dist/lib/executors/AgenticFunctionExecutor.js +619 -0
- package/dist/lib/executors/AgenticFunctionExecutor.js.map +1 -0
- package/dist/lib/executors/BaseFunctionExecutor.js +328 -0
- package/dist/lib/executors/BaseFunctionExecutor.js.map +1 -0
- package/dist/lib/executors/CascadeExecutor.js +418 -0
- package/dist/lib/executors/CascadeExecutor.js.map +1 -0
- package/dist/lib/executors/CodeFunctionExecutor.js +904 -0
- package/dist/lib/executors/CodeFunctionExecutor.js.map +1 -0
- package/dist/lib/executors/GenerativeFunctionExecutor.js +904 -0
- package/dist/lib/executors/GenerativeFunctionExecutor.js.map +1 -0
- package/dist/lib/executors/HumanFunctionExecutor.js +884 -0
- package/dist/lib/executors/HumanFunctionExecutor.js.map +1 -0
- package/dist/lib/executors/ParallelStepExecutor.js +308 -0
- package/dist/lib/executors/ParallelStepExecutor.js.map +1 -0
- package/dist/lib/executors/types.js +12 -0
- package/dist/lib/executors/types.js.map +1 -0
- package/dist/lib/experiments.js +89 -0
- package/dist/lib/experiments.js.map +1 -0
- package/dist/lib/flags/store.js +262 -0
- package/dist/lib/flags/store.js.map +1 -0
- package/dist/lib/functions/FunctionComposition.js +467 -0
- package/dist/lib/functions/FunctionComposition.js.map +1 -0
- package/dist/lib/functions/FunctionMiddleware.js +457 -0
- package/dist/lib/functions/FunctionMiddleware.js.map +1 -0
- package/dist/lib/functions/FunctionRegistry.js +426 -0
- package/dist/lib/functions/FunctionRegistry.js.map +1 -0
- package/dist/lib/functions/createFunction.js +1048 -0
- package/dist/lib/functions/createFunction.js.map +1 -0
- package/dist/lib/humans/index.js +68 -0
- package/dist/lib/humans/index.js.map +1 -0
- package/dist/lib/humans/templates.js +117 -0
- package/dist/lib/humans/templates.js.map +1 -0
- package/dist/lib/identity.js +98 -0
- package/dist/lib/identity.js.map +1 -0
- package/dist/lib/index.js +9 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/logging/error-logger.js +163 -0
- package/dist/lib/logging/error-logger.js.map +1 -0
- package/dist/lib/logging/index.js +160 -0
- package/dist/lib/logging/index.js.map +1 -0
- package/dist/lib/mixins/bash.js +753 -0
- package/dist/lib/mixins/bash.js.map +1 -0
- package/dist/lib/mixins/fs.js +648 -0
- package/dist/lib/mixins/fs.js.map +1 -0
- package/dist/lib/mixins/git.js +1006 -0
- package/dist/lib/mixins/git.js.map +1 -0
- package/dist/lib/mixins/npm.js +662 -0
- package/dist/lib/mixins/npm.js.map +1 -0
- package/dist/lib/noun-id.js +278 -0
- package/dist/lib/noun-id.js.map +1 -0
- package/dist/lib/rate-limit/sliding-window.js +148 -0
- package/dist/lib/rate-limit/sliding-window.js.map +1 -0
- package/dist/lib/rate-limit.js +110 -0
- package/dist/lib/rate-limit.js.map +1 -0
- package/dist/lib/rpc/bindings.js +548 -0
- package/dist/lib/rpc/bindings.js.map +1 -0
- package/dist/lib/rpc/index.js +64 -0
- package/dist/lib/rpc/index.js.map +1 -0
- package/dist/lib/safe-stringify.js +223 -0
- package/dist/lib/safe-stringify.js.map +1 -0
- package/dist/lib/sandbox/miniflare-sandbox.js +1007 -0
- package/dist/lib/sandbox/miniflare-sandbox.js.map +1 -0
- package/dist/lib/sqids.js +110 -0
- package/dist/lib/sqids.js.map +1 -0
- package/dist/lib/sql/adapters/index.js +10 -0
- package/dist/lib/sql/adapters/index.js.map +1 -0
- package/dist/lib/sql/adapters/node-sql-parser.js +552 -0
- package/dist/lib/sql/adapters/node-sql-parser.js.map +1 -0
- package/dist/lib/sql/adapters/pgsql-parser.js +1190 -0
- package/dist/lib/sql/adapters/pgsql-parser.js.map +1 -0
- package/dist/lib/sql/index.js +277 -0
- package/dist/lib/sql/index.js.map +1 -0
- package/dist/lib/sql/types.js +56 -0
- package/dist/lib/sql/types.js.map +1 -0
- package/dist/lib/type-classifier.js +126 -0
- package/dist/lib/type-classifier.js.map +1 -0
- package/dist/lib/utils/html.js +47 -0
- package/dist/lib/utils/html.js.map +1 -0
- package/dist/lib/validation.js +48 -0
- package/dist/lib/validation.js.map +1 -0
- package/dist/lib/vault/store.js +411 -0
- package/dist/lib/vault/store.js.map +1 -0
- package/dist/metrics/hunch.js +739 -0
- package/dist/metrics/hunch.js.map +1 -0
- package/dist/objects/API.js +302 -0
- package/dist/objects/API.js.map +1 -0
- package/dist/objects/Agent.js +179 -0
- package/dist/objects/Agent.js.map +1 -0
- package/dist/objects/AgenticFunctionExecutor.js +8 -0
- package/dist/objects/AgenticFunctionExecutor.js.map +1 -0
- package/dist/objects/App.js +83 -0
- package/dist/objects/App.js.map +1 -0
- package/dist/objects/Browser.js +884 -0
- package/dist/objects/Browser.js.map +1 -0
- package/dist/objects/Business.js +107 -0
- package/dist/objects/Business.js.map +1 -0
- package/dist/objects/CLI.js +221 -0
- package/dist/objects/CLI.js.map +1 -0
- package/dist/objects/CodeFunctionExecutor.js +8 -0
- package/dist/objects/CodeFunctionExecutor.js.map +1 -0
- package/dist/objects/Collection.js +161 -0
- package/dist/objects/Collection.js.map +1 -0
- package/dist/objects/DO.js +41 -0
- package/dist/objects/DO.js.map +1 -0
- package/dist/objects/DOBase.js +2309 -0
- package/dist/objects/DOBase.js.map +1 -0
- package/dist/objects/DOCache.js +153 -0
- package/dist/objects/DOCache.js.map +1 -0
- package/dist/objects/DOFull.js +1676 -0
- package/dist/objects/DOFull.js.map +1 -0
- package/dist/objects/DOTiny.js +207 -0
- package/dist/objects/DOTiny.js.map +1 -0
- package/dist/objects/Directory.js +199 -0
- package/dist/objects/Directory.js.map +1 -0
- package/dist/objects/Entity.js +413 -0
- package/dist/objects/Entity.js.map +1 -0
- package/dist/objects/Function.js +116 -0
- package/dist/objects/Function.js.map +1 -0
- package/dist/objects/Human.js +231 -0
- package/dist/objects/Human.js.map +1 -0
- package/dist/objects/HumanFunctionExecutor.js +8 -0
- package/dist/objects/HumanFunctionExecutor.js.map +1 -0
- package/dist/objects/IcebergMetadataDO.js +938 -0
- package/dist/objects/IcebergMetadataDO.js.map +1 -0
- package/dist/objects/IntegrationsDO.js +1174 -0
- package/dist/objects/IntegrationsDO.js.map +1 -0
- package/dist/objects/ObservabilityBroadcaster.js +149 -0
- package/dist/objects/ObservabilityBroadcaster.js.map +1 -0
- package/dist/objects/Package.js +154 -0
- package/dist/objects/Package.js.map +1 -0
- package/dist/objects/Product.js +193 -0
- package/dist/objects/Product.js.map +1 -0
- package/dist/objects/SDK.js +152 -0
- package/dist/objects/SDK.js.map +1 -0
- package/dist/objects/SaaS.js +235 -0
- package/dist/objects/SaaS.js.map +1 -0
- package/dist/objects/SandboxDO.js +759 -0
- package/dist/objects/SandboxDO.js.map +1 -0
- package/dist/objects/Service.js +337 -0
- package/dist/objects/Service.js.map +1 -0
- package/dist/objects/Site.js +80 -0
- package/dist/objects/Site.js.map +1 -0
- package/dist/objects/Startup.js +479 -0
- package/dist/objects/Startup.js.map +1 -0
- package/dist/objects/ThingsDO.js +170 -0
- package/dist/objects/ThingsDO.js.map +1 -0
- package/dist/objects/VectorShardDO.js +650 -0
- package/dist/objects/VectorShardDO.js.map +1 -0
- package/dist/objects/Worker.js +144 -0
- package/dist/objects/Worker.js.map +1 -0
- package/dist/objects/Workflow.js +196 -0
- package/dist/objects/Workflow.js.map +1 -0
- package/dist/objects/WorkflowFactory.js +313 -0
- package/dist/objects/WorkflowFactory.js.map +1 -0
- package/dist/objects/WorkflowRuntime.js +863 -0
- package/dist/objects/WorkflowRuntime.js.map +1 -0
- package/dist/objects/circuit-breaker-bulkhead.js +178 -0
- package/dist/objects/circuit-breaker-bulkhead.js.map +1 -0
- package/dist/objects/createFunction.js +934 -0
- package/dist/objects/createFunction.js.map +1 -0
- package/dist/objects/index.js +80 -0
- package/dist/objects/index.js.map +1 -0
- package/dist/objects/lifecycle/Branch.js +275 -0
- package/dist/objects/lifecycle/Branch.js.map +1 -0
- package/dist/objects/lifecycle/Clone.js +1499 -0
- package/dist/objects/lifecycle/Clone.js.map +1 -0
- package/dist/objects/lifecycle/Compact.js +237 -0
- package/dist/objects/lifecycle/Compact.js.map +1 -0
- package/dist/objects/lifecycle/Promote.js +476 -0
- package/dist/objects/lifecycle/Promote.js.map +1 -0
- package/dist/objects/lifecycle/Shard.js +560 -0
- package/dist/objects/lifecycle/Shard.js.map +1 -0
- package/dist/objects/lifecycle/index.js +15 -0
- package/dist/objects/lifecycle/index.js.map +1 -0
- package/dist/objects/lifecycle/types.js +33 -0
- package/dist/objects/lifecycle/types.js.map +1 -0
- package/dist/objects/mixins/infrastructure.js +171 -0
- package/dist/objects/mixins/infrastructure.js.map +1 -0
- package/dist/objects/modules/StoresModule.js +153 -0
- package/dist/objects/modules/StoresModule.js.map +1 -0
- package/dist/objects/persistence/checkpoint-manager.js +606 -0
- package/dist/objects/persistence/checkpoint-manager.js.map +1 -0
- package/dist/objects/persistence/index.js +72 -0
- package/dist/objects/persistence/index.js.map +1 -0
- package/dist/objects/persistence/migration-runner.js +562 -0
- package/dist/objects/persistence/migration-runner.js.map +1 -0
- package/dist/objects/persistence/replication-manager.js +501 -0
- package/dist/objects/persistence/replication-manager.js.map +1 -0
- package/dist/objects/persistence/tiered-storage-manager.js +595 -0
- package/dist/objects/persistence/tiered-storage-manager.js.map +1 -0
- package/dist/objects/persistence/types.js +14 -0
- package/dist/objects/persistence/types.js.map +1 -0
- package/dist/objects/persistence/wal-manager.js +653 -0
- package/dist/objects/persistence/wal-manager.js.map +1 -0
- package/dist/objects/presets/index.js +20 -0
- package/dist/objects/presets/index.js.map +1 -0
- package/dist/objects/presets/primitives.js +188 -0
- package/dist/objects/presets/primitives.js.map +1 -0
- package/dist/objects/primitives/alarm-adapter.js +141 -0
- package/dist/objects/primitives/alarm-adapter.js.map +1 -0
- package/dist/objects/primitives/index.js +337 -0
- package/dist/objects/primitives/index.js.map +1 -0
- package/dist/objects/primitives/storage-adapter.js +182 -0
- package/dist/objects/primitives/storage-adapter.js.map +1 -0
- package/dist/objects/primitives/with-primitives.js +102 -0
- package/dist/objects/primitives/with-primitives.js.map +1 -0
- package/dist/objects/services/StoreManager.js +227 -0
- package/dist/objects/services/StoreManager.js.map +1 -0
- package/dist/objects/services/index.js +13 -0
- package/dist/objects/services/index.js.map +1 -0
- package/dist/objects/transport/auth-layer.js +1451 -0
- package/dist/objects/transport/auth-layer.js.map +1 -0
- package/dist/objects/transport/capnweb-target.js +355 -0
- package/dist/objects/transport/capnweb-target.js.map +1 -0
- package/dist/objects/transport/chain.js +441 -0
- package/dist/objects/transport/chain.js.map +1 -0
- package/dist/objects/transport/handler.js +58 -0
- package/dist/objects/transport/handler.js.map +1 -0
- package/dist/objects/transport/index.js +53 -0
- package/dist/objects/transport/index.js.map +1 -0
- package/dist/objects/transport/mcp-server.js +691 -0
- package/dist/objects/transport/mcp-server.js.map +1 -0
- package/dist/objects/transport/rest-autowire.js +1508 -0
- package/dist/objects/transport/rest-autowire.js.map +1 -0
- package/dist/objects/transport/rest-router.js +440 -0
- package/dist/objects/transport/rest-router.js.map +1 -0
- package/dist/objects/transport/rpc-server.js +1539 -0
- package/dist/objects/transport/rpc-server.js.map +1 -0
- package/dist/objects/transport/shared.js +576 -0
- package/dist/objects/transport/shared.js.map +1 -0
- package/dist/objects/transport/sync-engine.js +291 -0
- package/dist/objects/transport/sync-engine.js.map +1 -0
- package/dist/objects/transport/types.js +8 -0
- package/dist/objects/transport/types.js.map +1 -0
- package/dist/sandbox/index.js +258 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/snippets/artifacts-config.js +241 -0
- package/dist/snippets/artifacts-config.js.map +1 -0
- package/dist/snippets/artifacts-ingest.js +832 -0
- package/dist/snippets/artifacts-ingest.js.map +1 -0
- package/dist/snippets/artifacts-serve.js +1035 -0
- package/dist/snippets/artifacts-serve.js.map +1 -0
- package/dist/snippets/artifacts-types.js +161 -0
- package/dist/snippets/artifacts-types.js.map +1 -0
- package/dist/snippets/cache-probe.js +376 -0
- package/dist/snippets/cache-probe.js.map +1 -0
- package/dist/snippets/cache.js +10 -0
- package/dist/snippets/cache.js.map +1 -0
- package/dist/snippets/events.js +469 -0
- package/dist/snippets/events.js.map +1 -0
- package/dist/snippets/index.js +7 -0
- package/dist/snippets/index.js.map +1 -0
- package/dist/snippets/proxy.js +495 -0
- package/dist/snippets/proxy.js.map +1 -0
- package/dist/snippets/search.js +1759 -0
- package/dist/snippets/search.js.map +1 -0
- package/dist/streams/index.js +30 -0
- package/dist/streams/index.js.map +1 -0
- package/dist/streams/observability.js +68 -0
- package/dist/streams/observability.js.map +1 -0
- package/dist/types/AI.js +92 -0
- package/dist/types/AI.js.map +1 -0
- package/dist/types/AIFunction.js +171 -0
- package/dist/types/AIFunction.js.map +1 -0
- package/dist/types/BrowseVerb.js +89 -0
- package/dist/types/BrowseVerb.js.map +1 -0
- package/dist/types/Browser.js +31 -0
- package/dist/types/Browser.js.map +1 -0
- package/dist/types/Chaos.js +15 -0
- package/dist/types/Chaos.js.map +1 -0
- package/dist/types/CloudflareBindings.js +109 -0
- package/dist/types/CloudflareBindings.js.map +1 -0
- package/dist/types/Collection.js +50 -0
- package/dist/types/Collection.js.map +1 -0
- package/dist/types/DO.js +2 -0
- package/dist/types/DO.js.map +1 -0
- package/dist/types/DOLocation.js +63 -0
- package/dist/types/DOLocation.js.map +1 -0
- package/dist/types/EventHandler.js +57 -0
- package/dist/types/EventHandler.js.map +1 -0
- package/dist/types/Experiment.js +33 -0
- package/dist/types/Experiment.js.map +1 -0
- package/dist/types/Flag.js +57 -0
- package/dist/types/Flag.js.map +1 -0
- package/dist/types/Lifecycle.js +13 -0
- package/dist/types/Lifecycle.js.map +1 -0
- package/dist/types/Location.js +169 -0
- package/dist/types/Location.js.map +1 -0
- package/dist/types/Noun.js +66 -0
- package/dist/types/Noun.js.map +1 -0
- package/dist/types/SessionEvent.js +194 -0
- package/dist/types/SessionEvent.js.map +1 -0
- package/dist/types/Thing.js +55 -0
- package/dist/types/Thing.js.map +1 -0
- package/dist/types/ThingDO.js +153 -0
- package/dist/types/ThingDO.js.map +1 -0
- package/dist/types/Things.js +2 -0
- package/dist/types/Things.js.map +1 -0
- package/dist/types/Verb.js +119 -0
- package/dist/types/Verb.js.map +1 -0
- package/dist/types/WorkflowContext.js +70 -0
- package/dist/types/WorkflowContext.js.map +1 -0
- package/dist/types/analytics-api.js +13 -0
- package/dist/types/analytics-api.js.map +1 -0
- package/dist/types/capabilities.js +135 -0
- package/dist/types/capabilities.js.map +1 -0
- package/dist/types/drizzle.js +12 -0
- package/dist/types/drizzle.js.map +1 -0
- package/dist/types/event.js +201 -0
- package/dist/types/event.js.map +1 -0
- package/dist/types/fn.js +12 -0
- package/dist/types/fn.js.map +1 -0
- package/dist/types/iceberg.js +48 -0
- package/dist/types/iceberg.js.map +1 -0
- package/dist/types/ids.js +170 -0
- package/dist/types/ids.js.map +1 -0
- package/dist/types/index.js +41 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/introspect.js +54 -0
- package/dist/types/introspect.js.map +1 -0
- package/dist/types/observability.js +124 -0
- package/dist/types/observability.js.map +1 -0
- package/dist/types/sync-protocol.js +175 -0
- package/dist/types/sync-protocol.js.map +1 -0
- package/dist/types/vector.js +13 -0
- package/dist/types/vector.js.map +1 -0
- package/dist/workflows/ScheduleManager.js +473 -0
- package/dist/workflows/ScheduleManager.js.map +1 -0
- package/dist/workflows/StepDOBridge.js +149 -0
- package/dist/workflows/StepDOBridge.js.map +1 -0
- package/dist/workflows/StepResultStorage.js +232 -0
- package/dist/workflows/StepResultStorage.js.map +1 -0
- package/dist/workflows/WaitForEventManager.js +461 -0
- package/dist/workflows/WaitForEventManager.js.map +1 -0
- package/dist/workflows/analyzer.js +332 -0
- package/dist/workflows/analyzer.js.map +1 -0
- package/dist/workflows/compat/activity-router.js +484 -0
- package/dist/workflows/compat/activity-router.js.map +1 -0
- package/dist/workflows/compat/backends/cloudflare-workflows.js +431 -0
- package/dist/workflows/compat/backends/cloudflare-workflows.js.map +1 -0
- package/dist/workflows/compat/backends/index.js +14 -0
- package/dist/workflows/compat/backends/index.js.map +1 -0
- package/dist/workflows/compat/errors/index.js +375 -0
- package/dist/workflows/compat/errors/index.js.map +1 -0
- package/dist/workflows/compat/index.js +79 -0
- package/dist/workflows/compat/index.js.map +1 -0
- package/dist/workflows/compat/inngest/index.js +989 -0
- package/dist/workflows/compat/inngest/index.js.map +1 -0
- package/dist/workflows/compat/qstash/index.js +1263 -0
- package/dist/workflows/compat/qstash/index.js.map +1 -0
- package/dist/workflows/compat/temporal/activities.js +739 -0
- package/dist/workflows/compat/temporal/activities.js.map +1 -0
- package/dist/workflows/compat/temporal/child-workflows.js +154 -0
- package/dist/workflows/compat/temporal/child-workflows.js.map +1 -0
- package/dist/workflows/compat/temporal/client.js +381 -0
- package/dist/workflows/compat/temporal/client.js.map +1 -0
- package/dist/workflows/compat/temporal/context.js +309 -0
- package/dist/workflows/compat/temporal/context.js.map +1 -0
- package/dist/workflows/compat/temporal/determinism.js +216 -0
- package/dist/workflows/compat/temporal/determinism.js.map +1 -0
- package/dist/workflows/compat/temporal/errors.js +128 -0
- package/dist/workflows/compat/temporal/errors.js.map +1 -0
- package/dist/workflows/compat/temporal/index.js +2464 -0
- package/dist/workflows/compat/temporal/index.js.map +1 -0
- package/dist/workflows/compat/temporal/saga.js +504 -0
- package/dist/workflows/compat/temporal/saga.js.map +1 -0
- package/dist/workflows/compat/temporal/signals.js +364 -0
- package/dist/workflows/compat/temporal/signals.js.map +1 -0
- package/dist/workflows/compat/temporal/storage.js +271 -0
- package/dist/workflows/compat/temporal/storage.js.map +1 -0
- package/dist/workflows/compat/temporal/timers.js +347 -0
- package/dist/workflows/compat/temporal/timers.js.map +1 -0
- package/dist/workflows/compat/temporal/types.js +7 -0
- package/dist/workflows/compat/temporal/types.js.map +1 -0
- package/dist/workflows/compat/temporal/unified-primitives.js +339 -0
- package/dist/workflows/compat/temporal/unified-primitives.js.map +1 -0
- package/dist/workflows/compat/trigger/index.js +468 -0
- package/dist/workflows/compat/trigger/index.js.map +1 -0
- package/dist/workflows/compat/utils/index.js +69 -0
- package/dist/workflows/compat/utils/index.js.map +1 -0
- package/dist/workflows/context/correlation-capability.js +266 -0
- package/dist/workflows/context/correlation-capability.js.map +1 -0
- package/dist/workflows/context/correlation.js +484 -0
- package/dist/workflows/context/correlation.js.map +1 -0
- package/dist/workflows/context/experiment.js +289 -0
- package/dist/workflows/context/experiment.js.map +1 -0
- package/dist/workflows/context/flag.js +244 -0
- package/dist/workflows/context/flag.js.map +1 -0
- package/dist/workflows/context/foundation.js +648 -0
- package/dist/workflows/context/foundation.js.map +1 -0
- package/dist/workflows/context/human-base.js +106 -0
- package/dist/workflows/context/human-base.js.map +1 -0
- package/dist/workflows/context/human.js +368 -0
- package/dist/workflows/context/human.js.map +1 -0
- package/dist/workflows/context/measure.js +354 -0
- package/dist/workflows/context/measure.js.map +1 -0
- package/dist/workflows/context/rate-limit.js +358 -0
- package/dist/workflows/context/rate-limit.js.map +1 -0
- package/dist/workflows/context/user.js +117 -0
- package/dist/workflows/context/user.js.map +1 -0
- package/dist/workflows/context/vault.js +360 -0
- package/dist/workflows/context/vault.js.map +1 -0
- package/dist/workflows/data/entity-events/entity-events.js +489 -0
- package/dist/workflows/data/entity-events/entity-events.js.map +1 -0
- package/dist/workflows/data/experiment/index.js +599 -0
- package/dist/workflows/data/experiment/index.js.map +1 -0
- package/dist/workflows/data/goal/context.js +558 -0
- package/dist/workflows/data/goal/context.js.map +1 -0
- package/dist/workflows/data/goal/index.js +32 -0
- package/dist/workflows/data/goal/index.js.map +1 -0
- package/dist/workflows/data/measure/index.js +840 -0
- package/dist/workflows/data/measure/index.js.map +1 -0
- package/dist/workflows/data/stream/index.js +1149 -0
- package/dist/workflows/data/stream/index.js.map +1 -0
- package/dist/workflows/data/track/context.js +883 -0
- package/dist/workflows/data/track/context.js.map +1 -0
- package/dist/workflows/data/track/index.js +15 -0
- package/dist/workflows/data/track/index.js.map +1 -0
- package/dist/workflows/data/view/context.js +864 -0
- package/dist/workflows/data/view/context.js.map +1 -0
- package/dist/workflows/domain.js +93 -0
- package/dist/workflows/domain.js.map +1 -0
- package/dist/workflows/flag.js +176 -0
- package/dist/workflows/flag.js.map +1 -0
- package/dist/workflows/flags.js +217 -0
- package/dist/workflows/flags.js.map +1 -0
- package/dist/workflows/hash.js +209 -0
- package/dist/workflows/hash.js.map +1 -0
- package/dist/workflows/index.js +50 -0
- package/dist/workflows/index.js.map +1 -0
- package/dist/workflows/on.js +378 -0
- package/dist/workflows/on.js.map +1 -0
- package/dist/workflows/pipeline-promise.js +481 -0
- package/dist/workflows/pipeline-promise.js.map +1 -0
- package/dist/workflows/pipeline-types.js +20 -0
- package/dist/workflows/pipeline-types.js.map +1 -0
- package/dist/workflows/proxy.js +76 -0
- package/dist/workflows/proxy.js.map +1 -0
- package/dist/workflows/runtime.js +310 -0
- package/dist/workflows/runtime.js.map +1 -0
- package/dist/workflows/schedule-builder.js +327 -0
- package/dist/workflows/schedule-builder.js.map +1 -0
- package/dist/workflows/visibility/index.js +146 -0
- package/dist/workflows/visibility/index.js.map +1 -0
- package/dist/workflows/visibility/query-parser.js +150 -0
- package/dist/workflows/visibility/query-parser.js.map +1 -0
- package/dist/workflows/visibility/store.js +223 -0
- package/dist/workflows/visibility/store.js.map +1 -0
- package/dist/workflows/visibility/types.js +30 -0
- package/dist/workflows/visibility/types.js.map +1 -0
- package/dist/workflows/workflow.js +53 -0
- package/dist/workflows/workflow.js.map +1 -0
- package/package.json +294 -46
|
@@ -0,0 +1,904 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GenerativeFunctionExecutor
|
|
3
|
+
*
|
|
4
|
+
* Executor for GenerativeFunction - calls LLM models (Claude, GPT, etc.)
|
|
5
|
+
* with prompt templates, structured output schemas, streaming support,
|
|
6
|
+
* and model configuration options.
|
|
7
|
+
*/
|
|
8
|
+
// ============================================================================
|
|
9
|
+
// ERROR TYPES
|
|
10
|
+
// ============================================================================
|
|
11
|
+
export class GenerativeModelError extends Error {
|
|
12
|
+
name = 'GenerativeModelError';
|
|
13
|
+
code;
|
|
14
|
+
constructor(message, code) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export class GenerativeValidationError extends Error {
|
|
20
|
+
name = 'GenerativeValidationError';
|
|
21
|
+
code;
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class GenerativeRateLimitError extends Error {
|
|
27
|
+
name = 'GenerativeRateLimitError';
|
|
28
|
+
code = 'rate_limit_exceeded';
|
|
29
|
+
retryAfter;
|
|
30
|
+
constructor(message, retryAfter) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.retryAfter = retryAfter;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class GenerativeTimeoutError extends Error {
|
|
36
|
+
name = 'GenerativeTimeoutError';
|
|
37
|
+
constructor(message = 'Generation timed out') {
|
|
38
|
+
super(message);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class GenerativeAbortError extends Error {
|
|
42
|
+
name = 'GenerativeAbortError';
|
|
43
|
+
constructor(message = 'Generation was aborted') {
|
|
44
|
+
super(message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export class GenerativeSchemaError extends Error {
|
|
48
|
+
name = 'GenerativeSchemaError';
|
|
49
|
+
validationErrors;
|
|
50
|
+
constructor(message, validationErrors) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.validationErrors = validationErrors;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export class GenerativeToolError extends Error {
|
|
56
|
+
name = 'GenerativeToolError';
|
|
57
|
+
toolName;
|
|
58
|
+
constructor(message, toolName) {
|
|
59
|
+
super(message);
|
|
60
|
+
this.toolName = toolName;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
// Model limits for validation
|
|
64
|
+
const MODEL_LIMITS = {
|
|
65
|
+
'claude-sonnet-4-20250514': { maxTokens: 8192 },
|
|
66
|
+
'claude-opus-4-20250514': { maxTokens: 8192 },
|
|
67
|
+
'gpt-4o': { maxTokens: 128000 },
|
|
68
|
+
'gpt-3.5-turbo': { maxTokens: 4096 },
|
|
69
|
+
};
|
|
70
|
+
const DEFAULT_MAX_TOKENS = 100000;
|
|
71
|
+
// Non-retryable error codes
|
|
72
|
+
const NON_RETRYABLE_ERRORS = new Set([
|
|
73
|
+
'authentication_error',
|
|
74
|
+
'invalid_api_key',
|
|
75
|
+
'permission_denied',
|
|
76
|
+
'invalid_request',
|
|
77
|
+
]);
|
|
78
|
+
// ============================================================================
|
|
79
|
+
// GENERATIVE FUNCTION EXECUTOR
|
|
80
|
+
// ============================================================================
|
|
81
|
+
export class GenerativeFunctionExecutor {
|
|
82
|
+
state;
|
|
83
|
+
env;
|
|
84
|
+
aiService;
|
|
85
|
+
onEvent;
|
|
86
|
+
constructor(context) {
|
|
87
|
+
this.state = context.state;
|
|
88
|
+
this.env = context.env;
|
|
89
|
+
this.aiService = context.aiService;
|
|
90
|
+
this.onEvent = context.onEvent;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Execute a generative function
|
|
94
|
+
*/
|
|
95
|
+
async execute(options) {
|
|
96
|
+
const startTime = Date.now();
|
|
97
|
+
const invocationId = crypto.randomUUID();
|
|
98
|
+
this.emit('generation.started', { invocationId });
|
|
99
|
+
try {
|
|
100
|
+
// Validate options
|
|
101
|
+
const validationError = this.validateOptions(options);
|
|
102
|
+
if (validationError) {
|
|
103
|
+
return this.createErrorResult(validationError, options.model, startTime);
|
|
104
|
+
}
|
|
105
|
+
// Resolve prompt
|
|
106
|
+
let prompt;
|
|
107
|
+
try {
|
|
108
|
+
prompt = await this.resolvePrompt(options);
|
|
109
|
+
}
|
|
110
|
+
catch (err) {
|
|
111
|
+
const error = err;
|
|
112
|
+
return this.createErrorResult(new GenerativeValidationError(error.message), options.model, startTime);
|
|
113
|
+
}
|
|
114
|
+
// Validate prompt is not empty
|
|
115
|
+
if (!prompt && !options.messages?.length) {
|
|
116
|
+
return this.createErrorResult(new GenerativeValidationError('prompt is empty or required'), options.model, startTime);
|
|
117
|
+
}
|
|
118
|
+
// Resolve system prompt template
|
|
119
|
+
const systemPrompt = options.systemPrompt
|
|
120
|
+
? this.substituteVariables(options.systemPrompt, options.variables || {})
|
|
121
|
+
: undefined;
|
|
122
|
+
// Load conversation history if requested
|
|
123
|
+
let messages = options.messages;
|
|
124
|
+
if (options.conversationId && options.loadHistory) {
|
|
125
|
+
const history = await this.loadConversationHistory(options.conversationId);
|
|
126
|
+
if (history) {
|
|
127
|
+
messages = [...history, ...(messages || [])];
|
|
128
|
+
if (prompt) {
|
|
129
|
+
messages.push({ role: 'user', content: prompt });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// Build messages if using prompt
|
|
134
|
+
if (!messages && prompt) {
|
|
135
|
+
messages = [{ role: 'user', content: prompt }];
|
|
136
|
+
}
|
|
137
|
+
// Validate messages
|
|
138
|
+
if (messages) {
|
|
139
|
+
const messageValidationError = this.validateMessages(messages);
|
|
140
|
+
if (messageValidationError) {
|
|
141
|
+
return this.createErrorResult(messageValidationError, options.model, startTime);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Check for tools
|
|
145
|
+
if (options.tools?.length) {
|
|
146
|
+
return this.executeWithTools(options, messages, systemPrompt, startTime, invocationId);
|
|
147
|
+
}
|
|
148
|
+
// Execute with retries
|
|
149
|
+
const result = await this.executeWithRetries(async () => this.aiService.generate({
|
|
150
|
+
model: options.model,
|
|
151
|
+
prompt,
|
|
152
|
+
messages,
|
|
153
|
+
systemPrompt,
|
|
154
|
+
temperature: options.temperature ?? 1.0,
|
|
155
|
+
maxTokens: options.maxTokens,
|
|
156
|
+
topP: options.topP,
|
|
157
|
+
topK: options.topK,
|
|
158
|
+
stopSequences: options.stopSequences,
|
|
159
|
+
presencePenalty: options.presencePenalty,
|
|
160
|
+
frequencyPenalty: options.frequencyPenalty,
|
|
161
|
+
}), options);
|
|
162
|
+
// Handle content filter
|
|
163
|
+
if (result.finishReason === 'content_filter') {
|
|
164
|
+
this.emit('generation.content_filtered', { invocationId });
|
|
165
|
+
}
|
|
166
|
+
// Track token usage
|
|
167
|
+
const usage = {
|
|
168
|
+
inputTokens: result.usage.inputTokens,
|
|
169
|
+
outputTokens: result.usage.outputTokens,
|
|
170
|
+
totalTokens: result.usage.inputTokens + result.usage.outputTokens,
|
|
171
|
+
};
|
|
172
|
+
this.emit('generation.tokens', usage);
|
|
173
|
+
// Handle schema validation if provided
|
|
174
|
+
let finalResult;
|
|
175
|
+
if (options.schema) {
|
|
176
|
+
try {
|
|
177
|
+
finalResult = await this.validateAndParseSchema(result.text, options.schema, options.coerceTypes ?? false, options.lenientParsing ?? false, options.schemaRetries ?? 1, options, messages, systemPrompt);
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
const error = err;
|
|
181
|
+
return this.createErrorResult(error instanceof GenerativeSchemaError ? error : new GenerativeSchemaError(error.message), options.model, startTime, usage, result.finishReason);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
finalResult = result.text;
|
|
186
|
+
}
|
|
187
|
+
// Save conversation history if requested
|
|
188
|
+
if (options.conversationId && options.saveHistory) {
|
|
189
|
+
await this.saveConversationHistory(options.conversationId, [
|
|
190
|
+
...(messages || []),
|
|
191
|
+
{ role: 'assistant', content: result.text },
|
|
192
|
+
]);
|
|
193
|
+
}
|
|
194
|
+
this.emit('generation.completed', {
|
|
195
|
+
invocationId,
|
|
196
|
+
conversationId: options.conversationId,
|
|
197
|
+
});
|
|
198
|
+
return {
|
|
199
|
+
success: true,
|
|
200
|
+
result: finalResult,
|
|
201
|
+
usage,
|
|
202
|
+
duration: Date.now() - startTime,
|
|
203
|
+
model: options.model,
|
|
204
|
+
finishReason: result.finishReason,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
const error = err;
|
|
209
|
+
return this.handleError(error, options.model, startTime);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Execute with streaming
|
|
214
|
+
*/
|
|
215
|
+
async executeStreaming(options, streamOptions) {
|
|
216
|
+
const invocationId = crypto.randomUUID();
|
|
217
|
+
this.emit('generation.stream.start', { invocationId });
|
|
218
|
+
// Validate options
|
|
219
|
+
const validationError = this.validateOptions(options);
|
|
220
|
+
if (validationError) {
|
|
221
|
+
throw validationError;
|
|
222
|
+
}
|
|
223
|
+
// Resolve prompt
|
|
224
|
+
const prompt = await this.resolvePrompt(options);
|
|
225
|
+
const systemPrompt = options.systemPrompt
|
|
226
|
+
? this.substituteVariables(options.systemPrompt, options.variables || {})
|
|
227
|
+
: undefined;
|
|
228
|
+
const messages = options.messages || (prompt ? [{ role: 'user', content: prompt }] : undefined);
|
|
229
|
+
const generator = this.aiService.stream({
|
|
230
|
+
model: options.model,
|
|
231
|
+
prompt,
|
|
232
|
+
messages,
|
|
233
|
+
systemPrompt,
|
|
234
|
+
temperature: options.temperature ?? 1.0,
|
|
235
|
+
maxTokens: options.maxTokens,
|
|
236
|
+
topP: options.topP,
|
|
237
|
+
topK: options.topK,
|
|
238
|
+
stopSequences: options.stopSequences,
|
|
239
|
+
presencePenalty: options.presencePenalty,
|
|
240
|
+
frequencyPenalty: options.frequencyPenalty,
|
|
241
|
+
});
|
|
242
|
+
let cancelled = false;
|
|
243
|
+
let collectedText = '';
|
|
244
|
+
let finalUsage;
|
|
245
|
+
const self = this;
|
|
246
|
+
const asyncIterator = async function* () {
|
|
247
|
+
try {
|
|
248
|
+
for await (const chunk of generator) {
|
|
249
|
+
if (cancelled) {
|
|
250
|
+
self.emit('generation.stream.aborted', { invocationId });
|
|
251
|
+
throw new GenerativeAbortError();
|
|
252
|
+
}
|
|
253
|
+
if (streamOptions?.signal?.aborted) {
|
|
254
|
+
self.emit('generation.stream.aborted', { invocationId });
|
|
255
|
+
throw new GenerativeAbortError();
|
|
256
|
+
}
|
|
257
|
+
if (chunk.type === 'text') {
|
|
258
|
+
collectedText += chunk.text;
|
|
259
|
+
self.emit('generation.stream.chunk', { text: chunk.text });
|
|
260
|
+
}
|
|
261
|
+
if (chunk.type === 'done') {
|
|
262
|
+
finalUsage = chunk.usage;
|
|
263
|
+
self.emit('generation.stream.end', { invocationId, usage: finalUsage });
|
|
264
|
+
}
|
|
265
|
+
yield chunk;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
if (err instanceof GenerativeAbortError) {
|
|
270
|
+
throw err;
|
|
271
|
+
}
|
|
272
|
+
throw err;
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
const iterator = asyncIterator();
|
|
276
|
+
return {
|
|
277
|
+
[Symbol.asyncIterator]() {
|
|
278
|
+
return iterator;
|
|
279
|
+
},
|
|
280
|
+
async toText() {
|
|
281
|
+
for await (const chunk of iterator) {
|
|
282
|
+
if (chunk.type === 'text') {
|
|
283
|
+
// Already collected in the iterator
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return collectedText;
|
|
287
|
+
},
|
|
288
|
+
async toJSON() {
|
|
289
|
+
let text = '';
|
|
290
|
+
for await (const chunk of asyncIterator()) {
|
|
291
|
+
if (chunk.type === 'text') {
|
|
292
|
+
text += chunk.text;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (options.schema) {
|
|
296
|
+
try {
|
|
297
|
+
const parsed = self.extractJSON(text, options.lenientParsing ?? false);
|
|
298
|
+
self.validateSchema(parsed, options.schema, options.coerceTypes ?? false);
|
|
299
|
+
return parsed;
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
const error = err;
|
|
303
|
+
throw new GenerativeSchemaError(error.message);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return JSON.parse(text);
|
|
307
|
+
},
|
|
308
|
+
cancel() {
|
|
309
|
+
cancelled = true;
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Execute with tools
|
|
315
|
+
*/
|
|
316
|
+
async executeWithTools(options, messages, systemPrompt, startTime, invocationId) {
|
|
317
|
+
// Validate tools
|
|
318
|
+
const toolValidationError = this.validateTools(options.tools);
|
|
319
|
+
if (toolValidationError) {
|
|
320
|
+
return this.createErrorResult(toolValidationError, options.model, startTime);
|
|
321
|
+
}
|
|
322
|
+
const maxIterations = options.maxToolIterations ?? 10;
|
|
323
|
+
let iterations = 0;
|
|
324
|
+
let currentMessages = [...messages];
|
|
325
|
+
let totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
326
|
+
while (iterations < maxIterations) {
|
|
327
|
+
iterations++;
|
|
328
|
+
const result = await this.aiService.generateWithTools({
|
|
329
|
+
model: options.model,
|
|
330
|
+
messages: currentMessages,
|
|
331
|
+
systemPrompt,
|
|
332
|
+
temperature: options.temperature ?? 1.0,
|
|
333
|
+
maxTokens: options.maxTokens,
|
|
334
|
+
topP: options.topP,
|
|
335
|
+
topK: options.topK,
|
|
336
|
+
stopSequences: options.stopSequences,
|
|
337
|
+
presencePenalty: options.presencePenalty,
|
|
338
|
+
frequencyPenalty: options.frequencyPenalty,
|
|
339
|
+
tools: options.tools,
|
|
340
|
+
});
|
|
341
|
+
totalUsage.inputTokens += result.usage.inputTokens;
|
|
342
|
+
totalUsage.outputTokens += result.usage.outputTokens;
|
|
343
|
+
totalUsage.totalTokens = totalUsage.inputTokens + totalUsage.outputTokens;
|
|
344
|
+
// No tool calls - we're done
|
|
345
|
+
if (!result.toolCalls?.length || result.finishReason !== 'tool_use') {
|
|
346
|
+
this.emit('generation.tokens', totalUsage);
|
|
347
|
+
this.emit('generation.completed', { invocationId, conversationId: options.conversationId });
|
|
348
|
+
return {
|
|
349
|
+
success: true,
|
|
350
|
+
result: result.text,
|
|
351
|
+
usage: totalUsage,
|
|
352
|
+
duration: Date.now() - startTime,
|
|
353
|
+
model: options.model,
|
|
354
|
+
finishReason: result.finishReason,
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
// Execute tool calls
|
|
358
|
+
const toolResults = await this.executeToolCalls(result.toolCalls, options.tools, options.parallelToolCalls ?? false);
|
|
359
|
+
// Add assistant message with tool calls and tool results to conversation
|
|
360
|
+
currentMessages.push({
|
|
361
|
+
role: 'assistant',
|
|
362
|
+
content: result.text || `[Tool calls: ${result.toolCalls.map(tc => tc.name).join(', ')}]`,
|
|
363
|
+
});
|
|
364
|
+
// Add tool results as user message
|
|
365
|
+
for (const toolResult of toolResults) {
|
|
366
|
+
currentMessages.push({
|
|
367
|
+
role: 'user',
|
|
368
|
+
content: `Tool result for ${toolResult.name}: ${JSON.stringify(toolResult.result)}`,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
// Max iterations reached
|
|
373
|
+
this.emit('generation.tokens', totalUsage);
|
|
374
|
+
return this.createErrorResult(new GenerativeToolError(`Max tool iterations (${maxIterations}) reached`), options.model, startTime, totalUsage);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Execute tool calls
|
|
378
|
+
*/
|
|
379
|
+
async executeToolCalls(toolCalls, toolDefinitions, parallel) {
|
|
380
|
+
const toolMap = new Map(toolDefinitions.map(t => [t.name, t]));
|
|
381
|
+
if (parallel) {
|
|
382
|
+
return Promise.all(toolCalls.map(async (call) => {
|
|
383
|
+
const tool = toolMap.get(call.name);
|
|
384
|
+
if (!tool?.execute) {
|
|
385
|
+
return { name: call.name, result: null, error: `Tool ${call.name} not found or has no executor` };
|
|
386
|
+
}
|
|
387
|
+
this.emit('generation.tool.called', { toolName: call.name, input: call.input });
|
|
388
|
+
try {
|
|
389
|
+
const result = await tool.execute(call.input);
|
|
390
|
+
this.emit('generation.tool.completed', { toolName: call.name, result });
|
|
391
|
+
return { name: call.name, result };
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
const error = err;
|
|
395
|
+
this.emit('generation.tool.error', { toolName: call.name, error: error.message });
|
|
396
|
+
return { name: call.name, result: null, error: error.message };
|
|
397
|
+
}
|
|
398
|
+
}));
|
|
399
|
+
}
|
|
400
|
+
const results = [];
|
|
401
|
+
for (const call of toolCalls) {
|
|
402
|
+
const tool = toolMap.get(call.name);
|
|
403
|
+
if (!tool?.execute) {
|
|
404
|
+
results.push({ name: call.name, result: null, error: `Tool ${call.name} not found or has no executor` });
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
this.emit('generation.tool.called', { toolName: call.name, input: call.input });
|
|
408
|
+
try {
|
|
409
|
+
const result = await tool.execute(call.input);
|
|
410
|
+
this.emit('generation.tool.completed', { toolName: call.name, result });
|
|
411
|
+
results.push({ name: call.name, result });
|
|
412
|
+
}
|
|
413
|
+
catch (err) {
|
|
414
|
+
const error = err;
|
|
415
|
+
this.emit('generation.tool.error', { toolName: call.name, error: error.message });
|
|
416
|
+
results.push({ name: call.name, result: null, error: error.message });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return results;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Execute with retries
|
|
423
|
+
*/
|
|
424
|
+
async executeWithRetries(fn, options) {
|
|
425
|
+
// If retryOnRateLimit or retryOnTimeout is set but maxRetries is not specified,
|
|
426
|
+
// default to a reasonable number of retries
|
|
427
|
+
const defaultRetries = (options.retryOnRateLimit || options.retryOnTimeout) ? 3 : 1;
|
|
428
|
+
const maxRetries = options.maxRetries ?? defaultRetries;
|
|
429
|
+
const retryDelay = options.retryDelay ?? 1000;
|
|
430
|
+
const retryBackoff = options.retryBackoff ?? 'exponential';
|
|
431
|
+
let lastError = null;
|
|
432
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
433
|
+
try {
|
|
434
|
+
// Wrap with timeout if specified
|
|
435
|
+
if (options.timeout) {
|
|
436
|
+
return await this.withTimeout(fn(), options.timeout);
|
|
437
|
+
}
|
|
438
|
+
return await fn();
|
|
439
|
+
}
|
|
440
|
+
catch (err) {
|
|
441
|
+
const error = err;
|
|
442
|
+
lastError = error;
|
|
443
|
+
// Check if error is retryable
|
|
444
|
+
if (error.code && NON_RETRYABLE_ERRORS.has(error.code)) {
|
|
445
|
+
throw error;
|
|
446
|
+
}
|
|
447
|
+
// Handle rate limit
|
|
448
|
+
if (error.code === 'rate_limit_exceeded') {
|
|
449
|
+
if (!options.retryOnRateLimit) {
|
|
450
|
+
throw new GenerativeRateLimitError(error.message, error.retryAfter);
|
|
451
|
+
}
|
|
452
|
+
if (attempt < maxRetries - 1) {
|
|
453
|
+
const waitTime = error.retryAfter ? error.retryAfter * 1000 : this.calculateDelay(attempt, retryDelay, retryBackoff);
|
|
454
|
+
this.emit('generation.retry', { attempt: attempt + 1, error: error.message });
|
|
455
|
+
await this.sleep(waitTime);
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
throw new GenerativeRateLimitError(error.message, error.retryAfter);
|
|
459
|
+
}
|
|
460
|
+
// Handle timeout
|
|
461
|
+
if (error instanceof GenerativeTimeoutError) {
|
|
462
|
+
if (!options.retryOnTimeout) {
|
|
463
|
+
throw error;
|
|
464
|
+
}
|
|
465
|
+
if (attempt < maxRetries - 1) {
|
|
466
|
+
this.emit('generation.retry', { attempt: attempt + 1, error: error.message });
|
|
467
|
+
await this.sleep(this.calculateDelay(attempt, retryDelay, retryBackoff));
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
throw error;
|
|
471
|
+
}
|
|
472
|
+
// Retry on transient errors
|
|
473
|
+
if (attempt < maxRetries - 1) {
|
|
474
|
+
this.emit('generation.retry', { attempt: attempt + 1, error: error.message });
|
|
475
|
+
await this.sleep(this.calculateDelay(attempt, retryDelay, retryBackoff));
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
throw lastError || new Error('Max retries exceeded');
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Execute with timeout
|
|
485
|
+
*/
|
|
486
|
+
async withTimeout(promise, timeout) {
|
|
487
|
+
let timeoutId;
|
|
488
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
489
|
+
timeoutId = setTimeout(() => {
|
|
490
|
+
this.emit('generation.timeout', {});
|
|
491
|
+
reject(new GenerativeTimeoutError());
|
|
492
|
+
}, timeout);
|
|
493
|
+
});
|
|
494
|
+
try {
|
|
495
|
+
return await Promise.race([promise, timeoutPromise]);
|
|
496
|
+
}
|
|
497
|
+
finally {
|
|
498
|
+
clearTimeout(timeoutId);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Calculate retry delay
|
|
503
|
+
*/
|
|
504
|
+
calculateDelay(attempt, baseDelay, backoff) {
|
|
505
|
+
if (backoff === 'exponential') {
|
|
506
|
+
return baseDelay * Math.pow(2, attempt);
|
|
507
|
+
}
|
|
508
|
+
return baseDelay * (attempt + 1);
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Sleep for specified duration
|
|
512
|
+
*/
|
|
513
|
+
sleep(ms) {
|
|
514
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Resolve prompt from options
|
|
518
|
+
*/
|
|
519
|
+
async resolvePrompt(options) {
|
|
520
|
+
if (!options.prompt) {
|
|
521
|
+
return '';
|
|
522
|
+
}
|
|
523
|
+
// Handle function prompts
|
|
524
|
+
if (typeof options.prompt === 'function') {
|
|
525
|
+
const result = options.prompt(options.input || {});
|
|
526
|
+
return result instanceof Promise ? await result : result;
|
|
527
|
+
}
|
|
528
|
+
// Handle template prompts
|
|
529
|
+
return this.substituteVariables(options.prompt, options.variables || {});
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Substitute variables in template
|
|
533
|
+
*/
|
|
534
|
+
substituteVariables(template, variables) {
|
|
535
|
+
// Handle escaped braces
|
|
536
|
+
let result = template.replace(/\\{{/g, '\x00ESCAPED_OPEN\x00');
|
|
537
|
+
// Replace variables
|
|
538
|
+
result = result.replace(/{{([^}]+)}}/g, (match, path) => {
|
|
539
|
+
const value = this.getNestedValue(variables, path.trim());
|
|
540
|
+
if (value === undefined || value === null) {
|
|
541
|
+
return '';
|
|
542
|
+
}
|
|
543
|
+
if (Array.isArray(value)) {
|
|
544
|
+
return value.join(',');
|
|
545
|
+
}
|
|
546
|
+
return String(value);
|
|
547
|
+
});
|
|
548
|
+
// Restore escaped braces
|
|
549
|
+
return result.replace(/\x00ESCAPED_OPEN\x00/g, '{{');
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Get nested value from object using dot notation or array indexing
|
|
553
|
+
*/
|
|
554
|
+
getNestedValue(obj, path) {
|
|
555
|
+
const parts = path.split(/\.|\[|\]/).filter(Boolean);
|
|
556
|
+
let current = obj;
|
|
557
|
+
for (const part of parts) {
|
|
558
|
+
if (current === null || current === undefined) {
|
|
559
|
+
return undefined;
|
|
560
|
+
}
|
|
561
|
+
if (typeof current === 'object') {
|
|
562
|
+
current = current[part];
|
|
563
|
+
}
|
|
564
|
+
else {
|
|
565
|
+
return undefined;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
return current;
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Validate options
|
|
572
|
+
*/
|
|
573
|
+
validateOptions(options) {
|
|
574
|
+
if (!options.model) {
|
|
575
|
+
return new GenerativeValidationError('model is required');
|
|
576
|
+
}
|
|
577
|
+
if (!options.prompt && !options.messages?.length) {
|
|
578
|
+
return new GenerativeValidationError('Either prompt or messages is required');
|
|
579
|
+
}
|
|
580
|
+
// Validate temperature
|
|
581
|
+
if (options.temperature !== undefined) {
|
|
582
|
+
if (options.temperature < 0) {
|
|
583
|
+
return new GenerativeValidationError('temperature must be >= 0');
|
|
584
|
+
}
|
|
585
|
+
if (options.temperature > 2) {
|
|
586
|
+
return new GenerativeValidationError('temperature must be <= 2');
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
// Validate maxTokens
|
|
590
|
+
if (options.maxTokens !== undefined) {
|
|
591
|
+
if (options.maxTokens <= 0) {
|
|
592
|
+
return new GenerativeValidationError('maxTokens must be > 0');
|
|
593
|
+
}
|
|
594
|
+
// Warn if exceeding model limits
|
|
595
|
+
const modelLimit = MODEL_LIMITS[options.model]?.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
596
|
+
if (options.maxTokens > modelLimit) {
|
|
597
|
+
this.emit('generation.warning', {
|
|
598
|
+
message: `maxTokens (${options.maxTokens}) exceeds model limit (${modelLimit})`,
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
// Validate topP
|
|
603
|
+
if (options.topP !== undefined) {
|
|
604
|
+
if (options.topP < 0 || options.topP > 1) {
|
|
605
|
+
return new GenerativeValidationError('topP must be between 0 and 1');
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
// Validate topK
|
|
609
|
+
if (options.topK !== undefined && options.topK < 0) {
|
|
610
|
+
return new GenerativeValidationError('topK must be >= 0');
|
|
611
|
+
}
|
|
612
|
+
// Validate penalties
|
|
613
|
+
if (options.presencePenalty !== undefined) {
|
|
614
|
+
if (options.presencePenalty < -2 || options.presencePenalty > 2) {
|
|
615
|
+
return new GenerativeValidationError('presencePenalty must be between -2 and 2');
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
if (options.frequencyPenalty !== undefined) {
|
|
619
|
+
if (options.frequencyPenalty < -2 || options.frequencyPenalty > 2) {
|
|
620
|
+
return new GenerativeValidationError('frequencyPenalty must be between -2 and 2');
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
// Validate schema
|
|
624
|
+
if (options.schema) {
|
|
625
|
+
const validTypes = ['object', 'array', 'string', 'number', 'boolean', 'null', 'integer'];
|
|
626
|
+
if (!validTypes.includes(options.schema.type)) {
|
|
627
|
+
return new GenerativeValidationError(`Invalid schema type: ${options.schema.type}`);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Validate messages
|
|
634
|
+
*/
|
|
635
|
+
validateMessages(messages) {
|
|
636
|
+
const validRoles = ['user', 'assistant', 'system'];
|
|
637
|
+
for (const message of messages) {
|
|
638
|
+
if (!validRoles.includes(message.role)) {
|
|
639
|
+
return new GenerativeValidationError(`Invalid message role: ${message.role}`);
|
|
640
|
+
}
|
|
641
|
+
const content = Array.isArray(message.content)
|
|
642
|
+
? message.content.map(c => c.type === 'text' ? c.text : '').join('')
|
|
643
|
+
: message.content;
|
|
644
|
+
if (!content || content.trim() === '') {
|
|
645
|
+
return new GenerativeValidationError('Message content cannot be empty');
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return null;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Validate tools
|
|
652
|
+
*/
|
|
653
|
+
validateTools(tools) {
|
|
654
|
+
for (const tool of tools) {
|
|
655
|
+
if (!tool.name || tool.name.trim() === '') {
|
|
656
|
+
return new GenerativeValidationError('Tool name is required and cannot be empty');
|
|
657
|
+
}
|
|
658
|
+
if (!tool.inputSchema) {
|
|
659
|
+
return new GenerativeValidationError(`Tool ${tool.name} requires inputSchema`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return null;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Validate and parse schema with retries
|
|
666
|
+
*/
|
|
667
|
+
async validateAndParseSchema(text, schema, coerceTypes, lenientParsing, maxRetries, options, messages, systemPrompt) {
|
|
668
|
+
let lastError = null;
|
|
669
|
+
let currentText = text;
|
|
670
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
671
|
+
try {
|
|
672
|
+
// Extract and parse JSON
|
|
673
|
+
const parsed = this.extractJSON(currentText, lenientParsing);
|
|
674
|
+
// Validate against schema
|
|
675
|
+
const validated = this.validateSchema(parsed, schema, coerceTypes);
|
|
676
|
+
return validated;
|
|
677
|
+
}
|
|
678
|
+
catch (err) {
|
|
679
|
+
const error = err;
|
|
680
|
+
lastError = error;
|
|
681
|
+
if (attempt < maxRetries - 1) {
|
|
682
|
+
// Retry with validation feedback
|
|
683
|
+
const feedbackPrompt = `Your previous response failed schema validation: ${error.message}. Please generate valid JSON matching the schema with required fields.`;
|
|
684
|
+
const retryMessages = [
|
|
685
|
+
...messages,
|
|
686
|
+
{ role: 'assistant', content: currentText },
|
|
687
|
+
{ role: 'user', content: feedbackPrompt },
|
|
688
|
+
];
|
|
689
|
+
const retryResult = await this.aiService.generate({
|
|
690
|
+
model: options.model,
|
|
691
|
+
prompt: feedbackPrompt,
|
|
692
|
+
messages: retryMessages,
|
|
693
|
+
systemPrompt,
|
|
694
|
+
temperature: options.temperature ?? 1.0,
|
|
695
|
+
maxTokens: options.maxTokens,
|
|
696
|
+
});
|
|
697
|
+
currentText = retryResult.text;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
throw lastError || new GenerativeSchemaError('Schema validation failed');
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Extract JSON from text
|
|
705
|
+
*/
|
|
706
|
+
extractJSON(text, lenientParsing) {
|
|
707
|
+
// Try direct parse first
|
|
708
|
+
try {
|
|
709
|
+
return JSON.parse(text);
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
// Continue with extraction
|
|
713
|
+
}
|
|
714
|
+
// Try extracting from markdown code blocks
|
|
715
|
+
const codeBlockMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
716
|
+
if (codeBlockMatch) {
|
|
717
|
+
try {
|
|
718
|
+
return JSON.parse(codeBlockMatch[1].trim());
|
|
719
|
+
}
|
|
720
|
+
catch {
|
|
721
|
+
// Continue
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
// Try extracting JSON object/array from text
|
|
725
|
+
const jsonMatch = text.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
|
|
726
|
+
if (jsonMatch) {
|
|
727
|
+
try {
|
|
728
|
+
return JSON.parse(jsonMatch[1]);
|
|
729
|
+
}
|
|
730
|
+
catch {
|
|
731
|
+
// Continue
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
// Try lenient parsing (handle trailing commas, etc.)
|
|
735
|
+
if (lenientParsing) {
|
|
736
|
+
try {
|
|
737
|
+
// Remove trailing commas
|
|
738
|
+
let cleaned = text.replace(/,(\s*[}\]])/g, '$1');
|
|
739
|
+
// Extract JSON again
|
|
740
|
+
const cleanedMatch = cleaned.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
|
|
741
|
+
if (cleanedMatch) {
|
|
742
|
+
return JSON.parse(cleanedMatch[1]);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
catch {
|
|
746
|
+
// Continue
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
throw new GenerativeSchemaError('Failed to parse JSON from response');
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Validate against JSON schema
|
|
753
|
+
*/
|
|
754
|
+
validateSchema(data, schema, coerceTypes) {
|
|
755
|
+
return this.validateSchemaRecursive(data, schema, coerceTypes, []);
|
|
756
|
+
}
|
|
757
|
+
validateSchemaRecursive(data, schema, coerceTypes, path) {
|
|
758
|
+
const pathStr = path.join('.');
|
|
759
|
+
// Handle enum validation first (applies to the value itself)
|
|
760
|
+
if (schema.enum) {
|
|
761
|
+
if (!schema.enum.includes(data)) {
|
|
762
|
+
throw new GenerativeSchemaError(`Invalid enum value at ${pathStr || 'root'}: ${data}. Expected one of: ${schema.enum.join(', ')}`);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
// Handle type validation with optional coercion
|
|
766
|
+
if (schema.type === 'string') {
|
|
767
|
+
if (typeof data === 'string')
|
|
768
|
+
return data;
|
|
769
|
+
if (coerceTypes && data !== null && data !== undefined)
|
|
770
|
+
return String(data);
|
|
771
|
+
throw new GenerativeSchemaError(`Expected string at ${pathStr || 'root'}, got ${typeof data}`);
|
|
772
|
+
}
|
|
773
|
+
if (schema.type === 'number' || schema.type === 'integer') {
|
|
774
|
+
if (typeof data === 'number')
|
|
775
|
+
return data;
|
|
776
|
+
if (coerceTypes && typeof data === 'string') {
|
|
777
|
+
const num = Number(data);
|
|
778
|
+
if (!isNaN(num))
|
|
779
|
+
return num;
|
|
780
|
+
}
|
|
781
|
+
throw new GenerativeSchemaError(`Expected number at ${pathStr || 'root'}, got ${typeof data}`);
|
|
782
|
+
}
|
|
783
|
+
if (schema.type === 'boolean') {
|
|
784
|
+
if (typeof data === 'boolean')
|
|
785
|
+
return data;
|
|
786
|
+
if (coerceTypes && typeof data === 'string') {
|
|
787
|
+
if (data === 'true')
|
|
788
|
+
return true;
|
|
789
|
+
if (data === 'false')
|
|
790
|
+
return false;
|
|
791
|
+
}
|
|
792
|
+
throw new GenerativeSchemaError(`Expected boolean at ${pathStr || 'root'}, got ${typeof data}`);
|
|
793
|
+
}
|
|
794
|
+
if (schema.type === 'null') {
|
|
795
|
+
if (data === null)
|
|
796
|
+
return data;
|
|
797
|
+
throw new GenerativeSchemaError(`Expected null at ${pathStr || 'root'}`);
|
|
798
|
+
}
|
|
799
|
+
if (schema.type === 'array') {
|
|
800
|
+
if (!Array.isArray(data)) {
|
|
801
|
+
throw new GenerativeSchemaError(`Expected array at ${pathStr || 'root'}`);
|
|
802
|
+
}
|
|
803
|
+
if (schema.items) {
|
|
804
|
+
return data.map((item, i) => this.validateSchemaRecursive(item, schema.items, coerceTypes, [...path, String(i)]));
|
|
805
|
+
}
|
|
806
|
+
return data;
|
|
807
|
+
}
|
|
808
|
+
if (schema.type === 'object') {
|
|
809
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
810
|
+
throw new GenerativeSchemaError(`Expected object at ${pathStr || 'root'}`);
|
|
811
|
+
}
|
|
812
|
+
const obj = data;
|
|
813
|
+
const result = {};
|
|
814
|
+
// Validate required fields
|
|
815
|
+
if (schema.required) {
|
|
816
|
+
for (const field of schema.required) {
|
|
817
|
+
if (!(field in obj)) {
|
|
818
|
+
throw new GenerativeSchemaError(`Missing required field: ${field}`);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
// Validate properties
|
|
823
|
+
if (schema.properties) {
|
|
824
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
825
|
+
if (key in obj) {
|
|
826
|
+
result[key] = this.validateSchemaRecursive(obj[key], propSchema, coerceTypes, [...path, key]);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
// Include properties without schema definition
|
|
831
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
832
|
+
if (!(key in result)) {
|
|
833
|
+
result[key] = value;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return result;
|
|
837
|
+
}
|
|
838
|
+
return data;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Load conversation history
|
|
842
|
+
*/
|
|
843
|
+
async loadConversationHistory(conversationId) {
|
|
844
|
+
const stored = await this.state.storage.get(`conversation:${conversationId}`);
|
|
845
|
+
if (stored && typeof stored === 'object' && 'messages' in stored) {
|
|
846
|
+
return stored.messages;
|
|
847
|
+
}
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* Save conversation history
|
|
852
|
+
*/
|
|
853
|
+
async saveConversationHistory(conversationId, messages) {
|
|
854
|
+
await this.state.storage.put(`conversation:${conversationId}`, { messages });
|
|
855
|
+
}
|
|
856
|
+
/**
|
|
857
|
+
* Create error result
|
|
858
|
+
*/
|
|
859
|
+
createErrorResult(error, model, startTime, usage, finishReason) {
|
|
860
|
+
return {
|
|
861
|
+
success: false,
|
|
862
|
+
error: error,
|
|
863
|
+
usage: usage || { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
864
|
+
duration: Date.now() - startTime,
|
|
865
|
+
model,
|
|
866
|
+
finishReason,
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Handle error and create result
|
|
871
|
+
*/
|
|
872
|
+
handleError(error, model, startTime) {
|
|
873
|
+
const errorWithCode = error;
|
|
874
|
+
this.emit('generation.error', { error: error.message });
|
|
875
|
+
// Preserve specific error types
|
|
876
|
+
if (error instanceof GenerativeTimeoutError) {
|
|
877
|
+
return this.createErrorResult(error, model, startTime);
|
|
878
|
+
}
|
|
879
|
+
if (error instanceof GenerativeRateLimitError) {
|
|
880
|
+
return this.createErrorResult(error, model, startTime);
|
|
881
|
+
}
|
|
882
|
+
if (error instanceof GenerativeSchemaError) {
|
|
883
|
+
return this.createErrorResult(error, model, startTime);
|
|
884
|
+
}
|
|
885
|
+
if (error instanceof GenerativeToolError) {
|
|
886
|
+
return this.createErrorResult(error, model, startTime);
|
|
887
|
+
}
|
|
888
|
+
if (error instanceof GenerativeAbortError) {
|
|
889
|
+
return this.createErrorResult(error, model, startTime);
|
|
890
|
+
}
|
|
891
|
+
// Convert to appropriate error type based on code
|
|
892
|
+
if (errorWithCode.code === 'rate_limit_exceeded') {
|
|
893
|
+
return this.createErrorResult(new GenerativeRateLimitError(error.message, errorWithCode.retryAfter), model, startTime);
|
|
894
|
+
}
|
|
895
|
+
return this.createErrorResult(new GenerativeModelError(error.message, errorWithCode.code), model, startTime);
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Emit event
|
|
899
|
+
*/
|
|
900
|
+
emit(event, data) {
|
|
901
|
+
this.onEvent?.(event, data);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
//# sourceMappingURL=GenerativeFunctionExecutor.js.map
|