@dcyfr/ai 1.0.3 → 2.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/CHANGELOG.md +106 -0
- package/LICENSE +27 -1
- package/README.md +720 -9
- package/dist/ai/agents/agent-loader.d.ts +12 -0
- package/dist/ai/agents/agent-loader.d.ts.map +1 -1
- package/dist/ai/agents/agent-loader.js +74 -65
- package/dist/ai/agents/agent-loader.js.map +1 -1
- package/dist/ai/agents/agent-registry.d.ts +2 -0
- package/dist/ai/agents/agent-registry.d.ts.map +1 -1
- package/dist/ai/agents/agent-registry.js +15 -14
- package/dist/ai/agents/agent-registry.js.map +1 -1
- package/dist/ai/agents/agent-router.d.ts +20 -5
- package/dist/ai/agents/agent-router.d.ts.map +1 -1
- package/dist/ai/agents/agent-router.js +89 -43
- package/dist/ai/agents/agent-router.js.map +1 -1
- package/dist/ai/agents/index.d.ts +6 -1
- package/dist/ai/agents/index.d.ts.map +1 -1
- package/dist/ai/agents/index.js +9 -3
- package/dist/ai/agents/index.js.map +1 -1
- package/dist/ai/agents/instruction-template.d.ts +45 -0
- package/dist/ai/agents/instruction-template.d.ts.map +1 -0
- package/dist/ai/agents/instruction-template.js +197 -0
- package/dist/ai/agents/instruction-template.js.map +1 -0
- package/dist/ai/agents/persona-resolver.d.ts +90 -0
- package/dist/ai/agents/persona-resolver.d.ts.map +1 -0
- package/dist/ai/agents/persona-resolver.js +121 -0
- package/dist/ai/agents/persona-resolver.js.map +1 -0
- package/dist/ai/agents/schema.d.ts +166 -0
- package/dist/ai/agents/schema.d.ts.map +1 -0
- package/dist/ai/agents/schema.js +94 -0
- package/dist/ai/agents/schema.js.map +1 -0
- package/dist/ai/agents/types.d.ts +102 -0
- package/dist/ai/agents/types.d.ts.map +1 -1
- package/dist/ai/agents-builtin/architecture/index.js +3 -3
- package/dist/ai/agents-builtin/content/index.js +1 -1
- package/dist/ai/agents-builtin/data/index.js +1 -1
- package/dist/ai/agents-builtin/development/index.js +4 -4
- package/dist/ai/agents-builtin/devops/index.js +1 -1
- package/dist/ai/agents-builtin/index.js +33 -33
- package/dist/ai/agents-builtin/performance/index.js +1 -1
- package/dist/ai/agents-builtin/research/index.js +1 -1
- package/dist/ai/agents-builtin/security/index.js +1 -1
- package/dist/ai/agents-builtin/testing/index.js +2 -2
- package/dist/ai/config/loader.d.ts.map +1 -1
- package/dist/ai/config/loader.js +6 -3
- package/dist/ai/config/loader.js.map +1 -1
- package/dist/ai/config/schema.d.ts +242 -1156
- package/dist/ai/config/schema.d.ts.map +1 -1
- package/dist/ai/config/schema.js +69 -20
- package/dist/ai/config/schema.js.map +1 -1
- package/dist/ai/core/provider-registry.d.ts +32 -0
- package/dist/ai/core/provider-registry.d.ts.map +1 -1
- package/dist/ai/core/provider-registry.js +189 -14
- package/dist/ai/core/provider-registry.js.map +1 -1
- package/dist/ai/core/telemetry-engine.d.ts +26 -0
- package/dist/ai/core/telemetry-engine.d.ts.map +1 -1
- package/dist/ai/core/telemetry-engine.js +81 -1
- package/dist/ai/core/telemetry-engine.js.map +1 -1
- package/dist/ai/delegation/agent-registry.d.ts +143 -0
- package/dist/ai/delegation/agent-registry.d.ts.map +1 -0
- package/dist/ai/delegation/agent-registry.js +231 -0
- package/dist/ai/delegation/agent-registry.js.map +1 -0
- package/dist/ai/delegation/blast-radius-tracker.d.ts +65 -0
- package/dist/ai/delegation/blast-radius-tracker.d.ts.map +1 -0
- package/dist/ai/delegation/blast-radius-tracker.js +81 -0
- package/dist/ai/delegation/blast-radius-tracker.js.map +1 -0
- package/dist/ai/delegation/capability-bootstrap.d.ts +40 -0
- package/dist/ai/delegation/capability-bootstrap.d.ts.map +1 -0
- package/dist/ai/delegation/capability-bootstrap.js +431 -0
- package/dist/ai/delegation/capability-bootstrap.js.map +1 -0
- package/dist/ai/delegation/capability-registry.d.ts +81 -0
- package/dist/ai/delegation/capability-registry.d.ts.map +1 -0
- package/dist/ai/delegation/capability-registry.js +339 -0
- package/dist/ai/delegation/capability-registry.js.map +1 -0
- package/dist/ai/delegation/chain-tracker.d.ts +152 -0
- package/dist/ai/delegation/chain-tracker.d.ts.map +1 -0
- package/dist/ai/delegation/chain-tracker.js +336 -0
- package/dist/ai/delegation/chain-tracker.js.map +1 -0
- package/dist/ai/delegation/circuit-breaker.d.ts +59 -0
- package/dist/ai/delegation/circuit-breaker.d.ts.map +1 -0
- package/dist/ai/delegation/circuit-breaker.js +153 -0
- package/dist/ai/delegation/circuit-breaker.js.map +1 -0
- package/dist/ai/delegation/contract-manager.d.ts +415 -0
- package/dist/ai/delegation/contract-manager.d.ts.map +1 -0
- package/dist/ai/delegation/contract-manager.js +1258 -0
- package/dist/ai/delegation/contract-manager.js.map +1 -0
- package/dist/ai/delegation/delegation-manager.d.ts +505 -0
- package/dist/ai/delegation/delegation-manager.d.ts.map +1 -0
- package/dist/ai/delegation/delegation-manager.js +773 -0
- package/dist/ai/delegation/delegation-manager.js.map +1 -0
- package/dist/ai/delegation/event-schemas.d.ts +101 -0
- package/dist/ai/delegation/event-schemas.d.ts.map +1 -0
- package/dist/ai/delegation/event-schemas.js +59 -0
- package/dist/ai/delegation/event-schemas.js.map +1 -0
- package/dist/ai/delegation/execution-mode-dashboard.d.ts +109 -0
- package/dist/ai/delegation/execution-mode-dashboard.d.ts.map +1 -0
- package/dist/ai/delegation/execution-mode-dashboard.js +167 -0
- package/dist/ai/delegation/execution-mode-dashboard.js.map +1 -0
- package/dist/ai/delegation/feature-flags.d.ts +191 -0
- package/dist/ai/delegation/feature-flags.d.ts.map +1 -0
- package/dist/ai/delegation/feature-flags.js +332 -0
- package/dist/ai/delegation/feature-flags.js.map +1 -0
- package/dist/ai/delegation/index.d.ts +51 -0
- package/dist/ai/delegation/index.d.ts.map +1 -0
- package/dist/ai/delegation/index.js +39 -0
- package/dist/ai/delegation/index.js.map +1 -0
- package/dist/ai/delegation/middleware/chain-depth-middleware.d.ts +39 -0
- package/dist/ai/delegation/middleware/chain-depth-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/chain-depth-middleware.js +77 -0
- package/dist/ai/delegation/middleware/chain-depth-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/chain-tracker-middleware.d.ts +46 -0
- package/dist/ai/delegation/middleware/chain-tracker-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/chain-tracker-middleware.js +89 -0
- package/dist/ai/delegation/middleware/chain-tracker-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/content-policy-middleware.d.ts +31 -0
- package/dist/ai/delegation/middleware/content-policy-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/content-policy-middleware.js +82 -0
- package/dist/ai/delegation/middleware/content-policy-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/feature-flag-middleware.d.ts +46 -0
- package/dist/ai/delegation/middleware/feature-flag-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/feature-flag-middleware.js +59 -0
- package/dist/ai/delegation/middleware/feature-flag-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/identity-middleware.d.ts +23 -0
- package/dist/ai/delegation/middleware/identity-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/identity-middleware.js +64 -0
- package/dist/ai/delegation/middleware/identity-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/permissions-middleware.d.ts +48 -0
- package/dist/ai/delegation/middleware/permissions-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/permissions-middleware.js +107 -0
- package/dist/ai/delegation/middleware/permissions-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/rate-limiter-middleware.d.ts +38 -0
- package/dist/ai/delegation/middleware/rate-limiter-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/rate-limiter-middleware.js +65 -0
- package/dist/ai/delegation/middleware/rate-limiter-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/reputation-middleware.d.ts +39 -0
- package/dist/ai/delegation/middleware/reputation-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/reputation-middleware.js +75 -0
- package/dist/ai/delegation/middleware/reputation-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/resource-limiter-middleware.d.ts +52 -0
- package/dist/ai/delegation/middleware/resource-limiter-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/resource-limiter-middleware.js +112 -0
- package/dist/ai/delegation/middleware/resource-limiter-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/threat-validator-middleware.d.ts +23 -0
- package/dist/ai/delegation/middleware/threat-validator-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/threat-validator-middleware.js +83 -0
- package/dist/ai/delegation/middleware/threat-validator-middleware.js.map +1 -0
- package/dist/ai/delegation/middleware/tlp-middleware.d.ts +23 -0
- package/dist/ai/delegation/middleware/tlp-middleware.d.ts.map +1 -0
- package/dist/ai/delegation/middleware/tlp-middleware.js +59 -0
- package/dist/ai/delegation/middleware/tlp-middleware.js.map +1 -0
- package/dist/ai/delegation/monitoring.d.ts +298 -0
- package/dist/ai/delegation/monitoring.d.ts.map +1 -0
- package/dist/ai/delegation/monitoring.js +584 -0
- package/dist/ai/delegation/monitoring.js.map +1 -0
- package/dist/ai/delegation/security-middleware-chain.d.ts +71 -0
- package/dist/ai/delegation/security-middleware-chain.d.ts.map +1 -0
- package/dist/ai/delegation/security-middleware-chain.js +163 -0
- package/dist/ai/delegation/security-middleware-chain.js.map +1 -0
- package/dist/ai/delegation/session-checkpoint.d.ts +77 -0
- package/dist/ai/delegation/session-checkpoint.d.ts.map +1 -0
- package/dist/ai/delegation/session-checkpoint.js +131 -0
- package/dist/ai/delegation/session-checkpoint.js.map +1 -0
- package/dist/ai/delegation/session-manager.d.ts +131 -0
- package/dist/ai/delegation/session-manager.d.ts.map +1 -0
- package/dist/ai/delegation/session-manager.js +243 -0
- package/dist/ai/delegation/session-manager.js.map +1 -0
- package/dist/ai/delegation/session-queue.d.ts +95 -0
- package/dist/ai/delegation/session-queue.d.ts.map +1 -0
- package/dist/ai/delegation/session-queue.js +136 -0
- package/dist/ai/delegation/session-queue.js.map +1 -0
- package/dist/ai/delegation/timeout-watchdog.d.ts +60 -0
- package/dist/ai/delegation/timeout-watchdog.d.ts.map +1 -0
- package/dist/ai/delegation/timeout-watchdog.js +100 -0
- package/dist/ai/delegation/timeout-watchdog.js.map +1 -0
- package/dist/ai/examples/integration-demo.d.ts +27 -0
- package/dist/ai/examples/integration-demo.d.ts.map +1 -0
- package/dist/ai/examples/integration-demo.js +536 -0
- package/dist/ai/examples/integration-demo.js.map +1 -0
- package/dist/ai/index.d.ts +27 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +32 -10
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/mcp/index.d.ts +14 -2
- package/dist/ai/mcp/index.d.ts.map +1 -1
- package/dist/ai/mcp/index.js +11 -1
- package/dist/ai/mcp/index.js.map +1 -1
- package/dist/ai/mcp/servers/analytics/index.d.ts +19 -0
- package/dist/ai/mcp/servers/analytics/index.d.ts.map +1 -0
- package/dist/ai/mcp/servers/analytics/index.js +612 -0
- package/dist/ai/mcp/servers/analytics/index.js.map +1 -0
- package/dist/ai/mcp/servers/content-manager/content-provider.d.ts +61 -0
- package/dist/ai/mcp/servers/content-manager/content-provider.d.ts.map +1 -0
- package/dist/ai/mcp/servers/content-manager/content-provider.js +8 -0
- package/dist/ai/mcp/servers/content-manager/content-provider.js.map +1 -0
- package/dist/ai/mcp/servers/content-manager/index.d.ts +19 -0
- package/dist/ai/mcp/servers/content-manager/index.d.ts.map +1 -0
- package/dist/ai/mcp/servers/content-manager/index.js +282 -0
- package/dist/ai/mcp/servers/content-manager/index.js.map +1 -0
- package/dist/ai/mcp/servers/delegation-monitor/index.d.ts +36 -0
- package/dist/ai/mcp/servers/delegation-monitor/index.d.ts.map +1 -0
- package/dist/ai/mcp/servers/delegation-monitor/index.js +757 -0
- package/dist/ai/mcp/servers/delegation-monitor/index.js.map +1 -0
- package/dist/ai/mcp/servers/design-tokens/index.d.ts +19 -0
- package/dist/ai/mcp/servers/design-tokens/index.d.ts.map +1 -0
- package/dist/ai/mcp/servers/design-tokens/index.js +445 -0
- package/dist/ai/mcp/servers/design-tokens/index.js.map +1 -0
- package/dist/ai/mcp/servers/design-tokens/token-provider.d.ts +59 -0
- package/dist/ai/mcp/servers/design-tokens/token-provider.d.ts.map +1 -0
- package/dist/ai/mcp/servers/design-tokens/token-provider.js +8 -0
- package/dist/ai/mcp/servers/design-tokens/token-provider.js.map +1 -0
- package/dist/ai/mcp/servers/promptintel/index.d.ts +19 -0
- package/dist/ai/mcp/servers/promptintel/index.d.ts.map +1 -0
- package/dist/ai/mcp/servers/promptintel/index.js +335 -0
- package/dist/ai/mcp/servers/promptintel/index.js.map +1 -0
- package/dist/ai/mcp/servers/shared/cache.d.ts +62 -0
- package/dist/ai/mcp/servers/shared/cache.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/cache.js +117 -0
- package/dist/ai/mcp/servers/shared/cache.js.map +1 -0
- package/dist/ai/mcp/servers/shared/promptintel-client.d.ts +53 -0
- package/dist/ai/mcp/servers/shared/promptintel-client.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/promptintel-client.js +185 -0
- package/dist/ai/mcp/servers/shared/promptintel-client.js.map +1 -0
- package/dist/ai/mcp/servers/shared/promptintel-types.d.ts +85 -0
- package/dist/ai/mcp/servers/shared/promptintel-types.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/promptintel-types.js +7 -0
- package/dist/ai/mcp/servers/shared/promptintel-types.js.map +1 -0
- package/dist/ai/mcp/servers/shared/rate-limiter.d.ts +54 -0
- package/dist/ai/mcp/servers/shared/rate-limiter.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/rate-limiter.js +124 -0
- package/dist/ai/mcp/servers/shared/rate-limiter.js.map +1 -0
- package/dist/ai/mcp/servers/shared/redis-client.d.ts +54 -0
- package/dist/ai/mcp/servers/shared/redis-client.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/redis-client.js +232 -0
- package/dist/ai/mcp/servers/shared/redis-client.js.map +1 -0
- package/dist/ai/mcp/servers/shared/types.d.ts +301 -0
- package/dist/ai/mcp/servers/shared/types.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/types.js +6 -0
- package/dist/ai/mcp/servers/shared/types.js.map +1 -0
- package/dist/ai/mcp/servers/shared/utils.d.ts +49 -0
- package/dist/ai/mcp/servers/shared/utils.d.ts.map +1 -0
- package/dist/ai/mcp/servers/shared/utils.js +233 -0
- package/dist/ai/mcp/servers/shared/utils.js.map +1 -0
- package/dist/ai/memory/config.d.ts +102 -0
- package/dist/ai/memory/config.d.ts.map +1 -0
- package/dist/ai/memory/config.js +200 -0
- package/dist/ai/memory/config.js.map +1 -0
- package/dist/ai/memory/dcyfr-memory.d.ts +67 -0
- package/dist/ai/memory/dcyfr-memory.d.ts.map +1 -0
- package/dist/ai/memory/dcyfr-memory.js +308 -0
- package/dist/ai/memory/dcyfr-memory.js.map +1 -0
- package/dist/ai/memory/index.d.ts +15 -0
- package/dist/ai/memory/index.d.ts.map +1 -0
- package/dist/ai/memory/index.js +15 -0
- package/dist/ai/memory/index.js.map +1 -0
- package/dist/ai/memory/mem0-client.d.ts +108 -0
- package/dist/ai/memory/mem0-client.d.ts.map +1 -0
- package/dist/ai/memory/mem0-client.js +205 -0
- package/dist/ai/memory/mem0-client.js.map +1 -0
- package/dist/ai/memory/types.d.ts +175 -0
- package/dist/ai/memory/types.d.ts.map +1 -0
- package/dist/ai/memory/types.js +10 -0
- package/dist/ai/memory/types.js.map +1 -0
- package/dist/ai/permissions/attenuation-engine.d.ts +159 -0
- package/dist/ai/permissions/attenuation-engine.d.ts.map +1 -0
- package/dist/ai/permissions/attenuation-engine.js +511 -0
- package/dist/ai/permissions/attenuation-engine.js.map +1 -0
- package/dist/ai/plugins/plugin-loader.d.ts +4 -0
- package/dist/ai/plugins/plugin-loader.d.ts.map +1 -1
- package/dist/ai/plugins/plugin-loader.js +28 -28
- package/dist/ai/plugins/plugin-loader.js.map +1 -1
- package/dist/ai/reputation/execution-mode-reputation.d.ts +104 -0
- package/dist/ai/reputation/execution-mode-reputation.d.ts.map +1 -0
- package/dist/ai/reputation/execution-mode-reputation.js +142 -0
- package/dist/ai/reputation/execution-mode-reputation.js.map +1 -0
- package/dist/ai/reputation/reputation-engine.d.ts +204 -0
- package/dist/ai/reputation/reputation-engine.d.ts.map +1 -0
- package/dist/ai/reputation/reputation-engine.js +426 -0
- package/dist/ai/reputation/reputation-engine.js.map +1 -0
- package/dist/ai/runtime/agent-runtime.d.ts +193 -0
- package/dist/ai/runtime/agent-runtime.d.ts.map +1 -0
- package/dist/ai/runtime/agent-runtime.js +1009 -0
- package/dist/ai/runtime/agent-runtime.js.map +1 -0
- package/dist/ai/runtime/index.d.ts +11 -0
- package/dist/ai/runtime/index.d.ts.map +1 -0
- package/dist/ai/runtime/index.js +9 -0
- package/dist/ai/runtime/index.js.map +1 -0
- package/dist/ai/runtime/telemetry-schema.d.ts +192 -0
- package/dist/ai/runtime/telemetry-schema.d.ts.map +1 -0
- package/dist/ai/runtime/telemetry-schema.js +200 -0
- package/dist/ai/runtime/telemetry-schema.js.map +1 -0
- package/dist/ai/runtime/types.d.ts +236 -0
- package/dist/ai/runtime/types.d.ts.map +1 -0
- package/dist/ai/runtime/types.js +10 -0
- package/dist/ai/runtime/types.js.map +1 -0
- package/dist/ai/src/batch-processor.d.ts +298 -0
- package/dist/ai/src/batch-processor.d.ts.map +1 -0
- package/dist/ai/src/batch-processor.js +520 -0
- package/dist/ai/src/batch-processor.js.map +1 -0
- package/dist/ai/src/capability-bootstrap.d.ts +222 -0
- package/dist/ai/src/capability-bootstrap.d.ts.map +1 -0
- package/dist/ai/src/capability-bootstrap.js +421 -0
- package/dist/ai/src/capability-bootstrap.js.map +1 -0
- package/dist/ai/src/capability-manifest-generator.d.ts +52 -0
- package/dist/ai/src/capability-manifest-generator.d.ts.map +1 -0
- package/dist/ai/src/capability-manifest-generator.js +691 -0
- package/dist/ai/src/capability-manifest-generator.js.map +1 -0
- package/dist/ai/src/capability-registry.d.ts +157 -0
- package/dist/ai/src/capability-registry.d.ts.map +1 -0
- package/dist/ai/src/capability-registry.js +577 -0
- package/dist/ai/src/capability-registry.js.map +1 -0
- package/dist/ai/src/cli/telemetry-dashboard.d.ts +132 -0
- package/dist/ai/src/cli/telemetry-dashboard.d.ts.map +1 -0
- package/dist/ai/src/cli/telemetry-dashboard.js +565 -0
- package/dist/ai/src/cli/telemetry-dashboard.js.map +1 -0
- package/dist/ai/src/delegation/feature-flags.d.ts +213 -0
- package/dist/ai/src/delegation/feature-flags.d.ts.map +1 -0
- package/dist/ai/src/delegation/feature-flags.js +395 -0
- package/dist/ai/src/delegation/feature-flags.js.map +1 -0
- package/dist/ai/src/delegation/liability-firebreak.d.ts +303 -0
- package/dist/ai/src/delegation/liability-firebreak.d.ts.map +1 -0
- package/dist/ai/src/delegation/liability-firebreak.js +643 -0
- package/dist/ai/src/delegation/liability-firebreak.js.map +1 -0
- package/dist/ai/src/delegation/security-threat-model.d.ts +171 -0
- package/dist/ai/src/delegation/security-threat-model.d.ts.map +1 -0
- package/dist/ai/src/delegation/security-threat-model.js +723 -0
- package/dist/ai/src/delegation/security-threat-model.js.map +1 -0
- package/dist/ai/src/delegation/tlp-enforcement.d.ts +146 -0
- package/dist/ai/src/delegation/tlp-enforcement.d.ts.map +1 -0
- package/dist/ai/src/delegation/tlp-enforcement.js +382 -0
- package/dist/ai/src/delegation/tlp-enforcement.js.map +1 -0
- package/dist/ai/src/delegation-capability-integration.d.ts +154 -0
- package/dist/ai/src/delegation-capability-integration.d.ts.map +1 -0
- package/dist/ai/src/delegation-capability-integration.js +351 -0
- package/dist/ai/src/delegation-capability-integration.js.map +1 -0
- package/dist/ai/src/end-to-end-workflow-orchestrator.d.ts +325 -0
- package/dist/ai/src/end-to-end-workflow-orchestrator.d.ts.map +1 -0
- package/dist/ai/src/end-to-end-workflow-orchestrator.js +801 -0
- package/dist/ai/src/end-to-end-workflow-orchestrator.js.map +1 -0
- package/dist/ai/src/enhanced-capability-detection.d.ts +237 -0
- package/dist/ai/src/enhanced-capability-detection.d.ts.map +1 -0
- package/dist/ai/src/enhanced-capability-detection.js +448 -0
- package/dist/ai/src/enhanced-capability-detection.js.map +1 -0
- package/dist/ai/src/intelligent-cache-manager.d.ts +327 -0
- package/dist/ai/src/intelligent-cache-manager.d.ts.map +1 -0
- package/dist/ai/src/intelligent-cache-manager.js +634 -0
- package/dist/ai/src/intelligent-cache-manager.js.map +1 -0
- package/dist/ai/src/mcp-auto-configuration.d.ts +232 -0
- package/dist/ai/src/mcp-auto-configuration.d.ts.map +1 -0
- package/dist/ai/src/mcp-auto-configuration.js +445 -0
- package/dist/ai/src/mcp-auto-configuration.js.map +1 -0
- package/dist/ai/src/performance-profiler.d.ts +351 -0
- package/dist/ai/src/performance-profiler.d.ts.map +1 -0
- package/dist/ai/src/performance-profiler.js +475 -0
- package/dist/ai/src/performance-profiler.js.map +1 -0
- package/dist/ai/src/personas/hooks/before-llm-call.d.ts +96 -0
- package/dist/ai/src/personas/hooks/before-llm-call.d.ts.map +1 -0
- package/dist/ai/src/personas/hooks/before-llm-call.js +83 -0
- package/dist/ai/src/personas/hooks/before-llm-call.js.map +1 -0
- package/dist/ai/src/personas/index.d.ts +10 -0
- package/dist/ai/src/personas/index.d.ts.map +1 -0
- package/dist/ai/src/personas/index.js +10 -0
- package/dist/ai/src/personas/index.js.map +1 -0
- package/dist/ai/src/personas/persona-loader.d.ts +42 -0
- package/dist/ai/src/personas/persona-loader.d.ts.map +1 -0
- package/dist/ai/src/personas/persona-loader.js +162 -0
- package/dist/ai/src/personas/persona-loader.js.map +1 -0
- package/dist/ai/src/personas/types.d.ts +199 -0
- package/dist/ai/src/personas/types.d.ts.map +1 -0
- package/dist/ai/src/personas/types.js +7 -0
- package/dist/ai/src/personas/types.js.map +1 -0
- package/dist/ai/src/personas/voice-resolver.d.ts +40 -0
- package/dist/ai/src/personas/voice-resolver.d.ts.map +1 -0
- package/dist/ai/src/personas/voice-resolver.js +201 -0
- package/dist/ai/src/personas/voice-resolver.js.map +1 -0
- package/dist/ai/src/resource-monitor.d.ts +311 -0
- package/dist/ai/src/resource-monitor.d.ts.map +1 -0
- package/dist/ai/src/resource-monitor.js +475 -0
- package/dist/ai/src/resource-monitor.js.map +1 -0
- package/dist/ai/src/runtime/agent-runtime.d.ts +340 -0
- package/dist/ai/src/runtime/agent-runtime.d.ts.map +1 -0
- package/dist/ai/src/runtime/agent-runtime.js +1084 -0
- package/dist/ai/src/runtime/agent-runtime.js.map +1 -0
- package/dist/ai/src/telemetry/delegation-telemetry.d.ts +287 -0
- package/dist/ai/src/telemetry/delegation-telemetry.d.ts.map +1 -0
- package/dist/ai/src/telemetry/delegation-telemetry.js +389 -0
- package/dist/ai/src/telemetry/delegation-telemetry.js.map +1 -0
- package/dist/ai/src/telemetry/index.d.ts +48 -0
- package/dist/ai/src/telemetry/index.d.ts.map +1 -0
- package/dist/ai/src/telemetry/index.js +48 -0
- package/dist/ai/src/telemetry/index.js.map +1 -0
- package/dist/ai/src/telemetry/runtime-telemetry-integration.d.ts +67 -0
- package/dist/ai/src/telemetry/runtime-telemetry-integration.d.ts.map +1 -0
- package/dist/ai/src/telemetry/runtime-telemetry-integration.js +415 -0
- package/dist/ai/src/telemetry/runtime-telemetry-integration.js.map +1 -0
- package/dist/ai/src/telemetry/telemetry-utils.d.ts +119 -0
- package/dist/ai/src/telemetry/telemetry-utils.d.ts.map +1 -0
- package/dist/ai/src/telemetry/telemetry-utils.js +250 -0
- package/dist/ai/src/telemetry/telemetry-utils.js.map +1 -0
- package/dist/ai/src/types/agent-capabilities.d.ts +227 -0
- package/dist/ai/src/types/agent-capabilities.d.ts.map +1 -0
- package/dist/ai/src/types/agent-capabilities.js +11 -0
- package/dist/ai/src/types/agent-capabilities.js.map +1 -0
- package/dist/ai/src/types/context-verification.d.ts +158 -0
- package/dist/ai/src/types/context-verification.d.ts.map +1 -0
- package/dist/ai/src/types/context-verification.js +73 -0
- package/dist/ai/src/types/context-verification.js.map +1 -0
- package/dist/ai/src/types/delegation-contracts.d.ts +296 -0
- package/dist/ai/src/types/delegation-contracts.d.ts.map +1 -0
- package/dist/ai/src/types/delegation-contracts.js +17 -0
- package/dist/ai/src/types/delegation-contracts.js.map +1 -0
- package/dist/ai/src/validation-pipeline-integration.d.ts +266 -0
- package/dist/ai/src/validation-pipeline-integration.d.ts.map +1 -0
- package/dist/ai/src/validation-pipeline-integration.js +695 -0
- package/dist/ai/src/validation-pipeline-integration.js.map +1 -0
- package/dist/ai/src/verification/multi-modal-formatters.d.ts +57 -0
- package/dist/ai/src/verification/multi-modal-formatters.d.ts.map +1 -0
- package/dist/ai/src/verification/multi-modal-formatters.js +655 -0
- package/dist/ai/src/verification/multi-modal-formatters.js.map +1 -0
- package/dist/ai/src/verification/output-formatter.d.ts +186 -0
- package/dist/ai/src/verification/output-formatter.d.ts.map +1 -0
- package/dist/ai/src/verification/output-formatter.js +296 -0
- package/dist/ai/src/verification/output-formatter.js.map +1 -0
- package/dist/ai/src/verification/parser-integration.d.ts +137 -0
- package/dist/ai/src/verification/parser-integration.d.ts.map +1 -0
- package/dist/ai/src/verification/parser-integration.js +273 -0
- package/dist/ai/src/verification/parser-integration.js.map +1 -0
- package/dist/ai/types/agent-capabilities.d.ts +387 -0
- package/dist/ai/types/agent-capabilities.d.ts.map +1 -0
- package/dist/ai/types/agent-capabilities.js +32 -0
- package/dist/ai/types/agent-capabilities.js.map +1 -0
- package/dist/ai/types/delegation-contracts.d.ts +291 -0
- package/dist/ai/types/delegation-contracts.d.ts.map +1 -0
- package/dist/ai/types/delegation-contracts.js +14 -0
- package/dist/ai/types/delegation-contracts.js.map +1 -0
- package/dist/ai/types/index.d.ts +4 -1
- package/dist/ai/types/index.d.ts.map +1 -1
- package/dist/ai/types/index.js +4 -1
- package/dist/ai/types/index.js.map +1 -1
- package/dist/ai/types/permission-tokens.d.ts +365 -0
- package/dist/ai/types/permission-tokens.d.ts.map +1 -0
- package/dist/ai/types/permission-tokens.js +13 -0
- package/dist/ai/types/permission-tokens.js.map +1 -0
- package/dist/ai/types/security-middleware.d.ts +130 -0
- package/dist/ai/types/security-middleware.d.ts.map +1 -0
- package/dist/ai/types/security-middleware.js +13 -0
- package/dist/ai/types/security-middleware.js.map +1 -0
- package/dist/ai/utils/storage.d.ts.map +1 -1
- package/dist/ai/utils/storage.js +6 -3
- package/dist/ai/utils/storage.js.map +1 -1
- package/dist/ai/validation/validation-framework.js +1 -1
- package/dist/ai/verification/policy-framework.d.ts +161 -0
- package/dist/ai/verification/policy-framework.d.ts.map +1 -0
- package/dist/ai/verification/policy-framework.js +436 -0
- package/dist/ai/verification/policy-framework.js.map +1 -0
- package/package.json +56 -6
|
@@ -0,0 +1,1009 @@
|
|
|
1
|
+
import { PermissionDeniedError } from './types.js';
|
|
2
|
+
function parseVersion(version) {
|
|
3
|
+
const parts = version.replace(/^[^\d]*/, '').split('.').map(Number);
|
|
4
|
+
return {
|
|
5
|
+
major: parts[0] || 0,
|
|
6
|
+
minor: parts[1] || 0,
|
|
7
|
+
patch: parts[2] || 0,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
function checkVersionCompatibility(runtimeVersion, agentsVersion) {
|
|
11
|
+
// Current @dcyfr/ai version
|
|
12
|
+
const runtime = parseVersion(runtimeVersion);
|
|
13
|
+
if (!agentsVersion) {
|
|
14
|
+
console.warn('[AgentRuntime] Warning: Unable to detect @dcyfr/ai-agents version. ' +
|
|
15
|
+
'Ensure versions are compatible. Current runtime: v' + runtimeVersion);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const agents = parseVersion(agentsVersion);
|
|
19
|
+
// Version compatibility rules:
|
|
20
|
+
// - Major version must match (1.x.x with 1.x.x)
|
|
21
|
+
// - Runtime can be newer minor version than agents
|
|
22
|
+
// - Agents should not be more than 1 major version ahead
|
|
23
|
+
if (runtime.major !== agents.major) {
|
|
24
|
+
console.warn('[AgentRuntime] Version Mismatch Warning: ' +
|
|
25
|
+
`Runtime v${runtimeVersion} (major ${runtime.major}) ` +
|
|
26
|
+
`with Agents v${agentsVersion} (major ${agents.major}). ` +
|
|
27
|
+
'Different major versions may cause compatibility issues. ' +
|
|
28
|
+
'Consider upgrading to matching versions.');
|
|
29
|
+
}
|
|
30
|
+
else if (agents.minor > runtime.minor + 2) {
|
|
31
|
+
console.warn('[AgentRuntime] Version Skew Warning: ' +
|
|
32
|
+
`Agents v${agentsVersion} is significantly ahead of runtime v${runtimeVersion}. ` +
|
|
33
|
+
'Consider upgrading @dcyfr/ai for latest features and compatibility.');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* AgentRuntime - Executes multi-step tasks with LLM integration
|
|
38
|
+
*
|
|
39
|
+
* Bridges agent execution loop with LLM providers, memory, and telemetry.
|
|
40
|
+
* Supports tool execution, observation recording, and multi-iteration reasoning.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* const runtime = new AgentRuntime(
|
|
45
|
+
* 'code-reviewer',
|
|
46
|
+
* providerRegistry,
|
|
47
|
+
* memory,
|
|
48
|
+
* telemetry
|
|
49
|
+
* );
|
|
50
|
+
*
|
|
51
|
+
* const result = await runtime.execute({
|
|
52
|
+
* task: 'Review the authentication logic in auth.ts',
|
|
53
|
+
* userId: 'user-123',
|
|
54
|
+
* sessionId: 'session-456',
|
|
55
|
+
* tools: [fileSearchTool, readFileTool]
|
|
56
|
+
* });
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export class AgentRuntime {
|
|
60
|
+
agentName;
|
|
61
|
+
providerRegistry;
|
|
62
|
+
memory;
|
|
63
|
+
telemetry;
|
|
64
|
+
config;
|
|
65
|
+
beforeExecuteHooks = [];
|
|
66
|
+
afterExecuteHooks = [];
|
|
67
|
+
constructor(agentName, providerRegistry, memory, telemetry, config) {
|
|
68
|
+
// Version compatibility check
|
|
69
|
+
this.performVersionCheck();
|
|
70
|
+
this.agentName = agentName;
|
|
71
|
+
this.providerRegistry = providerRegistry;
|
|
72
|
+
this.memory = memory;
|
|
73
|
+
this.telemetry = telemetry;
|
|
74
|
+
// Apply default configuration
|
|
75
|
+
this.config = {
|
|
76
|
+
maxIterations: config?.maxIterations ?? 10,
|
|
77
|
+
timeout: config?.timeout ?? 120000, // 2 minutes
|
|
78
|
+
memoryEnabled: config?.memoryEnabled ?? true,
|
|
79
|
+
memoryTimeout: config?.memoryTimeout ?? 3000,
|
|
80
|
+
memoryRelevanceThreshold: config?.memoryRelevanceThreshold ?? 0.7,
|
|
81
|
+
summarizationEnabled: config?.summarizationEnabled ?? true,
|
|
82
|
+
summarizationInterval: config?.summarizationInterval ?? 5,
|
|
83
|
+
workingMemoryEnabled: config?.workingMemoryEnabled ?? true,
|
|
84
|
+
persistWorkingMemory: config?.persistWorkingMemory ?? false,
|
|
85
|
+
debugWorkingMemory: config?.debugWorkingMemory ?? false,
|
|
86
|
+
systemPrompt: config?.systemPrompt ?? this.getDefaultSystemPrompt(),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Check version compatibility between @dcyfr/ai and @dcyfr/ai-agents
|
|
91
|
+
* Logs warnings if version mismatches could cause issues
|
|
92
|
+
*/
|
|
93
|
+
performVersionCheck() {
|
|
94
|
+
try {
|
|
95
|
+
// Get current runtime version from package.json
|
|
96
|
+
const runtimeVersion = '1.0.4'; // This should be dynamically imported in production
|
|
97
|
+
// Try to detect agents package version
|
|
98
|
+
let agentsVersion;
|
|
99
|
+
try {
|
|
100
|
+
// This is a best-effort detection - in practice, the calling package
|
|
101
|
+
// would need to provide this information
|
|
102
|
+
const process = globalThis.process;
|
|
103
|
+
if (process?.versions) {
|
|
104
|
+
// Check environment for version info
|
|
105
|
+
agentsVersion = process.env.DCYFR_AGENTS_VERSION;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// Ignore errors in version detection
|
|
110
|
+
}
|
|
111
|
+
checkVersionCompatibility(runtimeVersion, agentsVersion);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
// Don't fail initialization due to version checking issues
|
|
115
|
+
console.warn('[AgentRuntime] Version check failed:', error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Register a before-execution hook
|
|
120
|
+
*
|
|
121
|
+
* Hooks are called before task execution begins.
|
|
122
|
+
* A hook can reject execution by throwing PermissionDeniedError.
|
|
123
|
+
*
|
|
124
|
+
* @param hook - Function to call before execution
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```typescript
|
|
128
|
+
* runtime.beforeExecute(async (context) => {
|
|
129
|
+
* if (!hasPermission(context.userId, 'execute')) {
|
|
130
|
+
* throw new PermissionDeniedError('User lacks execute permission');
|
|
131
|
+
* }
|
|
132
|
+
* });
|
|
133
|
+
* ```
|
|
134
|
+
*/
|
|
135
|
+
beforeExecute(hook) {
|
|
136
|
+
this.beforeExecuteHooks.push(hook);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Register an after-execution hook
|
|
140
|
+
*
|
|
141
|
+
* Hooks are called after task execution completes (success or failure).
|
|
142
|
+
* Useful for logging, auditing, or cleanup operations.
|
|
143
|
+
*
|
|
144
|
+
* @param hook - Function to call after execution
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```typescript
|
|
148
|
+
* runtime.afterExecute(async (context, result) => {
|
|
149
|
+
* await auditLog.record({
|
|
150
|
+
* agent: context.agentName,
|
|
151
|
+
* task: context.task,
|
|
152
|
+
* success: result.success,
|
|
153
|
+
* cost: result.cost,
|
|
154
|
+
* });
|
|
155
|
+
* });
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
afterExecute(hook) {
|
|
159
|
+
this.afterExecuteHooks.push(hook);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Execute a task from start to completion
|
|
163
|
+
*
|
|
164
|
+
* @param context - Task context with description, tools, and metadata
|
|
165
|
+
* @returns Execution result with output, cost, and telemetry data
|
|
166
|
+
*/
|
|
167
|
+
async handlePermissionDenied(error, hookContext, startTime) {
|
|
168
|
+
const executionTime = Date.now() - startTime;
|
|
169
|
+
const result = {
|
|
170
|
+
success: false,
|
|
171
|
+
error: error.message,
|
|
172
|
+
outcome: 'error',
|
|
173
|
+
executionTime,
|
|
174
|
+
cost: 0,
|
|
175
|
+
iterations: 0,
|
|
176
|
+
};
|
|
177
|
+
await this.runAfterExecuteHooks(hookContext, result);
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
async runBeforeExecuteHooks(hookContext, startTime) {
|
|
181
|
+
for (const hook of this.beforeExecuteHooks) {
|
|
182
|
+
try {
|
|
183
|
+
await hook(hookContext);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
if (error instanceof PermissionDeniedError) {
|
|
187
|
+
return this.handlePermissionDenied(error, hookContext, startTime);
|
|
188
|
+
}
|
|
189
|
+
const hookError = error instanceof Error ? error : new Error(String(error));
|
|
190
|
+
Object.assign(hookError, { isHookError: true });
|
|
191
|
+
throw hookError;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
async execute(context) {
|
|
197
|
+
const startTime = Date.now();
|
|
198
|
+
let sessionManager;
|
|
199
|
+
let sessionId;
|
|
200
|
+
let memoryWriteFailed = false;
|
|
201
|
+
try {
|
|
202
|
+
// Create hook context
|
|
203
|
+
const hookContext = {
|
|
204
|
+
agentName: this.agentName,
|
|
205
|
+
task: context.task,
|
|
206
|
+
userId: context.userId,
|
|
207
|
+
sessionId: context.sessionId,
|
|
208
|
+
timestamp: Date.now(),
|
|
209
|
+
};
|
|
210
|
+
// Run before-execution hooks
|
|
211
|
+
const earlyResult = await this.runBeforeExecuteHooks(hookContext, startTime);
|
|
212
|
+
if (earlyResult !== null)
|
|
213
|
+
return earlyResult;
|
|
214
|
+
// Create telemetry session
|
|
215
|
+
// Note: startSession expects AgentType, but we have agentName as string
|
|
216
|
+
// For now, we'll use 'claude' as default - this should be configurable
|
|
217
|
+
sessionManager = this.telemetry.startSession('claude', // TODO: Make agentType configurable
|
|
218
|
+
{
|
|
219
|
+
taskType: 'feature',
|
|
220
|
+
description: context.task,
|
|
221
|
+
});
|
|
222
|
+
sessionId = sessionManager.getSession().sessionId;
|
|
223
|
+
// Emit start event
|
|
224
|
+
this.emitEvent({
|
|
225
|
+
type: 'start',
|
|
226
|
+
agentName: this.agentName,
|
|
227
|
+
task: context.task,
|
|
228
|
+
timestamp: Date.now(),
|
|
229
|
+
});
|
|
230
|
+
// Initialize state
|
|
231
|
+
const state = await this.initializeState(context);
|
|
232
|
+
// Execute with timeout
|
|
233
|
+
const result = await this.executeWithTimeout(state, context, startTime);
|
|
234
|
+
return await this.handleSuccessfulExecution(state, result, sessionManager, sessionId, context, startTime, memoryWriteFailed);
|
|
235
|
+
}
|
|
236
|
+
catch (error) {
|
|
237
|
+
return await this.handleFailedExecution(error, sessionManager, sessionId, context, startTime);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** @private Success path of execute() — persist memory, emit events, run after-hooks */
|
|
241
|
+
async handleSuccessfulExecution(state, result, sessionManager, sessionId, context, startTime, memoryWriteFailed) {
|
|
242
|
+
// Persist insights to memory
|
|
243
|
+
if (this.config.memoryEnabled && result.success) {
|
|
244
|
+
try {
|
|
245
|
+
await this.persistInsights(context, state, result);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
console.warn('[AgentRuntime] Failed to persist insights:', error);
|
|
249
|
+
memoryWriteFailed = true;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// Debug log working memory state
|
|
253
|
+
if (this.config.debugWorkingMemory && state.workingMemory.size > 0) {
|
|
254
|
+
const memorySnapshot = {};
|
|
255
|
+
state.workingMemory.forEach((value, key) => {
|
|
256
|
+
memorySnapshot[key] = value;
|
|
257
|
+
});
|
|
258
|
+
console.log('[WorkingMemory] Final state:', JSON.stringify(memorySnapshot, null, 2));
|
|
259
|
+
}
|
|
260
|
+
// Clear working memory unless persistence is enabled
|
|
261
|
+
if (!this.config.persistWorkingMemory) {
|
|
262
|
+
if (this.config.debugWorkingMemory) {
|
|
263
|
+
console.log('[WorkingMemory] Clearing ephemeral state');
|
|
264
|
+
}
|
|
265
|
+
state.workingMemory.clear();
|
|
266
|
+
}
|
|
267
|
+
// End telemetry session
|
|
268
|
+
if (sessionManager) {
|
|
269
|
+
await sessionManager.end(result.success ? 'success' : 'failed');
|
|
270
|
+
}
|
|
271
|
+
// Emit finish event
|
|
272
|
+
this.emitEvent({
|
|
273
|
+
type: 'finish',
|
|
274
|
+
success: result.success,
|
|
275
|
+
iterations: state.iteration,
|
|
276
|
+
output: result.output,
|
|
277
|
+
duration: Date.now() - startTime,
|
|
278
|
+
error: result.error,
|
|
279
|
+
});
|
|
280
|
+
const finalResult = {
|
|
281
|
+
...result,
|
|
282
|
+
sessionId,
|
|
283
|
+
memoryWriteFailed: memoryWriteFailed || undefined,
|
|
284
|
+
};
|
|
285
|
+
// Run after-execution hooks
|
|
286
|
+
const finalHookContext = {
|
|
287
|
+
agentName: this.agentName,
|
|
288
|
+
task: context.task,
|
|
289
|
+
userId: context.userId,
|
|
290
|
+
sessionId: context.sessionId,
|
|
291
|
+
timestamp: Date.now(),
|
|
292
|
+
};
|
|
293
|
+
await this.runAfterExecuteHooks(finalHookContext, finalResult);
|
|
294
|
+
return finalResult;
|
|
295
|
+
}
|
|
296
|
+
/** @private Error path of execute() — end session, emit error event, run after-hooks */
|
|
297
|
+
async handleFailedExecution(error, sessionManager, sessionId, context, startTime) {
|
|
298
|
+
// Re-throw hook errors to propagate them properly
|
|
299
|
+
if (error && typeof error === 'object' && 'isHookError' in error && error.isHookError) {
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
const executionTime = Date.now() - startTime;
|
|
303
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
304
|
+
// End telemetry session on error
|
|
305
|
+
if (sessionManager) {
|
|
306
|
+
await sessionManager.end('failed');
|
|
307
|
+
}
|
|
308
|
+
// Emit error event
|
|
309
|
+
this.emitEvent({
|
|
310
|
+
type: 'error',
|
|
311
|
+
error: error instanceof Error ? error : new Error(errorMessage),
|
|
312
|
+
context: 'execution',
|
|
313
|
+
timestamp: Date.now(),
|
|
314
|
+
});
|
|
315
|
+
const result = {
|
|
316
|
+
success: false,
|
|
317
|
+
error: errorMessage,
|
|
318
|
+
outcome: 'error',
|
|
319
|
+
executionTime,
|
|
320
|
+
cost: 0,
|
|
321
|
+
iterations: 0,
|
|
322
|
+
sessionId,
|
|
323
|
+
};
|
|
324
|
+
// Run after-execution hooks even on error
|
|
325
|
+
const errorHookContext = {
|
|
326
|
+
agentName: this.agentName,
|
|
327
|
+
task: context.task,
|
|
328
|
+
userId: context.userId,
|
|
329
|
+
sessionId: context.sessionId,
|
|
330
|
+
timestamp: Date.now(),
|
|
331
|
+
};
|
|
332
|
+
await this.runAfterExecuteHooks(errorHookContext, result);
|
|
333
|
+
return result;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Run all after-execution hooks
|
|
337
|
+
* @private
|
|
338
|
+
*/
|
|
339
|
+
async runAfterExecuteHooks(hookContext, result) {
|
|
340
|
+
for (const hook of this.afterExecuteHooks) {
|
|
341
|
+
try {
|
|
342
|
+
await hook(hookContext, result);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
// Log hook errors but don't fail execution
|
|
346
|
+
console.warn('[AgentRuntime] After-execute hook failed:', error);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Initialize execution state with memory context
|
|
352
|
+
*/
|
|
353
|
+
async initializeState(context) {
|
|
354
|
+
const state = {
|
|
355
|
+
messages: [],
|
|
356
|
+
observations: [],
|
|
357
|
+
iteration: 0,
|
|
358
|
+
workingMemory: new Map(),
|
|
359
|
+
isFinished: false,
|
|
360
|
+
steps: [],
|
|
361
|
+
};
|
|
362
|
+
// Retrieve memory context if enabled
|
|
363
|
+
let memoryContext = '';
|
|
364
|
+
if (this.config.memoryEnabled) {
|
|
365
|
+
memoryContext = await this.retrieveContext(context);
|
|
366
|
+
}
|
|
367
|
+
// Build system prompt with memory context
|
|
368
|
+
const systemPrompt = memoryContext
|
|
369
|
+
? `${this.config.systemPrompt}\n\nPrevious relevant information:\n${memoryContext}`
|
|
370
|
+
: this.config.systemPrompt;
|
|
371
|
+
// Initialize messages with system prompt and user task
|
|
372
|
+
state.messages.push({
|
|
373
|
+
role: 'system',
|
|
374
|
+
content: systemPrompt,
|
|
375
|
+
});
|
|
376
|
+
state.messages.push({
|
|
377
|
+
role: 'user',
|
|
378
|
+
content: context.task,
|
|
379
|
+
});
|
|
380
|
+
return state;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* Execute task with timeout enforcement
|
|
384
|
+
*/
|
|
385
|
+
async executeWithTimeout(state, context, startTime) {
|
|
386
|
+
return new Promise((resolve) => {
|
|
387
|
+
const timeoutHandle = setTimeout(() => {
|
|
388
|
+
resolve({
|
|
389
|
+
success: false,
|
|
390
|
+
outcome: 'timeout',
|
|
391
|
+
executionTime: Date.now() - startTime,
|
|
392
|
+
cost: this.calculateCost(state),
|
|
393
|
+
iterations: state.iteration,
|
|
394
|
+
error: `Execution exceeded timeout of ${this.config.timeout}ms`,
|
|
395
|
+
});
|
|
396
|
+
}, this.config.timeout);
|
|
397
|
+
this.executeIterations(state, context, startTime)
|
|
398
|
+
.then((result) => {
|
|
399
|
+
clearTimeout(timeoutHandle);
|
|
400
|
+
resolve(result);
|
|
401
|
+
})
|
|
402
|
+
.catch((error) => {
|
|
403
|
+
clearTimeout(timeoutHandle);
|
|
404
|
+
resolve({
|
|
405
|
+
success: false,
|
|
406
|
+
outcome: 'error',
|
|
407
|
+
executionTime: Date.now() - startTime,
|
|
408
|
+
cost: this.calculateCost(state),
|
|
409
|
+
iterations: state.iteration,
|
|
410
|
+
error: error instanceof Error ? error.message : String(error),
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Execute iteration loop until completion or max iterations
|
|
417
|
+
*/
|
|
418
|
+
async processDecisionAction(decision, context, state) {
|
|
419
|
+
if (decision.action) {
|
|
420
|
+
const observation = await this.executeTool(decision.action, context, state);
|
|
421
|
+
state.observations.push(observation);
|
|
422
|
+
state.steps[state.steps.length - 1].observation = observation.success
|
|
423
|
+
? String(observation.output)
|
|
424
|
+
: observation.error?.message || 'Tool execution failed';
|
|
425
|
+
state.messages.push({
|
|
426
|
+
role: 'tool',
|
|
427
|
+
content: observation.success
|
|
428
|
+
? JSON.stringify(observation.output)
|
|
429
|
+
: `Error: ${observation.error?.message}`,
|
|
430
|
+
name: observation.tool,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
state.isFinished = true;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async executeIterations(state, context, startTime) {
|
|
438
|
+
while (!state.isFinished && state.iteration < this.config.maxIterations) {
|
|
439
|
+
state.iteration++;
|
|
440
|
+
// Make decision via LLM
|
|
441
|
+
const decision = await this.makeDecision(state, context);
|
|
442
|
+
// Record step
|
|
443
|
+
state.steps.push({
|
|
444
|
+
iteration: state.iteration,
|
|
445
|
+
thought: decision.thought,
|
|
446
|
+
action: decision.action,
|
|
447
|
+
timestamp: Date.now(),
|
|
448
|
+
});
|
|
449
|
+
// Debug log working memory state after each step
|
|
450
|
+
if (this.config.debugWorkingMemory && state.workingMemory.size > 0) {
|
|
451
|
+
const memorySnapshot = {};
|
|
452
|
+
state.workingMemory.forEach((value, key) => {
|
|
453
|
+
memorySnapshot[key] = value;
|
|
454
|
+
});
|
|
455
|
+
console.log(`[WorkingMemory Step ${state.iteration}]`, JSON.stringify(memorySnapshot, null, 2));
|
|
456
|
+
}
|
|
457
|
+
// Emit step event
|
|
458
|
+
this.emitEvent({
|
|
459
|
+
type: 'step',
|
|
460
|
+
iteration: state.iteration,
|
|
461
|
+
thought: decision.thought,
|
|
462
|
+
action: decision.action,
|
|
463
|
+
timestamp: Date.now(),
|
|
464
|
+
});
|
|
465
|
+
// Execute action if present
|
|
466
|
+
await this.processDecisionAction(decision, context, state);
|
|
467
|
+
// Check for periodic summarization
|
|
468
|
+
if (this.config.summarizationEnabled &&
|
|
469
|
+
state.iteration === this.config.summarizationInterval) {
|
|
470
|
+
await this.summarizeMessages(state, context);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// Check if max iterations reached
|
|
474
|
+
if (state.iteration >= this.config.maxIterations && !state.isFinished) {
|
|
475
|
+
return {
|
|
476
|
+
success: false,
|
|
477
|
+
outcome: 'max_iterations_reached',
|
|
478
|
+
executionTime: Date.now() - startTime,
|
|
479
|
+
cost: this.calculateCost(state),
|
|
480
|
+
iterations: state.iteration,
|
|
481
|
+
error: `Reached maximum iterations (${this.config.maxIterations})`,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
// Extract final output from last assistant message
|
|
485
|
+
const lastAssistantMessage = [...state.messages]
|
|
486
|
+
.reverse()
|
|
487
|
+
.find((m) => m.role === 'assistant');
|
|
488
|
+
return {
|
|
489
|
+
success: true,
|
|
490
|
+
outcome: 'success',
|
|
491
|
+
output: lastAssistantMessage?.content || 'Task completed',
|
|
492
|
+
executionTime: Date.now() - startTime,
|
|
493
|
+
cost: this.calculateCost(state),
|
|
494
|
+
iterations: state.iteration,
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Make a decision using LLM via ProviderRegistry
|
|
499
|
+
*/
|
|
500
|
+
async makeDecision(state, context) {
|
|
501
|
+
// Format prompt with message history and tool descriptions
|
|
502
|
+
const prompt = this.formatPrompt(state, context);
|
|
503
|
+
// Build TaskContext for provider registry
|
|
504
|
+
const providerTask = {
|
|
505
|
+
description: context.task,
|
|
506
|
+
phase: 'implementation',
|
|
507
|
+
filesInProgress: [],
|
|
508
|
+
};
|
|
509
|
+
// Call LLM via provider registry with fallback
|
|
510
|
+
const result = await this.providerRegistry.executeWithFallback(providerTask, async (provider) => {
|
|
511
|
+
// TODO: Actual provider-specific API calls
|
|
512
|
+
// For now, return a mock response that demonstrates the format
|
|
513
|
+
// Real implementation would call:
|
|
514
|
+
// - Anthropic API for claude/anthropic
|
|
515
|
+
// - OpenAI API for openai/groq
|
|
516
|
+
// - Ollama API for ollama
|
|
517
|
+
// - Copilot API for copilot
|
|
518
|
+
console.warn(`[AgentRuntime] Calling LLM provider: ${provider} (mock response)`);
|
|
519
|
+
// Mock response that will be parsed
|
|
520
|
+
return {
|
|
521
|
+
content: `Thought: I need to analyze the task and determine the best approach.\nFinal Answer: Task analysis complete.`,
|
|
522
|
+
usage: {
|
|
523
|
+
inputTokens: prompt.length / 4, // Rough estimate
|
|
524
|
+
outputTokens: 50,
|
|
525
|
+
},
|
|
526
|
+
};
|
|
527
|
+
});
|
|
528
|
+
// Parse response into decision
|
|
529
|
+
const decision = this.parseDecision(result.data);
|
|
530
|
+
// Track token usage for cost calculation
|
|
531
|
+
if (result.data && typeof result.data === 'object') {
|
|
532
|
+
const data = result.data;
|
|
533
|
+
const usage = data.usage;
|
|
534
|
+
if (usage) {
|
|
535
|
+
const currentTokens = state.workingMemory.get('tokens') || {
|
|
536
|
+
input: 0,
|
|
537
|
+
output: 0,
|
|
538
|
+
};
|
|
539
|
+
state.workingMemory.set('tokens', {
|
|
540
|
+
input: currentTokens.input + (usage.inputTokens || 0),
|
|
541
|
+
output: currentTokens.output + (usage.outputTokens || 0),
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
// Track provider used for cost calculation
|
|
546
|
+
state.workingMemory.set('provider', result.provider);
|
|
547
|
+
// Add assistant response to messages
|
|
548
|
+
state.messages.push({
|
|
549
|
+
role: 'assistant',
|
|
550
|
+
content: `Thought: ${decision.thought}${decision.action ? `\nAction: ${decision.action.tool}\nAction Input: ${JSON.stringify(decision.action.input)}` : '\nFinal Answer: Complete'}`,
|
|
551
|
+
});
|
|
552
|
+
return decision;
|
|
553
|
+
}
|
|
554
|
+
/**
|
|
555
|
+
* Format prompt with message history and tool descriptions
|
|
556
|
+
*/
|
|
557
|
+
formatPrompt(state, context) {
|
|
558
|
+
// Build tool descriptions in machine-readable format
|
|
559
|
+
const toolDescriptions = context.tools?.map((tool) => {
|
|
560
|
+
return `Tool: ${tool.name}\nDescription: ${tool.description}\nInput schema: ${JSON.stringify(tool.schema, null, 2)}`;
|
|
561
|
+
}).join('\n\n') || '';
|
|
562
|
+
// Format message history
|
|
563
|
+
const messages = state.messages
|
|
564
|
+
.map((m) => {
|
|
565
|
+
if (m.role === 'tool') {
|
|
566
|
+
return `[tool:${m.name}]: ${m.content}`;
|
|
567
|
+
}
|
|
568
|
+
return `[${m.role}]: ${m.content}`;
|
|
569
|
+
})
|
|
570
|
+
.join('\n');
|
|
571
|
+
const toolSection = toolDescriptions
|
|
572
|
+
? `\n\nAvailable tools:\n${toolDescriptions}\n\nTo use a tool, respond with:\nThought: <your reasoning>\nAction: <tool_name>\nAction Input: <JSON input>\n\nOr to finish, respond with:\nThought: <final thoughts>\nFinal Answer: <response>`
|
|
573
|
+
: '';
|
|
574
|
+
return `${messages}${toolSection}`;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Parse LLM response into Decision object
|
|
578
|
+
* Supports both tool_use format and text-based format
|
|
579
|
+
*/
|
|
580
|
+
/** Parse Anthropic-style tool_use response from content array */
|
|
581
|
+
parseToolUseContent(content) {
|
|
582
|
+
const textBlock = content.find((block) => block.type === 'text');
|
|
583
|
+
const toolBlock = content.find((block) => block.type === 'tool_use');
|
|
584
|
+
if (!toolBlock)
|
|
585
|
+
return null;
|
|
586
|
+
return {
|
|
587
|
+
thought: textBlock?.text || 'Using tool',
|
|
588
|
+
action: { tool: toolBlock.name, input: toolBlock.input },
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
/** Parse an object-shaped response into a Decision */
|
|
592
|
+
parseObjectResponse(resp, original) {
|
|
593
|
+
// Check for tool_use format (Anthropic-style)
|
|
594
|
+
if (resp.content && Array.isArray(resp.content)) {
|
|
595
|
+
const toolUse = this.parseToolUseContent(resp.content);
|
|
596
|
+
if (toolUse)
|
|
597
|
+
return toolUse;
|
|
598
|
+
}
|
|
599
|
+
// Check for direct action format
|
|
600
|
+
if (resp.action) {
|
|
601
|
+
return {
|
|
602
|
+
thought: typeof resp.thought === 'string' ? resp.thought : 'Decision made',
|
|
603
|
+
action: resp.action,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
// Extract text content for text-based parsing
|
|
607
|
+
const textContent = typeof resp.content === 'string' ? resp.content :
|
|
608
|
+
typeof resp.text === 'string' ? resp.text :
|
|
609
|
+
String(original);
|
|
610
|
+
return this.parseTextDecision(textContent);
|
|
611
|
+
}
|
|
612
|
+
parseDecision(response) {
|
|
613
|
+
try {
|
|
614
|
+
if (typeof response === 'object' && response !== null) {
|
|
615
|
+
return this.parseObjectResponse(response, response);
|
|
616
|
+
}
|
|
617
|
+
return this.parseTextDecision(String(response));
|
|
618
|
+
}
|
|
619
|
+
catch (error) {
|
|
620
|
+
console.error('[AgentRuntime] Decision parsing failed:', error);
|
|
621
|
+
return { thought: 'Error parsing response', action: undefined };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Parse text-based decision format
|
|
626
|
+
* Expected format:
|
|
627
|
+
* Thought: <reasoning>
|
|
628
|
+
* Action: <tool_name>
|
|
629
|
+
* Action Input: <JSON>
|
|
630
|
+
* Or:
|
|
631
|
+
* Thought: <reasoning>
|
|
632
|
+
* Final Answer: <response>
|
|
633
|
+
*/
|
|
634
|
+
parseTextDecision(text) {
|
|
635
|
+
// Extract thought
|
|
636
|
+
const thoughtMatch = text.match(/Thought:\s*(.+?)(?=\n(?:Action|Final Answer)|$)/s);
|
|
637
|
+
const thought = thoughtMatch ? thoughtMatch[1].trim() : 'Thinking...';
|
|
638
|
+
// Check for Final Answer (agent is done)
|
|
639
|
+
if (text.includes('Final Answer:')) {
|
|
640
|
+
return { thought, action: undefined };
|
|
641
|
+
}
|
|
642
|
+
// Extract action
|
|
643
|
+
const actionMatch = text.match(/Action:\s*(.+?)(?=\n|$)/);
|
|
644
|
+
const actionInputMatch = text.match(/Action Input:\s*(.+?)(?=\n(?:Thought|Action|$)|$)/s);
|
|
645
|
+
if (actionMatch && actionInputMatch) {
|
|
646
|
+
const toolName = actionMatch[1].trim();
|
|
647
|
+
const inputStr = actionInputMatch[1].trim();
|
|
648
|
+
try {
|
|
649
|
+
const input = JSON.parse(inputStr);
|
|
650
|
+
return {
|
|
651
|
+
thought,
|
|
652
|
+
action: {
|
|
653
|
+
tool: toolName,
|
|
654
|
+
input,
|
|
655
|
+
},
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
catch (error) {
|
|
659
|
+
console.warn('[AgentRuntime] Failed to parse action input as JSON:', inputStr);
|
|
660
|
+
return { thought, action: undefined };
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
// No action found
|
|
664
|
+
return { thought, action: undefined };
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Execute a tool with Zod validation
|
|
668
|
+
*/
|
|
669
|
+
async executeTool(action, context, state) {
|
|
670
|
+
const startTime = Date.now();
|
|
671
|
+
const tool = context.tools?.find((t) => t.name === action.tool);
|
|
672
|
+
if (!tool) {
|
|
673
|
+
const observation = {
|
|
674
|
+
tool: action.tool,
|
|
675
|
+
input: action.input,
|
|
676
|
+
duration: Date.now() - startTime,
|
|
677
|
+
success: false,
|
|
678
|
+
error: new Error(`Tool not found: ${action.tool}`),
|
|
679
|
+
timestamp: Date.now(),
|
|
680
|
+
};
|
|
681
|
+
this.emitEvent({
|
|
682
|
+
type: 'error',
|
|
683
|
+
error: observation.error,
|
|
684
|
+
context: 'tool_not_found',
|
|
685
|
+
timestamp: Date.now(),
|
|
686
|
+
});
|
|
687
|
+
return observation;
|
|
688
|
+
}
|
|
689
|
+
// Emit tool_call event
|
|
690
|
+
this.emitEvent({
|
|
691
|
+
type: 'tool_call',
|
|
692
|
+
tool: action.tool,
|
|
693
|
+
input: action.input,
|
|
694
|
+
iteration: state.iteration,
|
|
695
|
+
timestamp: Date.now(),
|
|
696
|
+
});
|
|
697
|
+
try {
|
|
698
|
+
// Validate input against Zod schema if available
|
|
699
|
+
const schemaError = this.validateZodToolInput(tool, action, startTime);
|
|
700
|
+
if (schemaError !== null)
|
|
701
|
+
return schemaError;
|
|
702
|
+
// Build tool execution context
|
|
703
|
+
const toolContext = {
|
|
704
|
+
workingMemory: state.workingMemory,
|
|
705
|
+
queryMemory: this.createQueryMemoryHelper(context),
|
|
706
|
+
taskContext: context,
|
|
707
|
+
iteration: state.iteration,
|
|
708
|
+
};
|
|
709
|
+
// Check working memory cache if enabled
|
|
710
|
+
const cachedObservation = this.checkWorkingMemoryCache(action, state, startTime);
|
|
711
|
+
if (cachedObservation !== null)
|
|
712
|
+
return cachedObservation;
|
|
713
|
+
// Execute tool
|
|
714
|
+
const output = await tool.execute(action.input, toolContext);
|
|
715
|
+
const duration = Date.now() - startTime;
|
|
716
|
+
// Cache result in working memory if enabled
|
|
717
|
+
if (this.config.workingMemoryEnabled) {
|
|
718
|
+
const cacheKey = `tool:${action.tool}:${this.hashInput(action.input)}`;
|
|
719
|
+
state.workingMemory.set(cacheKey, output);
|
|
720
|
+
}
|
|
721
|
+
// Emit tool_result event
|
|
722
|
+
this.emitEvent({
|
|
723
|
+
type: 'tool_result',
|
|
724
|
+
tool: action.tool,
|
|
725
|
+
result: output,
|
|
726
|
+
duration,
|
|
727
|
+
timestamp: Date.now(),
|
|
728
|
+
});
|
|
729
|
+
return {
|
|
730
|
+
tool: action.tool,
|
|
731
|
+
input: action.input,
|
|
732
|
+
output,
|
|
733
|
+
duration,
|
|
734
|
+
success: true,
|
|
735
|
+
timestamp: Date.now(),
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
catch (error) {
|
|
739
|
+
const duration = Date.now() - startTime;
|
|
740
|
+
// Emit error event
|
|
741
|
+
this.emitEvent({
|
|
742
|
+
type: 'error',
|
|
743
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
744
|
+
context: 'tool_execution',
|
|
745
|
+
timestamp: Date.now(),
|
|
746
|
+
});
|
|
747
|
+
return {
|
|
748
|
+
tool: action.tool,
|
|
749
|
+
input: action.input,
|
|
750
|
+
duration,
|
|
751
|
+
success: false,
|
|
752
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
753
|
+
timestamp: Date.now(),
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
/** @private Validate tool input against Zod schema; mutates action.input on success. Returns error Observation or null. */
|
|
758
|
+
validateZodToolInput(tool, action, startTime) {
|
|
759
|
+
if (!tool.schema || typeof tool.schema.safeParse !== 'function') {
|
|
760
|
+
return null;
|
|
761
|
+
}
|
|
762
|
+
const schema = tool.schema;
|
|
763
|
+
const validationResult = schema.safeParse(action.input);
|
|
764
|
+
if (validationResult.success) {
|
|
765
|
+
action.input = validationResult.data;
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
const validationError = new Error(`Tool input validation failed for ${tool.name}: ${validationResult.error.message}`);
|
|
769
|
+
this.emitEvent({ type: 'error', error: validationError, context: 'tool_validation', timestamp: Date.now() });
|
|
770
|
+
return { tool: action.tool, input: action.input, duration: Date.now() - startTime, success: false, error: validationError, timestamp: Date.now() };
|
|
771
|
+
}
|
|
772
|
+
/** @private Check working memory cache for a prior tool result. Returns cached Observation or null. */
|
|
773
|
+
checkWorkingMemoryCache(action, state, startTime) {
|
|
774
|
+
if (!this.config.workingMemoryEnabled)
|
|
775
|
+
return null;
|
|
776
|
+
const cacheKey = `tool:${action.tool}:${this.hashInput(action.input)}`;
|
|
777
|
+
const cachedResult = state.workingMemory.get(cacheKey);
|
|
778
|
+
if (cachedResult === undefined)
|
|
779
|
+
return null;
|
|
780
|
+
this.emitEvent({ type: 'working_memory_hit', tool: action.tool, cacheKey, timestamp: Date.now() });
|
|
781
|
+
return { tool: action.tool, input: action.input, output: cachedResult, duration: Date.now() - startTime, success: true, timestamp: Date.now() };
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Hash input object for cache key
|
|
785
|
+
*/
|
|
786
|
+
hashInput(input) {
|
|
787
|
+
const sorted = Object.keys(input).sort((a, b) => a.localeCompare(b)).reduce((acc, key) => {
|
|
788
|
+
acc[key] = input[key];
|
|
789
|
+
return acc;
|
|
790
|
+
}, {});
|
|
791
|
+
return JSON.stringify(sorted);
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Retrieve relevant context from DCYFRMemory
|
|
795
|
+
*/
|
|
796
|
+
async retrieveContext(context) {
|
|
797
|
+
const startTime = Date.now();
|
|
798
|
+
try {
|
|
799
|
+
let memories = [];
|
|
800
|
+
// Determine scope and call appropriate search method
|
|
801
|
+
if (context.userId) {
|
|
802
|
+
memories = await Promise.race([
|
|
803
|
+
this.memory.searchUserMemories(context.userId, context.task, 5),
|
|
804
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
|
|
805
|
+
]);
|
|
806
|
+
}
|
|
807
|
+
else if (context.sessionId) {
|
|
808
|
+
// Session memory - for now, fallback to agent memory with sessionId filter
|
|
809
|
+
// TODO: Add searchSessionMemories once implemented in DCYFRMemory
|
|
810
|
+
memories = await Promise.race([
|
|
811
|
+
this.memory.searchAgentMemories(context.agentId || this.agentName, context.task, 5),
|
|
812
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
|
|
813
|
+
]);
|
|
814
|
+
}
|
|
815
|
+
else {
|
|
816
|
+
// Agent scope
|
|
817
|
+
memories = await Promise.race([
|
|
818
|
+
this.memory.searchAgentMemories(context.agentId || this.agentName, context.task, 5),
|
|
819
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Memory search timeout')), this.config.memoryTimeout)),
|
|
820
|
+
]);
|
|
821
|
+
}
|
|
822
|
+
// Filter by relevance threshold
|
|
823
|
+
const relevant = memories.filter((m) => m.relevance > this.config.memoryRelevanceThreshold);
|
|
824
|
+
// Emit memory retrieval telemetry event
|
|
825
|
+
this.emitEvent({
|
|
826
|
+
type: 'memory_retrieval',
|
|
827
|
+
agentName: this.agentName,
|
|
828
|
+
query: context.task,
|
|
829
|
+
memoriesFound: memories.length,
|
|
830
|
+
memoriesRelevant: relevant.length,
|
|
831
|
+
threshold: this.config.memoryRelevanceThreshold,
|
|
832
|
+
duration: Date.now() - startTime,
|
|
833
|
+
timestamp: Date.now(),
|
|
834
|
+
});
|
|
835
|
+
if (relevant.length === 0) {
|
|
836
|
+
return '';
|
|
837
|
+
}
|
|
838
|
+
return relevant.map((m) => `- ${m.content}`).join('\n');
|
|
839
|
+
}
|
|
840
|
+
catch (error) {
|
|
841
|
+
// Emit error event
|
|
842
|
+
this.emitEvent({
|
|
843
|
+
type: 'memory_retrieval',
|
|
844
|
+
agentName: this.agentName,
|
|
845
|
+
query: context.task,
|
|
846
|
+
memoriesFound: 0,
|
|
847
|
+
memoriesRelevant: 0,
|
|
848
|
+
threshold: this.config.memoryRelevanceThreshold,
|
|
849
|
+
duration: Date.now() - startTime,
|
|
850
|
+
error: error instanceof Error ? error.message : String(error),
|
|
851
|
+
timestamp: Date.now(),
|
|
852
|
+
});
|
|
853
|
+
console.warn('[AgentRuntime] Memory search failed:', error);
|
|
854
|
+
return '';
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Persist execution insights to DCYFRMemory
|
|
859
|
+
*/
|
|
860
|
+
async persistInsights(context, state, result) {
|
|
861
|
+
const summary = `Task: ${context.task}\nOutcome: ${result.outcome}\nIterations: ${state.iteration}\nTools used: ${state.observations.map((o) => o.tool).join(', ')}`;
|
|
862
|
+
// Store in user memory if userId is present
|
|
863
|
+
if (context.userId) {
|
|
864
|
+
await this.memory.addUserMemory(context.userId, summary, {
|
|
865
|
+
metadata: {
|
|
866
|
+
agentId: context.agentId || this.agentName,
|
|
867
|
+
sessionId: context.sessionId,
|
|
868
|
+
success: result.success,
|
|
869
|
+
toolsUsed: state.observations.map((o) => o.tool),
|
|
870
|
+
},
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
else {
|
|
874
|
+
// Store in agent memory
|
|
875
|
+
await this.memory.addAgentMemory(context.agentId || this.agentName, context.sessionId || `runtime-${Date.now()}`, {
|
|
876
|
+
task: context.task,
|
|
877
|
+
outcome: result.outcome,
|
|
878
|
+
iterations: state.iteration,
|
|
879
|
+
success: result.success,
|
|
880
|
+
toolsUsed: state.observations.map((o) => o.tool),
|
|
881
|
+
summary,
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Summarize message history to prevent prompt bloat
|
|
887
|
+
*/
|
|
888
|
+
async summarizeMessages(state, context) {
|
|
889
|
+
// TODO: Implement summarization via LLM
|
|
890
|
+
// Placeholder: truncate to last 2 iterations
|
|
891
|
+
const keepCount = 4; // system + user + last 2 iterations
|
|
892
|
+
if (state.messages.length > keepCount) {
|
|
893
|
+
state.messages = [
|
|
894
|
+
state.messages[0], // system
|
|
895
|
+
state.messages[1], // user
|
|
896
|
+
...state.messages.slice(-2), // last 2
|
|
897
|
+
];
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Create queryMemory helper for tools
|
|
902
|
+
*/
|
|
903
|
+
createQueryMemoryHelper(context) {
|
|
904
|
+
return async (params) => {
|
|
905
|
+
try {
|
|
906
|
+
let memories = [];
|
|
907
|
+
if (params.scope === 'user' && (params.userId || context.userId)) {
|
|
908
|
+
memories = await Promise.race([
|
|
909
|
+
this.memory.searchUserMemories(params.userId || context.userId, params.query, 5),
|
|
910
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Memory query timeout')), this.config.memoryTimeout)),
|
|
911
|
+
]);
|
|
912
|
+
}
|
|
913
|
+
else {
|
|
914
|
+
// Agent or session scope
|
|
915
|
+
memories = await Promise.race([
|
|
916
|
+
this.memory.searchAgentMemories(params.agentId || context.agentId || this.agentName, params.query, 5),
|
|
917
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('Memory query timeout')), this.config.memoryTimeout)),
|
|
918
|
+
]);
|
|
919
|
+
}
|
|
920
|
+
return memories
|
|
921
|
+
.filter((m) => m.relevance > this.config.memoryRelevanceThreshold)
|
|
922
|
+
.map((m) => ({
|
|
923
|
+
content: m.content,
|
|
924
|
+
score: m.relevance,
|
|
925
|
+
}));
|
|
926
|
+
}
|
|
927
|
+
catch (error) {
|
|
928
|
+
console.warn('[AgentRuntime] Tool memory query failed:', error);
|
|
929
|
+
return [];
|
|
930
|
+
}
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Calculate execution cost from token usage
|
|
935
|
+
*/
|
|
936
|
+
calculateCost(state) {
|
|
937
|
+
const tokens = state.workingMemory.get('tokens');
|
|
938
|
+
const provider = state.workingMemory.get('provider');
|
|
939
|
+
if (!tokens) {
|
|
940
|
+
return 0;
|
|
941
|
+
}
|
|
942
|
+
const totalTokens = (tokens.input || 0) + (tokens.output || 0);
|
|
943
|
+
// Provider-specific pricing (per million tokens)
|
|
944
|
+
const pricing = {
|
|
945
|
+
claude: 15.0, // $15 per 1M tokens
|
|
946
|
+
anthropic: 15.0, // Same as claude
|
|
947
|
+
openai: 10.0, // Approximate for GPT-4
|
|
948
|
+
copilot: 0, // Using GitHub's models
|
|
949
|
+
groq: 0, // Free tier
|
|
950
|
+
ollama: 0, // Local model
|
|
951
|
+
};
|
|
952
|
+
const pricePerMillion = pricing[provider] || 0;
|
|
953
|
+
// Calculate cost: (tokens / 1,000,000) * price per million
|
|
954
|
+
return (totalTokens / 1_000_000) * pricePerMillion;
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Event listeners for runtime events
|
|
958
|
+
*/
|
|
959
|
+
eventListeners = [];
|
|
960
|
+
/**
|
|
961
|
+
* Subscribe to runtime events
|
|
962
|
+
*/
|
|
963
|
+
on(listener) {
|
|
964
|
+
this.eventListeners.push(listener);
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Unsubscribe from runtime events
|
|
968
|
+
*/
|
|
969
|
+
off(listener) {
|
|
970
|
+
const index = this.eventListeners.indexOf(listener);
|
|
971
|
+
if (index !== -1) {
|
|
972
|
+
this.eventListeners.splice(index, 1);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
/**
|
|
976
|
+
* Emit lifecycle events to all listeners
|
|
977
|
+
*/
|
|
978
|
+
emitEvent(event) {
|
|
979
|
+
// Emit to registered listeners
|
|
980
|
+
for (const listener of this.eventListeners) {
|
|
981
|
+
try {
|
|
982
|
+
listener(event);
|
|
983
|
+
}
|
|
984
|
+
catch (error) {
|
|
985
|
+
console.error('[AgentRuntime] Event listener error:', error);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
// Also log for debugging (can be disabled in production)
|
|
989
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
990
|
+
console.log('[AgentRuntime Event]', event);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Get default system prompt for agent
|
|
995
|
+
*/
|
|
996
|
+
getDefaultSystemPrompt() {
|
|
997
|
+
return `You are ${this.agentName}, an AI agent that helps users complete tasks.
|
|
998
|
+
|
|
999
|
+
You have access to tools that you can use to accomplish your goals.
|
|
1000
|
+
|
|
1001
|
+
For each step:
|
|
1002
|
+
1. Think about what you need to do next
|
|
1003
|
+
2. Decide which tool to use (if any)
|
|
1004
|
+
3. Provide your reasoning
|
|
1005
|
+
|
|
1006
|
+
When you are done with the task, respond without selecting a tool.`;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
//# sourceMappingURL=agent-runtime.js.map
|