@eloxiv/kernel 0.0.0-stage → 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 +21 -0
- package/README.md +6 -2
- package/dist/AccountMail.d.ts +40 -0
- package/dist/AccountMail.d.ts.map +1 -0
- package/dist/AccountMail.js +169 -0
- package/dist/AccountMail.js.map +1 -0
- package/dist/AppConfig.d.ts +72 -0
- package/dist/AppConfig.d.ts.map +1 -0
- package/dist/AppConfig.js +87 -0
- package/dist/AppConfig.js.map +1 -0
- package/dist/Approvals.d.ts +132 -0
- package/dist/Approvals.d.ts.map +1 -0
- package/dist/Approvals.js +342 -0
- package/dist/Approvals.js.map +1 -0
- package/dist/Audit.d.ts +93 -0
- package/dist/Audit.d.ts.map +1 -0
- package/dist/Audit.js +275 -0
- package/dist/Audit.js.map +1 -0
- package/dist/AuthSeam.d.ts +58 -0
- package/dist/AuthSeam.d.ts.map +1 -0
- package/dist/AuthSeam.js +101 -0
- package/dist/AuthSeam.js.map +1 -0
- package/dist/Authority.d.ts +160 -0
- package/dist/Authority.d.ts.map +1 -0
- package/dist/Authority.js +325 -0
- package/dist/Authority.js.map +1 -0
- package/dist/Avatars.d.ts +26 -0
- package/dist/Avatars.d.ts.map +1 -0
- package/dist/Avatars.js +140 -0
- package/dist/Avatars.js.map +1 -0
- package/dist/Base64url.d.ts +9 -0
- package/dist/Base64url.d.ts.map +1 -0
- package/dist/Base64url.js +26 -0
- package/dist/Base64url.js.map +1 -0
- package/dist/BasePath.d.ts +39 -0
- package/dist/BasePath.d.ts.map +1 -0
- package/dist/BasePath.js +70 -0
- package/dist/BasePath.js.map +1 -0
- package/dist/CallActed.d.ts +10 -0
- package/dist/CallActed.d.ts.map +1 -0
- package/dist/CallActed.js +10 -0
- package/dist/CallActed.js.map +1 -0
- package/dist/Config.d.ts +459 -0
- package/dist/Config.d.ts.map +1 -0
- package/dist/Config.js +415 -0
- package/dist/Config.js.map +1 -0
- package/dist/DeliveryPolicy.d.ts +20 -0
- package/dist/DeliveryPolicy.d.ts.map +1 -0
- package/dist/DeliveryPolicy.js +35 -0
- package/dist/DeliveryPolicy.js.map +1 -0
- package/dist/DesktopSignIn.d.ts +24 -0
- package/dist/DesktopSignIn.d.ts.map +1 -0
- package/dist/DesktopSignIn.js +148 -0
- package/dist/DesktopSignIn.js.map +1 -0
- package/dist/Directory.d.ts +179 -0
- package/dist/Directory.d.ts.map +1 -0
- package/dist/Directory.js +1184 -0
- package/dist/Directory.js.map +1 -0
- package/dist/Flags.d.ts +59 -0
- package/dist/Flags.d.ts.map +1 -0
- package/dist/Flags.js +195 -0
- package/dist/Flags.js.map +1 -0
- package/dist/Gate.d.ts +42 -0
- package/dist/Gate.d.ts.map +1 -0
- package/dist/Gate.js +132 -0
- package/dist/Gate.js.map +1 -0
- package/dist/Hash.d.ts +4 -0
- package/dist/Hash.d.ts.map +1 -0
- package/dist/Hash.js +16 -0
- package/dist/Hash.js.map +1 -0
- package/dist/Identity.d.ts +327 -0
- package/dist/Identity.d.ts.map +1 -0
- package/dist/Identity.js +1232 -0
- package/dist/Identity.js.map +1 -0
- package/dist/IntervalJob.d.ts +40 -0
- package/dist/IntervalJob.d.ts.map +1 -0
- package/dist/IntervalJob.js +76 -0
- package/dist/IntervalJob.js.map +1 -0
- package/dist/Invocation.d.ts +210 -0
- package/dist/Invocation.d.ts.map +1 -0
- package/dist/Invocation.js +1680 -0
- package/dist/Invocation.js.map +1 -0
- package/dist/KernelHandlers.d.ts +19 -0
- package/dist/KernelHandlers.d.ts.map +1 -0
- package/dist/KernelHandlers.js +15 -0
- package/dist/KernelHandlers.js.map +1 -0
- package/dist/KernelModule.d.ts +65 -0
- package/dist/KernelModule.d.ts.map +1 -0
- package/dist/KernelModule.js +116 -0
- package/dist/KernelModule.js.map +1 -0
- package/dist/MemberRoutes.d.ts +6 -0
- package/dist/MemberRoutes.d.ts.map +1 -0
- package/dist/MemberRoutes.js +107 -0
- package/dist/MemberRoutes.js.map +1 -0
- package/dist/Module.d.ts +479 -0
- package/dist/Module.d.ts.map +1 -0
- package/dist/Module.js +30 -0
- package/dist/Module.js.map +1 -0
- package/dist/ModuleIdentity.d.ts +17 -0
- package/dist/ModuleIdentity.d.ts.map +1 -0
- package/dist/ModuleIdentity.js +106 -0
- package/dist/ModuleIdentity.js.map +1 -0
- package/dist/Notifications.d.ts +107 -0
- package/dist/Notifications.d.ts.map +1 -0
- package/dist/Notifications.js +475 -0
- package/dist/Notifications.js.map +1 -0
- package/dist/Outbox.d.ts +146 -0
- package/dist/Outbox.d.ts.map +1 -0
- package/dist/Outbox.js +518 -0
- package/dist/Outbox.js.map +1 -0
- package/dist/Privacy.d.ts +50 -0
- package/dist/Privacy.d.ts.map +1 -0
- package/dist/Privacy.js +167 -0
- package/dist/Privacy.js.map +1 -0
- package/dist/Progress.d.ts +42 -0
- package/dist/Progress.d.ts.map +1 -0
- package/dist/Progress.js +215 -0
- package/dist/Progress.js.map +1 -0
- package/dist/QuerySurface.d.ts +73 -0
- package/dist/QuerySurface.d.ts.map +1 -0
- package/dist/QuerySurface.js +440 -0
- package/dist/QuerySurface.js.map +1 -0
- package/dist/QueryViews.d.ts +70 -0
- package/dist/QueryViews.d.ts.map +1 -0
- package/dist/QueryViews.js +94 -0
- package/dist/QueryViews.js.map +1 -0
- package/dist/Readiness.d.ts +40 -0
- package/dist/Readiness.d.ts.map +1 -0
- package/dist/Readiness.js +203 -0
- package/dist/Readiness.js.map +1 -0
- package/dist/Redact.d.ts +11 -0
- package/dist/Redact.d.ts.map +1 -0
- package/dist/Redact.js +21 -0
- package/dist/Redact.js.map +1 -0
- package/dist/Registry.d.ts +117 -0
- package/dist/Registry.d.ts.map +1 -0
- package/dist/Registry.js +297 -0
- package/dist/Registry.js.map +1 -0
- package/dist/Release.d.ts +205 -0
- package/dist/Release.d.ts.map +1 -0
- package/dist/Release.js +880 -0
- package/dist/Release.js.map +1 -0
- package/dist/Retention.d.ts +43 -0
- package/dist/Retention.d.ts.map +1 -0
- package/dist/Retention.js +124 -0
- package/dist/Retention.js.map +1 -0
- package/dist/Scheduler.d.ts +56 -0
- package/dist/Scheduler.d.ts.map +1 -0
- package/dist/Scheduler.js +470 -0
- package/dist/Scheduler.js.map +1 -0
- package/dist/Server.d.ts +341 -0
- package/dist/Server.d.ts.map +1 -0
- package/dist/Server.js +1106 -0
- package/dist/Server.js.map +1 -0
- package/dist/Sessions.d.ts +38 -0
- package/dist/Sessions.d.ts.map +1 -0
- package/dist/Sessions.js +45 -0
- package/dist/Sessions.js.map +1 -0
- package/dist/Settings.d.ts +63 -0
- package/dist/Settings.d.ts.map +1 -0
- package/dist/Settings.js +219 -0
- package/dist/Settings.js.map +1 -0
- package/dist/Sharing.d.ts +99 -0
- package/dist/Sharing.d.ts.map +1 -0
- package/dist/Sharing.js +315 -0
- package/dist/Sharing.js.map +1 -0
- package/dist/Sync.d.ts +188 -0
- package/dist/Sync.d.ts.map +1 -0
- package/dist/Sync.js +1100 -0
- package/dist/Sync.js.map +1 -0
- package/dist/Telemetry.d.ts +154 -0
- package/dist/Telemetry.d.ts.map +1 -0
- package/dist/Telemetry.js +536 -0
- package/dist/Telemetry.js.map +1 -0
- package/dist/Versioning.d.ts +98 -0
- package/dist/Versioning.d.ts.map +1 -0
- package/dist/Versioning.js +387 -0
- package/dist/Versioning.js.map +1 -0
- package/dist/WorkItems.d.ts +67 -0
- package/dist/WorkItems.d.ts.map +1 -0
- package/dist/WorkItems.js +211 -0
- package/dist/WorkItems.js.map +1 -0
- package/dist/Workflows.d.ts +78 -0
- package/dist/Workflows.d.ts.map +1 -0
- package/dist/Workflows.js +478 -0
- package/dist/Workflows.js.map +1 -0
- package/dist/agent/Admission.d.ts +22 -0
- package/dist/agent/Admission.d.ts.map +1 -0
- package/dist/agent/Admission.js +34 -0
- package/dist/agent/Admission.js.map +1 -0
- package/dist/agent/Channels.d.ts +15 -0
- package/dist/agent/Channels.d.ts.map +1 -0
- package/dist/agent/Channels.js +50 -0
- package/dist/agent/Channels.js.map +1 -0
- package/dist/agent/Context.d.ts +73 -0
- package/dist/agent/Context.d.ts.map +1 -0
- package/dist/agent/Context.js +338 -0
- package/dist/agent/Context.js.map +1 -0
- package/dist/agent/Http.d.ts +18 -0
- package/dist/agent/Http.d.ts.map +1 -0
- package/dist/agent/Http.js +410 -0
- package/dist/agent/Http.js.map +1 -0
- package/dist/agent/Metering.d.ts +162 -0
- package/dist/agent/Metering.d.ts.map +1 -0
- package/dist/agent/Metering.js +315 -0
- package/dist/agent/Metering.js.map +1 -0
- package/dist/agent/ModelSetup.d.ts +10 -0
- package/dist/agent/ModelSetup.d.ts.map +1 -0
- package/dist/agent/ModelSetup.js +331 -0
- package/dist/agent/ModelSetup.js.map +1 -0
- package/dist/agent/Models.d.ts +197 -0
- package/dist/agent/Models.d.ts.map +1 -0
- package/dist/agent/Models.js +489 -0
- package/dist/agent/Models.js.map +1 -0
- package/dist/agent/Processors.d.ts +102 -0
- package/dist/agent/Processors.d.ts.map +1 -0
- package/dist/agent/Processors.js +80 -0
- package/dist/agent/Processors.js.map +1 -0
- package/dist/agent/Queue.d.ts +21 -0
- package/dist/agent/Queue.d.ts.map +1 -0
- package/dist/agent/Queue.js +64 -0
- package/dist/agent/Queue.js.map +1 -0
- package/dist/agent/Receipts.d.ts +41 -0
- package/dist/agent/Receipts.d.ts.map +1 -0
- package/dist/agent/Receipts.js +142 -0
- package/dist/agent/Receipts.js.map +1 -0
- package/dist/agent/Resources.d.ts +68 -0
- package/dist/agent/Resources.d.ts.map +1 -0
- package/dist/agent/Resources.js +207 -0
- package/dist/agent/Resources.js.map +1 -0
- package/dist/agent/Run.d.ts +178 -0
- package/dist/agent/Run.d.ts.map +1 -0
- package/dist/agent/Run.js +2896 -0
- package/dist/agent/Run.js.map +1 -0
- package/dist/agent/Runtime.d.ts +79 -0
- package/dist/agent/Runtime.d.ts.map +1 -0
- package/dist/agent/Runtime.js +366 -0
- package/dist/agent/Runtime.js.map +1 -0
- package/dist/agent/Settings.d.ts +126 -0
- package/dist/agent/Settings.d.ts.map +1 -0
- package/dist/agent/Settings.js +44 -0
- package/dist/agent/Settings.js.map +1 -0
- package/dist/agent/Skills.d.ts +73 -0
- package/dist/agent/Skills.d.ts.map +1 -0
- package/dist/agent/Skills.js +95 -0
- package/dist/agent/Skills.js.map +1 -0
- package/dist/agent/Store.d.ts +37 -0
- package/dist/agent/Store.d.ts.map +1 -0
- package/dist/agent/Store.js +50 -0
- package/dist/agent/Store.js.map +1 -0
- package/dist/agent/ToolSearch.d.ts +37 -0
- package/dist/agent/ToolSearch.d.ts.map +1 -0
- package/dist/agent/ToolSearch.js +119 -0
- package/dist/agent/ToolSearch.js.map +1 -0
- package/dist/agent/index.d.ts +37 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +44 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/module.d.ts +12889 -0
- package/dist/agent/module.d.ts.map +1 -0
- package/dist/agent/module.js +1550 -0
- package/dist/agent/module.js.map +1 -0
- package/dist/appState/Sweep.d.ts +21 -0
- package/dist/appState/Sweep.d.ts.map +1 -0
- package/dist/appState/Sweep.js +46 -0
- package/dist/appState/Sweep.js.map +1 -0
- package/dist/appState/module.d.ts +1710 -0
- package/dist/appState/module.d.ts.map +1 -0
- package/dist/appState/module.js +344 -0
- package/dist/appState/module.js.map +1 -0
- package/dist/audit/module.d.ts +158 -0
- package/dist/audit/module.d.ts.map +1 -0
- package/dist/audit/module.js +72 -0
- package/dist/audit/module.js.map +1 -0
- package/dist/auth/AuthProvider.d.ts +224 -0
- package/dist/auth/AuthProvider.d.ts.map +1 -0
- package/dist/auth/AuthProvider.js +104 -0
- package/dist/auth/AuthProvider.js.map +1 -0
- package/dist/auth/BetterAuthProvider.d.ts +40 -0
- package/dist/auth/BetterAuthProvider.d.ts.map +1 -0
- package/dist/auth/BetterAuthProvider.js +458 -0
- package/dist/auth/BetterAuthProvider.js.map +1 -0
- package/dist/auth/Methods.d.ts +7 -0
- package/dist/auth/Methods.d.ts.map +1 -0
- package/dist/auth/Methods.js +7 -0
- package/dist/auth/Methods.js.map +1 -0
- package/dist/auth/SessionTokens.d.ts +23 -0
- package/dist/auth/SessionTokens.d.ts.map +1 -0
- package/dist/auth/SessionTokens.js +150 -0
- package/dist/auth/SessionTokens.js.map +1 -0
- package/dist/collab/Collab.d.ts +105 -0
- package/dist/collab/Collab.d.ts.map +1 -0
- package/dist/collab/Collab.js +475 -0
- package/dist/collab/Collab.js.map +1 -0
- package/dist/collab/Housekeeping.d.ts +38 -0
- package/dist/collab/Housekeeping.d.ts.map +1 -0
- package/dist/collab/Housekeeping.js +146 -0
- package/dist/collab/Housekeeping.js.map +1 -0
- package/dist/collab/LiveCopy.d.ts +7 -0
- package/dist/collab/LiveCopy.d.ts.map +1 -0
- package/dist/collab/LiveCopy.js +79 -0
- package/dist/collab/LiveCopy.js.map +1 -0
- package/dist/collab/Socket.d.ts +19 -0
- package/dist/collab/Socket.d.ts.map +1 -0
- package/dist/collab/Socket.js +323 -0
- package/dist/collab/Socket.js.map +1 -0
- package/dist/collab/Store.d.ts +42 -0
- package/dist/collab/Store.d.ts.map +1 -0
- package/dist/collab/Store.js +59 -0
- package/dist/collab/Store.js.map +1 -0
- package/dist/collab/Ydoc.d.ts +88 -0
- package/dist/collab/Ydoc.d.ts.map +1 -0
- package/dist/collab/Ydoc.js +314 -0
- package/dist/collab/Ydoc.js.map +1 -0
- package/dist/collab/derive/bundle.gen.d.ts +2 -0
- package/dist/collab/derive/bundle.gen.d.ts.map +1 -0
- package/dist/collab/derive/bundle.gen.js +3 -0
- package/dist/collab/derive/bundle.gen.js.map +1 -0
- package/dist/collab/derive/entry.d.ts +3 -0
- package/dist/collab/derive/entry.d.ts.map +1 -0
- package/dist/collab/derive/entry.js +35 -0
- package/dist/collab/derive/entry.js.map +1 -0
- package/dist/collab/derive/polyfill.d.ts +3 -0
- package/dist/collab/derive/polyfill.d.ts.map +1 -0
- package/dist/collab/derive/polyfill.js +17 -0
- package/dist/collab/derive/polyfill.js.map +1 -0
- package/dist/collab/module.d.ts +305 -0
- package/dist/collab/module.d.ts.map +1 -0
- package/dist/collab/module.js +161 -0
- package/dist/collab/module.js.map +1 -0
- package/dist/connections/Connections.d.ts +199 -0
- package/dist/connections/Connections.d.ts.map +1 -0
- package/dist/connections/Connections.js +1633 -0
- package/dist/connections/Connections.js.map +1 -0
- package/dist/connections/Connector.d.ts +213 -0
- package/dist/connections/Connector.d.ts.map +1 -0
- package/dist/connections/Connector.js +55 -0
- package/dist/connections/Connector.js.map +1 -0
- package/dist/connections/Crypto.d.ts +55 -0
- package/dist/connections/Crypto.d.ts.map +1 -0
- package/dist/connections/Crypto.js +100 -0
- package/dist/connections/Crypto.js.map +1 -0
- package/dist/connections/Destinations.d.ts +63 -0
- package/dist/connections/Destinations.d.ts.map +1 -0
- package/dist/connections/Destinations.js +338 -0
- package/dist/connections/Destinations.js.map +1 -0
- package/dist/connections/Discovery.d.ts +53 -0
- package/dist/connections/Discovery.d.ts.map +1 -0
- package/dist/connections/Discovery.js +209 -0
- package/dist/connections/Discovery.js.map +1 -0
- package/dist/connections/EffectKinds.d.ts +17 -0
- package/dist/connections/EffectKinds.d.ts.map +1 -0
- package/dist/connections/EffectKinds.js +26 -0
- package/dist/connections/EffectKinds.js.map +1 -0
- package/dist/connections/Effects.d.ts +49 -0
- package/dist/connections/Effects.d.ts.map +1 -0
- package/dist/connections/Effects.js +347 -0
- package/dist/connections/Effects.js.map +1 -0
- package/dist/connections/Metering.d.ts +40 -0
- package/dist/connections/Metering.d.ts.map +1 -0
- package/dist/connections/Metering.js +142 -0
- package/dist/connections/Metering.js.map +1 -0
- package/dist/connections/ProviderApi.d.ts +47 -0
- package/dist/connections/ProviderApi.d.ts.map +1 -0
- package/dist/connections/ProviderApi.js +103 -0
- package/dist/connections/ProviderApi.js.map +1 -0
- package/dist/connections/Secrets.d.ts +78 -0
- package/dist/connections/Secrets.d.ts.map +1 -0
- package/dist/connections/Secrets.js +342 -0
- package/dist/connections/Secrets.js.map +1 -0
- package/dist/connections/Sync.d.ts +85 -0
- package/dist/connections/Sync.d.ts.map +1 -0
- package/dist/connections/Sync.js +201 -0
- package/dist/connections/Sync.js.map +1 -0
- package/dist/connections/module.d.ts +1061 -0
- package/dist/connections/module.d.ts.map +1 -0
- package/dist/connections/module.js +485 -0
- package/dist/connections/module.js.map +1 -0
- package/dist/data/Corpus.d.ts +79 -0
- package/dist/data/Corpus.d.ts.map +1 -0
- package/dist/data/Corpus.js +343 -0
- package/dist/data/Corpus.js.map +1 -0
- package/dist/data/Datasets.d.ts +88 -0
- package/dist/data/Datasets.d.ts.map +1 -0
- package/dist/data/Datasets.js +375 -0
- package/dist/data/Datasets.js.map +1 -0
- package/dist/data/Programs.d.ts +58 -0
- package/dist/data/Programs.d.ts.map +1 -0
- package/dist/data/Programs.js +197 -0
- package/dist/data/Programs.js.map +1 -0
- package/dist/data/module.d.ts +210 -0
- package/dist/data/module.d.ts.map +1 -0
- package/dist/data/module.js +140 -0
- package/dist/data/module.js.map +1 -0
- package/dist/db/Bootstrap.d.ts +508 -0
- package/dist/db/Bootstrap.d.ts.map +1 -0
- package/dist/db/Bootstrap.js +2368 -0
- package/dist/db/Bootstrap.js.map +1 -0
- package/dist/db/Catalog.d.ts +10 -0
- package/dist/db/Catalog.d.ts.map +1 -0
- package/dist/db/Catalog.js +9 -0
- package/dist/db/Catalog.js.map +1 -0
- package/dist/db/Conflicts.d.ts +18 -0
- package/dist/db/Conflicts.d.ts.map +1 -0
- package/dist/db/Conflicts.js +29 -0
- package/dist/db/Conflicts.js.map +1 -0
- package/dist/db/DirectoryLock.d.ts +16 -0
- package/dist/db/DirectoryLock.d.ts.map +1 -0
- package/dist/db/DirectoryLock.js +15 -0
- package/dist/db/DirectoryLock.js.map +1 -0
- package/dist/db/HandlerGate.d.ts +28 -0
- package/dist/db/HandlerGate.d.ts.map +1 -0
- package/dist/db/HandlerGate.js +76 -0
- package/dist/db/HandlerGate.js.map +1 -0
- package/dist/db/Host.d.ts +94 -0
- package/dist/db/Host.d.ts.map +1 -0
- package/dist/db/Host.js +189 -0
- package/dist/db/Host.js.map +1 -0
- package/dist/db/KernelSchema.d.ts +52 -0
- package/dist/db/KernelSchema.d.ts.map +1 -0
- package/dist/db/KernelSchema.js +4313 -0
- package/dist/db/KernelSchema.js.map +1 -0
- package/dist/db/MigrationCheck.d.ts +38 -0
- package/dist/db/MigrationCheck.d.ts.map +1 -0
- package/dist/db/MigrationCheck.js +180 -0
- package/dist/db/MigrationCheck.js.map +1 -0
- package/dist/db/QueryViewCheck.d.ts +172 -0
- package/dist/db/QueryViewCheck.d.ts.map +1 -0
- package/dist/db/QueryViewCheck.js +967 -0
- package/dist/db/QueryViewCheck.js.map +1 -0
- package/dist/db/ReadOnly.d.ts +13 -0
- package/dist/db/ReadOnly.d.ts.map +1 -0
- package/dist/db/ReadOnly.js +16 -0
- package/dist/db/ReadOnly.js.map +1 -0
- package/dist/db/Scram.d.ts +5 -0
- package/dist/db/Scram.d.ts.map +1 -0
- package/dist/db/Scram.js +17 -0
- package/dist/db/Scram.js.map +1 -0
- package/dist/db/SqlState.d.ts +36 -0
- package/dist/db/SqlState.d.ts.map +1 -0
- package/dist/db/SqlState.js +64 -0
- package/dist/db/SqlState.js.map +1 -0
- package/dist/db/Startup.d.ts +18 -0
- package/dist/db/Startup.d.ts.map +1 -0
- package/dist/db/Startup.js +22 -0
- package/dist/db/Startup.js.map +1 -0
- package/dist/db/ZeroDdl.d.ts +85 -0
- package/dist/db/ZeroDdl.d.ts.map +1 -0
- package/dist/db/ZeroDdl.js +240 -0
- package/dist/db/ZeroDdl.js.map +1 -0
- package/dist/db/ZeroPush.d.ts +7 -0
- package/dist/db/ZeroPush.d.ts.map +1 -0
- package/dist/db/ZeroPush.js +126 -0
- package/dist/db/ZeroPush.js.map +1 -0
- package/dist/devices/Devices.d.ts +130 -0
- package/dist/devices/Devices.d.ts.map +1 -0
- package/dist/devices/Devices.js +769 -0
- package/dist/devices/Devices.js.map +1 -0
- package/dist/devices/Flow.d.ts +47 -0
- package/dist/devices/Flow.d.ts.map +1 -0
- package/dist/devices/Flow.js +131 -0
- package/dist/devices/Flow.js.map +1 -0
- package/dist/devices/Http.d.ts +6 -0
- package/dist/devices/Http.d.ts.map +1 -0
- package/dist/devices/Http.js +103 -0
- package/dist/devices/Http.js.map +1 -0
- package/dist/devices/module.d.ts +1313 -0
- package/dist/devices/module.d.ts.map +1 -0
- package/dist/devices/module.js +266 -0
- package/dist/devices/module.js.map +1 -0
- package/dist/durable/Cluster.d.ts +13 -0
- package/dist/durable/Cluster.d.ts.map +1 -0
- package/dist/durable/Cluster.js +57 -0
- package/dist/durable/Cluster.js.map +1 -0
- package/dist/durable/Definition.d.ts +215 -0
- package/dist/durable/Definition.d.ts.map +1 -0
- package/dist/durable/Definition.js +18 -0
- package/dist/durable/Definition.js.map +1 -0
- package/dist/durable/Schedule.d.ts +46 -0
- package/dist/durable/Schedule.d.ts.map +1 -0
- package/dist/durable/Schedule.js +120 -0
- package/dist/durable/Schedule.js.map +1 -0
- package/dist/durable/Trust.d.ts +90 -0
- package/dist/durable/Trust.d.ts.map +1 -0
- package/dist/durable/Trust.js +61 -0
- package/dist/durable/Trust.js.map +1 -0
- package/dist/enterprise/Routes.d.ts +32 -0
- package/dist/enterprise/Routes.d.ts.map +1 -0
- package/dist/enterprise/Routes.js +448 -0
- package/dist/enterprise/Routes.js.map +1 -0
- package/dist/enterprise/WorkOs.d.ts +42 -0
- package/dist/enterprise/WorkOs.d.ts.map +1 -0
- package/dist/enterprise/WorkOs.js +109 -0
- package/dist/enterprise/WorkOs.js.map +1 -0
- package/dist/files/FileTable.d.ts +937 -0
- package/dist/files/FileTable.d.ts.map +1 -0
- package/dist/files/FileTable.js +79 -0
- package/dist/files/FileTable.js.map +1 -0
- package/dist/files/Files.d.ts +169 -0
- package/dist/files/Files.d.ts.map +1 -0
- package/dist/files/Files.js +1232 -0
- package/dist/files/Files.js.map +1 -0
- package/dist/files/Http.d.ts +13 -0
- package/dist/files/Http.d.ts.map +1 -0
- package/dist/files/Http.js +30 -0
- package/dist/files/Http.js.map +1 -0
- package/dist/files/LocalStorage.d.ts +7 -0
- package/dist/files/LocalStorage.d.ts.map +1 -0
- package/dist/files/LocalStorage.js +284 -0
- package/dist/files/LocalStorage.js.map +1 -0
- package/dist/files/Providers.d.ts +64 -0
- package/dist/files/Providers.d.ts.map +1 -0
- package/dist/files/Providers.js +245 -0
- package/dist/files/Providers.js.map +1 -0
- package/dist/files/S3Storage.d.ts +27 -0
- package/dist/files/S3Storage.d.ts.map +1 -0
- package/dist/files/S3Storage.js +301 -0
- package/dist/files/S3Storage.js.map +1 -0
- package/dist/files/SigV4.d.ts +65 -0
- package/dist/files/SigV4.d.ts.map +1 -0
- package/dist/files/SigV4.js +152 -0
- package/dist/files/SigV4.js.map +1 -0
- package/dist/files/Sniff.d.ts +50 -0
- package/dist/files/Sniff.d.ts.map +1 -0
- package/dist/files/Sniff.js +223 -0
- package/dist/files/Sniff.js.map +1 -0
- package/dist/files/Storage.d.ts +75 -0
- package/dist/files/Storage.d.ts.map +1 -0
- package/dist/files/Storage.js +70 -0
- package/dist/files/Storage.js.map +1 -0
- package/dist/files/module.d.ts +666 -0
- package/dist/files/module.d.ts.map +1 -0
- package/dist/files/module.js +217 -0
- package/dist/files/module.js.map +1 -0
- package/dist/flags/module.d.ts +966 -0
- package/dist/flags/module.d.ts.map +1 -0
- package/dist/flags/module.js +146 -0
- package/dist/flags/module.js.map +1 -0
- package/dist/inbox/Flow.d.ts +49 -0
- package/dist/inbox/Flow.d.ts.map +1 -0
- package/dist/inbox/Flow.js +425 -0
- package/dist/inbox/Flow.js.map +1 -0
- package/dist/inbox/System.d.ts +11 -0
- package/dist/inbox/System.d.ts.map +1 -0
- package/dist/inbox/System.js +26 -0
- package/dist/inbox/System.js.map +1 -0
- package/dist/inbox/approvals.d.ts +1548 -0
- package/dist/inbox/approvals.d.ts.map +1 -0
- package/dist/inbox/approvals.js +268 -0
- package/dist/inbox/approvals.js.map +1 -0
- package/dist/inbox/consent.d.ts +1213 -0
- package/dist/inbox/consent.d.ts.map +1 -0
- package/dist/inbox/consent.js +281 -0
- package/dist/inbox/consent.js.map +1 -0
- package/dist/inbox/index.d.ts +2231 -0
- package/dist/inbox/index.d.ts.map +1 -0
- package/dist/inbox/index.js +22 -0
- package/dist/inbox/index.js.map +1 -0
- package/dist/inbox/notifications.d.ts +2743 -0
- package/dist/inbox/notifications.d.ts.map +1 -0
- package/dist/inbox/notifications.js +362 -0
- package/dist/inbox/notifications.js.map +1 -0
- package/dist/inbox/tables.d.ts +1992 -0
- package/dist/inbox/tables.d.ts.map +1 -0
- package/dist/inbox/tables.js +149 -0
- package/dist/inbox/tables.js.map +1 -0
- package/dist/inbox/workItems.d.ts +1188 -0
- package/dist/inbox/workItems.d.ts.map +1 -0
- package/dist/inbox/workItems.js +158 -0
- package/dist/inbox/workItems.js.map +1 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +154 -0
- package/dist/index.js.map +1 -0
- package/dist/ingestion/Chunk.d.ts +15 -0
- package/dist/ingestion/Chunk.d.ts.map +1 -0
- package/dist/ingestion/Chunk.js +49 -0
- package/dist/ingestion/Chunk.js.map +1 -0
- package/dist/ingestion/Extract.d.ts +69 -0
- package/dist/ingestion/Extract.d.ts.map +1 -0
- package/dist/ingestion/Extract.js +376 -0
- package/dist/ingestion/Extract.js.map +1 -0
- package/dist/ingestion/ExtractChild.d.ts +2 -0
- package/dist/ingestion/ExtractChild.d.ts.map +1 -0
- package/dist/ingestion/ExtractChild.js +54 -0
- package/dist/ingestion/ExtractChild.js.map +1 -0
- package/dist/ingestion/ExtractPool.d.ts +38 -0
- package/dist/ingestion/ExtractPool.d.ts.map +1 -0
- package/dist/ingestion/ExtractPool.js +203 -0
- package/dist/ingestion/ExtractPool.js.map +1 -0
- package/dist/ingestion/Ingestion.d.ts +183 -0
- package/dist/ingestion/Ingestion.d.ts.map +1 -0
- package/dist/ingestion/Ingestion.js +650 -0
- package/dist/ingestion/Ingestion.js.map +1 -0
- package/dist/ingestion/Isolated.d.ts +18 -0
- package/dist/ingestion/Isolated.d.ts.map +1 -0
- package/dist/ingestion/Isolated.js +15 -0
- package/dist/ingestion/Isolated.js.map +1 -0
- package/dist/ingestion/Markup.d.ts +29 -0
- package/dist/ingestion/Markup.d.ts.map +1 -0
- package/dist/ingestion/Markup.js +111 -0
- package/dist/ingestion/Markup.js.map +1 -0
- package/dist/ingestion/Pdf.d.ts +6 -0
- package/dist/ingestion/Pdf.d.ts.map +1 -0
- package/dist/ingestion/Pdf.js +192 -0
- package/dist/ingestion/Pdf.js.map +1 -0
- package/dist/ingestion/Runs.d.ts +59 -0
- package/dist/ingestion/Runs.d.ts.map +1 -0
- package/dist/ingestion/Runs.js +128 -0
- package/dist/ingestion/Runs.js.map +1 -0
- package/dist/ingestion/Scrub.d.ts +16 -0
- package/dist/ingestion/Scrub.d.ts.map +1 -0
- package/dist/ingestion/Scrub.js +15 -0
- package/dist/ingestion/Scrub.js.map +1 -0
- package/dist/ingestion/Zip.d.ts +19 -0
- package/dist/ingestion/Zip.d.ts.map +1 -0
- package/dist/ingestion/Zip.js +85 -0
- package/dist/ingestion/Zip.js.map +1 -0
- package/dist/ingestion/module.d.ts +111 -0
- package/dist/ingestion/module.d.ts.map +1 -0
- package/dist/ingestion/module.js +51 -0
- package/dist/ingestion/module.js.map +1 -0
- package/dist/ingress/Definition.d.ts +146 -0
- package/dist/ingress/Definition.d.ts.map +1 -0
- package/dist/ingress/Definition.js +12 -0
- package/dist/ingress/Definition.js.map +1 -0
- package/dist/ingress/Ingress.d.ts +61 -0
- package/dist/ingress/Ingress.d.ts.map +1 -0
- package/dist/ingress/Ingress.js +929 -0
- package/dist/ingress/Ingress.js.map +1 -0
- package/dist/ingress/Verifiers.d.ts +43 -0
- package/dist/ingress/Verifiers.d.ts.map +1 -0
- package/dist/ingress/Verifiers.js +137 -0
- package/dist/ingress/Verifiers.js.map +1 -0
- package/dist/machine/MachineIdentity.d.ts +34 -0
- package/dist/machine/MachineIdentity.d.ts.map +1 -0
- package/dist/machine/MachineIdentity.js +200 -0
- package/dist/machine/MachineIdentity.js.map +1 -0
- package/dist/machine/Managed.d.ts +40 -0
- package/dist/machine/Managed.d.ts.map +1 -0
- package/dist/machine/Managed.js +163 -0
- package/dist/machine/Managed.js.map +1 -0
- package/dist/machine/OAuth.d.ts +11 -0
- package/dist/machine/OAuth.d.ts.map +1 -0
- package/dist/machine/OAuth.js +913 -0
- package/dist/machine/OAuth.js.map +1 -0
- package/dist/machine/Pages.d.ts +64 -0
- package/dist/machine/Pages.d.ts.map +1 -0
- package/dist/machine/Pages.js +54 -0
- package/dist/machine/Pages.js.map +1 -0
- package/dist/machine/Tokens.d.ts +25 -0
- package/dist/machine/Tokens.d.ts.map +1 -0
- package/dist/machine/Tokens.js +62 -0
- package/dist/machine/Tokens.js.map +1 -0
- package/dist/make/Credentials.d.ts +8 -0
- package/dist/make/Credentials.d.ts.map +1 -0
- package/dist/make/Credentials.js +29 -0
- package/dist/make/Credentials.js.map +1 -0
- package/dist/make/Example.d.ts +159 -0
- package/dist/make/Example.d.ts.map +1 -0
- package/dist/make/Example.js +94 -0
- package/dist/make/Example.js.map +1 -0
- package/dist/make/Execute.d.ts +151 -0
- package/dist/make/Execute.d.ts.map +1 -0
- package/dist/make/Execute.js +316 -0
- package/dist/make/Execute.js.map +1 -0
- package/dist/make/Http.d.ts +17 -0
- package/dist/make/Http.d.ts.map +1 -0
- package/dist/make/Http.js +63 -0
- package/dist/make/Http.js.map +1 -0
- package/dist/make/Lifecycle.d.ts +167 -0
- package/dist/make/Lifecycle.d.ts.map +1 -0
- package/dist/make/Lifecycle.js +580 -0
- package/dist/make/Lifecycle.js.map +1 -0
- package/dist/make/Manifest.d.ts +61 -0
- package/dist/make/Manifest.d.ts.map +1 -0
- package/dist/make/Manifest.js +792 -0
- package/dist/make/Manifest.js.map +1 -0
- package/dist/make/Repair.d.ts +111 -0
- package/dist/make/Repair.d.ts.map +1 -0
- package/dist/make/Repair.js +236 -0
- package/dist/make/Repair.js.map +1 -0
- package/dist/make/Runtime.d.ts +144 -0
- package/dist/make/Runtime.d.ts.map +1 -0
- package/dist/make/Runtime.js +309 -0
- package/dist/make/Runtime.js.map +1 -0
- package/dist/make/Session.d.ts +19 -0
- package/dist/make/Session.d.ts.map +1 -0
- package/dist/make/Session.js +27 -0
- package/dist/make/Session.js.map +1 -0
- package/dist/make/SqlGuard.d.ts +48 -0
- package/dist/make/SqlGuard.d.ts.map +1 -0
- package/dist/make/SqlGuard.js +333 -0
- package/dist/make/SqlGuard.js.map +1 -0
- package/dist/make/Subscribe.d.ts +18 -0
- package/dist/make/Subscribe.d.ts.map +1 -0
- package/dist/make/Subscribe.js +175 -0
- package/dist/make/Subscribe.js.map +1 -0
- package/dist/make/Validate.d.ts +47 -0
- package/dist/make/Validate.d.ts.map +1 -0
- package/dist/make/Validate.js +222 -0
- package/dist/make/Validate.js.map +1 -0
- package/dist/make/ViewStep.d.ts +27 -0
- package/dist/make/ViewStep.d.ts.map +1 -0
- package/dist/make/ViewStep.js +43 -0
- package/dist/make/ViewStep.js.map +1 -0
- package/dist/make/module.d.ts +808 -0
- package/dist/make/module.d.ts.map +1 -0
- package/dist/make/module.js +232 -0
- package/dist/make/module.js.map +1 -0
- package/dist/notifications/Decide.d.ts +29 -0
- package/dist/notifications/Decide.d.ts.map +1 -0
- package/dist/notifications/Decide.js +395 -0
- package/dist/notifications/Decide.js.map +1 -0
- package/dist/notifications/Providers.d.ts +110 -0
- package/dist/notifications/Providers.d.ts.map +1 -0
- package/dist/notifications/Providers.js +404 -0
- package/dist/notifications/Providers.js.map +1 -0
- package/dist/notifications/Push.d.ts +189 -0
- package/dist/notifications/Push.d.ts.map +1 -0
- package/dist/notifications/Push.js +457 -0
- package/dist/notifications/Push.js.map +1 -0
- package/dist/notifications/Smtp.d.ts +74 -0
- package/dist/notifications/Smtp.d.ts.map +1 -0
- package/dist/notifications/Smtp.js +344 -0
- package/dist/notifications/Smtp.js.map +1 -0
- package/dist/policy/CedarSchema.d.ts +47 -0
- package/dist/policy/CedarSchema.d.ts.map +1 -0
- package/dist/policy/CedarSchema.js +115 -0
- package/dist/policy/CedarSchema.js.map +1 -0
- package/dist/policy/Compiler.d.ts +364 -0
- package/dist/policy/Compiler.d.ts.map +1 -0
- package/dist/policy/Compiler.js +1311 -0
- package/dist/policy/Compiler.js.map +1 -0
- package/dist/policy/Policy.d.ts +70 -0
- package/dist/policy/Policy.d.ts.map +1 -0
- package/dist/policy/Policy.js +114 -0
- package/dist/policy/Policy.js.map +1 -0
- package/dist/policy/Rls.d.ts +110 -0
- package/dist/policy/Rls.d.ts.map +1 -0
- package/dist/policy/Rls.js +314 -0
- package/dist/policy/Rls.js.map +1 -0
- package/dist/policy/Row.d.ts +17 -0
- package/dist/policy/Row.d.ts.map +1 -0
- package/dist/policy/Row.js +3 -0
- package/dist/policy/Row.js.map +1 -0
- package/dist/privacy/Flow.d.ts +20 -0
- package/dist/privacy/Flow.d.ts.map +1 -0
- package/dist/privacy/Flow.js +193 -0
- package/dist/privacy/Flow.js.map +1 -0
- package/dist/privacy/Inventory.d.ts +110 -0
- package/dist/privacy/Inventory.d.ts.map +1 -0
- package/dist/privacy/Inventory.js +1704 -0
- package/dist/privacy/Inventory.js.map +1 -0
- package/dist/privacy/Sources.d.ts +86 -0
- package/dist/privacy/Sources.d.ts.map +1 -0
- package/dist/privacy/Sources.js +598 -0
- package/dist/privacy/Sources.js.map +1 -0
- package/dist/privacy/Visits.d.ts +21 -0
- package/dist/privacy/Visits.d.ts.map +1 -0
- package/dist/privacy/Visits.js +279 -0
- package/dist/privacy/Visits.js.map +1 -0
- package/dist/privacy/ZeroCvr.d.ts +15 -0
- package/dist/privacy/ZeroCvr.d.ts.map +1 -0
- package/dist/privacy/ZeroCvr.js +63 -0
- package/dist/privacy/ZeroCvr.js.map +1 -0
- package/dist/privacy/module.d.ts +2505 -0
- package/dist/privacy/module.d.ts.map +1 -0
- package/dist/privacy/module.js +228 -0
- package/dist/privacy/module.js.map +1 -0
- package/dist/progress/module.d.ts +1572 -0
- package/dist/progress/module.d.ts.map +1 -0
- package/dist/progress/module.js +139 -0
- package/dist/progress/module.js.map +1 -0
- package/dist/proposals/module.d.ts +275 -0
- package/dist/proposals/module.d.ts.map +1 -0
- package/dist/proposals/module.js +269 -0
- package/dist/proposals/module.js.map +1 -0
- package/dist/query/module.d.ts +91 -0
- package/dist/query/module.d.ts.map +1 -0
- package/dist/query/module.js +50 -0
- package/dist/query/module.js.map +1 -0
- package/dist/records/Access.d.ts +26 -0
- package/dist/records/Access.d.ts.map +1 -0
- package/dist/records/Access.js +43 -0
- package/dist/records/Access.js.map +1 -0
- package/dist/records/References.d.ts +18 -0
- package/dist/records/References.d.ts.map +1 -0
- package/dist/records/References.js +47 -0
- package/dist/records/References.js.map +1 -0
- package/dist/runtime/bun.d.ts +29 -0
- package/dist/runtime/bun.d.ts.map +1 -0
- package/dist/runtime/bun.js +71 -0
- package/dist/runtime/bun.js.map +1 -0
- package/dist/runtime/idle.d.ts +5 -0
- package/dist/runtime/idle.d.ts.map +1 -0
- package/dist/runtime/idle.js +61 -0
- package/dist/runtime/idle.js.map +1 -0
- package/dist/runtime/node.d.ts +36 -0
- package/dist/runtime/node.d.ts.map +1 -0
- package/dist/runtime/node.js +86 -0
- package/dist/runtime/node.js.map +1 -0
- package/dist/runtime/resolve.d.ts +8 -0
- package/dist/runtime/resolve.d.ts.map +1 -0
- package/dist/runtime/resolve.js +136 -0
- package/dist/runtime/resolve.js.map +1 -0
- package/dist/sandbox/Sandbox.d.ts +86 -0
- package/dist/sandbox/Sandbox.d.ts.map +1 -0
- package/dist/sandbox/Sandbox.js +246 -0
- package/dist/sandbox/Sandbox.js.map +1 -0
- package/dist/sandbox/worker.d.ts +93 -0
- package/dist/sandbox/worker.d.ts.map +1 -0
- package/dist/sandbox/worker.js +503 -0
- package/dist/sandbox/worker.js.map +1 -0
- package/dist/scheduler/Automations.d.ts +99 -0
- package/dist/scheduler/Automations.d.ts.map +1 -0
- package/dist/scheduler/Automations.js +247 -0
- package/dist/scheduler/Automations.js.map +1 -0
- package/dist/scheduler/History.d.ts +61 -0
- package/dist/scheduler/History.d.ts.map +1 -0
- package/dist/scheduler/History.js +154 -0
- package/dist/scheduler/History.js.map +1 -0
- package/dist/scheduler/module.d.ts +2365 -0
- package/dist/scheduler/module.d.ts.map +1 -0
- package/dist/scheduler/module.js +370 -0
- package/dist/scheduler/module.js.map +1 -0
- package/dist/search/RecordLock.d.ts +22 -0
- package/dist/search/RecordLock.d.ts.map +1 -0
- package/dist/search/RecordLock.js +21 -0
- package/dist/search/RecordLock.js.map +1 -0
- package/dist/search/Search.d.ts +63 -0
- package/dist/search/Search.d.ts.map +1 -0
- package/dist/search/Search.js +424 -0
- package/dist/search/Search.js.map +1 -0
- package/dist/search/Sources.d.ts +56 -0
- package/dist/search/Sources.d.ts.map +1 -0
- package/dist/search/Sources.js +121 -0
- package/dist/search/Sources.js.map +1 -0
- package/dist/search/module.d.ts +72 -0
- package/dist/search/module.d.ts.map +1 -0
- package/dist/search/module.js +44 -0
- package/dist/search/module.js.map +1 -0
- package/dist/settings/module.d.ts +677 -0
- package/dist/settings/module.d.ts.map +1 -0
- package/dist/settings/module.js +103 -0
- package/dist/settings/module.js.map +1 -0
- package/dist/sharing/module.d.ts +1105 -0
- package/dist/sharing/module.d.ts.map +1 -0
- package/dist/sharing/module.js +295 -0
- package/dist/sharing/module.js.map +1 -0
- package/dist/spaces/module.d.ts +1787 -0
- package/dist/spaces/module.d.ts.map +1 -0
- package/dist/spaces/module.js +248 -0
- package/dist/spaces/module.js.map +1 -0
- package/dist/surfaces/Agent.d.ts +89 -0
- package/dist/surfaces/Agent.d.ts.map +1 -0
- package/dist/surfaces/Agent.js +112 -0
- package/dist/surfaces/Agent.js.map +1 -0
- package/dist/surfaces/CookieGuard.d.ts +77 -0
- package/dist/surfaces/CookieGuard.d.ts.map +1 -0
- package/dist/surfaces/CookieGuard.js +373 -0
- package/dist/surfaces/CookieGuard.js.map +1 -0
- package/dist/surfaces/Http.d.ts +15 -0
- package/dist/surfaces/Http.d.ts.map +1 -0
- package/dist/surfaces/Http.js +250 -0
- package/dist/surfaces/Http.js.map +1 -0
- package/dist/surfaces/Mcp.d.ts +90 -0
- package/dist/surfaces/Mcp.d.ts.map +1 -0
- package/dist/surfaces/Mcp.js +443 -0
- package/dist/surfaces/Mcp.js.map +1 -0
- package/dist/surfaces/Rpc.d.ts +15 -0
- package/dist/surfaces/Rpc.d.ts.map +1 -0
- package/dist/surfaces/Rpc.js +68 -0
- package/dist/surfaces/Rpc.js.map +1 -0
- package/dist/surfaces/headers.d.ts +9 -0
- package/dist/surfaces/headers.d.ts.map +1 -0
- package/dist/surfaces/headers.js +15 -0
- package/dist/surfaces/headers.js.map +1 -0
- package/dist/surfaces/request.d.ts +68 -0
- package/dist/surfaces/request.d.ts.map +1 -0
- package/dist/surfaces/request.js +130 -0
- package/dist/surfaces/request.js.map +1 -0
- package/dist/telemetry/module.d.ts +74 -0
- package/dist/telemetry/module.d.ts.map +1 -0
- package/dist/telemetry/module.js +77 -0
- package/dist/telemetry/module.js.map +1 -0
- package/dist/versioning/module.d.ts +231 -0
- package/dist/versioning/module.d.ts.map +1 -0
- package/dist/versioning/module.js +151 -0
- package/dist/versioning/module.js.map +1 -0
- package/package.json +71 -3
- package/src/AccountMail.ts +218 -0
- package/src/AppConfig.ts +148 -0
- package/src/Approvals.ts +555 -0
- package/src/Audit.ts +381 -0
- package/src/AuthSeam.ts +136 -0
- package/src/Authority.ts +577 -0
- package/src/Avatars.ts +172 -0
- package/src/Base64url.ts +23 -0
- package/src/BasePath.ts +80 -0
- package/src/CallActed.ts +10 -0
- package/src/Config.ts +857 -0
- package/src/DeliveryPolicy.ts +52 -0
- package/src/DesktopSignIn.ts +181 -0
- package/src/Directory.ts +1792 -0
- package/src/Flags.ts +281 -0
- package/src/Gate.ts +159 -0
- package/src/Hash.ts +14 -0
- package/src/Identity.ts +1811 -0
- package/src/IntervalJob.ts +96 -0
- package/src/Invocation.ts +2387 -0
- package/src/KernelHandlers.ts +29 -0
- package/src/KernelModule.ts +165 -0
- package/src/MemberRoutes.ts +146 -0
- package/src/Module.ts +573 -0
- package/src/ModuleIdentity.ts +134 -0
- package/src/Notifications.ts +665 -0
- package/src/Outbox.ts +761 -0
- package/src/Privacy.ts +265 -0
- package/src/Progress.ts +360 -0
- package/src/QuerySurface.ts +559 -0
- package/src/QueryViews.ts +165 -0
- package/src/Readiness.ts +284 -0
- package/src/Redact.ts +22 -0
- package/src/Registry.ts +399 -0
- package/src/Release.ts +1197 -0
- package/src/Retention.ts +167 -0
- package/src/Scheduler.ts +657 -0
- package/src/Server.ts +1838 -0
- package/src/Sessions.ts +56 -0
- package/src/Settings.ts +312 -0
- package/src/Sharing.ts +525 -0
- package/src/Sync.ts +1478 -0
- package/src/Telemetry.ts +754 -0
- package/src/Versioning.ts +588 -0
- package/src/WorkItems.ts +367 -0
- package/src/Workflows.ts +746 -0
- package/src/agent/Admission.ts +37 -0
- package/src/agent/Channels.ts +58 -0
- package/src/agent/Context.ts +430 -0
- package/src/agent/Http.ts +523 -0
- package/src/agent/Metering.ts +625 -0
- package/src/agent/ModelSetup.ts +414 -0
- package/src/agent/Models.ts +850 -0
- package/src/agent/Processors.ts +156 -0
- package/src/agent/Queue.ts +97 -0
- package/src/agent/Receipts.ts +192 -0
- package/src/agent/Resources.ts +376 -0
- package/src/agent/Run.ts +3762 -0
- package/src/agent/Runtime.ts +635 -0
- package/src/agent/Settings.ts +171 -0
- package/src/agent/Skills.ts +118 -0
- package/src/agent/Store.ts +73 -0
- package/src/agent/ToolSearch.ts +152 -0
- package/src/agent/index.ts +68 -0
- package/src/agent/migrations/agent/0000_agent.sql +162 -0
- package/src/agent/migrations/agent/0001_model_call.sql +33 -0
- package/src/agent/migrations/agent/0002_device.sql +2 -0
- package/src/agent/migrations/agent/0003_authority.sql +1 -0
- package/src/agent/migrations/agent/0004_budget_alert.sql +2 -0
- package/src/agent/migrations/agent/0005_feedback.sql +13 -0
- package/src/agent/migrations/agent/0095_run_options.sql +3 -0
- package/src/agent/migrations/agent/0096_conversation_meta.sql +7 -0
- package/src/agent/migrations/agent/0097_submission.sql +26 -0
- package/src/agent/migrations/agent/0098_threads.sql +21 -0
- package/src/agent/migrations/agent/0099_submission_refused.sql +4 -0
- package/src/agent/migrations/agent/0142_teams.sql +19 -0
- package/src/agent/module.ts +1793 -0
- package/src/appState/Sweep.ts +66 -0
- package/src/appState/migrations/0000_app_state.sql +35 -0
- package/src/appState/module.ts +418 -0
- package/src/audit/migrations/README.md +1 -0
- package/src/audit/module.ts +95 -0
- package/src/auth/AuthProvider.ts +293 -0
- package/src/auth/BetterAuthProvider.ts +476 -0
- package/src/auth/Methods.ts +7 -0
- package/src/auth/SessionTokens.ts +156 -0
- package/src/collab/Collab.ts +708 -0
- package/src/collab/Housekeeping.ts +193 -0
- package/src/collab/LiveCopy.ts +98 -0
- package/src/collab/Socket.ts +380 -0
- package/src/collab/Store.ts +105 -0
- package/src/collab/Ydoc.ts +337 -0
- package/src/collab/derive/bundle.gen.ts +2 -0
- package/src/collab/derive/entry.ts +34 -0
- package/src/collab/derive/polyfill.ts +15 -0
- package/src/collab/migrations/.gitkeep +0 -0
- package/src/collab/module.ts +237 -0
- package/src/connections/Connections.ts +2315 -0
- package/src/connections/Connector.ts +304 -0
- package/src/connections/Crypto.ts +134 -0
- package/src/connections/Destinations.ts +351 -0
- package/src/connections/Discovery.ts +251 -0
- package/src/connections/EffectKinds.ts +30 -0
- package/src/connections/Effects.ts +541 -0
- package/src/connections/Metering.ts +205 -0
- package/src/connections/ProviderApi.ts +137 -0
- package/src/connections/Secrets.ts +581 -0
- package/src/connections/Sync.ts +318 -0
- package/src/connections/migrations/.gitkeep +0 -0
- package/src/connections/module.ts +584 -0
- package/src/data/Corpus.ts +434 -0
- package/src/data/Datasets.ts +479 -0
- package/src/data/Programs.ts +285 -0
- package/src/data/migrations/README.md +1 -0
- package/src/data/module.ts +177 -0
- package/src/db/Bootstrap.ts +2832 -0
- package/src/db/Catalog.ts +10 -0
- package/src/db/Conflicts.ts +42 -0
- package/src/db/DirectoryLock.ts +19 -0
- package/src/db/HandlerGate.ts +107 -0
- package/src/db/Host.ts +250 -0
- package/src/db/KernelSchema.ts +4422 -0
- package/src/db/MigrationCheck.ts +221 -0
- package/src/db/QueryViewCheck.ts +1035 -0
- package/src/db/ReadOnly.ts +23 -0
- package/src/db/Scram.ts +20 -0
- package/src/db/SqlState.ts +77 -0
- package/src/db/Startup.ts +25 -0
- package/src/db/ZeroDdl.ts +272 -0
- package/src/db/ZeroPush.ts +128 -0
- package/src/db/schema.snapshot.json +13831 -0
- package/src/devices/Devices.ts +1219 -0
- package/src/devices/Flow.ts +198 -0
- package/src/devices/Http.ts +212 -0
- package/src/devices/migrations/0000_devices.sql +53 -0
- package/src/devices/migrations/0001_parent_run.sql +2 -0
- package/src/devices/migrations/0002_authority.sql +1 -0
- package/src/devices/migrations/0003_follow_up.sql +4 -0
- package/src/devices/migrations/0004_commands.sql +30 -0
- package/src/devices/migrations/0005_command_cancel.sql +7 -0
- package/src/devices/module.ts +313 -0
- package/src/durable/Cluster.ts +90 -0
- package/src/durable/Definition.ts +244 -0
- package/src/durable/Schedule.ts +155 -0
- package/src/durable/Trust.ts +149 -0
- package/src/enterprise/Routes.ts +501 -0
- package/src/enterprise/WorkOs.ts +133 -0
- package/src/files/FileTable.ts +84 -0
- package/src/files/Files.ts +1652 -0
- package/src/files/Http.ts +46 -0
- package/src/files/LocalStorage.ts +348 -0
- package/src/files/Providers.ts +356 -0
- package/src/files/S3Storage.ts +403 -0
- package/src/files/SigV4.ts +222 -0
- package/src/files/Sniff.ts +218 -0
- package/src/files/Storage.ts +143 -0
- package/src/files/migrations/README.md +1 -0
- package/src/files/module.ts +282 -0
- package/src/flags/migrations/0000_flags.sql +20 -0
- package/src/flags/module.ts +178 -0
- package/src/inbox/Flow.ts +548 -0
- package/src/inbox/System.ts +33 -0
- package/src/inbox/approvals.ts +335 -0
- package/src/inbox/consent.ts +331 -0
- package/src/inbox/index.ts +24 -0
- package/src/inbox/migrations/approvals/0000_approvals.sql +36 -0
- package/src/inbox/migrations/approvals/0001_provenance.sql +1 -0
- package/src/inbox/migrations/approvals/0002_withdrawn.sql +3 -0
- package/src/inbox/migrations/approvals/0003_title.sql +11 -0
- package/src/inbox/migrations/consent/0000_consent.sql +31 -0
- package/src/inbox/migrations/consent/0001_consent_revoked.sql +3 -0
- package/src/inbox/migrations/consent/0002_permission_request.sql +1 -0
- package/src/inbox/migrations/consent/0003_title.sql +11 -0
- package/src/inbox/migrations/inbox/0000_work_items.sql +31 -0
- package/src/inbox/migrations/notifications/0000_notifications.sql +66 -0
- package/src/inbox/notifications.ts +471 -0
- package/src/inbox/tables.ts +163 -0
- package/src/inbox/workItems.ts +199 -0
- package/src/index.ts +229 -0
- package/src/ingestion/Chunk.ts +49 -0
- package/src/ingestion/Extract.ts +387 -0
- package/src/ingestion/ExtractChild.ts +67 -0
- package/src/ingestion/ExtractPool.ts +270 -0
- package/src/ingestion/Ingestion.ts +929 -0
- package/src/ingestion/Isolated.ts +26 -0
- package/src/ingestion/Markup.ts +117 -0
- package/src/ingestion/Pdf.ts +167 -0
- package/src/ingestion/Runs.ts +192 -0
- package/src/ingestion/Scrub.ts +22 -0
- package/src/ingestion/Zip.ts +87 -0
- package/src/ingestion/migrations/README.md +1 -0
- package/src/ingestion/module.ts +65 -0
- package/src/ingress/Definition.ts +158 -0
- package/src/ingress/Ingress.ts +1220 -0
- package/src/ingress/Verifiers.ts +166 -0
- package/src/machine/MachineIdentity.ts +310 -0
- package/src/machine/Managed.ts +228 -0
- package/src/machine/OAuth.ts +1140 -0
- package/src/machine/Pages.ts +139 -0
- package/src/machine/Tokens.ts +75 -0
- package/src/make/Credentials.ts +36 -0
- package/src/make/Example.ts +104 -0
- package/src/make/Execute.ts +534 -0
- package/src/make/Http.ts +71 -0
- package/src/make/Lifecycle.ts +911 -0
- package/src/make/Manifest.ts +884 -0
- package/src/make/Repair.ts +262 -0
- package/src/make/Runtime.ts +494 -0
- package/src/make/Session.ts +33 -0
- package/src/make/SqlGuard.ts +362 -0
- package/src/make/Subscribe.ts +282 -0
- package/src/make/Validate.ts +247 -0
- package/src/make/ViewStep.ts +64 -0
- package/src/make/migrations/README.md +1 -0
- package/src/make/module.ts +261 -0
- package/src/notifications/Decide.ts +483 -0
- package/src/notifications/Providers.ts +532 -0
- package/src/notifications/Push.ts +594 -0
- package/src/notifications/Smtp.ts +379 -0
- package/src/policy/CedarSchema.ts +156 -0
- package/src/policy/Compiler.ts +1627 -0
- package/src/policy/Policy.ts +178 -0
- package/src/policy/Rls.ts +460 -0
- package/src/policy/Row.ts +15 -0
- package/src/privacy/Flow.ts +283 -0
- package/src/privacy/Inventory.ts +2414 -0
- package/src/privacy/Sources.ts +831 -0
- package/src/privacy/Visits.ts +339 -0
- package/src/privacy/ZeroCvr.ts +66 -0
- package/src/privacy/migrations/0000_privacy.sql +48 -0
- package/src/privacy/module.ts +280 -0
- package/src/progress/migrations/0000_progress.sql +27 -0
- package/src/progress/migrations/0001_notify.sql +1 -0
- package/src/progress/module.ts +161 -0
- package/src/proposals/migrations/README.md +1 -0
- package/src/proposals/module.ts +338 -0
- package/src/query/migrations/README.md +1 -0
- package/src/query/module.ts +66 -0
- package/src/records/Access.ts +97 -0
- package/src/records/References.ts +65 -0
- package/src/runtime/bun.ts +131 -0
- package/src/runtime/idle.ts +88 -0
- package/src/runtime/node.ts +140 -0
- package/src/runtime/resolve.ts +141 -0
- package/src/sandbox/Sandbox.ts +330 -0
- package/src/sandbox/worker.ts +577 -0
- package/src/scheduler/Automations.ts +319 -0
- package/src/scheduler/History.ts +231 -0
- package/src/scheduler/migrations/0000_schedules.sql +11 -0
- package/src/scheduler/migrations/0001_resumed_at.sql +1 -0
- package/src/scheduler/migrations/0002_origin.sql +3 -0
- package/src/scheduler/migrations/0003_authority.sql +1 -0
- package/src/scheduler/migrations/0004_operate.sql +18 -0
- package/src/scheduler/module.ts +445 -0
- package/src/search/RecordLock.ts +25 -0
- package/src/search/Search.ts +563 -0
- package/src/search/Sources.ts +157 -0
- package/src/search/migrations/README.md +1 -0
- package/src/search/module.ts +49 -0
- package/src/settings/migrations/0000_settings.sql +15 -0
- package/src/settings/module.ts +126 -0
- package/src/sharing/migrations/0000_access_requests.sql +17 -0
- package/src/sharing/module.ts +351 -0
- package/src/spaces/migrations/0000_spaces.sql +35 -0
- package/src/spaces/module.ts +287 -0
- package/src/surfaces/Agent.ts +224 -0
- package/src/surfaces/CookieGuard.ts +433 -0
- package/src/surfaces/Http.ts +341 -0
- package/src/surfaces/Mcp.ts +585 -0
- package/src/surfaces/Rpc.ts +101 -0
- package/src/surfaces/headers.ts +16 -0
- package/src/surfaces/request.ts +173 -0
- package/src/telemetry/migrations/.gitkeep +0 -0
- package/src/telemetry/module.ts +94 -0
- package/src/versioning/migrations/.gitkeep +0 -0
- package/src/versioning/module.ts +194 -0
|
@@ -0,0 +1,2896 @@
|
|
|
1
|
+
import { decisionLabel, AgentToolPolicy, AuthorityChain, AuthorityRecord, Forbidden, ModelUsage, RunDevice, RunLimits as RunLimitsSchema, RunContinuation, RunMode, RunVerification as RunVerificationSchema, StopReason, TurnUsage, WorkflowFailed, WriteReceipt, } from "@eloxiv/contracts";
|
|
2
|
+
import { Cause, Context, Effect, Option, Schema } from "effect";
|
|
3
|
+
import { SqlClient } from "effect/sql";
|
|
4
|
+
import { Audit } from "../Audit.js";
|
|
5
|
+
import { Authority, extend } from "../Authority.js";
|
|
6
|
+
import { defineKernelWorkflow } from "../durable/Trust.js";
|
|
7
|
+
import { canonicalJson, sha256 } from "../Hash.js";
|
|
8
|
+
import { Identity, SYSTEM_ACTOR } from "../Identity.js";
|
|
9
|
+
import { Invocation } from "../Invocation.js";
|
|
10
|
+
import { asSystem } from "../inbox/System.js";
|
|
11
|
+
import { Outbox } from "../Outbox.js";
|
|
12
|
+
import { QueryViews } from "../QueryViews.js";
|
|
13
|
+
import { Registry } from "../Registry.js";
|
|
14
|
+
import { scopeAllows } from "../machine/Tokens.js";
|
|
15
|
+
import { AgentTools } from "../surfaces/Agent.js";
|
|
16
|
+
import { assemble, ATTACHMENT_LIMITS, countTokens } from "./Context.js";
|
|
17
|
+
import { abandonCalls, Metering, recordSubscriptionUsage, settleCall } from "./Metering.js";
|
|
18
|
+
import { ModelProviders } from "./Models.js";
|
|
19
|
+
import { PERSON_ONLY_ACTIONS } from "./module.js";
|
|
20
|
+
import { chunkGuard, finalGuard, toolGuard } from "./Processors.js";
|
|
21
|
+
import { annotation, checkMessage, flagged, needsChallenge, writeReceipt } from "./Receipts.js";
|
|
22
|
+
import { searchTools, toolIndex, TOOL_SEARCH, toolSearchDefinition } from "./ToolSearch.js";
|
|
23
|
+
import { AgentResources } from "./Resources.js";
|
|
24
|
+
import { AgentHub, AgentSettings } from "./Settings.js";
|
|
25
|
+
import { promoteQueued } from "./Queue.js";
|
|
26
|
+
import { AGENT_MODULE, appendEvent, asAgent, clockSeq, inAgent, inAgentFor, mayReply } from "./Store.js";
|
|
27
|
+
export const AGENT_RUN_WORKFLOW = "eloxiv.agent-run";
|
|
28
|
+
/** The action the query surface publishes (another part of the kernel); used when the app has it. */
|
|
29
|
+
export const QUERY_ACTION = "eloxiv.query";
|
|
30
|
+
/**
|
|
31
|
+
* How a run acts, recorded on it when it is queued (`run.options`): its mode, its tool policy (the organisation's
|
|
32
|
+
* `agent.tools`), its delegation depth (0 for a person's run) and, for a sub-agent, the profile it runs as.
|
|
33
|
+
*/
|
|
34
|
+
const RunOptions = Schema.Struct({
|
|
35
|
+
mode: RunMode,
|
|
36
|
+
tools: AgentToolPolicy,
|
|
37
|
+
depth: Schema.Number,
|
|
38
|
+
profile: Schema.optionalKey(Schema.String),
|
|
39
|
+
/** A seat of its parent's team (the `team` tool's `spawn`): its name. The run then has the team tool for messages. */
|
|
40
|
+
seat: Schema.optionalKey(Schema.String),
|
|
41
|
+
/** How many files the person attached to the message that started the run (their content is read at its start). */
|
|
42
|
+
attachments: Schema.optionalKey(Schema.Number),
|
|
43
|
+
/** The interrupted turn it continues (`agent.continue`, or an automatic continuation). */
|
|
44
|
+
continuation: Schema.optionalKey(RunContinuation),
|
|
45
|
+
/**
|
|
46
|
+
* The agent edit group its changes are kept with (the Versioning contract): the conversation and the person's
|
|
47
|
+
* message that started the run, or its parent's (a sub-agent's). Absent for a run queued before groups were kept.
|
|
48
|
+
*/
|
|
49
|
+
editGroup: Schema.optionalKey(Schema.Struct({ conversationId: Schema.String, messageId: Schema.NullOr(Schema.String) })),
|
|
50
|
+
});
|
|
51
|
+
const DEFAULT_OPTIONS = { mode: "act", tools: { discovery: "all" }, depth: 0 };
|
|
52
|
+
// (A sub-agent queued before options were recorded is at depth 1.)
|
|
53
|
+
const optionsOf = (spec) => spec.options ?? (spec.kind === "subagent" ? { ...DEFAULT_OPTIONS, depth: 1 } : DEFAULT_OPTIONS);
|
|
54
|
+
const Spec = Schema.Struct({
|
|
55
|
+
runId: Schema.String,
|
|
56
|
+
orgId: Schema.String,
|
|
57
|
+
userId: Schema.String,
|
|
58
|
+
conversationId: Schema.String,
|
|
59
|
+
parentRunId: Schema.NullOr(Schema.String),
|
|
60
|
+
kind: Schema.String,
|
|
61
|
+
limits: RunLimitsSchema,
|
|
62
|
+
tools: Schema.NullOr(Schema.Array(Schema.String)),
|
|
63
|
+
agentSessionId: Schema.NullOr(Schema.String),
|
|
64
|
+
startedAt: Schema.Number,
|
|
65
|
+
/** Where the run executes instead of the deployment's model: one of the person's paired devices. */
|
|
66
|
+
device: Schema.optionalKey(Schema.NullOr(RunDevice)),
|
|
67
|
+
/**
|
|
68
|
+
* The authority of the call that started the run (`agent.send`): its scope, which every tool call stays within
|
|
69
|
+
* (beside the run's own tool rules), and its chain, which every tool call and every read or write the run makes on
|
|
70
|
+
* the person's behalf asserts (Authority), with the conversation's agent session. A delegate inherits it.
|
|
71
|
+
* `unrecorded`: a run queued before authorities were recorded, which acts on nothing.
|
|
72
|
+
*/
|
|
73
|
+
authority: Schema.optionalKey(Schema.Union([AuthorityRecord, Schema.Literal("unrecorded")])),
|
|
74
|
+
/** How the run acts (recorded when it was queued; absent for a run queued before options were). */
|
|
75
|
+
options: Schema.optionalKey(RunOptions),
|
|
76
|
+
/** The conversation's owner, when it is not the run's person (a reply in a conversation shared with them). */
|
|
77
|
+
conversationOwner: Schema.optionalKey(Schema.String),
|
|
78
|
+
/**
|
|
79
|
+
* The run's agent edit group (the Versioning contract): the run, and the conversation and message that started its
|
|
80
|
+
* top-level run (a sub-agent's, its parent's). Every tool call carries it, so the changes it makes are kept with it.
|
|
81
|
+
*/
|
|
82
|
+
editGroup: Schema.optionalKey(Schema.Struct({ runId: Schema.String, conversationId: Schema.String, messageId: Schema.NullOr(Schema.String) })),
|
|
83
|
+
});
|
|
84
|
+
const ToolCallSchema = Schema.Struct({ toolCallId: Schema.String, toolName: Schema.String, input: Schema.Unknown });
|
|
85
|
+
const ModelOutcome = Schema.Union([
|
|
86
|
+
Schema.Struct({
|
|
87
|
+
kind: Schema.Literal("response"),
|
|
88
|
+
text: Schema.String,
|
|
89
|
+
toolCalls: Schema.Array(ToolCallSchema),
|
|
90
|
+
usage: ModelUsage,
|
|
91
|
+
/** Every model call the step made (lost attempts, compaction and this one) and their tokens: the run's limits count them. */
|
|
92
|
+
calls: Schema.optionalKey(Schema.Number),
|
|
93
|
+
tokens: Schema.optionalKey(Schema.Number),
|
|
94
|
+
}),
|
|
95
|
+
Schema.Struct({
|
|
96
|
+
kind: Schema.Literal("stop"),
|
|
97
|
+
reason: StopReason,
|
|
98
|
+
message: Schema.String,
|
|
99
|
+
/** A transient failure of the model call (the provider rate-limited or timed it out): the turn may continue. */
|
|
100
|
+
retryable: Schema.optionalKey(Schema.Boolean),
|
|
101
|
+
}),
|
|
102
|
+
]);
|
|
103
|
+
const Decision = Schema.Union([
|
|
104
|
+
Schema.Struct({ kind: Schema.Literal("consent"), status: Schema.Literals(["approved", "rejected"]) }),
|
|
105
|
+
Schema.Struct({ kind: Schema.Literal("cancel") }),
|
|
106
|
+
Schema.Struct({ kind: Schema.Literal("child"), status: Schema.String, result: Schema.NullOr(Schema.String) }),
|
|
107
|
+
/** A device turn the run waits for settled (`devices.turnSettled`). */
|
|
108
|
+
Schema.Struct({ kind: Schema.Literal("device"), status: Schema.String }),
|
|
109
|
+
/** A seat of the run's team finished, or a message arrived for it (`team` waits). */
|
|
110
|
+
Schema.Struct({ kind: Schema.Literal("team") }),
|
|
111
|
+
]);
|
|
112
|
+
/** What a run (or a sub-agent, for its parent) has spent of its limits: model calls and tokens. */
|
|
113
|
+
const Consumed = Schema.Struct({ calls: Schema.Number, tokens: Schema.Number });
|
|
114
|
+
const ToolOutcome = Schema.Union([
|
|
115
|
+
Schema.Struct({
|
|
116
|
+
kind: Schema.Literal("result"),
|
|
117
|
+
result: Schema.Unknown,
|
|
118
|
+
/** A sub-agent's answer: what it spent, which its parent's limits count. */
|
|
119
|
+
consumed: Schema.optionalKey(Consumed),
|
|
120
|
+
/** A processor tripped its guard on this result: the run stops before its next model call. */
|
|
121
|
+
tripped: Schema.optionalKey(Schema.Struct({ processor: Schema.String, reason: Schema.String })),
|
|
122
|
+
}),
|
|
123
|
+
Schema.Struct({
|
|
124
|
+
kind: Schema.Literal("consent"),
|
|
125
|
+
consentId: Schema.String,
|
|
126
|
+
signal: Schema.String,
|
|
127
|
+
decided: Schema.NullOr(Decision),
|
|
128
|
+
}),
|
|
129
|
+
Schema.Struct({ kind: Schema.Literal("started"), childRunId: Schema.String, signal: Schema.String }),
|
|
130
|
+
Schema.Struct({ kind: Schema.Literal("cancelled") }),
|
|
131
|
+
]);
|
|
132
|
+
const Finished = Schema.Struct({
|
|
133
|
+
status: Schema.String,
|
|
134
|
+
stopReason: Schema.NullOr(Schema.String),
|
|
135
|
+
result: Schema.NullOr(Schema.String),
|
|
136
|
+
});
|
|
137
|
+
/** The kernel's own instructions, first in every model call. */
|
|
138
|
+
export const BASE_INSTRUCTIONS = `You are the agent of one person in their organisation, working in an Eloxiv app. You act only through the tools you are given: each is an action of the app, run with the person's own permissions, checked by policy and audited. Read data with the query tool (published, policy-filtered views); change data only with actions.
|
|
139
|
+
- A tool result {"ok":true,"output":{"kind":"output",...}} is the action's output; {"kind":"replay",...} means the call had already run and returns its receipt. {"ok":false,"error":...} is a refusal or failure: explain it, never retry blindly.
|
|
140
|
+
- ConsentRejected means the person declined that call: do not ask again unless they say so.
|
|
141
|
+
- Read a skill with load_skill before relying on it; one the person invokes (/name) or mentions (@name) is already given to you whole. Remember durable facts the person asks you to keep with agent_remember.
|
|
142
|
+
- Answer concisely once the work is done.`;
|
|
143
|
+
const COMPACTION_INSTRUCTIONS = `You compact a conversation between a person and their agent into an observation: a dense, dated record of what happened in the stretch below, which replaces it. Write a dense summary that replaces the transcript below. Keep, verbatim: names, numbers, identifiers, dates, decisions, commitments, what each tool call did and its outcome, open questions, and every fact the person asked to remember. Leave out pleasantries. Write in the third person, past tense.`;
|
|
144
|
+
const REFLECTION_INSTRUCTIONS = `You condense the observations (and any earlier reflection) of a long conversation between a person and their agent into one reflection: the long-arc summary that replaces them. Keep, verbatim: names, numbers, identifiers, dates, decisions, commitments, the outcome of each piece of work, open questions, and every fact the person asked to remember. Leave out what later observations superseded. Write in the third person, past tense.`;
|
|
145
|
+
/**
|
|
146
|
+
* A step of the run failed unexpectedly: the cause is the kernel's (its message and trace may carry what the kernel
|
|
147
|
+
* holds), so it is logged under a reference, and the run's error, which its owner reads, names only the reference.
|
|
148
|
+
*/
|
|
149
|
+
const unexpected = (what) => (cause) => Effect.gen(function* () {
|
|
150
|
+
// A refusal is not a failure of the kernel's: the run's authority no longer holds (a credential revoked, the
|
|
151
|
+
// person removed, a consent withdrawn), and the run ends saying so.
|
|
152
|
+
const failure = Cause.findErrorOption(cause);
|
|
153
|
+
if (Option.isSome(failure) && isRefusal(failure.value)) {
|
|
154
|
+
return yield* new WorkflowFailed({
|
|
155
|
+
message: `The authority this run acts under no longer holds: ${failure.value.message}`,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
const reference = crypto.randomUUID();
|
|
159
|
+
yield* Effect.logError(`Agent ${what} failed unexpectedly (reference ${reference})`, cause);
|
|
160
|
+
return yield* new WorkflowFailed({
|
|
161
|
+
message: `Agent ${what} failed unexpectedly (reference ${reference}); the kernel's log has the details`,
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
/** An authority's refusal (`Unauthenticated`, `Forbidden`): what `Authority.assert` fails with. */
|
|
165
|
+
const isRefusal = (error) => typeof error === "object" &&
|
|
166
|
+
error !== null &&
|
|
167
|
+
(error._tag === "Unauthenticated" || error._tag === "Forbidden");
|
|
168
|
+
const withServices = (services, what) => (effect) => effect.pipe(Effect.updateContext((current) => Context.merge(current, services)), Effect.catchCause(unexpected(what)));
|
|
169
|
+
/**
|
|
170
|
+
* The tools a run in `orgId` may use: every action except people's own (the app's, and the MAKE modules'
|
|
171
|
+
* installed in the organisation), the agent's internal tools (with `tool_search` when its tools are found by
|
|
172
|
+
* search), narrowed by `allowed`.
|
|
173
|
+
*/
|
|
174
|
+
export const runTools = (orgId, options = DEFAULT_OPTIONS) => Effect.gen(function* () {
|
|
175
|
+
const tools = yield* AgentTools;
|
|
176
|
+
const registry = yield* Registry;
|
|
177
|
+
const queryViews = yield* QueryViews;
|
|
178
|
+
const resources = yield* AgentResources;
|
|
179
|
+
const definitions = [];
|
|
180
|
+
for (const definition of (yield* tools.definitionsFor(orgId)).values()) {
|
|
181
|
+
// A person's action, or one the agent surface does not offer: not the agent's tool.
|
|
182
|
+
if (PERSON_ONLY_ACTIONS.has(definition.action))
|
|
183
|
+
continue;
|
|
184
|
+
if (registry.actions.get(definition.action)?.contract.exposure.agent === false)
|
|
185
|
+
continue;
|
|
186
|
+
definitions.push({
|
|
187
|
+
name: definition.name,
|
|
188
|
+
description: definition.description,
|
|
189
|
+
inputSchema: definition.inputSchema,
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
if (!registry.actions.has(QUERY_ACTION)) {
|
|
193
|
+
const views = queryViews.views.map((v) => `${v.id} (${v.description})`).join("; ");
|
|
194
|
+
definitions.push({
|
|
195
|
+
name: "query",
|
|
196
|
+
description: `Read rows of a published query view, filtered by what you may read (read-only). Views: ${views || "none"}.`,
|
|
197
|
+
inputSchema: {
|
|
198
|
+
type: "object",
|
|
199
|
+
properties: { view: { type: "string" }, limit: { type: "number" } },
|
|
200
|
+
required: ["view"],
|
|
201
|
+
additionalProperties: false,
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
const skills = resources.app.filter((r) => r.kind === "skill").map((r) => r.path);
|
|
206
|
+
definitions.push({
|
|
207
|
+
name: "load_skill",
|
|
208
|
+
description: `Read a skill's document (personal, organisation or app). Skills: ${skills.join(", ") || "none"}.`,
|
|
209
|
+
inputSchema: {
|
|
210
|
+
type: "object",
|
|
211
|
+
properties: { skill: { type: "string" } },
|
|
212
|
+
required: ["skill"],
|
|
213
|
+
additionalProperties: false,
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
const { maxOutputTokens, maxDelegationDepth, profiles } = yield* AgentSettings;
|
|
217
|
+
if (options.tools.discovery === "search")
|
|
218
|
+
definitions.push(toolSearchDefinition);
|
|
219
|
+
const deeper = options.depth + 1 < maxDelegationDepth;
|
|
220
|
+
definitions.push({
|
|
221
|
+
name: "delegate",
|
|
222
|
+
description: `Hand a self-contained task to a sub-agent with a subset of your tools (by name); you get its final answer. ${deeper ? "A sub-agent may delegate further only if you give it the delegate tool." : "Sub-agents cannot delegate further."} ` +
|
|
223
|
+
(profiles.length === 0
|
|
224
|
+
? ""
|
|
225
|
+
: `To use a custom agent, name its profile (its instructions apply; without tools it gets the profile's): ${profiles.map((p) => `${p.name} (${p.description})`).join("; ")}. `) +
|
|
226
|
+
`Leave out limits unless you must constrain it: it then gets up to 8 model calls and the tokens you have left. maxSteps counts its model calls (a task that calls one tool and then answers needs 2); maxTokens counts the input and output of all of them, and each call needs room for ${maxOutputTokens} output tokens.`,
|
|
227
|
+
inputSchema: {
|
|
228
|
+
type: "object",
|
|
229
|
+
properties: {
|
|
230
|
+
task: { type: "string" },
|
|
231
|
+
tools: { type: "array", items: { type: "string" } },
|
|
232
|
+
...(profiles.length === 0 ? {} : { profile: { type: "string", enum: profiles.map((p) => p.name) } }),
|
|
233
|
+
limits: {
|
|
234
|
+
type: "object",
|
|
235
|
+
properties: { maxSteps: { type: "number" }, maxTokens: { type: "number" }, maxWallMs: { type: "number" } },
|
|
236
|
+
additionalProperties: false,
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
required: profiles.length === 0 ? ["task", "tools"] : ["task"],
|
|
240
|
+
additionalProperties: false,
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
definitions.push(teamDefinition(profiles));
|
|
244
|
+
return definitions.sort((a, b) => a.name.localeCompare(b.name));
|
|
245
|
+
});
|
|
246
|
+
/** The tool that runs sub-agents in parallel (a team of seats) and carries messages between them. */
|
|
247
|
+
export const TEAM = "team";
|
|
248
|
+
const TEAM_DESCRIPTION = `Work with a team of sub-agents running in parallel. action "spawn" starts a seat on a self-contained task with a subset of your tools (by name, as for delegate) and returns its id at once, while it works. action "wait" waits until all (until "all", the default) or any (until "any") of your running seats (or those named in seats) finished, or until a message arrives for you. action "send" messages a seat ("to": its id, or "lead" for the run that started you). action "list" shows your team. Every result also carries the messages that arrived for you and the answers of your seats that finished since your last team call. A seat's limits are reserved from yours while it runs; leave them out and it gets up to 8 model calls, at most half of those you have left, and half your tokens. Seats still running when you answer are cancelled: wait for them first.`;
|
|
249
|
+
const SEAT_DESCRIPTION = `Talk with your team: you are a seat working in parallel with others. action "send" messages your lead ("to": "lead") or another seat (its id); action "wait" waits until a message arrives for you; action "list" shows your team. Every result also carries the messages that arrived for you. Your final answer goes to your lead.`;
|
|
250
|
+
const teamDefinition = (profiles) => ({
|
|
251
|
+
name: TEAM,
|
|
252
|
+
description: TEAM_DESCRIPTION,
|
|
253
|
+
inputSchema: {
|
|
254
|
+
type: "object",
|
|
255
|
+
properties: {
|
|
256
|
+
action: { type: "string", enum: ["spawn", "wait", "send", "list"] },
|
|
257
|
+
task: { type: "string" },
|
|
258
|
+
name: { type: "string" },
|
|
259
|
+
tools: { type: "array", items: { type: "string" } },
|
|
260
|
+
...(profiles.length === 0 ? {} : { profile: { type: "string", enum: profiles.map((p) => p.name) } }),
|
|
261
|
+
limits: {
|
|
262
|
+
type: "object",
|
|
263
|
+
properties: { maxSteps: { type: "number" }, maxTokens: { type: "number" }, maxWallMs: { type: "number" } },
|
|
264
|
+
additionalProperties: false,
|
|
265
|
+
},
|
|
266
|
+
seats: { type: "array", items: { type: "string" } },
|
|
267
|
+
until: { type: "string", enum: ["all", "any"] },
|
|
268
|
+
to: { type: "string" },
|
|
269
|
+
text: { type: "string" },
|
|
270
|
+
},
|
|
271
|
+
required: ["action"],
|
|
272
|
+
additionalProperties: false,
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
/**
|
|
276
|
+
* The team tool as a run is offered it: with `spawn` (and the tools a seat may be given) when the run may start seats
|
|
277
|
+
* (given the tool, within the delegation depth); a seat that may not is offered only its messages.
|
|
278
|
+
*/
|
|
279
|
+
const teamWithChoices = (tool, choices, spawns) => {
|
|
280
|
+
const schema = tool.inputSchema;
|
|
281
|
+
if (spawns) {
|
|
282
|
+
return {
|
|
283
|
+
...tool,
|
|
284
|
+
inputSchema: {
|
|
285
|
+
...schema,
|
|
286
|
+
properties: { ...schema.properties, tools: { type: "array", items: { type: "string", enum: [...choices] } } },
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
const { to, text, until } = schema.properties;
|
|
291
|
+
return {
|
|
292
|
+
...tool,
|
|
293
|
+
description: SEAT_DESCRIPTION,
|
|
294
|
+
inputSchema: {
|
|
295
|
+
...schema,
|
|
296
|
+
properties: { action: { type: "string", enum: ["wait", "send", "list"] }, to, text, until },
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
};
|
|
300
|
+
/** May the run start seats: it was given the team tool (a seat always has it, for its messages) within the depth. */
|
|
301
|
+
const spawnsSeats = (spec, maxDelegationDepth) => (spec.tools === null || spec.tools.includes(TEAM)) && optionsOf(spec).depth < maxDelegationDepth;
|
|
302
|
+
const allowedTools = (all, spec) => spec.tools === null
|
|
303
|
+
? all
|
|
304
|
+
: all.filter((tool) => spec.tools.includes(tool.name) || (tool.name === TEAM && optionsOf(spec).seat !== undefined));
|
|
305
|
+
/** Is `action` read-only (`hints.readOnly`)? An action the registry does not declare (a MAKE module's) is not. */
|
|
306
|
+
const readOnly = (registry, action) => registry.actions.get(action)?.contract.hints.readOnly === true;
|
|
307
|
+
/** What people see `action` called: its title in the registry, or its readable name (always, for a MAKE action). */
|
|
308
|
+
const actionTitle = (registry, action) => decisionLabel(action, registry.actions.get(action)?.contract.title);
|
|
309
|
+
/** The run's own tools that change nothing (offered in plan mode). */
|
|
310
|
+
const READ_TOOLS = new Set(["query", "load_skill", TOOL_SEARCH, "delegate", TEAM]);
|
|
311
|
+
/**
|
|
312
|
+
* The tools the run may be offered now: its allowed tools, without the actions its agent cannot reach now
|
|
313
|
+
* (`AgentTools.reachable`: hidden by the policy, or in a tool group the app disabled for agents) and, in plan mode,
|
|
314
|
+
* without every action that is not read-only. A call the model makes to one anyway is refused: by the run (plan
|
|
315
|
+
* mode) or by the invocation path, which audits it.
|
|
316
|
+
*/
|
|
317
|
+
const availableTools = (spec) => Effect.gen(function* () {
|
|
318
|
+
const tools = yield* AgentTools;
|
|
319
|
+
const registry = yield* Registry;
|
|
320
|
+
const options = optionsOf(spec);
|
|
321
|
+
const allowed = allowedTools(yield* runTools(spec.orgId, options), spec);
|
|
322
|
+
const identity = identityOf(spec);
|
|
323
|
+
const reachable = new Set(yield* tools.reachable(spec.agentSessionId === null ? { identity } : { identity, agentSession: spec.agentSessionId }));
|
|
324
|
+
// Every action tool, the app's and the organisation's MAKE modules', is offered only if reach lets the agent call
|
|
325
|
+
// it; the run's own tools (query, load_skill, tool_search, delegate) are not actions.
|
|
326
|
+
const actionTools = yield* tools.definitionsFor(spec.orgId);
|
|
327
|
+
const available = allowed.filter((tool) => {
|
|
328
|
+
const action = actionTools.get(tool.name);
|
|
329
|
+
if (action === undefined)
|
|
330
|
+
return options.mode === "act" || READ_TOOLS.has(tool.name);
|
|
331
|
+
return reachable.has(tool.name) && (options.mode === "act" || readOnly(registry, action.action));
|
|
332
|
+
});
|
|
333
|
+
return { available, actionTools };
|
|
334
|
+
});
|
|
335
|
+
/**
|
|
336
|
+
* The tools offered to the model on this call. With every tool (`discovery: all`): all the run may be offered.
|
|
337
|
+
* Found by search: the run's own tools, the policy's `eager` tools and those the run loaded with `tool_search`; the
|
|
338
|
+
* others are named in the tool index (`deferred`).
|
|
339
|
+
*/
|
|
340
|
+
const offeredTools = (spec, loaded = new Set()) => Effect.gen(function* () {
|
|
341
|
+
const { available, actionTools } = yield* availableTools(spec);
|
|
342
|
+
const policy = optionsOf(spec).tools;
|
|
343
|
+
const eager = new Set(policy.eager ?? []);
|
|
344
|
+
const offered = policy.discovery === "all"
|
|
345
|
+
? available
|
|
346
|
+
: available.filter((tool) => !actionTools.has(tool.name) || eager.has(tool.name) || loaded.has(tool.name));
|
|
347
|
+
const deferred = available.filter((tool) => !offered.includes(tool));
|
|
348
|
+
// The delegate tool names the tools a sub-agent may be given: exactly the others the run may use (never one the
|
|
349
|
+
// policy hides), so the model picks real names (a real model was seen writing `functions.notebook_write`); the
|
|
350
|
+
// delegate tool itself only while the sub-agent would be within the delegation depth.
|
|
351
|
+
const { maxDelegationDepth } = yield* AgentSettings;
|
|
352
|
+
const deeper = optionsOf(spec).depth + 2 <= maxDelegationDepth;
|
|
353
|
+
const spawns = spawnsSeats(spec, maxDelegationDepth);
|
|
354
|
+
const choices = available
|
|
355
|
+
.map((tool) => tool.name)
|
|
356
|
+
.filter((name) => ((name !== "delegate" && name !== TEAM) || deeper) && (name !== TEAM || spawns) && name !== TOOL_SEARCH);
|
|
357
|
+
return {
|
|
358
|
+
offered: [
|
|
359
|
+
...offered.map((tool) => tool.name === "delegate"
|
|
360
|
+
? delegateWithChoices(tool, choices)
|
|
361
|
+
: tool.name === TEAM
|
|
362
|
+
? teamWithChoices(tool, choices, spawns)
|
|
363
|
+
: tool),
|
|
364
|
+
// A run a job or schedule started may say it found nothing to do, distinct from finishing with nothing to show.
|
|
365
|
+
...(spec.kind === "job" ? [NO_OP_TOOL] : []),
|
|
366
|
+
],
|
|
367
|
+
deferred,
|
|
368
|
+
};
|
|
369
|
+
});
|
|
370
|
+
/** The tool a run of kind `job` ends with when it finds nothing to do: the run succeeds as a no-op, with the reason. */
|
|
371
|
+
export const NO_OP_TOOL = {
|
|
372
|
+
name: "no_op",
|
|
373
|
+
description: "Call this, instead of answering, when this background job finds nothing to do: say why in one sentence (no personal data). The run then ends as a no-op, distinct from work done.",
|
|
374
|
+
inputSchema: {
|
|
375
|
+
type: "object",
|
|
376
|
+
properties: { reason: { type: "string" } },
|
|
377
|
+
required: ["reason"],
|
|
378
|
+
additionalProperties: false,
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
const delegateWithChoices = (tool, choices) => {
|
|
382
|
+
const schema = tool.inputSchema;
|
|
383
|
+
return {
|
|
384
|
+
...tool,
|
|
385
|
+
inputSchema: {
|
|
386
|
+
...schema,
|
|
387
|
+
properties: { ...schema.properties, tools: { type: "array", items: { type: "string", enum: [...choices] } } },
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
};
|
|
391
|
+
const refused = (tag, message, extra = {}) => ({
|
|
392
|
+
ok: false,
|
|
393
|
+
error: { _tag: tag, message, ...extra },
|
|
394
|
+
});
|
|
395
|
+
const identityOf = (spec) => spec.userId === SYSTEM_ACTOR
|
|
396
|
+
? {
|
|
397
|
+
kind: "system",
|
|
398
|
+
orgId: spec.orgId,
|
|
399
|
+
// A system run started within a scope (a tool-limited parent's) stays within it.
|
|
400
|
+
...(typeof spec.authority === "object" && spec.authority.scope !== null
|
|
401
|
+
? { scope: [...spec.authority.scope] }
|
|
402
|
+
: {}),
|
|
403
|
+
}
|
|
404
|
+
: {
|
|
405
|
+
kind: "user",
|
|
406
|
+
userId: spec.userId,
|
|
407
|
+
orgId: spec.orgId,
|
|
408
|
+
// The authority the run was started with: every call of the run is within it, and only while it holds.
|
|
409
|
+
authority: spec.authority ?? "unrecorded",
|
|
410
|
+
};
|
|
411
|
+
/**
|
|
412
|
+
* The run's effective authority, as a record a successor can carry: its scope, and its chain with the agent session its
|
|
413
|
+
* calls were made through. Null for a run that recorded none (it acts on nothing).
|
|
414
|
+
*/
|
|
415
|
+
const effectiveAuthority = (spec) => {
|
|
416
|
+
const chain = runChain(spec);
|
|
417
|
+
return chain === "unrecorded" || spec.authority === undefined || spec.authority === "unrecorded"
|
|
418
|
+
? null
|
|
419
|
+
: { ...spec.authority, chain };
|
|
420
|
+
};
|
|
421
|
+
/**
|
|
422
|
+
* The identity a tool call acts as: the run's, within the scope it was started with and, when the run may use only
|
|
423
|
+
* some tools (a sub-agent's, a profile's), within the actions those tools are. The narrowed scope is the call's
|
|
424
|
+
* recorded authority, so a deputy the call reaches (a read program's reads, a collection's pages, a nested call)
|
|
425
|
+
* stays within the run's tools too, not only the call the model made.
|
|
426
|
+
*/
|
|
427
|
+
const toolIdentity = (spec) => Effect.gen(function* () {
|
|
428
|
+
const identity = identityOf(spec);
|
|
429
|
+
if (spec.tools === null)
|
|
430
|
+
return identity;
|
|
431
|
+
// The tool subset applies whoever the run acts as: a person (within the scope it was started with) or the
|
|
432
|
+
// organisation's system actor (a job's run, its sub-agents).
|
|
433
|
+
const kept = identity.kind === "system"
|
|
434
|
+
? (identity.scope ?? null)
|
|
435
|
+
: typeof identity.authority === "object"
|
|
436
|
+
? identity.authority.scope
|
|
437
|
+
: undefined;
|
|
438
|
+
if (kept === undefined)
|
|
439
|
+
return identity;
|
|
440
|
+
const tools = yield* AgentTools;
|
|
441
|
+
const registry = yield* Registry;
|
|
442
|
+
const allowed = new Set(spec.tools);
|
|
443
|
+
const actions = [...(yield* tools.definitionsFor(spec.orgId)).values()]
|
|
444
|
+
.filter((definition) => allowed.has(definition.name))
|
|
445
|
+
.map((definition) => definition.action);
|
|
446
|
+
const scope = [...new Set(actions)]
|
|
447
|
+
.filter((action) => scopeAllows(kept, action, (permission) => registry.permissions.get(permission)?.actions))
|
|
448
|
+
.map((action) => `action:${action}`);
|
|
449
|
+
return identity.kind === "system"
|
|
450
|
+
? { ...identity, scope }
|
|
451
|
+
: { ...identity, authority: { ...identity.authority, scope } };
|
|
452
|
+
});
|
|
453
|
+
/** The run's chain of authorities (Authority), with the agent session its calls are made through. */
|
|
454
|
+
const runChain = (spec) => spec.authority === undefined || spec.authority === "unrecorded"
|
|
455
|
+
? "unrecorded"
|
|
456
|
+
: extend(spec.authority.chain, spec.agentSessionId === null ? [] : [{ kind: "agent-session", id: spec.agentSessionId }]);
|
|
457
|
+
/**
|
|
458
|
+
* What the run asserts (Authority) whenever it reads or writes the person's data itself (not through an action,
|
|
459
|
+
* which asserts in the invocation path): its whole chain, with the conversation's agent session and the person's
|
|
460
|
+
* membership, within the scope it was started with. The capability `Authority.within` gives for it is what the
|
|
461
|
+
* person's resources, memory, skills, query views and transcript are read and written with.
|
|
462
|
+
*/
|
|
463
|
+
const runAuthority = (spec) => ({
|
|
464
|
+
chain: runChain(spec),
|
|
465
|
+
who: { userId: spec.userId, orgId: spec.orgId },
|
|
466
|
+
scope: spec.authority === undefined || spec.authority === "unrecorded" || spec.authority.scope === null
|
|
467
|
+
? null
|
|
468
|
+
: [...spec.authority.scope],
|
|
469
|
+
});
|
|
470
|
+
/**
|
|
471
|
+
* Read or write the person's transcript (their conversation's messages, and the run's events that carry them) on their
|
|
472
|
+
* behalf: in a transaction of its own whose first act is asserting the run's authority, with the capability
|
|
473
|
+
* `inAgentFor` requires. A refusal fails with the reason (the run then ends saying so).
|
|
474
|
+
*/
|
|
475
|
+
/**
|
|
476
|
+
* The team a conversation's runs work in: the one it is bound to (`agent.updateConversation`'s `team`), or undefined,
|
|
477
|
+
* which AgentResources takes as the person's active team. The one resolution for the run's context and `load_skill`.
|
|
478
|
+
*/
|
|
479
|
+
const teamOfConversation = (asserted, sql, conversationId) => inAgentFor(asserted, sql, sql `SELECT team FROM eloxiv_agent.conversation WHERE id = ${conversationId}`).pipe(Effect.orDie, Effect.map(([bound]) => bound?.team ?? undefined));
|
|
480
|
+
const inTranscript = (spec, write) => Effect.gen(function* () {
|
|
481
|
+
const sql = yield* SqlClient.SqlClient;
|
|
482
|
+
return yield* (yield* Authority).within(runAuthority(spec), (asserted) => replying(sql, spec).pipe(Effect.andThen(inAgentFor(asserted, sql, write(sql)))));
|
|
483
|
+
});
|
|
484
|
+
/**
|
|
485
|
+
* A reply in a conversation shared with the run's person: before every read or write of its transcript, inside that
|
|
486
|
+
* transaction, the person must still hold `reply` on it (the conversation's `send` policy, as them). A revoked grant
|
|
487
|
+
* stops the run at its next read or write (the run ends saying its authority no longer holds). Nothing for a run in
|
|
488
|
+
* its person's own conversation.
|
|
489
|
+
*/
|
|
490
|
+
const replying = (sql, spec) => spec.conversationOwner === undefined
|
|
491
|
+
? Effect.void
|
|
492
|
+
: mayReply(sql, { userId: spec.userId, orgId: spec.orgId, conversationId: spec.conversationId }).pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)), Effect.flatMap((allowed) => allowed
|
|
493
|
+
? Effect.void
|
|
494
|
+
: Effect.fail(new Forbidden({
|
|
495
|
+
action: "agent.send",
|
|
496
|
+
message: "The conversation is no longer shared with you to reply in",
|
|
497
|
+
}))));
|
|
498
|
+
// --- start -----------------------------------------------------------------------------------------------------------
|
|
499
|
+
const startRun = (runId, orgId) => Effect.gen(function* () {
|
|
500
|
+
const sql = yield* SqlClient.SqlClient;
|
|
501
|
+
const settings = yield* AgentSettings;
|
|
502
|
+
const identity = yield* Identity;
|
|
503
|
+
const [run] = yield* inAgent(sql, orgId, sql `SELECT r.user_id AS "userId", r.conversation_id AS "conversationId", r.parent_run_id AS "parentRunId", r.kind,
|
|
504
|
+
r.limits, r.tools, c.agent_session_id AS "sessionId", r.started_at AS "startedAt", r.device, r.authority,
|
|
505
|
+
r.options, c.user_id AS "ownerId"
|
|
506
|
+
FROM eloxiv_agent.run r JOIN eloxiv_agent.conversation c ON c.id = r.conversation_id WHERE r.id = ${runId}`);
|
|
507
|
+
if (run === undefined)
|
|
508
|
+
return yield* Effect.die(new Error(`No agent run ${runId}`));
|
|
509
|
+
// The conversation's agent session: every tool call of its runs is agent-originated through it (consent's
|
|
510
|
+
// session-scoped permissions cover the conversation). Issued once; a sub-agent uses its parent's and never gets a
|
|
511
|
+
// new one: if the parent's was revoked, the sub-agent's calls are refused.
|
|
512
|
+
let sessionId = null;
|
|
513
|
+
if (run.userId !== SYSTEM_ACTOR && run.parentRunId !== null) {
|
|
514
|
+
sessionId = run.sessionId;
|
|
515
|
+
}
|
|
516
|
+
else if (run.userId !== SYSTEM_ACTOR && run.userId !== run.ownerId) {
|
|
517
|
+
// A reply in a conversation shared with the person: the conversation's session is its owner's, never theirs. The
|
|
518
|
+
// run gets a session of its own person's, for as long as it may run.
|
|
519
|
+
const issued = yield* identity.issueAgentSession({
|
|
520
|
+
userId: run.userId,
|
|
521
|
+
orgId,
|
|
522
|
+
label: `agent reply in conversation ${run.conversationId}`,
|
|
523
|
+
ttlMs: Math.max(60 * 60 * 1000, (run.limits?.maxWallMs ?? settings.limits.maxWallMs) + 60 * 60 * 1000),
|
|
524
|
+
authority: { scope: null, chain: [] },
|
|
525
|
+
});
|
|
526
|
+
sessionId = issued.id;
|
|
527
|
+
}
|
|
528
|
+
else if (run.userId !== SYSTEM_ACTOR) {
|
|
529
|
+
sessionId = run.sessionId;
|
|
530
|
+
const valid = sessionId !== null &&
|
|
531
|
+
(yield* sql `SELECT (revoked_at IS NULL AND expires_at > now() + interval '1 hour'
|
|
532
|
+
AND authority IS NOT NULL) AS ok
|
|
533
|
+
FROM eloxiv.agent_session WHERE id = ${sessionId}`)[0]?.ok === true;
|
|
534
|
+
if (!valid) {
|
|
535
|
+
const issued = yield* identity.issueAgentSession({
|
|
536
|
+
userId: run.userId,
|
|
537
|
+
orgId,
|
|
538
|
+
label: `agent conversation ${run.conversationId}`,
|
|
539
|
+
ttlMs: 30 * 24 * 60 * 60 * 1000,
|
|
540
|
+
// The conversation's own session: a link of each run's chain, standing for nothing beyond itself (each run
|
|
541
|
+
// records what it was started under).
|
|
542
|
+
authority: { scope: null, chain: [] },
|
|
543
|
+
});
|
|
544
|
+
sessionId = issued.id;
|
|
545
|
+
yield* inAgent(sql, orgId, sql `UPDATE eloxiv_agent.conversation SET agent_session_id = ${sessionId} WHERE id = ${run.conversationId}`);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// The run's limits: the deployment's, with what was recorded on the run when it was queued (the organisation's
|
|
549
|
+
// loop policy, a sub-agent's carved limits) over them, each capped at the deployment's ceiling.
|
|
550
|
+
const recorded = { ...settings.limits, ...run.limits };
|
|
551
|
+
const limits = {
|
|
552
|
+
maxSteps: Math.min(recorded.maxSteps, settings.maxLimits.maxSteps),
|
|
553
|
+
maxTokens: Math.min(recorded.maxTokens, settings.maxLimits.maxTokens),
|
|
554
|
+
maxWallMs: Math.min(recorded.maxWallMs, settings.maxLimits.maxWallMs),
|
|
555
|
+
};
|
|
556
|
+
const [started] = yield* inAgent(sql, orgId, sql `UPDATE eloxiv_agent.run SET status = 'running', limits = ${JSON.stringify(limits)}::jsonb,
|
|
557
|
+
started_at = coalesce(started_at, now()) WHERE id = ${runId} RETURNING started_at AS "startedAt"`);
|
|
558
|
+
return {
|
|
559
|
+
runId,
|
|
560
|
+
orgId,
|
|
561
|
+
userId: run.userId,
|
|
562
|
+
conversationId: run.conversationId,
|
|
563
|
+
parentRunId: run.parentRunId,
|
|
564
|
+
kind: run.kind,
|
|
565
|
+
limits,
|
|
566
|
+
tools: run.tools === null ? null : [...run.tools],
|
|
567
|
+
agentSessionId: sessionId,
|
|
568
|
+
startedAt: new Date(started.startedAt).getTime(),
|
|
569
|
+
device: run.device,
|
|
570
|
+
// A run queued before authorities were recorded acts on nothing (it fails closed at its first act).
|
|
571
|
+
authority: run.authority ?? "unrecorded",
|
|
572
|
+
...(run.options === null ? {} : { options: run.options }),
|
|
573
|
+
...(run.ownerId === run.userId || run.parentRunId !== null ? {} : { conversationOwner: run.ownerId }),
|
|
574
|
+
...(run.options?.editGroup === undefined ? {} : { editGroup: { runId, ...run.options.editGroup } }),
|
|
575
|
+
};
|
|
576
|
+
});
|
|
577
|
+
// --- context -----------------------------------------------------------------------------------------------------------
|
|
578
|
+
/** The kernel's instructions for a run in plan mode. */
|
|
579
|
+
const PLAN_INSTRUCTIONS = `You are in plan mode: read what you need and answer with a plan, but change nothing. Only read-only tools are available; actions that change data are refused in this mode. Describe each change you would make (which action, with what input) so the person can approve the plan and run it.`;
|
|
580
|
+
/**
|
|
581
|
+
* The kernel's instructions for a run: its own, plus plan mode's, the sub-agent's profile's, and (tools found by
|
|
582
|
+
* search) the index of tools it may load.
|
|
583
|
+
*/
|
|
584
|
+
const instructionsFor = (spec, deferred, note = null) => Effect.gen(function* () {
|
|
585
|
+
const options = optionsOf(spec);
|
|
586
|
+
const { profiles } = yield* AgentSettings;
|
|
587
|
+
const profile = options.profile === undefined ? undefined : profiles.find((p) => p.name === options.profile);
|
|
588
|
+
return [
|
|
589
|
+
BASE_INSTRUCTIONS,
|
|
590
|
+
...(options.mode === "plan" ? [PLAN_INSTRUCTIONS] : []),
|
|
591
|
+
...(profile === undefined ? [] : [`You are the custom agent "${profile.name}".\n${profile.instructions}`]),
|
|
592
|
+
...(options.seat === undefined
|
|
593
|
+
? []
|
|
594
|
+
: [
|
|
595
|
+
`You are the seat "${options.seat}" (${spec.runId}) of a team working in parallel on your lead's task. Use the team tool to message your lead or another seat, and to wait for their messages. Your final answer goes to your lead.`,
|
|
596
|
+
]),
|
|
597
|
+
...(options.tools.discovery === "search" && deferred.length > 0 ? [toolIndex(deferred)] : []),
|
|
598
|
+
...(note === null ? [] : [note]),
|
|
599
|
+
].join("\n\n");
|
|
600
|
+
});
|
|
601
|
+
/** What the model is sent for the next call of `spec`'s run: assembled from the stored state, with its inventory. */
|
|
602
|
+
const contextFor = (spec, tools, deferred = [], note = null) => Effect.gen(function* () {
|
|
603
|
+
const sql = yield* SqlClient.SqlClient;
|
|
604
|
+
const settings = yield* AgentSettings;
|
|
605
|
+
const resources = yield* AgentResources;
|
|
606
|
+
const authority = yield* Authority;
|
|
607
|
+
// The person's conversation, memory and resources, read under the run's authority.
|
|
608
|
+
const { effective, memory, messages, directives, about } = yield* authority
|
|
609
|
+
.within(runAuthority(spec), (asserted) => Effect.gen(function* () {
|
|
610
|
+
yield* replying(sql, spec);
|
|
611
|
+
const team = yield* teamOfConversation(asserted, sql, spec.conversationId);
|
|
612
|
+
const effective = yield* resources.effective(asserted, undefined, team);
|
|
613
|
+
const memory = yield* resources.recall(asserted, team);
|
|
614
|
+
const read = yield* inAgentFor(asserted, sql, Effect.gen(function* () {
|
|
615
|
+
const rows = yield* sql `SELECT id, role, content,
|
|
616
|
+
seq::float8 AS seq, user_id AS "userId" FROM eloxiv_agent.message
|
|
617
|
+
WHERE conversation_id = ${spec.conversationId} AND covered_by IS NULL ORDER BY seq, id`;
|
|
618
|
+
const directives = yield* sql `
|
|
619
|
+
SELECT ref, directive FROM eloxiv_agent.directive WHERE conversation_id = ${spec.conversationId}`;
|
|
620
|
+
const [conversation] = yield* sql `
|
|
621
|
+
SELECT resource_module AS module, resource_entity AS entity, resource_id AS id
|
|
622
|
+
FROM eloxiv_agent.conversation WHERE id = ${spec.conversationId}`;
|
|
623
|
+
return { messages: ownView(spec, rows), directives, about: conversation };
|
|
624
|
+
}));
|
|
625
|
+
return { effective, memory, ...read };
|
|
626
|
+
}))
|
|
627
|
+
.pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)));
|
|
628
|
+
const base = yield* instructionsFor(spec, deferred, note);
|
|
629
|
+
return assemble({
|
|
630
|
+
base: about?.module == null || about.entity == null || about.id == null
|
|
631
|
+
? base
|
|
632
|
+
: `${base}\n\nThis conversation is about the record ${about.module}.${about.entity} ${JSON.stringify(about.id)}: read it with your tools (under the person's permissions) when you need it.`,
|
|
633
|
+
resources: effective.filter((r) => r.kind !== "file"),
|
|
634
|
+
memory,
|
|
635
|
+
messages,
|
|
636
|
+
tools,
|
|
637
|
+
budgets: settings.budgets,
|
|
638
|
+
directives: new Map(directives.map((d) => [d.ref, d.directive])),
|
|
639
|
+
});
|
|
640
|
+
});
|
|
641
|
+
/**
|
|
642
|
+
* A conversation's messages as one person's run sees them: everyone's words, but tool calls, their results and
|
|
643
|
+
* compaction summaries only of the run's own person. In a shared conversation another participant's agent read what that person may read, so
|
|
644
|
+
* its tool results (and the calls they answer) stay out of this person's context.
|
|
645
|
+
*/
|
|
646
|
+
const ownView = (spec, rows) => rows.flatMap((row) => {
|
|
647
|
+
const message = { id: row.id, role: row.role, content: row.content, seq: row.seq };
|
|
648
|
+
if (row.userId === spec.userId)
|
|
649
|
+
return [message];
|
|
650
|
+
// (A summary another person's run wrote can quote its tool results.)
|
|
651
|
+
if (row.role === "tool" || row.role === "summary")
|
|
652
|
+
return [];
|
|
653
|
+
// Another person's message in its public form only: their words or their agent's answer, never their attachments'
|
|
654
|
+
// text, their agent's tool calls or what those read.
|
|
655
|
+
const text = String(row.content?.text ?? "");
|
|
656
|
+
if (text === "")
|
|
657
|
+
return [];
|
|
658
|
+
return [{ ...message, content: row.role === "assistant" ? { text, toolCalls: [] } : { text, attachments: [] } }];
|
|
659
|
+
});
|
|
660
|
+
/** Render stored messages as a plain transcript for the compaction model. */
|
|
661
|
+
const transcript = (messages) => messages
|
|
662
|
+
.map((m) => {
|
|
663
|
+
const c = m.content ?? {};
|
|
664
|
+
if (m.role === "summary")
|
|
665
|
+
return `${c.tier === "reflection" ? "Reflection" : "Observation"}: ${c.text ?? ""}`;
|
|
666
|
+
if (m.role === "user")
|
|
667
|
+
return `Person: ${c.text ?? ""}`;
|
|
668
|
+
if (m.role === "assistant") {
|
|
669
|
+
const calls = (c.toolCalls ?? [])
|
|
670
|
+
.map((t) => ` [called ${t.toolName} with ${JSON.stringify(t.input)}]`)
|
|
671
|
+
.join("");
|
|
672
|
+
return `Agent: ${c.text ?? ""}${calls}`;
|
|
673
|
+
}
|
|
674
|
+
return `Tool ${c.toolName ?? ""} result: ${JSON.stringify(c.result ?? null).slice(0, 2_000)}`;
|
|
675
|
+
})
|
|
676
|
+
.join("\n");
|
|
677
|
+
const tierOf = (m) => (m.content?.tier === "reflection" ? "reflection" : "observation");
|
|
678
|
+
const TIER_INSTRUCTIONS = {
|
|
679
|
+
observation: COMPACTION_INSTRUCTIONS,
|
|
680
|
+
reflection: REFLECTION_INSTRUCTIONS,
|
|
681
|
+
};
|
|
682
|
+
/**
|
|
683
|
+
* One fold of Memory's tiers: `items` (raw messages for an observation; observations, and an earlier reflection, for a
|
|
684
|
+
* reflection) summarised by the organisation's model into one `summary` message of `tier`, which records what it
|
|
685
|
+
* covers (their ids, the time they span, their tokens before and after) and marks them covered by it. Metered like any
|
|
686
|
+
* model call (its worst case reserved first) and counted in its run; written, with the covered marks and the
|
|
687
|
+
* `compacted` event, in one transaction under `authorityOf`, which is asserted again there (a refused write is not
|
|
688
|
+
* made: null). Its id is derived from what it covers, so a fold made again after a crash writes nothing new.
|
|
689
|
+
*/
|
|
690
|
+
const fold = (spec, authorityOf, tier, items, room) => Effect.gen(function* () {
|
|
691
|
+
const sql = yield* SqlClient.SqlClient;
|
|
692
|
+
const settings = yield* AgentSettings;
|
|
693
|
+
const models = yield* ModelProviders;
|
|
694
|
+
const metering = yield* Metering;
|
|
695
|
+
const authority = yield* Authority;
|
|
696
|
+
const text = transcript(items);
|
|
697
|
+
const instructions = TIER_INSTRUCTIONS[tier];
|
|
698
|
+
const { choice } = yield* models.resolveFor(spec.orgId, spec.userId);
|
|
699
|
+
const prompt = [
|
|
700
|
+
{ role: "system", content: instructions },
|
|
701
|
+
{ role: "user", content: [{ type: "text", text }] },
|
|
702
|
+
];
|
|
703
|
+
const estimate = countTokens(instructions) + countTokens(text);
|
|
704
|
+
if (room !== undefined && estimate + settings.maxOutputTokens > room.tokens)
|
|
705
|
+
return null;
|
|
706
|
+
const pricing = models.pricing(choice);
|
|
707
|
+
// Metering: the call's worst case is reserved before it is made, and settled with the fold.
|
|
708
|
+
const reservation = yield* metering.reserve({
|
|
709
|
+
orgId: spec.orgId,
|
|
710
|
+
userId: spec.userId,
|
|
711
|
+
runId: spec.runId,
|
|
712
|
+
step: spec.step ?? null,
|
|
713
|
+
kind: "compaction",
|
|
714
|
+
choice,
|
|
715
|
+
pricing,
|
|
716
|
+
inputTokens: estimate,
|
|
717
|
+
maxOutputTokens: settings.maxOutputTokens,
|
|
718
|
+
});
|
|
719
|
+
const generated = yield* models
|
|
720
|
+
.generate({
|
|
721
|
+
orgId: spec.orgId,
|
|
722
|
+
userId: spec.userId,
|
|
723
|
+
model: choice,
|
|
724
|
+
messages: prompt,
|
|
725
|
+
maxOutputTokens: settings.maxOutputTokens,
|
|
726
|
+
timeoutMs: settings.modelCallTimeoutMs,
|
|
727
|
+
})
|
|
728
|
+
.pipe(Effect.onError(() => metering.release(reservation)));
|
|
729
|
+
const summaryId = `${spec.conversationId}:${tier}:${items[items.length - 1].id}`;
|
|
730
|
+
const covers = items.map((m) => m.id);
|
|
731
|
+
const tokensBefore = items.reduce((sum, m) => sum + countTokens(JSON.stringify(m.content ?? null)), 0);
|
|
732
|
+
const tokensAfter = countTokens(generated.text);
|
|
733
|
+
const spans = items.map((m) => m.createdAt).filter((at) => typeof at === "string");
|
|
734
|
+
const content = {
|
|
735
|
+
text: generated.text,
|
|
736
|
+
tier,
|
|
737
|
+
covers,
|
|
738
|
+
tokensBefore,
|
|
739
|
+
tokensAfter,
|
|
740
|
+
// When what it covers was said (an observation is dated).
|
|
741
|
+
from: spans.length === 0 ? null : spans.reduce((a, b) => (a < b ? a : b)),
|
|
742
|
+
to: spans.length === 0 ? null : spans.reduce((a, b) => (a > b ? a : b)),
|
|
743
|
+
};
|
|
744
|
+
const written = yield* authority
|
|
745
|
+
.within(authorityOf, (asserted) => inAgentFor(asserted, sql, Effect.gen(function* () {
|
|
746
|
+
// The call was made: it is metered (and counted in its run) whether or not its fold is the one kept.
|
|
747
|
+
if (yield* settleCall(sql, reservation, generated.usage)) {
|
|
748
|
+
if (spec.runId !== null) {
|
|
749
|
+
yield* sql `UPDATE eloxiv_agent.run SET steps = steps + 1,
|
|
750
|
+
input_tokens = input_tokens + ${generated.usage.inputTokens},
|
|
751
|
+
output_tokens = output_tokens + ${generated.usage.outputTokens} WHERE id = ${spec.runId}`;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
755
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
756
|
+
VALUES (${summaryId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${Math.min(...items.map((m) => m.seq))},
|
|
757
|
+
'summary', ${JSON.stringify(content)}::jsonb, ${generated.text})
|
|
758
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
759
|
+
if (inserted.length === 0)
|
|
760
|
+
return;
|
|
761
|
+
yield* sql `UPDATE eloxiv_agent.message SET covered_by = ${summaryId} WHERE id = ANY(${covers}::text[])`;
|
|
762
|
+
if (spec.runId !== null) {
|
|
763
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "compacted", {
|
|
764
|
+
summaryId,
|
|
765
|
+
tier,
|
|
766
|
+
covers: covers.length,
|
|
767
|
+
tokensBefore,
|
|
768
|
+
tokensAfter,
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
})))
|
|
772
|
+
.pipe(Effect.as(true), Effect.catchTag("SqlError", (e) => Effect.die(e)), Effect.catchTags({ Unauthenticated: () => Effect.succeed(false), Forbidden: () => Effect.succeed(false) }));
|
|
773
|
+
if (!written) {
|
|
774
|
+
yield* inAgent(sql, spec.orgId, settleCall(sql, reservation, generated.usage)).pipe(Effect.orDie);
|
|
775
|
+
return null;
|
|
776
|
+
}
|
|
777
|
+
return {
|
|
778
|
+
summary: {
|
|
779
|
+
id: summaryId,
|
|
780
|
+
conversationId: spec.conversationId,
|
|
781
|
+
covers,
|
|
782
|
+
content: generated.text,
|
|
783
|
+
tokensBefore,
|
|
784
|
+
tokensAfter,
|
|
785
|
+
},
|
|
786
|
+
usage: generated.usage,
|
|
787
|
+
};
|
|
788
|
+
});
|
|
789
|
+
/**
|
|
790
|
+
* Compaction (Memory), in three tiers. The last `keepRecentMessages` messages stay **raw**, verbatim (the kept window
|
|
791
|
+
* starts at a person's message, so no tool call is parted from its result). The older raw messages are folded into an
|
|
792
|
+
* **observation** (a dense, dated record of that stretch); observations accumulate, each covering its own stretch.
|
|
793
|
+
* Once the observations not yet reflected pass `reflectAbove` tokens, they (and an earlier reflection) are folded into
|
|
794
|
+
* a **reflection**, the long-arc summary. Every fold keeps provenance: it lists what it covers, which stays, marked
|
|
795
|
+
* covered by it. Only the compacting person's own messages are folded (in a shared conversation another participant's
|
|
796
|
+
* stay as they are). A run's folds are its model calls: `room.calls` is how many it may make (the reflection is made
|
|
797
|
+
* only with a call to spare), `room.tokens` what they may spend. Returns the last fold and what all of them used, or
|
|
798
|
+
* null when nothing was old enough or nothing fit.
|
|
799
|
+
*/
|
|
800
|
+
export const compactConversation = (spec,
|
|
801
|
+
/**
|
|
802
|
+
* What the compaction reads and writes the transcript under (Authority): a run's, or the person's credential's.
|
|
803
|
+
* Its read, and its writes after each model call, assert it; a write it refuses is not made.
|
|
804
|
+
*/
|
|
805
|
+
authorityOf,
|
|
806
|
+
/** For a run: the model calls and tokens its folds may spend. */
|
|
807
|
+
room) => Effect.gen(function* () {
|
|
808
|
+
const sql = yield* SqlClient.SqlClient;
|
|
809
|
+
const settings = yield* AgentSettings;
|
|
810
|
+
const authority = yield* Authority;
|
|
811
|
+
const read = () => authority
|
|
812
|
+
.within(authorityOf, (asserted) => inAgentFor(asserted, sql,
|
|
813
|
+
// Only the compacting person's own messages: another participant's (in a shared conversation) are theirs,
|
|
814
|
+
// and stay as they are, never folded into this person's tiers.
|
|
815
|
+
sql `SELECT id, role, content, seq::float8 AS seq, created_at::text AS "createdAt"
|
|
816
|
+
FROM eloxiv_agent.message
|
|
817
|
+
WHERE conversation_id = ${spec.conversationId} AND covered_by IS NULL AND user_id = ${spec.userId}
|
|
818
|
+
ORDER BY seq, id`))
|
|
819
|
+
.pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)));
|
|
820
|
+
let calls = 0;
|
|
821
|
+
let tokens = 0;
|
|
822
|
+
let last = null;
|
|
823
|
+
const roomLeft = () => room === undefined ? undefined : { tokens: room.tokens - tokens, calls: room.calls - calls };
|
|
824
|
+
// Observe: the raw messages before the recent window.
|
|
825
|
+
const stored = yield* read();
|
|
826
|
+
const raw = stored.filter((m) => m.role !== "summary");
|
|
827
|
+
let boundary = Math.max(0, raw.length - settings.keepRecentMessages);
|
|
828
|
+
while (boundary > 0 && raw[boundary]?.role !== "user")
|
|
829
|
+
boundary--;
|
|
830
|
+
if (boundary > 0 && (roomLeft()?.calls ?? 1) >= 1) {
|
|
831
|
+
const observed = yield* fold(spec, authorityOf, "observation", raw.slice(0, boundary), roomLeft());
|
|
832
|
+
if (observed !== null) {
|
|
833
|
+
calls += 1;
|
|
834
|
+
tokens += observed.usage.inputTokens + observed.usage.outputTokens;
|
|
835
|
+
last = observed;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
// Reflect: the observations not yet reflected, once they pass the threshold (with an earlier reflection).
|
|
839
|
+
const tiers = (yield* read()).filter((m) => m.role === "summary");
|
|
840
|
+
const observations = tiers.filter((m) => tierOf(m) === "observation");
|
|
841
|
+
const observed = observations.reduce((sum, m) => sum + countTokens(String(m.content?.text ?? "")), 0);
|
|
842
|
+
if (observations.length > 0 && observed > settings.reflectAbove && (roomLeft()?.calls ?? 1) >= 1) {
|
|
843
|
+
const reflections = tiers.filter((m) => tierOf(m) === "reflection");
|
|
844
|
+
const reflected = yield* fold(spec, authorityOf, "reflection", [...reflections, ...observations], roomLeft());
|
|
845
|
+
if (reflected !== null) {
|
|
846
|
+
calls += 1;
|
|
847
|
+
tokens += reflected.usage.inputTokens + reflected.usage.outputTokens;
|
|
848
|
+
last = reflected;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
if (last === null)
|
|
852
|
+
return null;
|
|
853
|
+
return { summary: last.summary, usage: last.usage, calls, tokens };
|
|
854
|
+
});
|
|
855
|
+
// --- model step ------------------------------------------------------------------------------------------------------
|
|
856
|
+
/** Make the call ids of one response unique (a repeated id gets `#2`, `#3`), so each call has its own result. */
|
|
857
|
+
const uniqueCallIds = (calls) => {
|
|
858
|
+
const seen = new Map();
|
|
859
|
+
return calls.map((call) => {
|
|
860
|
+
const n = (seen.get(call.toolCallId) ?? 0) + 1;
|
|
861
|
+
seen.set(call.toolCallId, n);
|
|
862
|
+
return n === 1 ? call : { ...call, toolCallId: `${call.toolCallId}#${n}` };
|
|
863
|
+
});
|
|
864
|
+
};
|
|
865
|
+
const CANCELLED_ERROR = "The run was cancelled";
|
|
866
|
+
const CANCELLED = { kind: "stop", reason: "cancelled", message: CANCELLED_ERROR };
|
|
867
|
+
/**
|
|
868
|
+
* The ancestors of a run (its parent, the parent's parent, up to the person's run) as a recursive CTE fragment named
|
|
869
|
+
* `ancestors (id, depth)`, depth 1 for the parent.
|
|
870
|
+
*/
|
|
871
|
+
const ANCESTORS = (sql, parentRunId) => sql `WITH RECURSIVE ancestors (id, parent, depth) AS (
|
|
872
|
+
SELECT id, parent_run_id, 1 FROM eloxiv_agent.run WHERE id = ${parentRunId}
|
|
873
|
+
UNION ALL
|
|
874
|
+
SELECT r.id, r.parent_run_id, a.depth + 1 FROM eloxiv_agent.run r JOIN ancestors a ON r.id = a.parent
|
|
875
|
+
)`;
|
|
876
|
+
/**
|
|
877
|
+
* Whether any of a sub-agent's ancestors was cancelled or has ended, every ancestor's row held (FOR SHARE) until the
|
|
878
|
+
* caller's transaction ends, the oldest first (false for a run without a parent). A sub-agent is cancelled with every
|
|
879
|
+
* run above it: `agent.cancel` commits a run's flag holding that run's row, so every check of a sub-agent that holds
|
|
880
|
+
* its own row holds all its ancestors' first (always in that order), and sees a cancellation of any of them that
|
|
881
|
+
* committed before it, while one that commits after waits for it. (The kernel's reaction then records the flag on
|
|
882
|
+
* the cancelled run's whole subtree, and wakes each.) A run that ended while seats of its team still ran is the same:
|
|
883
|
+
* its seats (an orphaned seat, too, resumed after a restart) stop at their next check.
|
|
884
|
+
*/
|
|
885
|
+
const parentCancelled = (sql, run) => run.parentRunId === null
|
|
886
|
+
? Effect.succeed(false)
|
|
887
|
+
: sql `${ANCESTORS(sql, run.parentRunId)}
|
|
888
|
+
SELECT r.finished_at IS NOT NULL OR r.cancel_requested_at IS NOT NULL AS cancelled
|
|
889
|
+
FROM eloxiv_agent.run r JOIN ancestors a ON a.id = r.id
|
|
890
|
+
ORDER BY a.depth DESC FOR SHARE OF r`.pipe(Effect.map((rows) => rows.some((row) => row.cancelled)));
|
|
891
|
+
/**
|
|
892
|
+
* The run's row, locked, in the transaction that applies a model's or a device's reply: whether its cancellation
|
|
893
|
+
* (or its parent's) committed. `agent.cancel` locks the same row, so a cancellation either committed first (and the
|
|
894
|
+
* reply is discarded) or commits after the reply is applied (and the run ends cancelled at its finish).
|
|
895
|
+
*/
|
|
896
|
+
const cancelledForUpdate = (sql, spec) => Effect.gen(function* () {
|
|
897
|
+
const parent = yield* parentCancelled(sql, spec);
|
|
898
|
+
const [row] = yield* sql `SELECT cancel_requested_at IS NOT NULL AS cancelled
|
|
899
|
+
FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`;
|
|
900
|
+
return parent || row?.cancelled === true;
|
|
901
|
+
});
|
|
902
|
+
/** The run as processors see it. */
|
|
903
|
+
const processorRun = (spec) => ({
|
|
904
|
+
runId: spec.runId,
|
|
905
|
+
orgId: spec.orgId,
|
|
906
|
+
userId: spec.userId,
|
|
907
|
+
conversationId: spec.conversationId,
|
|
908
|
+
parentRunId: spec.parentRunId,
|
|
909
|
+
});
|
|
910
|
+
const trippedStop = (tripped) => ({
|
|
911
|
+
kind: "stop",
|
|
912
|
+
reason: "processor",
|
|
913
|
+
message: `The processor ${tripped.processor} stopped the run: ${tripped.reason}`,
|
|
914
|
+
});
|
|
915
|
+
const modelStep = (spec, step, consumed, loaded, note = null) => Effect.gen(function* () {
|
|
916
|
+
const sql = yield* SqlClient.SqlClient;
|
|
917
|
+
const settings = yield* AgentSettings;
|
|
918
|
+
const models = yield* ModelProviders;
|
|
919
|
+
const metering = yield* Metering;
|
|
920
|
+
const hub = yield* AgentHub;
|
|
921
|
+
const messageId = `${spec.runId}:m:${step}`;
|
|
922
|
+
const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId };
|
|
923
|
+
const maxOutputTokens = settings.maxOutputTokens;
|
|
924
|
+
const stored = (content) => ({
|
|
925
|
+
kind: "response",
|
|
926
|
+
text: String(content.text ?? ""),
|
|
927
|
+
toolCalls: content.toolCalls ?? [],
|
|
928
|
+
usage: content.usage ?? { inputTokens: 0, outputTokens: 0 },
|
|
929
|
+
calls: content.consumed?.calls ?? 1,
|
|
930
|
+
tokens: content.consumed?.tokens ?? (content.usage?.inputTokens ?? 0) + (content.usage?.outputTokens ?? 0),
|
|
931
|
+
});
|
|
932
|
+
// Fenced: a step that already persisted its response (and was cut off before the journal recorded it)
|
|
933
|
+
// returns that response; one response is applied per step.
|
|
934
|
+
const [persisted] = yield* inTranscript(spec, (sql) => sql `SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`);
|
|
935
|
+
if (persisted !== undefined)
|
|
936
|
+
return stored(persisted.content);
|
|
937
|
+
// Calls this step started whose answers were lost (the process died between the provider's answer and its
|
|
938
|
+
// record): the step runs again and calls the model again, and each lost call is metered, and counted in the
|
|
939
|
+
// run, at what it reserved. Also when the run was cancelled meanwhile: the lost call was made all the same.
|
|
940
|
+
const lost = yield* inAgent(sql, spec.orgId, Effect.gen(function* () {
|
|
941
|
+
const lost = yield* abandonCalls(sql, { orgId: spec.orgId, runId: spec.runId, step });
|
|
942
|
+
if (lost.calls > 0) {
|
|
943
|
+
yield* sql `UPDATE eloxiv_agent.run SET steps = steps + ${lost.calls},
|
|
944
|
+
input_tokens = input_tokens + ${lost.inputTokens}, output_tokens = output_tokens + ${lost.outputTokens}
|
|
945
|
+
WHERE id = ${spec.runId}`;
|
|
946
|
+
}
|
|
947
|
+
return lost;
|
|
948
|
+
}));
|
|
949
|
+
if (yield* isCancelled(spec))
|
|
950
|
+
return CANCELLED;
|
|
951
|
+
let calls = lost.calls;
|
|
952
|
+
let tokens = lost.tokens;
|
|
953
|
+
if (consumed.calls + calls >= spec.limits.maxSteps) {
|
|
954
|
+
return {
|
|
955
|
+
kind: "stop",
|
|
956
|
+
reason: "steps",
|
|
957
|
+
message: `The run reached its step limit (${spec.limits.maxSteps})`,
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
if (Date.now() - spec.startedAt > spec.limits.maxWallMs) {
|
|
961
|
+
return {
|
|
962
|
+
kind: "stop",
|
|
963
|
+
reason: "wall-time",
|
|
964
|
+
message: `The run reached its wall-time limit (${spec.limits.maxWallMs} ms)`,
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
const { offered: tools, deferred } = yield* offeredTools(spec, loaded);
|
|
968
|
+
let context = yield* contextFor(spec, tools, deferred, note);
|
|
969
|
+
const conversationTokens = (context.totals["messages"] ?? 0) + (context.totals["tool-results"] ?? 0);
|
|
970
|
+
// (Only the conversation's owner's runs compact it: a summary another person's run wrote would quote what that
|
|
971
|
+
// person's agent read with their permissions.)
|
|
972
|
+
if (spec.conversationOwner === undefined &&
|
|
973
|
+
conversationTokens > settings.budgets.messages &&
|
|
974
|
+
consumed.calls + calls + 1 < spec.limits.maxSteps) {
|
|
975
|
+
// Over the conversation budget, with room for the compaction and the call: compact, then assemble again.
|
|
976
|
+
// The compaction is one of the run's model calls. A compaction that does not fit the run's tokens or a
|
|
977
|
+
// budget is not made (the call's own checks below then decide).
|
|
978
|
+
// Its folds may take every model call but the one after them.
|
|
979
|
+
const compacted = yield* compactConversation({ ...spec, step }, runAuthority(spec), {
|
|
980
|
+
tokens: spec.limits.maxTokens - consumed.tokens - tokens,
|
|
981
|
+
calls: spec.limits.maxSteps - consumed.calls - calls - 1,
|
|
982
|
+
}).pipe(Effect.catchTag("BudgetExceeded", () => Effect.succeed(null)));
|
|
983
|
+
if (compacted !== null) {
|
|
984
|
+
calls += compacted.calls;
|
|
985
|
+
tokens += compacted.tokens;
|
|
986
|
+
context = yield* contextFor(spec, tools, deferred, note);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
// The run's token limit counts the call's worst case: its context and the most it may write.
|
|
990
|
+
const used = consumed.tokens + tokens;
|
|
991
|
+
if (used + context.total + maxOutputTokens > spec.limits.maxTokens) {
|
|
992
|
+
return {
|
|
993
|
+
kind: "stop",
|
|
994
|
+
reason: "tokens",
|
|
995
|
+
message: `The next model call (about ${context.total} tokens in, up to ${maxOutputTokens} out) would pass the run's token limit (${spec.limits.maxTokens}; ${used} used)`,
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
const resolved = yield* models.resolveFor(spec.orgId, spec.userId).pipe(Effect.result);
|
|
999
|
+
if (resolved._tag === "Failure")
|
|
1000
|
+
return { kind: "stop", reason: "model-error", message: resolved.failure.message };
|
|
1001
|
+
const choice = { success: resolved.success.choice };
|
|
1002
|
+
const pricing = models.pricing(choice.success);
|
|
1003
|
+
// Metering: the call's worst case is reserved before it is made (the call is recorded as started), never after.
|
|
1004
|
+
const reserved = yield* metering
|
|
1005
|
+
.reserve({
|
|
1006
|
+
orgId: spec.orgId,
|
|
1007
|
+
userId: spec.userId,
|
|
1008
|
+
runId: spec.runId,
|
|
1009
|
+
step,
|
|
1010
|
+
kind: "run",
|
|
1011
|
+
choice: choice.success,
|
|
1012
|
+
pricing,
|
|
1013
|
+
inputTokens: context.total,
|
|
1014
|
+
maxOutputTokens,
|
|
1015
|
+
})
|
|
1016
|
+
.pipe(Effect.result);
|
|
1017
|
+
if (reserved._tag === "Failure")
|
|
1018
|
+
return { kind: "stop", reason: "budget", message: reserved.failure.message };
|
|
1019
|
+
const reservation = reserved.success;
|
|
1020
|
+
// This model call of the step: its streamed text is told apart from an earlier call's (one cut off by a restart).
|
|
1021
|
+
const attempt = reservation.id;
|
|
1022
|
+
// The app's processors see each streamed piece; once one trips, nothing more reaches the clients following the
|
|
1023
|
+
// run, and the reply is not applied.
|
|
1024
|
+
const guard = chunkGuard(settings.processors, processorRun(spec), step);
|
|
1025
|
+
const generated = yield* models
|
|
1026
|
+
.generate({
|
|
1027
|
+
orgId: spec.orgId,
|
|
1028
|
+
userId: spec.userId,
|
|
1029
|
+
model: choice.success,
|
|
1030
|
+
messages: context.messages,
|
|
1031
|
+
tools: context.tools,
|
|
1032
|
+
maxOutputTokens,
|
|
1033
|
+
timeoutMs: settings.modelCallTimeoutMs,
|
|
1034
|
+
onDelta: (delta) => {
|
|
1035
|
+
if (guard.push(delta))
|
|
1036
|
+
hub.publish(spec.runId, { step, attempt, delta });
|
|
1037
|
+
},
|
|
1038
|
+
})
|
|
1039
|
+
.pipe(Effect.result);
|
|
1040
|
+
if (generated._tag === "Failure") {
|
|
1041
|
+
yield* metering.release(reservation);
|
|
1042
|
+
const transient = generated.failure.reason === "rate-limited" || generated.failure.reason === "timeout";
|
|
1043
|
+
return {
|
|
1044
|
+
kind: "stop",
|
|
1045
|
+
reason: "model-error",
|
|
1046
|
+
message: generated.failure.message,
|
|
1047
|
+
...(transient ? { retryable: true } : {}),
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
const result = { ...generated.success, toolCalls: uniqueCallIds(generated.success.toolCalls) };
|
|
1051
|
+
const tripped = guard.tripped();
|
|
1052
|
+
calls += 1;
|
|
1053
|
+
tokens += result.usage.inputTokens + result.usage.outputTokens;
|
|
1054
|
+
const inventory = {
|
|
1055
|
+
runId: spec.runId,
|
|
1056
|
+
step,
|
|
1057
|
+
items: context.items,
|
|
1058
|
+
totals: context.totals,
|
|
1059
|
+
budgets: settings.budgets,
|
|
1060
|
+
total: context.total,
|
|
1061
|
+
evicted: context.evicted,
|
|
1062
|
+
};
|
|
1063
|
+
const content = {
|
|
1064
|
+
text: result.text,
|
|
1065
|
+
toolCalls: result.toolCalls,
|
|
1066
|
+
usage: result.usage,
|
|
1067
|
+
model: choice.success,
|
|
1068
|
+
finishReason: result.finishReason,
|
|
1069
|
+
consumed: { calls, tokens },
|
|
1070
|
+
};
|
|
1071
|
+
// The call was made: metered once, whatever happens to its response (counted in the run).
|
|
1072
|
+
const settle = Effect.gen(function* () {
|
|
1073
|
+
if (yield* settleCall(sql, reservation, result.usage)) {
|
|
1074
|
+
yield* sql `UPDATE eloxiv_agent.run SET steps = steps + 1, input_tokens = input_tokens + ${result.usage.inputTokens},
|
|
1075
|
+
output_tokens = output_tokens + ${result.usage.outputTokens} WHERE id = ${spec.runId}`;
|
|
1076
|
+
}
|
|
1077
|
+
});
|
|
1078
|
+
// The reply joins the person's transcript only while the run's authority holds; a refused reply is metered all
|
|
1079
|
+
// the same, and the run ends with the refusal. A reply that arrives after the run's cancellation committed is
|
|
1080
|
+
// metered and recorded as discarded (`reply-discarded`, with its usage), never applied: not in the conversation,
|
|
1081
|
+
// none of its tool calls made, and the run ends cancelled.
|
|
1082
|
+
const applied = yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
1083
|
+
const cancelled = yield* cancelledForUpdate(sql, spec);
|
|
1084
|
+
yield* settle;
|
|
1085
|
+
if (cancelled) {
|
|
1086
|
+
// (A response stored first for this step stays the step's.)
|
|
1087
|
+
const [first] = yield* sql `SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`;
|
|
1088
|
+
if (first !== undefined)
|
|
1089
|
+
return stored(first.content);
|
|
1090
|
+
yield* appendEvent(sql, run, "reply-discarded", {
|
|
1091
|
+
step,
|
|
1092
|
+
attempt,
|
|
1093
|
+
reason: "cancelled",
|
|
1094
|
+
usage: result.usage,
|
|
1095
|
+
toolCalls: result.toolCalls.length,
|
|
1096
|
+
// A late answer: kept (the owner's) for a continuation to see, never acted on.
|
|
1097
|
+
text: result.text,
|
|
1098
|
+
});
|
|
1099
|
+
return CANCELLED;
|
|
1100
|
+
}
|
|
1101
|
+
if (tripped !== undefined) {
|
|
1102
|
+
// A processor stopped the reply: metered (above), recorded, never applied (no message, no tool call).
|
|
1103
|
+
const [first] = yield* sql `SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`;
|
|
1104
|
+
if (first !== undefined)
|
|
1105
|
+
return stored(first.content);
|
|
1106
|
+
yield* appendEvent(sql, run, "processor-tripped", {
|
|
1107
|
+
step,
|
|
1108
|
+
attempt,
|
|
1109
|
+
at: "chunk",
|
|
1110
|
+
processor: tripped.processor,
|
|
1111
|
+
reason: tripped.reason,
|
|
1112
|
+
usage: result.usage,
|
|
1113
|
+
toolCalls: result.toolCalls.length,
|
|
1114
|
+
});
|
|
1115
|
+
return trippedStop(tripped);
|
|
1116
|
+
}
|
|
1117
|
+
const seq = yield* clockSeq(sql);
|
|
1118
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
1119
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
1120
|
+
VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'assistant',
|
|
1121
|
+
${JSON.stringify(content)}::jsonb, ${result.text})
|
|
1122
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
1123
|
+
// One response is applied per step: one stored first wins, and this one's effects never happen.
|
|
1124
|
+
if (inserted.length === 0) {
|
|
1125
|
+
const [first] = yield* sql `SELECT content FROM eloxiv_agent.message WHERE id = ${messageId}`;
|
|
1126
|
+
return stored(first.content);
|
|
1127
|
+
}
|
|
1128
|
+
yield* sql `INSERT INTO eloxiv_agent.inventory (id, org_id, user_id, run_id, step, data)
|
|
1129
|
+
VALUES (${`${spec.runId}:${step}`}, ${spec.orgId}, ${spec.userId}, ${spec.runId}, ${step}, ${JSON.stringify(inventory)}::jsonb)`;
|
|
1130
|
+
yield* appendEvent(sql, run, "model-step", {
|
|
1131
|
+
step,
|
|
1132
|
+
text: result.text,
|
|
1133
|
+
toolCalls: result.toolCalls,
|
|
1134
|
+
usage: result.usage,
|
|
1135
|
+
contextTokens: context.total,
|
|
1136
|
+
});
|
|
1137
|
+
return undefined;
|
|
1138
|
+
})).pipe(Effect.tapError((refusal) => isRefusal(refusal) ? inAgent(sql, spec.orgId, settle).pipe(Effect.orDie) : Effect.void));
|
|
1139
|
+
yield* metering.alert(spec.orgId, spec.userId);
|
|
1140
|
+
if (applied !== undefined)
|
|
1141
|
+
return applied;
|
|
1142
|
+
return {
|
|
1143
|
+
kind: "response",
|
|
1144
|
+
text: result.text,
|
|
1145
|
+
toolCalls: result.toolCalls,
|
|
1146
|
+
usage: result.usage,
|
|
1147
|
+
calls,
|
|
1148
|
+
tokens,
|
|
1149
|
+
};
|
|
1150
|
+
});
|
|
1151
|
+
// --- attachments ------------------------------------------------------------------------------------------------------
|
|
1152
|
+
const READ_TEXT = "files.readText";
|
|
1153
|
+
/**
|
|
1154
|
+
* Read the content of the files attached to the run's message (C-027), each with `files.readText` called as the
|
|
1155
|
+
* person's agent through the invocation path: so only a file the person may read now, under the run's authority and
|
|
1156
|
+
* the agent's reach, audited; a refusal is kept as the reason. Each file's text is bounded (`ATTACHMENT_LIMITS`), and
|
|
1157
|
+
* recorded on the message (`content.attachmentText`, by file id), which the model is shown with the message. Read-only:
|
|
1158
|
+
* a step run again reads again.
|
|
1159
|
+
*/
|
|
1160
|
+
const readAttachments = (spec, key) => Effect.gen(function* () {
|
|
1161
|
+
const [message] = yield* inTranscript(spec, (sql) => sql `SELECT id, content
|
|
1162
|
+
FROM eloxiv_agent.message WHERE run_id = ${spec.runId} AND role = 'user' ORDER BY seq LIMIT 1`);
|
|
1163
|
+
if (message === undefined)
|
|
1164
|
+
return null;
|
|
1165
|
+
const read = {};
|
|
1166
|
+
let left = ATTACHMENT_LIMITS.total;
|
|
1167
|
+
// Each file once, at most `files` of them.
|
|
1168
|
+
const attachments = [...new Map((message.content.attachments ?? []).map((a) => [a.fileId, a])).values()].slice(0, ATTACHMENT_LIMITS.files);
|
|
1169
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
1170
|
+
if (left <= 0) {
|
|
1171
|
+
read[attachment.fileId] = { refused: "LimitReached", message: "The attachments' text limit was reached" };
|
|
1172
|
+
continue;
|
|
1173
|
+
}
|
|
1174
|
+
const limit = Math.min(ATTACHMENT_LIMITS.perFile, left);
|
|
1175
|
+
// A read: a fresh key per attempt, so a step run again after a crash reads the text again (never a replay).
|
|
1176
|
+
const { result, cancelled } = yield* executeTool(spec, { action: READ_TEXT }, { toolCallId: `attachment-${index}`, toolName: "files_readText", input: { fileId: attachment.fileId, limit } }, `${key}:${index}:${crypto.randomUUID()}`);
|
|
1177
|
+
if (cancelled)
|
|
1178
|
+
return null;
|
|
1179
|
+
if (!result.ok) {
|
|
1180
|
+
read[attachment.fileId] = { refused: result.error._tag };
|
|
1181
|
+
continue;
|
|
1182
|
+
}
|
|
1183
|
+
const page = result.output
|
|
1184
|
+
.output;
|
|
1185
|
+
const text = (page?.text ?? "").slice(0, limit);
|
|
1186
|
+
left -= text.length;
|
|
1187
|
+
read[attachment.fileId] = { text, truncated: page?.nextOffset !== null && page?.nextOffset !== undefined };
|
|
1188
|
+
}
|
|
1189
|
+
yield* inTranscript(spec, (sql) => sql `UPDATE eloxiv_agent.message SET content = jsonb_set(content, '{attachmentText}', ${JSON.stringify(read)}::jsonb)
|
|
1190
|
+
WHERE id = ${message.id}`);
|
|
1191
|
+
return null;
|
|
1192
|
+
});
|
|
1193
|
+
// --- tool steps -------------------------------------------------------------------------------------------------------
|
|
1194
|
+
const isCancelled = (spec) => Effect.gen(function* () {
|
|
1195
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1196
|
+
const [state] = yield* inAgent(sql, spec.orgId,
|
|
1197
|
+
// The run's own flag, or any ancestor's (or an ancestor that ended: its seats stop with it).
|
|
1198
|
+
sql `WITH RECURSIVE chain (id, parent, cancelled) AS (
|
|
1199
|
+
SELECT id, parent_run_id, cancel_requested_at IS NOT NULL FROM eloxiv_agent.run WHERE id = ${spec.runId}
|
|
1200
|
+
UNION ALL
|
|
1201
|
+
SELECT r.id, r.parent_run_id, r.cancel_requested_at IS NOT NULL OR r.finished_at IS NOT NULL
|
|
1202
|
+
FROM eloxiv_agent.run r JOIN chain c ON r.id = c.parent
|
|
1203
|
+
) SELECT bool_or(cancelled) AS cancelled FROM chain`);
|
|
1204
|
+
return state?.cancelled === true;
|
|
1205
|
+
});
|
|
1206
|
+
/**
|
|
1207
|
+
* The run's cancellation, checked inside a tool call's own transaction (`InvocationRequest.guard`): it reads the
|
|
1208
|
+
* run's flag and holds the run's row (FOR SHARE) until the call commits, so a cancellation either committed
|
|
1209
|
+
* before (and the call is refused, nothing of it commits) or commits after the call did. `cancelled` is set when
|
|
1210
|
+
* it refuses. It runs in the invocation's fiber (needing nothing from its context, so the invocation's own
|
|
1211
|
+
* transaction connection is the one it uses).
|
|
1212
|
+
*/
|
|
1213
|
+
const cancelGuard = (sql, spec, refused) => Effect.gen(function* () {
|
|
1214
|
+
const cancelled = yield* asAgent(sql, spec.orgId, Effect.gen(function* () {
|
|
1215
|
+
const parent = yield* parentCancelled(sql, spec);
|
|
1216
|
+
const [row] = yield* sql `SELECT cancel_requested_at IS NOT NULL AS cancelled
|
|
1217
|
+
FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR SHARE`;
|
|
1218
|
+
return parent || row?.cancelled === true;
|
|
1219
|
+
})).pipe(Effect.orDie);
|
|
1220
|
+
if (!cancelled)
|
|
1221
|
+
return;
|
|
1222
|
+
refused.cancelled = true;
|
|
1223
|
+
return yield* new Forbidden({ action: "agent.run", message: "The agent run was cancelled; this call did not run" });
|
|
1224
|
+
});
|
|
1225
|
+
/**
|
|
1226
|
+
* Run a tool's action as the run's person, refused inside its transaction if the run was cancelled, unless the
|
|
1227
|
+
* call is the run's own clean-up after its cancellation (`unguarded`: cancelling its device turn).
|
|
1228
|
+
*/
|
|
1229
|
+
const executeTool = (spec, definition, call, key, options = {}) => Effect.gen(function* () {
|
|
1230
|
+
const tools = yield* AgentTools;
|
|
1231
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1232
|
+
const refusal = { cancelled: false };
|
|
1233
|
+
const guard = options.unguarded === true ? undefined : cancelGuard(sql, spec, refusal);
|
|
1234
|
+
const identity = yield* toolIdentity(spec);
|
|
1235
|
+
const agentRun = {
|
|
1236
|
+
runId: spec.runId,
|
|
1237
|
+
conversationId: spec.conversationId,
|
|
1238
|
+
step: options.step ?? 0,
|
|
1239
|
+
toolCallId: call.toolCallId,
|
|
1240
|
+
};
|
|
1241
|
+
const result = yield* tools.execute({
|
|
1242
|
+
action: definition.action,
|
|
1243
|
+
input: call.input,
|
|
1244
|
+
idempotencyKey: key,
|
|
1245
|
+
caller: spec.agentSessionId === null
|
|
1246
|
+
? { identity, agentRun, editGroup: spec.editGroup, ...(guard === undefined ? {} : { guard }) }
|
|
1247
|
+
: {
|
|
1248
|
+
identity,
|
|
1249
|
+
agentSession: spec.agentSessionId,
|
|
1250
|
+
agentRun,
|
|
1251
|
+
editGroup: spec.editGroup,
|
|
1252
|
+
...(guard === undefined ? {} : { guard }),
|
|
1253
|
+
},
|
|
1254
|
+
});
|
|
1255
|
+
return { result, cancelled: refusal.cancelled };
|
|
1256
|
+
});
|
|
1257
|
+
const labelOf = (definition) => ({
|
|
1258
|
+
action: definition.action,
|
|
1259
|
+
title: definition.title,
|
|
1260
|
+
});
|
|
1261
|
+
/**
|
|
1262
|
+
* Persist a tool call's result (once: the message id is the step's) and announce it, with the action and its title
|
|
1263
|
+
* (`label`) when the call is an action's, so a client names it without a table of modules.
|
|
1264
|
+
*/
|
|
1265
|
+
const persistResult = (spec, step, call, raw, consumed, label) => Effect.gen(function* () {
|
|
1266
|
+
const messageId = `${spec.runId}:t:${step}:${call.toolCallId}`;
|
|
1267
|
+
// Stored, journalled and read by the model as JSON (a Date becomes its ISO string): the step's result is
|
|
1268
|
+
// exactly what the conversation holds.
|
|
1269
|
+
const result = JSON.parse(JSON.stringify(raw));
|
|
1270
|
+
// Into the person's transcript only while the run's authority holds.
|
|
1271
|
+
yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
1272
|
+
const seq = yield* clockSeq(sql);
|
|
1273
|
+
const content = { toolCallId: call.toolCallId, toolName: call.toolName, result };
|
|
1274
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
1275
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
1276
|
+
VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'tool',
|
|
1277
|
+
${JSON.stringify(content)}::jsonb, '')
|
|
1278
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
1279
|
+
if (inserted.length > 0) {
|
|
1280
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`;
|
|
1281
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
|
|
1282
|
+
step,
|
|
1283
|
+
toolCallId: call.toolCallId,
|
|
1284
|
+
toolName: call.toolName,
|
|
1285
|
+
...label,
|
|
1286
|
+
ok: result.ok,
|
|
1287
|
+
error: result.ok ? null : result.error._tag,
|
|
1288
|
+
result,
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
}));
|
|
1292
|
+
return (consumed === undefined ? { kind: "result", result } : { kind: "result", result, consumed });
|
|
1293
|
+
});
|
|
1294
|
+
/**
|
|
1295
|
+
* The internal tools that are not actions: the query fallback and `load_skill`. Each reads the person's data with
|
|
1296
|
+
* the capability the run's authority gives (`Authority.within`): refused, audited, once any link of the run's chain
|
|
1297
|
+
* no longer holds, or when the run's scope does not cover the read (a view read is the query surface's).
|
|
1298
|
+
*/
|
|
1299
|
+
const internalTool = (spec, call, key, loaded) => Effect.gen(function* () {
|
|
1300
|
+
const input = (call.input ?? {});
|
|
1301
|
+
const refusedBy = (error) => refused(error._tag, error.message);
|
|
1302
|
+
if (call.toolName === TOOL_SEARCH) {
|
|
1303
|
+
// Over exactly the action tools the run could be offered now (allowed, reachable, plan mode).
|
|
1304
|
+
const { available, actionTools } = yield* availableTools(spec);
|
|
1305
|
+
const searchable = available.filter((tool) => actionTools.has(tool.name));
|
|
1306
|
+
return { ok: true, output: searchTools(call.input, searchable, loaded) };
|
|
1307
|
+
}
|
|
1308
|
+
if (call.toolName === "load_skill") {
|
|
1309
|
+
const resources = yield* AgentResources;
|
|
1310
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1311
|
+
// The same team as the run's context: the conversation's bound team, else the person's active team.
|
|
1312
|
+
const skills = yield* (yield* Authority)
|
|
1313
|
+
.within(runAuthority(spec), (asserted) => teamOfConversation(asserted, sql, spec.conversationId).pipe(Effect.flatMap((team) => resources.effective(asserted, "skill", team))))
|
|
1314
|
+
.pipe(Effect.result);
|
|
1315
|
+
if (skills._tag === "Failure")
|
|
1316
|
+
return refusedBy(skills.failure);
|
|
1317
|
+
const skill = skills.success.find((s) => s.path === input["skill"]);
|
|
1318
|
+
return skill === undefined
|
|
1319
|
+
? refused("InvalidInput", `No skill ${String(input["skill"])}`)
|
|
1320
|
+
: {
|
|
1321
|
+
ok: true,
|
|
1322
|
+
output: { skill: skill.path, scope: skill.scope, content: skill.content },
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
// query: a published view read as the person (read-only, filtered by their read policy), audited as the agent's.
|
|
1326
|
+
const queryViews = yield* QueryViews;
|
|
1327
|
+
const identity = yield* Identity;
|
|
1328
|
+
const audit = yield* Audit;
|
|
1329
|
+
// As the agent session's person (a revoked session stops reads too), or the system actor for a job's run.
|
|
1330
|
+
const actor = yield* (spec.agentSessionId === null
|
|
1331
|
+
? identity.resolve(identityOf(spec))
|
|
1332
|
+
: identity.resolveAgentSession(spec.agentSessionId, identityOf(spec)).pipe(Effect.map((r) => r.actor))).pipe(Effect.result);
|
|
1333
|
+
const view = typeof input["view"] === "string" ? input["view"] : "";
|
|
1334
|
+
const inputHash = yield* Effect.promise(() => sha256(canonicalJson(call.input ?? null)));
|
|
1335
|
+
const record = (outcome, errorTag) => audit.record({
|
|
1336
|
+
invocationId: crypto.randomUUID(),
|
|
1337
|
+
action: "eloxiv.queryView",
|
|
1338
|
+
surface: "agent",
|
|
1339
|
+
actorUserId: spec.userId,
|
|
1340
|
+
orgId: spec.orgId,
|
|
1341
|
+
outcome,
|
|
1342
|
+
inputHash,
|
|
1343
|
+
idempotencyKey: key,
|
|
1344
|
+
errorTag,
|
|
1345
|
+
affected: null,
|
|
1346
|
+
requested: null,
|
|
1347
|
+
completion: null,
|
|
1348
|
+
});
|
|
1349
|
+
if (actor._tag === "Failure") {
|
|
1350
|
+
yield* record("denied", actor.failure._tag);
|
|
1351
|
+
return refused(actor.failure._tag, actor.failure.message);
|
|
1352
|
+
}
|
|
1353
|
+
const limit = typeof input["limit"] === "number" ? Math.min(Math.max(0, input["limit"]), 200) : 50;
|
|
1354
|
+
const rows = yield* (yield* Authority)
|
|
1355
|
+
.within(runAuthority(spec), (asserted) => queryViews.readAs({ asserted, actor: actor.success, view, limit }))
|
|
1356
|
+
.pipe(Effect.result);
|
|
1357
|
+
if (rows._tag === "Failure") {
|
|
1358
|
+
const denied = rows.failure._tag === "Unauthenticated" || rows.failure._tag === "Forbidden";
|
|
1359
|
+
yield* record(denied ? "denied" : "failed", rows.failure._tag);
|
|
1360
|
+
return refusedBy(rows.failure);
|
|
1361
|
+
}
|
|
1362
|
+
yield* record("succeeded", null);
|
|
1363
|
+
// As JSON (timestamps as ISO strings): the result is journalled and stored, and the model reads JSON.
|
|
1364
|
+
return { ok: true, output: { view, rows: JSON.parse(JSON.stringify(rows.success)) } };
|
|
1365
|
+
});
|
|
1366
|
+
/**
|
|
1367
|
+
* A call held for the person's consent: record the run's wait for it, unless the run is cancelled, in one
|
|
1368
|
+
* statement (a cancellation that committed before it is seen here; one that commits after finds the wait and
|
|
1369
|
+
* signals it), and read whether the person already decided (before the wait was recorded, nothing would wake it).
|
|
1370
|
+
*/
|
|
1371
|
+
const holdForConsent = (spec, step, call, action, title, consentId) => Effect.gen(function* () {
|
|
1372
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1373
|
+
const signal = `wait/${step}/${call.toolCallId}`;
|
|
1374
|
+
const waiting = yield* inAgent(sql, spec.orgId, Effect.gen(function* () {
|
|
1375
|
+
// Every ancestor's row held first: a cancellation of any of them that committed before is seen here.
|
|
1376
|
+
if (yield* parentCancelled(sql, spec))
|
|
1377
|
+
return false;
|
|
1378
|
+
const waiting = yield* sql `UPDATE eloxiv_agent.run SET status = 'waiting',
|
|
1379
|
+
wait = ${JSON.stringify({ signal, consentId, toolCallId: call.toolCallId })}::jsonb
|
|
1380
|
+
WHERE id = ${spec.runId} AND cancel_requested_at IS NULL RETURNING id`;
|
|
1381
|
+
if (waiting.length === 0)
|
|
1382
|
+
return false;
|
|
1383
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "consent-required", {
|
|
1384
|
+
step,
|
|
1385
|
+
toolCallId: call.toolCallId,
|
|
1386
|
+
action,
|
|
1387
|
+
// What the person sees it called (the action's title), so a client needs no table of modules.
|
|
1388
|
+
title,
|
|
1389
|
+
consentId,
|
|
1390
|
+
});
|
|
1391
|
+
return true;
|
|
1392
|
+
}));
|
|
1393
|
+
if (!waiting)
|
|
1394
|
+
return { kind: "cancel", signal };
|
|
1395
|
+
const [request] = yield* sql.withTransaction(asSystem(sql, "consent", spec.orgId, sql `SELECT status FROM eloxiv_consent.request WHERE id = ${consentId}`));
|
|
1396
|
+
const decided = request?.status === "approved" || request?.status === "used"
|
|
1397
|
+
? { kind: "consent", status: "approved" }
|
|
1398
|
+
: request?.status === "rejected"
|
|
1399
|
+
? { kind: "consent", status: "rejected" }
|
|
1400
|
+
: null;
|
|
1401
|
+
return { kind: "held", signal, decided };
|
|
1402
|
+
});
|
|
1403
|
+
/**
|
|
1404
|
+
* Apply the person's decision on a held call to the run: back to running (recorded as `consent-decided`). True
|
|
1405
|
+
* when the run was cancelled meanwhile: then nothing runs.
|
|
1406
|
+
*/
|
|
1407
|
+
const consentDecided = (spec, step, call, consentId, approved) => Effect.gen(function* () {
|
|
1408
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1409
|
+
return yield* inAgent(sql, spec.orgId, Effect.gen(function* () {
|
|
1410
|
+
const parent = yield* parentCancelled(sql, spec);
|
|
1411
|
+
const [run] = yield* sql `
|
|
1412
|
+
SELECT status, cancel_requested_at IS NOT NULL AS cancelled FROM eloxiv_agent.run WHERE id = ${spec.runId}
|
|
1413
|
+
FOR UPDATE`;
|
|
1414
|
+
const cancelled = parent || run?.cancelled === true;
|
|
1415
|
+
if (run?.status !== "waiting")
|
|
1416
|
+
return cancelled;
|
|
1417
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`;
|
|
1418
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "consent-decided", {
|
|
1419
|
+
step,
|
|
1420
|
+
toolCallId: call.toolCallId,
|
|
1421
|
+
consentId,
|
|
1422
|
+
status: approved ? "approved" : "rejected",
|
|
1423
|
+
ran: approved && !cancelled,
|
|
1424
|
+
});
|
|
1425
|
+
return cancelled;
|
|
1426
|
+
}));
|
|
1427
|
+
});
|
|
1428
|
+
const toolStep = (spec, step, call, key, loaded) => Effect.gen(function* () {
|
|
1429
|
+
const tools = yield* AgentTools;
|
|
1430
|
+
if (yield* isCancelled(spec))
|
|
1431
|
+
return { kind: "cancelled" };
|
|
1432
|
+
const allowed = allowedTools(yield* runTools(spec.orgId, optionsOf(spec)), spec);
|
|
1433
|
+
if (!allowed.some((t) => t.name === call.toolName)) {
|
|
1434
|
+
return yield* persistResult(spec, step, call, refused("ToolNotAllowed", `This run may not use the tool ${call.toolName}`, { tool: call.toolName }));
|
|
1435
|
+
}
|
|
1436
|
+
const definition = (yield* tools.definitionsFor(spec.orgId)).get(call.toolName);
|
|
1437
|
+
if (definition === undefined)
|
|
1438
|
+
return yield* persistResult(spec, step, call, yield* internalTool(spec, call, key, loaded));
|
|
1439
|
+
// Plan mode: an action that is not read-only is refused here, before the invocation path (it never runs).
|
|
1440
|
+
if (optionsOf(spec).mode === "plan" && !readOnly(yield* Registry, definition.action)) {
|
|
1441
|
+
return yield* persistResult(spec, step, call, refused("PlanMode", `This run is in plan mode: ${definition.action} changes data, so it was not called. Describe it in your plan instead.`, { action: definition.action }), undefined, labelOf(definition));
|
|
1442
|
+
}
|
|
1443
|
+
const { result, cancelled } = yield* executeTool(spec, definition, call, key, { step });
|
|
1444
|
+
if (cancelled)
|
|
1445
|
+
return { kind: "cancelled" };
|
|
1446
|
+
if (!result.ok && result.error._tag === "ConsentRequired") {
|
|
1447
|
+
const consentId = String(result.error["consentId"]);
|
|
1448
|
+
const held = yield* holdForConsent(spec, step, call, definition.action, definition.title, consentId);
|
|
1449
|
+
if (held.kind === "cancel")
|
|
1450
|
+
return { kind: "consent", consentId, signal: held.signal, decided: { kind: "cancel" } };
|
|
1451
|
+
return { kind: "consent", consentId, signal: held.signal, decided: held.decided };
|
|
1452
|
+
}
|
|
1453
|
+
return yield* persistResult(spec, step, call, result, undefined, labelOf(definition));
|
|
1454
|
+
});
|
|
1455
|
+
/**
|
|
1456
|
+
* A tool's result through the app's processors (inside the tool's journalled step): a trip is recorded on the run's
|
|
1457
|
+
* stream (`processor-tripped`) and carried on the outcome, so the run stops before its next model call.
|
|
1458
|
+
*/
|
|
1459
|
+
const processTool = (spec, step, call, outcome) => Effect.gen(function* () {
|
|
1460
|
+
const { processors } = yield* AgentSettings;
|
|
1461
|
+
if (outcome.kind !== "result" || !processors.some((p) => p.onToolResult !== undefined))
|
|
1462
|
+
return outcome;
|
|
1463
|
+
const tripped = yield* toolGuard(processors, { run: processorRun(spec), step, call, result: outcome.result });
|
|
1464
|
+
if (tripped === undefined)
|
|
1465
|
+
return outcome;
|
|
1466
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "processor-tripped", {
|
|
1467
|
+
step,
|
|
1468
|
+
at: "tool-result",
|
|
1469
|
+
toolCallId: call.toolCallId,
|
|
1470
|
+
processor: tripped.processor,
|
|
1471
|
+
reason: tripped.reason,
|
|
1472
|
+
}));
|
|
1473
|
+
return { ...outcome, tripped };
|
|
1474
|
+
});
|
|
1475
|
+
/**
|
|
1476
|
+
* The person decided a held call. A decision that finds the run cancelled is recorded (`consent-decided`, with
|
|
1477
|
+
* `ran: false`) and runs nothing; an approved call runs once, refused inside its transaction if a cancellation
|
|
1478
|
+
* commits before it does.
|
|
1479
|
+
*/
|
|
1480
|
+
const afterConsent = (spec, step, call, decision, consentId, key) => Effect.gen(function* () {
|
|
1481
|
+
const tools = yield* AgentTools;
|
|
1482
|
+
const approved = decision.kind === "consent" && decision.status === "approved";
|
|
1483
|
+
const cancelled = yield* consentDecided(spec, step, call, consentId, approved);
|
|
1484
|
+
if (cancelled)
|
|
1485
|
+
return { kind: "cancelled" };
|
|
1486
|
+
// The tool's definition now: gone when its action was removed while the call waited (a MAKE rollback).
|
|
1487
|
+
const definition = (yield* tools.definitionsFor(spec.orgId)).get(call.toolName);
|
|
1488
|
+
const label = definition === undefined ? undefined : labelOf(definition);
|
|
1489
|
+
if (!approved) {
|
|
1490
|
+
// The decision never needs the definition: its label is omitted when it is gone (a client keeps the one the
|
|
1491
|
+
// held call showed).
|
|
1492
|
+
return yield* persistResult(spec, step, call, refused("ConsentRejected", "The person declined this call; it did not run."), undefined, label);
|
|
1493
|
+
}
|
|
1494
|
+
if (definition === undefined) {
|
|
1495
|
+
return yield* persistResult(spec, step, call, refused("ToolUnavailable", `The tool ${call.toolName} is no longer available (its action was removed while the call waited); it did not run.`, { tool: call.toolName }));
|
|
1496
|
+
}
|
|
1497
|
+
const executed = yield* executeTool(spec, definition, call, key, { step });
|
|
1498
|
+
if (executed.cancelled)
|
|
1499
|
+
return { kind: "cancelled" };
|
|
1500
|
+
return yield* persistResult(spec, step, call, executed.result, undefined, labelOf(definition));
|
|
1501
|
+
});
|
|
1502
|
+
// --- a run on a paired device ------------------------------------------------------------------------------------------
|
|
1503
|
+
/**
|
|
1504
|
+
* A run whose spec names a device executes there (the Daemon contract's integration with the agent runtime): the
|
|
1505
|
+
* device's local harness runs the whole turn on the person's own subscription, so the run asks for it with
|
|
1506
|
+
* `devices.sendTurn` (as the person's agent, so their consent applies), records itself as the turn's parent run,
|
|
1507
|
+
* waits durably for `devices.turnSettled` (the kernel's `devices.settled` reaction signals it), then takes the
|
|
1508
|
+
* turn's answer as its reply, its events as run events and its usage as the run's (recorded with Metering as
|
|
1509
|
+
* subscription usage, which no deployment budget counts).
|
|
1510
|
+
*/
|
|
1511
|
+
const SEND_TURN = "devices.sendTurn";
|
|
1512
|
+
const CANCEL_TURN = "devices.cancelTurn";
|
|
1513
|
+
const DEVICE_CALL_ID = "device";
|
|
1514
|
+
const DeviceSent = Schema.Union([
|
|
1515
|
+
Schema.Struct({ kind: Schema.Literal("sent"), turnId: Schema.String }),
|
|
1516
|
+
Schema.Struct({
|
|
1517
|
+
kind: Schema.Literal("consent"),
|
|
1518
|
+
consentId: Schema.String,
|
|
1519
|
+
signal: Schema.String,
|
|
1520
|
+
decided: Schema.NullOr(Decision),
|
|
1521
|
+
}),
|
|
1522
|
+
Schema.Struct({ kind: Schema.Literal("refused"), message: Schema.String }),
|
|
1523
|
+
Schema.Struct({ kind: Schema.Literal("cancelled") }),
|
|
1524
|
+
]);
|
|
1525
|
+
const DeviceWait = Schema.Union([
|
|
1526
|
+
Schema.Struct({ kind: Schema.Literal("waiting"), signal: Schema.String }),
|
|
1527
|
+
Schema.Struct({ kind: Schema.Literal("settled") }),
|
|
1528
|
+
Schema.Struct({ kind: Schema.Literal("cancelled") }),
|
|
1529
|
+
]);
|
|
1530
|
+
/** The device's turn request: the person's latest message, and the device's options (journalled once). */
|
|
1531
|
+
const deviceCall = (spec, device) => Effect.gen(function* () {
|
|
1532
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1533
|
+
// The person's message, read under the run's authority (a refusal fails the step).
|
|
1534
|
+
const [message] = yield* (yield* Authority)
|
|
1535
|
+
.within(runAuthority(spec), (asserted) => inAgentFor(asserted, sql, sql `SELECT text FROM eloxiv_agent.message
|
|
1536
|
+
WHERE conversation_id = ${spec.conversationId} AND run_id = ${spec.runId} AND role = 'user'
|
|
1537
|
+
ORDER BY seq DESC LIMIT 1`))
|
|
1538
|
+
.pipe(Effect.catchTag("SqlError", (e) => Effect.die(e)));
|
|
1539
|
+
return {
|
|
1540
|
+
toolCallId: DEVICE_CALL_ID,
|
|
1541
|
+
toolName: SEND_TURN,
|
|
1542
|
+
input: { ...device, prompt: message?.text ?? "" },
|
|
1543
|
+
};
|
|
1544
|
+
});
|
|
1545
|
+
/** What a sendTurn result says: the turn it created (from its output, or a replay receipt's created record). */
|
|
1546
|
+
const sentTurn = (result) => {
|
|
1547
|
+
if (!result.ok) {
|
|
1548
|
+
const message = result.error["message"];
|
|
1549
|
+
return { kind: "refused", message: `${result.error._tag}: ${typeof message === "string" ? message : ""}` };
|
|
1550
|
+
}
|
|
1551
|
+
const envelope = result.output;
|
|
1552
|
+
const turnId = envelope.kind === "output" ? envelope.output.turnId : envelope.receipt.created[0];
|
|
1553
|
+
return turnId === undefined
|
|
1554
|
+
? { kind: "refused", message: "The device turn was not created" }
|
|
1555
|
+
: { kind: "sent", turnId };
|
|
1556
|
+
};
|
|
1557
|
+
/** Ask the device for the turn, as the person's agent; a call held for consent suspends the run (as a tool's). */
|
|
1558
|
+
const sendToDevice = (spec, call, key) => Effect.gen(function* () {
|
|
1559
|
+
if (yield* isCancelled(spec))
|
|
1560
|
+
return { kind: "cancelled" };
|
|
1561
|
+
const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId };
|
|
1562
|
+
// The device's request (its prompt) joins the person's run events only while the run's authority holds.
|
|
1563
|
+
const title = actionTitle(yield* Registry, SEND_TURN);
|
|
1564
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, run, "tool-call", {
|
|
1565
|
+
step: 0,
|
|
1566
|
+
toolCallId: call.toolCallId,
|
|
1567
|
+
toolName: call.toolName,
|
|
1568
|
+
action: SEND_TURN,
|
|
1569
|
+
title,
|
|
1570
|
+
input: call.input,
|
|
1571
|
+
}));
|
|
1572
|
+
const { result, cancelled } = yield* executeTool(spec, { action: SEND_TURN }, call, key);
|
|
1573
|
+
if (cancelled)
|
|
1574
|
+
return { kind: "cancelled" };
|
|
1575
|
+
if (!result.ok && result.error._tag === "ConsentRequired") {
|
|
1576
|
+
const consentId = String(result.error["consentId"]);
|
|
1577
|
+
const held = yield* holdForConsent(spec, 0, call, SEND_TURN, title, consentId);
|
|
1578
|
+
return held.kind === "cancel"
|
|
1579
|
+
? { kind: "consent", consentId, signal: held.signal, decided: { kind: "cancel" } }
|
|
1580
|
+
: { kind: "consent", consentId, signal: held.signal, decided: held.decided };
|
|
1581
|
+
}
|
|
1582
|
+
return sentTurn(result);
|
|
1583
|
+
});
|
|
1584
|
+
/**
|
|
1585
|
+
* The device turn the run asked for, in the person's run events: the result of its `devices.sendTurn` call (its
|
|
1586
|
+
* `tool-call` event went before), naming the turn, so a client follows a run on a device to the turn it is.
|
|
1587
|
+
*/
|
|
1588
|
+
const announceTurn = (spec, call, turnId) => Effect.flatMap(Registry, (registry) => inTranscript(spec, (sql) => appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
|
|
1589
|
+
step: 0,
|
|
1590
|
+
toolCallId: call.toolCallId,
|
|
1591
|
+
toolName: call.toolName,
|
|
1592
|
+
action: SEND_TURN,
|
|
1593
|
+
title: actionTitle(registry, SEND_TURN),
|
|
1594
|
+
ok: true,
|
|
1595
|
+
error: null,
|
|
1596
|
+
result: { ok: true, output: { turnId } },
|
|
1597
|
+
}))).pipe(Effect.as(null));
|
|
1598
|
+
/** The person decided the held request: an approved one is sent once (refused if the run was cancelled meanwhile). */
|
|
1599
|
+
const sendAfterConsent = (spec, call, decision, consentId, key) => Effect.gen(function* () {
|
|
1600
|
+
const approved = decision.kind === "consent" && decision.status === "approved";
|
|
1601
|
+
if (yield* consentDecided(spec, 0, call, consentId, approved))
|
|
1602
|
+
return { kind: "cancelled" };
|
|
1603
|
+
if (!approved)
|
|
1604
|
+
return { kind: "refused", message: "The person declined the device turn; it was not sent." };
|
|
1605
|
+
const executed = yield* executeTool(spec, { action: SEND_TURN }, call, key);
|
|
1606
|
+
if (executed.cancelled)
|
|
1607
|
+
return { kind: "cancelled" };
|
|
1608
|
+
return sentTurn(executed.result);
|
|
1609
|
+
});
|
|
1610
|
+
/**
|
|
1611
|
+
* Record the run as the turn's parent and its wait, in one transaction holding the turn's row: a settlement that
|
|
1612
|
+
* committed first is seen here (no wait), one that commits after finds the parent and the wait, and signals it.
|
|
1613
|
+
*/
|
|
1614
|
+
const awaitTurn = (spec, turnId) => Effect.gen(function* () {
|
|
1615
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1616
|
+
const signal = `device/${turnId}`;
|
|
1617
|
+
return yield* sql.withTransaction(Effect.gen(function* () {
|
|
1618
|
+
const [turn] = yield* asSystem(sql, "devices", spec.orgId, sql `UPDATE eloxiv_devices.turn SET parent_run_id = ${spec.runId}
|
|
1619
|
+
WHERE id = ${turnId} AND requested_by = ${spec.userId} RETURNING status`);
|
|
1620
|
+
if (turn === undefined)
|
|
1621
|
+
return yield* Effect.die(new Error(`No device turn ${turnId} for run ${spec.runId}`));
|
|
1622
|
+
if (turn.status !== "queued" && turn.status !== "running")
|
|
1623
|
+
return { kind: "settled" };
|
|
1624
|
+
const waiting = yield* asAgent(sql, spec.orgId, sql `UPDATE eloxiv_agent.run SET status = 'waiting',
|
|
1625
|
+
wait = ${JSON.stringify({ signal, turnId })}::jsonb
|
|
1626
|
+
WHERE id = ${spec.runId} AND cancel_requested_at IS NULL RETURNING id`);
|
|
1627
|
+
return waiting.length === 0 ? { kind: "cancelled" } : { kind: "waiting", signal };
|
|
1628
|
+
}));
|
|
1629
|
+
});
|
|
1630
|
+
/**
|
|
1631
|
+
* Cancel the run's device turn (as the person's agent), when the run is cancelled while the device works. The
|
|
1632
|
+
* run is cancelled by then, so this call is not refused for it (`unguarded`: the cancellation guard of the run's
|
|
1633
|
+
* tool calls refused it, and the turn ran on). A refusal of the cancellation itself is logged as an error.
|
|
1634
|
+
*/
|
|
1635
|
+
const cancelDeviceTurn = (spec, turnId, key) => Effect.gen(function* () {
|
|
1636
|
+
const { result } = yield* executeTool(spec, { action: CANCEL_TURN }, { toolCallId: `${DEVICE_CALL_ID}-cancel`, toolName: CANCEL_TURN, input: { id: turnId } }, key, { unguarded: true });
|
|
1637
|
+
if (!result.ok) {
|
|
1638
|
+
yield* Effect.logError(`Run ${spec.runId}: its device turn ${turnId} was not cancelled`, result.error);
|
|
1639
|
+
}
|
|
1640
|
+
return null;
|
|
1641
|
+
});
|
|
1642
|
+
/** A turn event as the run's: text as a model step's text, tool calls and results as the run's. */
|
|
1643
|
+
const runEventOf = (event) => {
|
|
1644
|
+
const data = (event.data ?? {});
|
|
1645
|
+
switch (event.type) {
|
|
1646
|
+
case "text":
|
|
1647
|
+
return {
|
|
1648
|
+
type: "model-step",
|
|
1649
|
+
data: { step: 0, text: typeof data["text"] === "string" ? data["text"] : "", toolCalls: [], device: true },
|
|
1650
|
+
};
|
|
1651
|
+
case "tool-call":
|
|
1652
|
+
return { type: "tool-call", data: { step: 0, ...data, device: true } };
|
|
1653
|
+
case "tool-result":
|
|
1654
|
+
return { type: "tool-result", data: { step: 0, ...data, device: true } };
|
|
1655
|
+
default:
|
|
1656
|
+
return undefined;
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
/**
|
|
1660
|
+
* Take the settled turn as the run's outcome, once (the reply's message id is the turn's): its result as the
|
|
1661
|
+
* assistant's reply, its events as run events, its usage as the run's and as subscription usage with Metering.
|
|
1662
|
+
*/
|
|
1663
|
+
const takeTurn = (spec, turnId) => Effect.gen(function* () {
|
|
1664
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1665
|
+
const { turn, events } = yield* sql.withTransaction(asSystem(sql, "devices", spec.orgId, Effect.gen(function* () {
|
|
1666
|
+
const [turn] = yield* sql `SELECT status, result, error, harness, model, usage FROM eloxiv_devices.turn WHERE id = ${turnId}`;
|
|
1667
|
+
const events = yield* sql `SELECT type, data FROM eloxiv_devices.turn_event
|
|
1668
|
+
WHERE turn_id = ${turnId} AND attempt = (SELECT attempt FROM eloxiv_devices.turn WHERE id = ${turnId})
|
|
1669
|
+
ORDER BY seq`;
|
|
1670
|
+
return { turn, events };
|
|
1671
|
+
})));
|
|
1672
|
+
if (turn === undefined)
|
|
1673
|
+
return yield* Effect.die(new Error(`No device turn ${turnId}`));
|
|
1674
|
+
const usage = turn.usage ?? { inputTokens: 0, outputTokens: 0, cachedInputTokens: null, costUsd: null };
|
|
1675
|
+
const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId };
|
|
1676
|
+
const text = turn.result ?? "";
|
|
1677
|
+
// The device's reply joins the person's transcript only while the run's authority holds, and only if the run's
|
|
1678
|
+
// cancellation had not committed: then it is metered and recorded as discarded (once), and the run ends cancelled.
|
|
1679
|
+
const discarded = yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
1680
|
+
const cancelled = yield* cancelledForUpdate(sql, spec);
|
|
1681
|
+
const meter = Effect.gen(function* () {
|
|
1682
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'running', wait = NULL, steps = steps + 1,
|
|
1683
|
+
input_tokens = input_tokens + ${usage.inputTokens}, output_tokens = output_tokens + ${usage.outputTokens}
|
|
1684
|
+
WHERE id = ${spec.runId}`;
|
|
1685
|
+
yield* recordSubscriptionUsage(sql, {
|
|
1686
|
+
orgId: spec.orgId,
|
|
1687
|
+
userId: spec.userId,
|
|
1688
|
+
runId: spec.runId,
|
|
1689
|
+
provider: `device:${turn.harness}`,
|
|
1690
|
+
model: turn.model ?? turn.harness,
|
|
1691
|
+
inputTokens: usage.inputTokens,
|
|
1692
|
+
outputTokens: usage.outputTokens,
|
|
1693
|
+
costMicros: Math.round((usage.costUsd ?? 0) * 1_000_000),
|
|
1694
|
+
callId: `device:${turnId}`,
|
|
1695
|
+
});
|
|
1696
|
+
});
|
|
1697
|
+
const [applied] = yield* sql `SELECT id FROM eloxiv_agent.message
|
|
1698
|
+
WHERE id = ${`${spec.runId}:device:${turnId}`}`;
|
|
1699
|
+
if (applied !== undefined)
|
|
1700
|
+
return false;
|
|
1701
|
+
if (cancelled) {
|
|
1702
|
+
const [recorded] = yield* sql `SELECT id FROM eloxiv_agent.run_event
|
|
1703
|
+
WHERE run_id = ${spec.runId} AND type = 'reply-discarded' AND data->>'turnId' = ${turnId}`;
|
|
1704
|
+
if (recorded === undefined) {
|
|
1705
|
+
yield* appendEvent(sql, run, "reply-discarded", {
|
|
1706
|
+
step: 0,
|
|
1707
|
+
turnId,
|
|
1708
|
+
reason: "cancelled",
|
|
1709
|
+
usage: { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens },
|
|
1710
|
+
device: true,
|
|
1711
|
+
text,
|
|
1712
|
+
});
|
|
1713
|
+
yield* meter;
|
|
1714
|
+
}
|
|
1715
|
+
return true;
|
|
1716
|
+
}
|
|
1717
|
+
const seq = yield* clockSeq(sql);
|
|
1718
|
+
const content = { text, toolCalls: [], usage, device: { turnId, harness: turn.harness, model: turn.model } };
|
|
1719
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
1720
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
1721
|
+
VALUES (${`${spec.runId}:device:${turnId}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId},
|
|
1722
|
+
${spec.runId}, ${seq}, 'assistant', ${JSON.stringify(content)}::jsonb, ${text})
|
|
1723
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
1724
|
+
if (inserted.length === 0)
|
|
1725
|
+
return false;
|
|
1726
|
+
for (const event of events) {
|
|
1727
|
+
const mapped = runEventOf(event);
|
|
1728
|
+
if (mapped !== undefined)
|
|
1729
|
+
yield* appendEvent(sql, run, mapped.type, mapped.data);
|
|
1730
|
+
}
|
|
1731
|
+
yield* meter;
|
|
1732
|
+
return false;
|
|
1733
|
+
}));
|
|
1734
|
+
if (discarded)
|
|
1735
|
+
return { status: "cancelled", stopReason: "cancelled", result: null, error: CANCELLED_ERROR };
|
|
1736
|
+
const succeeded = turn.status === "succeeded";
|
|
1737
|
+
return {
|
|
1738
|
+
status: succeeded ? "succeeded" : turn.status === "cancelled" ? "cancelled" : "failed",
|
|
1739
|
+
stopReason: succeeded ? "completed" : turn.status === "cancelled" ? "cancelled" : "error",
|
|
1740
|
+
result: turn.result,
|
|
1741
|
+
error: succeeded ? null : (turn.error ?? `The device turn ${turn.status}`),
|
|
1742
|
+
};
|
|
1743
|
+
});
|
|
1744
|
+
const PLAN_ON_DEVICE = "Plan mode is not available for a run on a device: its harness runs its own tools";
|
|
1745
|
+
/**
|
|
1746
|
+
* A device's answer through the app's processors: its text through `onChunk` (as one piece) and `onFinal`. A trip is
|
|
1747
|
+
* recorded (`processor-tripped`) and returned as the run's error; null when none tripped.
|
|
1748
|
+
*/
|
|
1749
|
+
const deviceCheck = (spec, text) => Effect.gen(function* () {
|
|
1750
|
+
const { processors } = yield* AgentSettings;
|
|
1751
|
+
const guard = chunkGuard(processors, processorRun(spec), 0);
|
|
1752
|
+
guard.push(text);
|
|
1753
|
+
const tripped = guard.tripped() ??
|
|
1754
|
+
(yield* finalGuard(processors, { run: processorRun(spec), text, receipts: [], challenged: true })).tripped;
|
|
1755
|
+
if (tripped === undefined)
|
|
1756
|
+
return null;
|
|
1757
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "processor-tripped", {
|
|
1758
|
+
step: 0,
|
|
1759
|
+
at: "final",
|
|
1760
|
+
device: true,
|
|
1761
|
+
processor: tripped.processor,
|
|
1762
|
+
reason: tripped.reason,
|
|
1763
|
+
}));
|
|
1764
|
+
return trippedStop(tripped).message;
|
|
1765
|
+
});
|
|
1766
|
+
const DeviceOutcome = Schema.Struct({
|
|
1767
|
+
status: Schema.String,
|
|
1768
|
+
stopReason: Schema.String,
|
|
1769
|
+
result: Schema.NullOr(Schema.String),
|
|
1770
|
+
error: Schema.NullOr(Schema.String),
|
|
1771
|
+
});
|
|
1772
|
+
// --- delegation --------------------------------------------------------------------------------------------------------
|
|
1773
|
+
const DelegateInput = Schema.Struct({
|
|
1774
|
+
task: Schema.String,
|
|
1775
|
+
/** A seat's name (the team tool's `spawn`). */
|
|
1776
|
+
name: Schema.optionalKey(Schema.String),
|
|
1777
|
+
tools: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
1778
|
+
profile: Schema.optionalKey(Schema.String),
|
|
1779
|
+
limits: Schema.optionalKey(Schema.Struct({
|
|
1780
|
+
maxSteps: Schema.optionalKey(Schema.Number),
|
|
1781
|
+
maxTokens: Schema.optionalKey(Schema.Number),
|
|
1782
|
+
maxWallMs: Schema.optionalKey(Schema.Number),
|
|
1783
|
+
})),
|
|
1784
|
+
});
|
|
1785
|
+
/**
|
|
1786
|
+
* Start a child run: its tools must all be ones the parent may use (never `delegate`), its limits at most what
|
|
1787
|
+
* the parent has left, and it acts as the same person through the same agent session, so it cannot exceed the
|
|
1788
|
+
* parent's permissions. Returns the child's id and the signal its end sends, or a refusal for the model.
|
|
1789
|
+
*
|
|
1790
|
+
* A seat (`seat`: the team tool's `spawn`) is started the same way, but its parent does not wait: the seat's id is
|
|
1791
|
+
* the tool's result at once, and its limits are reserved from the parent's (`consumed`, which the parent's limits
|
|
1792
|
+
* count until it collects the seat's answer and what it really spent). Its parent keeps a model call of its own.
|
|
1793
|
+
*/
|
|
1794
|
+
const startChild = (spec, step, call, consumed, seat = false) => Effect.gen(function* () {
|
|
1795
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1796
|
+
const outbox = yield* Outbox;
|
|
1797
|
+
if (yield* isCancelled(spec))
|
|
1798
|
+
return { kind: "cancelled" };
|
|
1799
|
+
const decoded = Schema.decodeUnknownOption(DelegateInput)(call.input);
|
|
1800
|
+
if (decoded._tag === "None") {
|
|
1801
|
+
return yield* persistResult(spec, step, call, refused("InvalidInput", "delegate needs a task and a list of tools"));
|
|
1802
|
+
}
|
|
1803
|
+
const request = decoded.value;
|
|
1804
|
+
const options = optionsOf(spec);
|
|
1805
|
+
const { maxDelegationDepth, profiles } = yield* AgentSettings;
|
|
1806
|
+
const profile = request.profile === undefined ? undefined : profiles.find((p) => p.name === request.profile);
|
|
1807
|
+
if (request.profile !== undefined && profile === undefined) {
|
|
1808
|
+
return yield* persistResult(spec, step, call, refused("InvalidInput", `No agent profile ${request.profile}`));
|
|
1809
|
+
}
|
|
1810
|
+
// (A seat's own team tool, for its messages, is a tool it may give only when it may start seats itself.)
|
|
1811
|
+
const parentTools = new Set(allowedTools(yield* runTools(spec.orgId, options), spec)
|
|
1812
|
+
.map((t) => t.name)
|
|
1813
|
+
.filter((name) => name !== TEAM || spawnsSeats(spec, maxDelegationDepth)));
|
|
1814
|
+
// A profile's tools, when the call names none, narrowed to the parent's own.
|
|
1815
|
+
const childTools = request.tools ?? (profile?.tools ?? []).filter((t) => parentTools.has(t));
|
|
1816
|
+
if (request.tools === undefined && profile === undefined) {
|
|
1817
|
+
return yield* persistResult(spec, step, call, refused("InvalidInput", "delegate needs a list of tools (or a profile)"));
|
|
1818
|
+
}
|
|
1819
|
+
// The child is one level deeper; it may delegate (or start seats) only while that is within the deployment's depth.
|
|
1820
|
+
const childMayDelegate = options.depth + 2 <= maxDelegationDepth;
|
|
1821
|
+
const outside = childTools.filter((t) => ((t === "delegate" || t === TEAM) && !childMayDelegate) || t === TOOL_SEARCH || !parentTools.has(t));
|
|
1822
|
+
if (outside.length > 0) {
|
|
1823
|
+
return yield* persistResult(spec, step, call, refused("ToolNotAllowed", `A sub-agent may only use tools this run may use${childMayDelegate ? "" : " (not delegate: the delegation depth is reached)"}: ${outside.join(", ")}`, {
|
|
1824
|
+
tool: outside[0],
|
|
1825
|
+
}));
|
|
1826
|
+
}
|
|
1827
|
+
const childOptions = {
|
|
1828
|
+
mode: options.mode,
|
|
1829
|
+
// A sub-agent is offered its few tools directly.
|
|
1830
|
+
tools: { discovery: "all" },
|
|
1831
|
+
depth: options.depth + 1,
|
|
1832
|
+
...(profile === undefined ? {} : { profile: profile.name }),
|
|
1833
|
+
...(seat ? { seat: (request.name ?? request.task).trim().slice(0, 60) || "seat" } : {}),
|
|
1834
|
+
// Its changes belong to its parent's group: reverting the parent's message undoes them too.
|
|
1835
|
+
...(spec.editGroup === undefined
|
|
1836
|
+
? {}
|
|
1837
|
+
: { editGroup: { conversationId: spec.editGroup.conversationId, messageId: spec.editGroup.messageId } }),
|
|
1838
|
+
};
|
|
1839
|
+
const elapsed = Date.now() - spec.startedAt;
|
|
1840
|
+
// Carved from what the parent has left (its own calls and earlier sub-agents' all count), so the parent and its
|
|
1841
|
+
// sub-agents together never pass the parent's limits.
|
|
1842
|
+
// (A seat's parent goes on while it runs: it keeps one model call for itself, and a seat left without limits gets
|
|
1843
|
+
// a share of what is left, so the parent can start others beside it.)
|
|
1844
|
+
const remaining = {
|
|
1845
|
+
maxSteps: Math.max(0, spec.limits.maxSteps - consumed.calls - (seat ? 1 : 0)),
|
|
1846
|
+
maxTokens: Math.max(0, spec.limits.maxTokens - consumed.tokens),
|
|
1847
|
+
maxWallMs: Math.max(0, spec.limits.maxWallMs - elapsed),
|
|
1848
|
+
};
|
|
1849
|
+
const limits = {
|
|
1850
|
+
maxSteps: Math.min(request.limits?.maxSteps ?? (seat ? Math.min(8, Math.max(1, Math.floor(remaining.maxSteps / 2))) : 8), remaining.maxSteps),
|
|
1851
|
+
maxTokens: Math.min(request.limits?.maxTokens ?? (seat ? Math.floor(remaining.maxTokens / 2) : remaining.maxTokens), remaining.maxTokens),
|
|
1852
|
+
maxWallMs: Math.min(request.limits?.maxWallMs ?? remaining.maxWallMs, remaining.maxWallMs),
|
|
1853
|
+
};
|
|
1854
|
+
if (limits.maxSteps < 1 || limits.maxTokens < 1 || limits.maxWallMs < 1) {
|
|
1855
|
+
return yield* persistResult(spec, step, call, refused("LimitReached", "This run has no budget left to delegate"));
|
|
1856
|
+
}
|
|
1857
|
+
// A sub-agent whose token limit cannot hold even one model call's worst case (its output limit alone) would stop
|
|
1858
|
+
// before doing anything: refuse it now, telling the model why, instead of starting a child that cannot act.
|
|
1859
|
+
const { maxOutputTokens } = yield* AgentSettings;
|
|
1860
|
+
if (limits.maxTokens <= maxOutputTokens) {
|
|
1861
|
+
return yield* persistResult(spec, step, call, request.limits?.maxTokens !== undefined && request.limits.maxTokens < remaining.maxTokens
|
|
1862
|
+
? refused("InvalidInput", `maxTokens ${request.limits.maxTokens} is too small for a sub-agent: each model call needs room for ${maxOutputTokens} output tokens plus its input. Leave maxTokens out, or give more than ${maxOutputTokens}.`)
|
|
1863
|
+
: refused("LimitReached", "This run has too few tokens left to delegate"));
|
|
1864
|
+
}
|
|
1865
|
+
// A sub-agent acts under its parent's agent session and authority: none is started once they no longer hold
|
|
1866
|
+
// (asserted again, locked, in the transaction that creates it).
|
|
1867
|
+
const parentHolds = yield* (yield* Authority).check(runAuthority(spec)).pipe(Effect.result);
|
|
1868
|
+
if (parentHolds._tag === "Failure") {
|
|
1869
|
+
return yield* persistResult(spec, step, call, refused(parentHolds.failure._tag, `This run's authority no longer holds, so it cannot delegate: ${parentHolds.failure.message}`));
|
|
1870
|
+
}
|
|
1871
|
+
const childRunId = `${spec.runId}:sub:${step}:${call.toolCallId}`;
|
|
1872
|
+
const conversationId = `${childRunId}:conversation`;
|
|
1873
|
+
const signal = `child/${childRunId}`;
|
|
1874
|
+
// The child's records as the agent module; its start request in the kernel's outbox, in the same transaction.
|
|
1875
|
+
const created = yield* sql.withTransaction(Effect.gen(function* () {
|
|
1876
|
+
// Authority: the parent's chain still holds, its rows held until the child is recorded.
|
|
1877
|
+
const asserted = yield* (yield* Authority).assert(runAuthority(spec));
|
|
1878
|
+
const created = yield* inAgentFor(asserted, sql, Effect.gen(function* () {
|
|
1879
|
+
// Its ancestors' rows and then its own, locked: a cancellation of any of them committed before is seen, and
|
|
1880
|
+
// one after finds the child (and cancels it, with the whole subtree).
|
|
1881
|
+
if (yield* parentCancelled(sql, spec))
|
|
1882
|
+
return "cancelled";
|
|
1883
|
+
const [parent] = yield* sql `SELECT cancel_requested_at IS NOT NULL AS cancelled
|
|
1884
|
+
FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`;
|
|
1885
|
+
if (parent?.cancelled === true)
|
|
1886
|
+
return "cancelled";
|
|
1887
|
+
// The child inherits the parent's authority: the scope and chain it was started with (and, through its
|
|
1888
|
+
// conversation, the parent's agent session).
|
|
1889
|
+
const created = yield* sql `INSERT INTO eloxiv_agent.run
|
|
1890
|
+
(id, org_id, user_id, conversation_id, parent_run_id, kind, status, task, limits, tools, authority, options)
|
|
1891
|
+
VALUES (${childRunId}, ${spec.orgId}, ${spec.userId}, ${conversationId}, ${spec.runId}, 'subagent', 'queued',
|
|
1892
|
+
${request.task}, ${JSON.stringify(limits)}::jsonb, ${JSON.stringify(childTools)}::jsonb,
|
|
1893
|
+
${spec.authority === undefined || spec.authority === "unrecorded" ? null : JSON.stringify(spec.authority)}::jsonb,
|
|
1894
|
+
${JSON.stringify(childOptions)}::jsonb)
|
|
1895
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
1896
|
+
if (created.length === 0)
|
|
1897
|
+
return false;
|
|
1898
|
+
// The parent's own agent session (the one its calls are made with), never a renewed one.
|
|
1899
|
+
yield* sql `INSERT INTO eloxiv_agent.conversation (id, org_id, user_id, title, agent_session_id)
|
|
1900
|
+
VALUES (${conversationId}, ${spec.orgId}, ${spec.userId}, ${`Sub-agent: ${request.task.slice(0, 60)}`},
|
|
1901
|
+
${spec.agentSessionId})`;
|
|
1902
|
+
const seq = yield* clockSeq(sql);
|
|
1903
|
+
yield* sql `INSERT INTO eloxiv_agent.message (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
1904
|
+
VALUES (${`${childRunId}:task`}, ${spec.orgId}, ${spec.userId}, ${conversationId}, ${childRunId}, ${seq}, 'user',
|
|
1905
|
+
${JSON.stringify({ text: request.task, attachments: [] })}::jsonb, ${request.task})`;
|
|
1906
|
+
yield* appendEvent(sql, { id: childRunId, orgId: spec.orgId, userId: spec.userId }, "run-started", {
|
|
1907
|
+
conversationId,
|
|
1908
|
+
parentRunId: spec.runId,
|
|
1909
|
+
});
|
|
1910
|
+
if (!seat) {
|
|
1911
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'waiting',
|
|
1912
|
+
wait = ${JSON.stringify({ signal, childRunId, toolCallId: call.toolCallId })}::jsonb WHERE id = ${spec.runId}`;
|
|
1913
|
+
}
|
|
1914
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, seat ? "seat-spawned" : "delegated", {
|
|
1915
|
+
step,
|
|
1916
|
+
toolCallId: call.toolCallId,
|
|
1917
|
+
childRunId,
|
|
1918
|
+
task: request.task,
|
|
1919
|
+
tools: childTools,
|
|
1920
|
+
limits,
|
|
1921
|
+
...(profile === undefined ? {} : { profile: profile.name }),
|
|
1922
|
+
...(childOptions.seat === undefined ? {} : { name: childOptions.seat }),
|
|
1923
|
+
depth: childOptions.depth,
|
|
1924
|
+
});
|
|
1925
|
+
return true;
|
|
1926
|
+
}));
|
|
1927
|
+
if (created === true) {
|
|
1928
|
+
yield* outbox.publish({
|
|
1929
|
+
invocationId: childRunId,
|
|
1930
|
+
type: "agent.runRequested",
|
|
1931
|
+
module: AGENT_MODULE,
|
|
1932
|
+
orgId: spec.orgId,
|
|
1933
|
+
payload: { runId: childRunId },
|
|
1934
|
+
});
|
|
1935
|
+
}
|
|
1936
|
+
return created;
|
|
1937
|
+
}));
|
|
1938
|
+
if (created === "cancelled")
|
|
1939
|
+
return { kind: "cancelled" };
|
|
1940
|
+
if (!seat)
|
|
1941
|
+
return { kind: "started", childRunId, signal };
|
|
1942
|
+
// The seat's limits, reserved from the parent's until its answer is collected (a re-run step reserves the same).
|
|
1943
|
+
return yield* persistResult(spec, step, call, { ok: true, output: { seat: childRunId, name: childOptions.seat, status: "running", limits } }, { calls: limits.maxSteps, tokens: limits.maxTokens });
|
|
1944
|
+
});
|
|
1945
|
+
// --- teams --------------------------------------------------------------------------------------------------------------
|
|
1946
|
+
/**
|
|
1947
|
+
* What a sub-agent that ended is charged with, with everything below it, for its parent's limits (each run's counters
|
|
1948
|
+
* are its own model calls only, so the subtree is summed). A run below it that has not ended, or still has a model
|
|
1949
|
+
* call open (a reply in flight, or one lost to a crash and not yet metered), is charged its whole limits: what it may
|
|
1950
|
+
* still spend stays reserved, so a late or abandoned call can never take the parent past its limits.
|
|
1951
|
+
*/
|
|
1952
|
+
const SUBTREE_CHARGE = (sql, runId) => sql `WITH RECURSIVE subtree (id) AS (
|
|
1953
|
+
SELECT id FROM eloxiv_agent.run WHERE id = ${runId}
|
|
1954
|
+
UNION ALL
|
|
1955
|
+
SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
|
|
1956
|
+
), charged AS (
|
|
1957
|
+
SELECT r.steps, r.input_tokens + r.output_tokens AS tokens,
|
|
1958
|
+
r.finished_at IS NULL OR EXISTS (SELECT 1 FROM eloxiv_agent.model_call c
|
|
1959
|
+
WHERE c.run_id = r.id AND c.status = 'started') AS open,
|
|
1960
|
+
coalesce((r.limits->>'maxSteps')::int, 0) AS max_steps, coalesce((r.limits->>'maxTokens')::int, 0) AS max_tokens
|
|
1961
|
+
FROM eloxiv_agent.run r JOIN subtree t ON t.id = r.id
|
|
1962
|
+
)
|
|
1963
|
+
SELECT coalesce(sum(CASE WHEN open THEN greatest(steps, max_steps) ELSE steps END), 0)::int AS calls,
|
|
1964
|
+
coalesce(sum(CASE WHEN open THEN greatest(tokens, max_tokens) ELSE tokens END), 0)::int AS tokens
|
|
1965
|
+
FROM charged`;
|
|
1966
|
+
const TeamInput = Schema.Struct({
|
|
1967
|
+
action: Schema.Literals(["spawn", "wait", "send", "list"]),
|
|
1968
|
+
seats: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
1969
|
+
until: Schema.optionalKey(Schema.Literals(["all", "any"])),
|
|
1970
|
+
to: Schema.optionalKey(Schema.String),
|
|
1971
|
+
text: Schema.optionalKey(Schema.String),
|
|
1972
|
+
});
|
|
1973
|
+
/** A team call's step: its result, or (`wait`) the signal it waits for before it looks again. */
|
|
1974
|
+
const TeamOutcome = Schema.Union([
|
|
1975
|
+
ToolOutcome,
|
|
1976
|
+
Schema.Struct({ kind: Schema.Literal("team-wait"), signal: Schema.String }),
|
|
1977
|
+
]);
|
|
1978
|
+
/**
|
|
1979
|
+
* A team call's result, stored once (the message id is the step's): a step re-run after its result committed returns
|
|
1980
|
+
* the stored one, so the transcript, the journal and the ledger agree on which messages and answers were delivered.
|
|
1981
|
+
* Seats collected give back what they reserved, less what they spent with everything below them.
|
|
1982
|
+
*/
|
|
1983
|
+
const persistTeam = (spec, step, call, raw, ledger) => Effect.gen(function* () {
|
|
1984
|
+
const messageId = `${spec.runId}:t:${step}:${call.toolCallId}`;
|
|
1985
|
+
const result = JSON.parse(JSON.stringify(raw));
|
|
1986
|
+
const stored = yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
1987
|
+
const seq = yield* clockSeq(sql);
|
|
1988
|
+
const content = { toolCallId: call.toolCallId, toolName: call.toolName, result };
|
|
1989
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
1990
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
1991
|
+
VALUES (${messageId}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId}, ${seq}, 'tool',
|
|
1992
|
+
${JSON.stringify(content)}::jsonb, '')
|
|
1993
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
1994
|
+
if (inserted.length === 0) {
|
|
1995
|
+
const [row] = yield* sql `SELECT content->'result' AS result
|
|
1996
|
+
FROM eloxiv_agent.message WHERE id = ${messageId}`;
|
|
1997
|
+
return row?.result ?? result;
|
|
1998
|
+
}
|
|
1999
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'running', wait = NULL WHERE id = ${spec.runId}`;
|
|
2000
|
+
yield* appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "tool-result", {
|
|
2001
|
+
step,
|
|
2002
|
+
toolCallId: call.toolCallId,
|
|
2003
|
+
toolName: call.toolName,
|
|
2004
|
+
ok: result.ok,
|
|
2005
|
+
error: result.ok ? null : result.error._tag,
|
|
2006
|
+
result,
|
|
2007
|
+
});
|
|
2008
|
+
return result;
|
|
2009
|
+
}));
|
|
2010
|
+
const finished = stored.ok ? (stored.output?.finished ?? []) : [];
|
|
2011
|
+
if (finished.length === 0)
|
|
2012
|
+
return { kind: "result", result: stored };
|
|
2013
|
+
const consumed = { calls: 0, tokens: 0 };
|
|
2014
|
+
for (const seat of finished) {
|
|
2015
|
+
const reserved = ledger.reserved[seat.seat] ?? { calls: 0, tokens: 0 };
|
|
2016
|
+
consumed.calls += seat.spent.calls - reserved.calls;
|
|
2017
|
+
consumed.tokens += seat.spent.tokens - reserved.tokens;
|
|
2018
|
+
}
|
|
2019
|
+
return { kind: "result", result: stored, consumed };
|
|
2020
|
+
});
|
|
2021
|
+
/**
|
|
2022
|
+
* The team tool's `wait`, `send` and `list` (`spawn` is `startChild`). In one transaction, under the run's authority,
|
|
2023
|
+
* its ancestors' rows and then its own held (a `wait` holds its own for update): `send` records the message on the
|
|
2024
|
+
* sender's stream, holding the recipient's row, and asks the kernel to wake the recipient; then the run's seats and
|
|
2025
|
+
* the messages addressed to it are read. A `wait` that finds nothing yet records that it waits (`wait.team`), so a
|
|
2026
|
+
* seat that finishes or a message sent after this transaction finds the wait and signals it, and one that committed
|
|
2027
|
+
* before is seen here: no wake-up is lost. Every result carries the messages not yet delivered and the answers of the
|
|
2028
|
+
* seats not yet collected.
|
|
2029
|
+
*/
|
|
2030
|
+
const teamCall = (spec, step, call, k, ledger) => Effect.gen(function* () {
|
|
2031
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2032
|
+
const outbox = yield* Outbox;
|
|
2033
|
+
const decoded = Schema.decodeUnknownOption(TeamInput)(call.input);
|
|
2034
|
+
if (decoded._tag === "None") {
|
|
2035
|
+
return yield* persistTeam(spec, step, call, refused("InvalidInput", 'team needs an action: "spawn", "wait", "send" or "list"'), ledger);
|
|
2036
|
+
}
|
|
2037
|
+
const input = decoded.value;
|
|
2038
|
+
const seat = optionsOf(spec).seat;
|
|
2039
|
+
const lead = seat === undefined ? null : spec.parentRunId;
|
|
2040
|
+
const key = `${spec.runId}:team/${step}/${call.toolCallId}`;
|
|
2041
|
+
const signal = `team/${step}/${call.toolCallId}/${k}`;
|
|
2042
|
+
const me = { id: spec.runId, orgId: spec.orgId, userId: spec.userId };
|
|
2043
|
+
const SEATS = (parent) => sql `SELECT id, options->>'seat' AS name, status, result,
|
|
2044
|
+
finished_at IS NOT NULL AS finished
|
|
2045
|
+
FROM eloxiv_agent.run WHERE parent_run_id = ${parent} AND options ? 'seat' ORDER BY created_at, id`;
|
|
2046
|
+
const read = yield* sql.withTransaction(Effect.gen(function* () {
|
|
2047
|
+
const asserted = yield* (yield* Authority).assert(runAuthority(spec));
|
|
2048
|
+
yield* replying(sql, spec);
|
|
2049
|
+
const read = yield* inAgentFor(asserted, sql, Effect.gen(function* () {
|
|
2050
|
+
if (yield* parentCancelled(sql, spec))
|
|
2051
|
+
return { kind: "cancelled" };
|
|
2052
|
+
const [own] = input.action === "wait"
|
|
2053
|
+
? yield* sql `SELECT cancel_requested_at IS NOT NULL AS cancelled
|
|
2054
|
+
FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR UPDATE`
|
|
2055
|
+
: yield* sql `SELECT cancel_requested_at IS NOT NULL AS cancelled
|
|
2056
|
+
FROM eloxiv_agent.run WHERE id = ${spec.runId} FOR SHARE`;
|
|
2057
|
+
if (own?.cancelled === true)
|
|
2058
|
+
return { kind: "cancelled" };
|
|
2059
|
+
const refusal = (message) => ({ kind: "refused", error: refused("InvalidInput", message) });
|
|
2060
|
+
let sent = null;
|
|
2061
|
+
// A send this step committed before (re-run after a crash before its result was stored) was delivered,
|
|
2062
|
+
// whatever its recipient has done since: it succeeds again, and its recipient was woken then.
|
|
2063
|
+
const [sentBefore] = input.action === "send"
|
|
2064
|
+
? yield* sql `SELECT data->>'to' AS recipient FROM eloxiv_agent.run_event
|
|
2065
|
+
WHERE run_id = ${spec.runId} AND type = 'team-message' AND data->>'key' = ${key}`
|
|
2066
|
+
: [];
|
|
2067
|
+
if (sentBefore !== undefined)
|
|
2068
|
+
sent = sentBefore.recipient;
|
|
2069
|
+
else if (input.action === "send") {
|
|
2070
|
+
const to = input.to === "lead" ? lead : (input.to ?? null);
|
|
2071
|
+
const text = (input.text ?? "").trim();
|
|
2072
|
+
if (text === "")
|
|
2073
|
+
return refusal("send needs a text");
|
|
2074
|
+
// A member of the run's team (its lead, its seats, its lead's other seats), its row held until this
|
|
2075
|
+
// commits: the recipient's wait either saw this message or is woken for it.
|
|
2076
|
+
const [target] = yield* sql `SELECT finished_at IS NOT NULL AS finished
|
|
2077
|
+
FROM eloxiv_agent.run WHERE id = ${to} AND id <> ${spec.runId} AND (id = ${lead} OR parent_run_id = ${spec.runId}
|
|
2078
|
+
OR (parent_run_id = ${lead} AND options ? 'seat')) FOR SHARE`;
|
|
2079
|
+
if (target === undefined)
|
|
2080
|
+
return refusal(`${String(input.to)} is not in your team (list shows who is)`);
|
|
2081
|
+
if (target.finished)
|
|
2082
|
+
return refusal(`${to} has finished; it reads no more messages`);
|
|
2083
|
+
yield* appendEvent(sql, me, "team-message", { key, to, text: text.slice(0, 8_000), name: seat ?? "lead" });
|
|
2084
|
+
sent = to;
|
|
2085
|
+
}
|
|
2086
|
+
// The messages addressed to the run by its team (a sender's own messages are to others).
|
|
2087
|
+
const addressed = yield* sql `
|
|
2088
|
+
SELECT run_id AS "runId", seq, data FROM eloxiv_agent.run_event
|
|
2089
|
+
WHERE type = 'team-message' AND data->>'to' = ${spec.runId} AND run_id IN (SELECT id FROM eloxiv_agent.run
|
|
2090
|
+
WHERE id = ${lead} OR parent_run_id = ${spec.runId} OR (parent_run_id = ${lead} AND options ? 'seat'))
|
|
2091
|
+
ORDER BY at, run_id, seq`;
|
|
2092
|
+
const seats = yield* SEATS(spec.runId);
|
|
2093
|
+
const others = lead === null ? [] : (yield* SEATS(lead)).filter((s) => s.id !== spec.runId);
|
|
2094
|
+
const messages = addressed
|
|
2095
|
+
.filter((m) => m.seq > (ledger.seen[m.runId] ?? -1))
|
|
2096
|
+
.map((m) => ({
|
|
2097
|
+
from: m.runId === lead ? "lead" : m.runId,
|
|
2098
|
+
name: m.data.name ?? "lead",
|
|
2099
|
+
text: m.data.text,
|
|
2100
|
+
seq: m.seq,
|
|
2101
|
+
sender: m.runId,
|
|
2102
|
+
}));
|
|
2103
|
+
const fresh = seats.filter((s) => s.finished && !ledger.collected.includes(s.id));
|
|
2104
|
+
if (input.action === "wait") {
|
|
2105
|
+
const unknown = (input.seats ?? []).filter((id) => !seats.some((s) => s.id === id));
|
|
2106
|
+
if (unknown.length > 0)
|
|
2107
|
+
return refusal(`Not your seats: ${unknown.join(", ")}`);
|
|
2108
|
+
const watched = input.seats === undefined ? seats : seats.filter((s) => input.seats.includes(s.id));
|
|
2109
|
+
const ready = messages.length > 0 ||
|
|
2110
|
+
(watched.length === 0
|
|
2111
|
+
? seat === undefined
|
|
2112
|
+
: input.until === "any"
|
|
2113
|
+
? watched.some((s) => s.finished && !ledger.collected.includes(s.id)) ||
|
|
2114
|
+
watched.every((s) => s.finished)
|
|
2115
|
+
: watched.every((s) => s.finished));
|
|
2116
|
+
if (!ready) {
|
|
2117
|
+
yield* sql `UPDATE eloxiv_agent.run SET status = 'waiting',
|
|
2118
|
+
wait = ${JSON.stringify({ signal, team: true, toolCallId: call.toolCallId })}::jsonb
|
|
2119
|
+
WHERE id = ${spec.runId}`;
|
|
2120
|
+
return { kind: "waiting" };
|
|
2121
|
+
}
|
|
2122
|
+
}
|
|
2123
|
+
// What each seat collected is charged, with everything below it (SUBTREE_CHARGE).
|
|
2124
|
+
const finished = [];
|
|
2125
|
+
for (const s of fresh) {
|
|
2126
|
+
const [spent] = yield* SUBTREE_CHARGE(sql, s.id);
|
|
2127
|
+
finished.push({
|
|
2128
|
+
seat: s.id,
|
|
2129
|
+
name: s.name,
|
|
2130
|
+
status: s.status,
|
|
2131
|
+
result: s.result,
|
|
2132
|
+
spent: { calls: spent?.calls ?? 0, tokens: spent?.tokens ?? 0 },
|
|
2133
|
+
});
|
|
2134
|
+
}
|
|
2135
|
+
return { kind: "ready", seats, others, messages, finished, sent, wakes: sentBefore === undefined };
|
|
2136
|
+
}));
|
|
2137
|
+
if (read.kind === "ready" && read.sent !== null && read.wakes) {
|
|
2138
|
+
yield* outbox.publish({
|
|
2139
|
+
invocationId: key,
|
|
2140
|
+
type: "agent.teamWake",
|
|
2141
|
+
module: AGENT_MODULE,
|
|
2142
|
+
orgId: spec.orgId,
|
|
2143
|
+
payload: { runId: read.sent },
|
|
2144
|
+
});
|
|
2145
|
+
}
|
|
2146
|
+
return read;
|
|
2147
|
+
}));
|
|
2148
|
+
if (read.kind === "cancelled")
|
|
2149
|
+
return { kind: "cancelled" };
|
|
2150
|
+
if (read.kind === "waiting")
|
|
2151
|
+
return { kind: "team-wait", signal };
|
|
2152
|
+
if (read.kind === "refused")
|
|
2153
|
+
return yield* persistTeam(spec, step, call, read.error, ledger);
|
|
2154
|
+
const view = (s) => ({ seat: s.id, name: s.name, status: s.status });
|
|
2155
|
+
const delivered = { finished: read.finished, messages: read.messages };
|
|
2156
|
+
const output = input.action === "list"
|
|
2157
|
+
? { lead, seats: read.seats.map(view), team: read.others.map(view), ...delivered }
|
|
2158
|
+
: input.action === "send"
|
|
2159
|
+
? { sent: read.sent, ...delivered }
|
|
2160
|
+
: { ...delivered, running: read.seats.filter((s) => !s.finished).map(view) };
|
|
2161
|
+
return yield* persistTeam(spec, step, call, { ok: true, output }, ledger);
|
|
2162
|
+
});
|
|
2163
|
+
// --- interrupted turns ------------------------------------------------------------------------------------------------
|
|
2164
|
+
const Reconciled = Schema.Struct({
|
|
2165
|
+
note: Schema.NullOr(Schema.String),
|
|
2166
|
+
/** The receipts of the logical turn's writes so far (recorded or reconciled), the continuation's evidence. */
|
|
2167
|
+
receipts: Schema.optionalKey(Schema.Array(Schema.Struct({ tool: Schema.String, receipt: WriteReceipt }))),
|
|
2168
|
+
});
|
|
2169
|
+
const NOT_RUN = (message) => ({ ok: false, error: { _tag: "NotRun", message } });
|
|
2170
|
+
/**
|
|
2171
|
+
* Before a continuation's first model call (its journalled `reconcile` step): every tool call the run it continues
|
|
2172
|
+
* asked for but never recorded a result of is given its outcome, from the receipt store (C-033), and recorded in the
|
|
2173
|
+
* conversation as that call's result: `completed` (it committed before the interruption: its replay receipt), `unknown`
|
|
2174
|
+
* (it committed, and scheduled external effects the provider has not confirmed) or `not-run` (no receipt: it never
|
|
2175
|
+
* committed, and the run that could have made it has ended). A sub-agent the call started answers with its outcome.
|
|
2176
|
+
* The answers that arrived after that run was cancelled (`reply-discarded`: never applied, none of their tool calls
|
|
2177
|
+
* made) are collected as late answers. The continuation is told all of it (the returned note), and the stream records
|
|
2178
|
+
* it (`reconciled`). A step run again finds the results recorded (their ids are the calls').
|
|
2179
|
+
*/
|
|
2180
|
+
const reconcile = (spec, continuation) => Effect.gen(function* () {
|
|
2181
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2182
|
+
const tools = yield* AgentTools;
|
|
2183
|
+
const invocation = yield* Invocation;
|
|
2184
|
+
const registry = yield* Registry;
|
|
2185
|
+
const authority = yield* Authority;
|
|
2186
|
+
const previous = continuation.previous;
|
|
2187
|
+
// The interrupted run's execution: its tool steps' idempotency keys start with its id.
|
|
2188
|
+
const [execution] = yield* sql `SELECT id FROM eloxiv.workflow_execution
|
|
2189
|
+
WHERE workflow = ${AGENT_RUN_WORKFLOW} AND key = ${previous}`;
|
|
2190
|
+
const read = yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
2191
|
+
const assistant = yield* sql `
|
|
2192
|
+
SELECT id, content FROM eloxiv_agent.message WHERE run_id = ${previous} AND role = 'assistant' ORDER BY seq`;
|
|
2193
|
+
const results = yield* sql `SELECT id FROM eloxiv_agent.message
|
|
2194
|
+
WHERE run_id = ${previous} AND role = 'tool'`;
|
|
2195
|
+
const late = yield* sql `SELECT data FROM eloxiv_agent.run_event
|
|
2196
|
+
WHERE run_id = ${previous} AND type = 'reply-discarded' ORDER BY seq`;
|
|
2197
|
+
const children = yield* sql `
|
|
2198
|
+
SELECT id, status, result, finished_at IS NOT NULL AS finished FROM eloxiv_agent.run
|
|
2199
|
+
WHERE parent_run_id = ${previous}`;
|
|
2200
|
+
return { assistant, results, late, children };
|
|
2201
|
+
}));
|
|
2202
|
+
const recorded = new Set(read.results.map((m) => m.id));
|
|
2203
|
+
const missing = read.assistant.flatMap((message) => {
|
|
2204
|
+
const step = /:m:(\d+)$/u.exec(message.id)?.[1];
|
|
2205
|
+
return step === undefined
|
|
2206
|
+
? []
|
|
2207
|
+
: (message.content.toolCalls ?? [])
|
|
2208
|
+
.filter((call) => !recorded.has(`${previous}:t:${step}:${call.toolCallId}`))
|
|
2209
|
+
.map((call) => ({ step: Number(step), call }));
|
|
2210
|
+
});
|
|
2211
|
+
const definitions = yield* tools.definitionsFor(spec.orgId);
|
|
2212
|
+
const outcomes = [];
|
|
2213
|
+
for (const { step, call } of missing) {
|
|
2214
|
+
let result = NOT_RUN("The interrupted run did not make this call");
|
|
2215
|
+
let outcome = "not-run";
|
|
2216
|
+
const definition = definitions.get(call.toolName);
|
|
2217
|
+
if (call.toolName === "delegate") {
|
|
2218
|
+
const child = read.children.find((c) => c.id === `${previous}:sub:${step}:${call.toolCallId}`);
|
|
2219
|
+
if (child?.finished === true) {
|
|
2220
|
+
result = { ok: true, output: { runId: child.id, status: child.status, result: child.result } };
|
|
2221
|
+
outcome = "completed";
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
else if (definition !== undefined && execution !== undefined) {
|
|
2225
|
+
const key = `${execution.id}:tool/${previous}/${step}/${call.toolCallId}`;
|
|
2226
|
+
let receipt = null;
|
|
2227
|
+
for (const candidate of [key, `${key}/decided`]) {
|
|
2228
|
+
receipt ??= yield* authority.within(runAuthority(spec), (asserted) => invocation.receiptFor(asserted, definition.action, candidate));
|
|
2229
|
+
}
|
|
2230
|
+
if (receipt !== null) {
|
|
2231
|
+
const contract = registry.actions.get(definition.action)?.contract;
|
|
2232
|
+
const envelope = { kind: "replay", receipt };
|
|
2233
|
+
const written = contract === undefined ? undefined : writeReceipt(contract, envelope);
|
|
2234
|
+
result = { ok: true, output: envelope, ...(written === undefined ? {} : { receipt: written }) };
|
|
2235
|
+
outcome = (receipt.effects?.length ?? 0) > 0 ? "unknown" : "completed";
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
const reconciled = outcome;
|
|
2239
|
+
yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
2240
|
+
const seq = yield* clockSeq(sql);
|
|
2241
|
+
const content = { toolCallId: call.toolCallId, toolName: call.toolName, result, reconciled };
|
|
2242
|
+
yield* sql `INSERT INTO eloxiv_agent.message (id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
2243
|
+
VALUES (${`${previous}:t:${step}:${call.toolCallId}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId},
|
|
2244
|
+
${previous}, ${seq}, 'tool', ${JSON.stringify(content)}::jsonb, '')
|
|
2245
|
+
ON CONFLICT (id) DO NOTHING`;
|
|
2246
|
+
}));
|
|
2247
|
+
outcomes.push({ toolCallId: call.toolCallId, tool: call.toolName, outcome });
|
|
2248
|
+
}
|
|
2249
|
+
const late = read.late.flatMap((event) => typeof event.data.text === "string" && event.data.text !== "" ? [event.data.text.slice(0, 2_000)] : []);
|
|
2250
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, { id: spec.runId, orgId: spec.orgId, userId: spec.userId }, "reconciled", {
|
|
2251
|
+
previous,
|
|
2252
|
+
calls: outcomes,
|
|
2253
|
+
late: late.length,
|
|
2254
|
+
}));
|
|
2255
|
+
// The turn's writes so far, by every run of it before this one (their recorded and reconciled results): the
|
|
2256
|
+
// continuation's final answer is checked against them as against its own.
|
|
2257
|
+
const written = yield* inTranscript(spec, (sql) => sql `SELECT m.content->>'toolName' AS tool, m.content->'result'->'receipt' AS receipt
|
|
2258
|
+
FROM eloxiv_agent.message m JOIN eloxiv_agent.run r ON r.id = m.run_id
|
|
2259
|
+
WHERE m.conversation_id = ${spec.conversationId} AND m.role = 'tool' AND r.id <> ${spec.runId}
|
|
2260
|
+
AND (m.content->'result'->>'ok')::boolean AND m.content->'result'->'receipt' IS NOT NULL
|
|
2261
|
+
AND (r.id = ${continuation.of} OR r.options->'continuation'->>'of' = ${continuation.of})
|
|
2262
|
+
ORDER BY m.seq`);
|
|
2263
|
+
const receipts = written.map((row) => ({
|
|
2264
|
+
tool: row.tool,
|
|
2265
|
+
receipt: Schema.decodeUnknownSync(WriteReceipt)(row.receipt),
|
|
2266
|
+
}));
|
|
2267
|
+
const lines = [
|
|
2268
|
+
`You are continuing the person's last request: the run working on it was interrupted (continuation ${continuation.attempt}${continuation.automatic ? ", started automatically after the model failed" : ", asked for by the person"}). Every tool call it asked for is accounted for in the conversation: a result of kind "replay" ran before the interruption, NotRun did not run, and a call marked unknown ran but its external effects are not confirmed yet. Never repeat a call that already ran; go on from where it stopped.`,
|
|
2269
|
+
...(late.length === 0
|
|
2270
|
+
? []
|
|
2271
|
+
: [
|
|
2272
|
+
`These answers arrived after the interruption and were not acted on (nothing they asked for was done):\n${late.map((text) => `- ${text}`).join("\n")}`,
|
|
2273
|
+
]),
|
|
2274
|
+
];
|
|
2275
|
+
return { note: lines.join("\n\n"), receipts };
|
|
2276
|
+
});
|
|
2277
|
+
/**
|
|
2278
|
+
* A person's (or a job's) run that failed transiently continues its logical turn, at most `max` times: a new run (in
|
|
2279
|
+
* the transaction that recorded the failure), with the same authority, limits and options, marked as the turn's next
|
|
2280
|
+
* continuation. Null when the turn has had its continuations, or the run executed on a device.
|
|
2281
|
+
*/
|
|
2282
|
+
const continueAutomatically = (sql, runId, max,
|
|
2283
|
+
/** The interrupted run's effective authority: its record, its chain extended by its agent session. */
|
|
2284
|
+
effective) => Effect.gen(function* () {
|
|
2285
|
+
const [run] = yield* sql `SELECT org_id AS "orgId", user_id AS "userId", conversation_id AS "conversationId", kind, device, limits,
|
|
2286
|
+
authority, options FROM eloxiv_agent.run WHERE id = ${runId}`;
|
|
2287
|
+
if (run === undefined || run.device !== null || run.options === null)
|
|
2288
|
+
return null;
|
|
2289
|
+
const attempt = (run.options.continuation?.attempt ?? 0) + 1;
|
|
2290
|
+
if (attempt > max)
|
|
2291
|
+
return null;
|
|
2292
|
+
const id = crypto.randomUUID();
|
|
2293
|
+
const options = {
|
|
2294
|
+
...run.options,
|
|
2295
|
+
continuation: { of: run.options.continuation?.of ?? runId, previous: runId, attempt, automatic: true },
|
|
2296
|
+
};
|
|
2297
|
+
const json = (value) => (value === null || value === undefined ? null : JSON.stringify(value));
|
|
2298
|
+
yield* sql `INSERT INTO eloxiv_agent.run (id, org_id, user_id, conversation_id, kind, status, authority, limits, options)
|
|
2299
|
+
VALUES (${id}, ${run.orgId}, ${run.userId}, ${run.conversationId}, ${run.kind}, 'queued',
|
|
2300
|
+
${JSON.stringify(effective)}::jsonb, ${json(run.limits)}::jsonb, ${JSON.stringify(options)}::jsonb)`;
|
|
2301
|
+
yield* appendEvent(sql, { id, orgId: run.orgId, userId: run.userId }, "run-started", {
|
|
2302
|
+
conversationId: run.conversationId,
|
|
2303
|
+
continues: runId,
|
|
2304
|
+
automatic: true,
|
|
2305
|
+
});
|
|
2306
|
+
return id;
|
|
2307
|
+
});
|
|
2308
|
+
// --- the final-answer check ---------------------------------------------------------------------------------------
|
|
2309
|
+
const CheckOutcome = Schema.Union([
|
|
2310
|
+
Schema.Struct({ kind: Schema.Literal("retry"), challengedBy: Schema.Array(Schema.String) }),
|
|
2311
|
+
Schema.Struct({ kind: Schema.Literal("abort"), message: Schema.String }),
|
|
2312
|
+
Schema.Struct({
|
|
2313
|
+
kind: Schema.Literal("accept"),
|
|
2314
|
+
result: Schema.String,
|
|
2315
|
+
verification: Schema.NullOr(RunVerificationSchema),
|
|
2316
|
+
}),
|
|
2317
|
+
]);
|
|
2318
|
+
/**
|
|
2319
|
+
* The final answer, checked against the receipts of the run's writes and the app's final-answer processors (in its
|
|
2320
|
+
* own journalled step). A receipt saying a write changed nothing or failed a check, or a processor's challenge, gets
|
|
2321
|
+
* the model challenged once (if the run has a model call left): the challenge joins the conversation as the run's
|
|
2322
|
+
* next user turn (`content.check`), and the model answers again. Receipts still unverified after that annotate the
|
|
2323
|
+
* answer (`Write check: ...`). What the check found is persisted on the run (`verification`) and on its stream
|
|
2324
|
+
* (`answer-checked`); a processor's trip ends the run `stopped`.
|
|
2325
|
+
*/
|
|
2326
|
+
const finalCheck = (spec, step, text, receipts,
|
|
2327
|
+
/** The processors whose challenge the run already answered (it is challenged at most once). */
|
|
2328
|
+
challengers, room) => Effect.gen(function* () {
|
|
2329
|
+
const { processors } = yield* AgentSettings;
|
|
2330
|
+
const run = { id: spec.runId, orgId: spec.orgId, userId: spec.userId };
|
|
2331
|
+
const retried = challengers !== null;
|
|
2332
|
+
const pending = flagged(receipts);
|
|
2333
|
+
const verdict = yield* finalGuard(processors, { run: processorRun(spec), text, receipts, challenged: retried });
|
|
2334
|
+
if (verdict.tripped !== undefined) {
|
|
2335
|
+
const tripped = verdict.tripped;
|
|
2336
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, run, "processor-tripped", {
|
|
2337
|
+
step,
|
|
2338
|
+
at: "final",
|
|
2339
|
+
processor: tripped.processor,
|
|
2340
|
+
reason: tripped.reason,
|
|
2341
|
+
}));
|
|
2342
|
+
return { kind: "abort", message: trippedStop(tripped).message };
|
|
2343
|
+
}
|
|
2344
|
+
const challengedBy = verdict.challenges.map((c) => c.processor);
|
|
2345
|
+
if ((needsChallenge(pending) || verdict.challenges.length > 0) && !retried && room) {
|
|
2346
|
+
const message = checkMessage(pending, verdict.challenges.map((c) => c.message));
|
|
2347
|
+
yield* inTranscript(spec, (sql) => Effect.gen(function* () {
|
|
2348
|
+
const seq = yield* clockSeq(sql);
|
|
2349
|
+
const inserted = yield* sql `INSERT INTO eloxiv_agent.message
|
|
2350
|
+
(id, org_id, user_id, conversation_id, run_id, seq, role, content, text)
|
|
2351
|
+
VALUES (${`${spec.runId}:check:${step}`}, ${spec.orgId}, ${spec.userId}, ${spec.conversationId}, ${spec.runId},
|
|
2352
|
+
${seq}, 'user', ${JSON.stringify({ text: message, attachments: [], check: { receipts: pending, challengedBy } })}::jsonb,
|
|
2353
|
+
${message})
|
|
2354
|
+
ON CONFLICT (id) DO NOTHING RETURNING id`;
|
|
2355
|
+
if (inserted.length > 0) {
|
|
2356
|
+
yield* appendEvent(sql, run, "answer-checked", {
|
|
2357
|
+
step,
|
|
2358
|
+
outcome: "retried",
|
|
2359
|
+
receipts: pending,
|
|
2360
|
+
challengedBy,
|
|
2361
|
+
});
|
|
2362
|
+
}
|
|
2363
|
+
}));
|
|
2364
|
+
return { kind: "retry", challengedBy };
|
|
2365
|
+
}
|
|
2366
|
+
const outcome = pending.length > 0 ? "annotated" : retried ? "retried" : "passed";
|
|
2367
|
+
// Who challenged the answer in this run: before (the challenge answered) or now (not acted on).
|
|
2368
|
+
const challenged = [...new Set([...(challengers ?? []), ...challengedBy])];
|
|
2369
|
+
if (pending.length > 0) {
|
|
2370
|
+
yield* inTranscript(spec, (sql) => appendEvent(sql, run, "answer-checked", { step, outcome, receipts: pending, challengedBy: challenged }));
|
|
2371
|
+
}
|
|
2372
|
+
return {
|
|
2373
|
+
kind: "accept",
|
|
2374
|
+
result: pending.length > 0 ? `${text}${annotation(pending)}` : text,
|
|
2375
|
+
verification: receipts.length === 0 && !retried
|
|
2376
|
+
? null
|
|
2377
|
+
: { outcome, receipts: [...receipts], ...(challenged.length === 0 ? {} : { challengedBy: challenged }) },
|
|
2378
|
+
};
|
|
2379
|
+
});
|
|
2380
|
+
/**
|
|
2381
|
+
* Record a run's outcome (once), end its event stream, and tell its parent. Inside a transaction. A run whose
|
|
2382
|
+
* cancellation committed ends `cancelled`, whatever outcome its execution reached: the one statement that records
|
|
2383
|
+
* the outcome reads the flag on the run's row it locks, and `agent.cancel` locks the same row, so either the
|
|
2384
|
+
* cancellation committed first (and the run ends cancelled) or the outcome did (and the cancellation is refused).
|
|
2385
|
+
* Returns the run's outcome as recorded.
|
|
2386
|
+
*/
|
|
2387
|
+
const recordFinish = (run, outcome) => Effect.gen(function* () {
|
|
2388
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2389
|
+
const outbox = yield* Outbox;
|
|
2390
|
+
const recorded = yield* asAgent(sql, run.orgId, Effect.gen(function* () {
|
|
2391
|
+
// (A sub-agent ends cancelled with its parent.)
|
|
2392
|
+
const parent = yield* parentCancelled(sql, run);
|
|
2393
|
+
const [updated] = yield* sql `UPDATE eloxiv_agent.run
|
|
2394
|
+
SET status = CASE WHEN cancel_requested_at IS NULL AND NOT ${parent} THEN ${outcome.status}
|
|
2395
|
+
ELSE 'cancelled' END,
|
|
2396
|
+
stop_reason = CASE WHEN cancel_requested_at IS NULL AND NOT ${parent} THEN ${outcome.stopReason}
|
|
2397
|
+
ELSE 'cancelled' END,
|
|
2398
|
+
error = CASE WHEN (cancel_requested_at IS NULL AND NOT ${parent}) OR ${outcome.status} = 'cancelled'
|
|
2399
|
+
THEN ${outcome.error} ELSE ${CANCELLED_ERROR} END,
|
|
2400
|
+
result = ${outcome.result}, wait = NULL, finished_at = now(),
|
|
2401
|
+
verification = ${outcome.verification == null ? null : JSON.stringify(outcome.verification)}::jsonb
|
|
2402
|
+
WHERE id = ${run.runId} AND finished_at IS NULL
|
|
2403
|
+
RETURNING status, stop_reason AS "stopReason", result, error,
|
|
2404
|
+
input_tokens AS "inputTokens", output_tokens AS "outputTokens", steps, conversation_id AS "conversationId"`;
|
|
2405
|
+
if (updated === undefined) {
|
|
2406
|
+
// Recorded already (a finish step re-run after its commit): the outcome stored is the run's.
|
|
2407
|
+
const [stored] = yield* sql `SELECT status, stop_reason AS "stopReason", result, error
|
|
2408
|
+
FROM eloxiv_agent.run WHERE id = ${run.runId}`;
|
|
2409
|
+
return { recorded: false, outcome: stored ?? outcome, conversationId: null, orphans: false };
|
|
2410
|
+
}
|
|
2411
|
+
const final = {
|
|
2412
|
+
status: updated.status,
|
|
2413
|
+
stopReason: updated.stopReason,
|
|
2414
|
+
result: updated.result,
|
|
2415
|
+
error: updated.error,
|
|
2416
|
+
};
|
|
2417
|
+
yield* appendEvent(sql, { id: run.runId, orgId: run.orgId, userId: run.userId }, "run-finished", {
|
|
2418
|
+
...final,
|
|
2419
|
+
usage: { inputTokens: updated.inputTokens, outputTokens: updated.outputTokens },
|
|
2420
|
+
steps: updated.steps,
|
|
2421
|
+
});
|
|
2422
|
+
// Seats of its team (or a sub-agent left by a failed execution) still running: they stop with it (each reads
|
|
2423
|
+
// that its ancestor ended at its next check), and the kernel's reaction records it on them and wakes them.
|
|
2424
|
+
const [live] = yield* sql `WITH RECURSIVE subtree (id) AS (
|
|
2425
|
+
SELECT id FROM eloxiv_agent.run WHERE parent_run_id = ${run.runId}
|
|
2426
|
+
UNION ALL
|
|
2427
|
+
SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
|
|
2428
|
+
)
|
|
2429
|
+
SELECT count(*)::int AS n FROM eloxiv_agent.run WHERE id IN (SELECT id FROM subtree) AND finished_at IS NULL`;
|
|
2430
|
+
return {
|
|
2431
|
+
recorded: true,
|
|
2432
|
+
outcome: final,
|
|
2433
|
+
conversationId: updated.conversationId,
|
|
2434
|
+
orphans: (live?.n ?? 0) > 0,
|
|
2435
|
+
};
|
|
2436
|
+
}));
|
|
2437
|
+
// A person's (or a job's) run that failed transiently continues its turn (at most the deployment's number of times);
|
|
2438
|
+
// otherwise, a run that ended makes way for the conversation's next queued message, in the same transaction (each
|
|
2439
|
+
// queued reply's access checked as its sender).
|
|
2440
|
+
const { automaticContinuations } = yield* AgentSettings;
|
|
2441
|
+
const continuing = recorded.recorded &&
|
|
2442
|
+
run.parentRunId === null &&
|
|
2443
|
+
outcome.retryable === true &&
|
|
2444
|
+
recorded.outcome.status === "failed" &&
|
|
2445
|
+
run.spec !== undefined;
|
|
2446
|
+
// The successor acts under the interrupted run's whole chain, its agent session included (a link `runChain` adds):
|
|
2447
|
+
// a session revoked meanwhile is in its chain, so it can act on nothing; and none is started once that chain no
|
|
2448
|
+
// longer holds.
|
|
2449
|
+
const effective = continuing && run.spec !== undefined ? effectiveAuthority(run.spec) : null;
|
|
2450
|
+
const holds = effective === null
|
|
2451
|
+
? false
|
|
2452
|
+
: (yield* (yield* Authority).check(runAuthority(run.spec)).pipe(Effect.result))._tag === "Success";
|
|
2453
|
+
const continued = effective !== null && holds
|
|
2454
|
+
? yield* asAgent(sql, run.orgId, continueAutomatically(sql, run.runId, automaticContinuations, effective))
|
|
2455
|
+
: null;
|
|
2456
|
+
const promoted = continued !== null
|
|
2457
|
+
? continued
|
|
2458
|
+
: recorded.recorded && run.parentRunId === null
|
|
2459
|
+
? yield* promoteQueued(sql, { orgId: run.orgId, userId: run.userId, conversationId: recorded.conversationId })
|
|
2460
|
+
: null;
|
|
2461
|
+
if (promoted !== null) {
|
|
2462
|
+
yield* outbox.publish({
|
|
2463
|
+
invocationId: promoted,
|
|
2464
|
+
type: "agent.runRequested",
|
|
2465
|
+
module: AGENT_MODULE,
|
|
2466
|
+
orgId: run.orgId,
|
|
2467
|
+
payload: { runId: promoted },
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
if (recorded.orphans) {
|
|
2471
|
+
yield* outbox.publish({
|
|
2472
|
+
invocationId: run.runId,
|
|
2473
|
+
type: "agent.cancelRequested",
|
|
2474
|
+
module: AGENT_MODULE,
|
|
2475
|
+
orgId: run.orgId,
|
|
2476
|
+
payload: { runId: run.runId },
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
if (recorded.recorded && run.parentRunId !== null) {
|
|
2480
|
+
yield* outbox.publish({
|
|
2481
|
+
invocationId: run.runId,
|
|
2482
|
+
type: "agent.runFinished",
|
|
2483
|
+
module: AGENT_MODULE,
|
|
2484
|
+
orgId: run.orgId,
|
|
2485
|
+
payload: {
|
|
2486
|
+
runId: run.runId,
|
|
2487
|
+
parentRunId: run.parentRunId,
|
|
2488
|
+
status: recorded.outcome.status,
|
|
2489
|
+
result: recorded.outcome.result,
|
|
2490
|
+
},
|
|
2491
|
+
});
|
|
2492
|
+
}
|
|
2493
|
+
return recorded.outcome;
|
|
2494
|
+
});
|
|
2495
|
+
const finishRun = (spec, outcome) => Effect.gen(function* () {
|
|
2496
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2497
|
+
const recorded = yield* sql.withTransaction(recordFinish({ ...spec, spec }, outcome));
|
|
2498
|
+
return { status: recorded.status, stopReason: recorded.stopReason, result: recorded.result };
|
|
2499
|
+
});
|
|
2500
|
+
/**
|
|
2501
|
+
* The run's execution failed outside the loop's own handling (its start, its finish, a defect): the run ends
|
|
2502
|
+
* `failed` all the same, its stream closes, its parent hears, and a model call it left open is metered as lost.
|
|
2503
|
+
*/
|
|
2504
|
+
const failRun = (runId, orgId, message) => Effect.gen(function* () {
|
|
2505
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2506
|
+
yield* sql.withTransaction(Effect.gen(function* () {
|
|
2507
|
+
const run = yield* asAgent(sql, orgId, Effect.gen(function* () {
|
|
2508
|
+
const [run] = yield* sql `SELECT user_id AS "userId",
|
|
2509
|
+
parent_run_id AS "parentRunId" FROM eloxiv_agent.run WHERE id = ${runId} AND finished_at IS NULL FOR UPDATE`;
|
|
2510
|
+
if (run === undefined)
|
|
2511
|
+
return undefined;
|
|
2512
|
+
const lost = yield* abandonCalls(sql, { orgId, runId });
|
|
2513
|
+
if (lost.calls > 0) {
|
|
2514
|
+
yield* sql `UPDATE eloxiv_agent.run SET steps = steps + ${lost.calls},
|
|
2515
|
+
input_tokens = input_tokens + ${lost.inputTokens}, output_tokens = output_tokens + ${lost.outputTokens}
|
|
2516
|
+
WHERE id = ${runId}`;
|
|
2517
|
+
}
|
|
2518
|
+
return run;
|
|
2519
|
+
}));
|
|
2520
|
+
if (run === undefined)
|
|
2521
|
+
return;
|
|
2522
|
+
yield* recordFinish({ runId, orgId, userId: run.userId, parentRunId: run.parentRunId }, { status: "failed", stopReason: "error", result: null, error: message.slice(0, 2_000) });
|
|
2523
|
+
}));
|
|
2524
|
+
});
|
|
2525
|
+
/** What a finished sub-agent is charged, with everything below it, for its parent's limits (SUBTREE_CHARGE). */
|
|
2526
|
+
const childConsumed = (spec, childRunId) => Effect.gen(function* () {
|
|
2527
|
+
const sql = yield* SqlClient.SqlClient;
|
|
2528
|
+
const [child] = yield* inAgent(sql, spec.orgId, SUBTREE_CHARGE(sql, childRunId));
|
|
2529
|
+
return { calls: child?.calls ?? 0, tokens: child?.tokens ?? 0 };
|
|
2530
|
+
});
|
|
2531
|
+
// --- the workflow -------------------------------------------------------------------------------------------------------
|
|
2532
|
+
export const agentRunWorkflow = defineKernelWorkflow({
|
|
2533
|
+
name: AGENT_RUN_WORKFLOW,
|
|
2534
|
+
input: Schema.Struct({ runId: Schema.String }),
|
|
2535
|
+
output: Finished,
|
|
2536
|
+
run: ({ runId }, ctx) => Effect.gen(function* () {
|
|
2537
|
+
const services = yield* Effect.context();
|
|
2538
|
+
const R = (what) => withServices(services, what);
|
|
2539
|
+
const spec = yield* ctx.step("start", Spec, () => R("start")(startRun(runId, ctx.identity.orgId)));
|
|
2540
|
+
const finish = (status, stopReason, result, error = null, verification = null, retryable = false) => ctx.step("finish", Finished, () => R("finish")(finishRun(spec, { status, stopReason, result, error, verification, retryable })));
|
|
2541
|
+
const device = spec.device;
|
|
2542
|
+
const checksDevice = (yield* AgentSettings).processors.some((p) => p.onChunk !== undefined || p.onFinal !== undefined);
|
|
2543
|
+
if (device !== undefined && device !== null) {
|
|
2544
|
+
// The run executes on the person's device: one turn there, waited for durably, is the whole run. Plan mode
|
|
2545
|
+
// cannot be enforced there (the device's harness runs its own tools), so such a run is refused (`agent.send`
|
|
2546
|
+
// refuses it too).
|
|
2547
|
+
if (optionsOf(spec).mode === "plan") {
|
|
2548
|
+
return yield* finish("failed", "error", null, PLAN_ON_DEVICE);
|
|
2549
|
+
}
|
|
2550
|
+
const deviceRun = Effect.gen(function* () {
|
|
2551
|
+
const call = yield* ctx.step("device/call", ToolCallSchema, () => R("device turn")(deviceCall(spec, device)));
|
|
2552
|
+
let sent = yield* ctx.step("device/send", DeviceSent, (key) => R("device turn")(sendToDevice(spec, call, key)));
|
|
2553
|
+
if (sent.kind === "consent") {
|
|
2554
|
+
const decision = sent.decided ?? (yield* ctx.waitForSignal(sent.signal, Decision));
|
|
2555
|
+
if (decision.kind === "cancel")
|
|
2556
|
+
return yield* finish("cancelled", "cancelled", null, "The run was cancelled");
|
|
2557
|
+
const consentId = sent.consentId;
|
|
2558
|
+
sent = yield* ctx.step("device/send/decided", DeviceSent, (key) => R("device turn")(sendAfterConsent(spec, call, decision, consentId, key)));
|
|
2559
|
+
}
|
|
2560
|
+
if (sent.kind === "cancelled")
|
|
2561
|
+
return yield* finish("cancelled", "cancelled", null, "The run was cancelled");
|
|
2562
|
+
if (sent.kind !== "sent") {
|
|
2563
|
+
return yield* finish("failed", "error", null, sent.kind === "refused" ? sent.message : "The turn was not sent");
|
|
2564
|
+
}
|
|
2565
|
+
const turnId = sent.turnId;
|
|
2566
|
+
yield* ctx.step("device/sent", Schema.Null, () => R("device turn")(announceTurn(spec, call, turnId)));
|
|
2567
|
+
const wait = yield* ctx.step("device/wait", DeviceWait, () => R("device turn")(awaitTurn(spec, turnId)));
|
|
2568
|
+
const woken = wait.kind === "waiting" ? yield* ctx.waitForSignal(wait.signal, Decision) : undefined;
|
|
2569
|
+
if (wait.kind === "cancelled" || woken?.kind === "cancel") {
|
|
2570
|
+
yield* ctx.step("device/cancel", Schema.Null, (key) => R("device turn")(cancelDeviceTurn(spec, turnId, key)));
|
|
2571
|
+
return yield* finish("cancelled", "cancelled", null, "The run was cancelled");
|
|
2572
|
+
}
|
|
2573
|
+
const outcome = yield* ctx.step("device/result", DeviceOutcome, () => R("device turn")(takeTurn(spec, turnId)));
|
|
2574
|
+
// The app's processors see the device's answer as they see a model's (its text, then the final answer); a
|
|
2575
|
+
// trip stops the run. The answer was the device's whole turn, so a challenge cannot be acted on.
|
|
2576
|
+
if (outcome.status === "succeeded" && checksDevice) {
|
|
2577
|
+
const tripped = yield* ctx.step("device/check", Schema.NullOr(Schema.String), () => R("device turn")(deviceCheck(spec, outcome.result ?? "")));
|
|
2578
|
+
if (tripped !== null)
|
|
2579
|
+
return yield* finish("stopped", "processor", outcome.result, tripped);
|
|
2580
|
+
}
|
|
2581
|
+
return yield* finish(outcome.status, outcome.stopReason, outcome.result, outcome.error);
|
|
2582
|
+
});
|
|
2583
|
+
return yield* deviceRun.pipe(Effect.catchTag("WorkflowFailed", (failure) => finish("failed", "error", null, failure.message)));
|
|
2584
|
+
}
|
|
2585
|
+
// What the run has spent of its limits: its model calls (compaction and lost attempts included) and its
|
|
2586
|
+
// sub-agents', and their tokens. From journalled step results only, so a replay counts the same.
|
|
2587
|
+
// The attached files' content, read once as the person's agent before the first model call.
|
|
2588
|
+
// A continuation of an interrupted turn: an automatic one waits out its backoff, then every continuation first
|
|
2589
|
+
// reconciles what the run it continues did (journalled), and is told so.
|
|
2590
|
+
const continuation = optionsOf(spec).continuation;
|
|
2591
|
+
let note = null;
|
|
2592
|
+
let inherited = [];
|
|
2593
|
+
if (continuation !== undefined) {
|
|
2594
|
+
const { continuationBackoffMs } = yield* AgentSettings;
|
|
2595
|
+
if (continuation.automatic && continuationBackoffMs > 0) {
|
|
2596
|
+
yield* ctx.sleep("continuation/backoff", continuationBackoffMs * 2 ** (continuation.attempt - 1));
|
|
2597
|
+
}
|
|
2598
|
+
const reconciled = yield* ctx.step("reconcile", Reconciled, () => R("reconcile")(reconcile(spec, continuation)));
|
|
2599
|
+
note = reconciled.note;
|
|
2600
|
+
inherited = reconciled.receipts ?? [];
|
|
2601
|
+
}
|
|
2602
|
+
if ((optionsOf(spec).attachments ?? 0) > 0) {
|
|
2603
|
+
yield* ctx.step("attachments", Schema.Null, (key) => R("attachments")(readAttachments(spec, key)));
|
|
2604
|
+
}
|
|
2605
|
+
const consumed = { calls: 0, tokens: 0 };
|
|
2606
|
+
let last = "";
|
|
2607
|
+
// Also from journalled results only: the tools the run loaded with tool_search, the receipts of its writes, and
|
|
2608
|
+
// whether its answer was challenged already.
|
|
2609
|
+
const loaded = new Set();
|
|
2610
|
+
// A continuation starts from its logical turn's writes (journalled in its `reconcile` step).
|
|
2611
|
+
const receipts = [...inherited];
|
|
2612
|
+
// The processors whose challenge was answered, once the answer was challenged (null before).
|
|
2613
|
+
let challengers = null;
|
|
2614
|
+
const { processors, maxDelegationDepth } = yield* AgentSettings;
|
|
2615
|
+
const checksAnswers = processors.some((p) => p.onFinal !== undefined);
|
|
2616
|
+
// The run's team (also from journalled results only): see TeamLedger.
|
|
2617
|
+
const team = {
|
|
2618
|
+
seen: {},
|
|
2619
|
+
collected: [],
|
|
2620
|
+
reserved: {},
|
|
2621
|
+
};
|
|
2622
|
+
const loop = Effect.gen(function* () {
|
|
2623
|
+
for (let step = 0;; step++) {
|
|
2624
|
+
if (consumed.calls >= spec.limits.maxSteps) {
|
|
2625
|
+
return yield* finish("stopped", "steps", last || null, `The run reached its step limit (${spec.limits.maxSteps})`);
|
|
2626
|
+
}
|
|
2627
|
+
const spent = { ...consumed };
|
|
2628
|
+
const offered = new Set(loaded);
|
|
2629
|
+
const outcome = yield* ctx.step(`model/${step}`, ModelOutcome, () => R("model call")(modelStep(spec, step, spent, offered, note)));
|
|
2630
|
+
if (outcome.kind === "stop") {
|
|
2631
|
+
const status = outcome.reason === "cancelled" ? "cancelled" : outcome.reason === "model-error" ? "failed" : "stopped";
|
|
2632
|
+
return yield* finish(status, outcome.reason, last || null, outcome.message, null, "retryable" in outcome && outcome.retryable);
|
|
2633
|
+
}
|
|
2634
|
+
consumed.calls += outcome.calls ?? 1;
|
|
2635
|
+
consumed.tokens += outcome.tokens ?? outcome.usage.inputTokens + outcome.usage.outputTokens;
|
|
2636
|
+
if (outcome.text.length > 0)
|
|
2637
|
+
last = outcome.text;
|
|
2638
|
+
if (outcome.toolCalls.length === 0) {
|
|
2639
|
+
// Nothing to check (no write left unverified, no final-answer processor, no challenge answered): the answer
|
|
2640
|
+
// stands, with its writes' receipts as the run's evidence, decided from journalled results alone.
|
|
2641
|
+
if (flagged(receipts).length === 0 && !checksAnswers && challengers === null) {
|
|
2642
|
+
return yield* finish("succeeded", "completed", outcome.text, null, receipts.length === 0 ? null : { outcome: "passed", receipts: [...receipts] });
|
|
2643
|
+
}
|
|
2644
|
+
const answer = outcome.text;
|
|
2645
|
+
const check = yield* ctx.step(`check/${step}`, CheckOutcome, () => R("answer check")(finalCheck(spec, step, answer, [...receipts], challengers, consumed.calls < spec.limits.maxSteps)));
|
|
2646
|
+
if (check.kind === "retry") {
|
|
2647
|
+
challengers = check.challengedBy;
|
|
2648
|
+
continue;
|
|
2649
|
+
}
|
|
2650
|
+
if (check.kind === "abort")
|
|
2651
|
+
return yield* finish("stopped", "processor", answer || null, check.message);
|
|
2652
|
+
return yield* finish("succeeded", "completed", check.result, null, check.verification);
|
|
2653
|
+
}
|
|
2654
|
+
for (const call of outcome.toolCalls) {
|
|
2655
|
+
// A job's run that found nothing to do: it ends a no-op (the execution's typed outcome too), with the reason.
|
|
2656
|
+
if (call.toolName === "no_op" && spec.kind === "job") {
|
|
2657
|
+
const given = call.input?.reason;
|
|
2658
|
+
const reason = (typeof given === "string" && given.trim() !== "" ? given.trim() : "Nothing to do").slice(0, 500);
|
|
2659
|
+
yield* ctx.noop(reason);
|
|
2660
|
+
return yield* finish("succeeded", "noop", reason);
|
|
2661
|
+
}
|
|
2662
|
+
// The run's id is in the step's name, so its idempotency key (and every audit record of the call)
|
|
2663
|
+
// names the run: `<execution id>:tool/<run id>/<step>/<tool call id>`.
|
|
2664
|
+
const name = `tool/${spec.runId}/${step}/${call.toolCallId}`;
|
|
2665
|
+
let tool;
|
|
2666
|
+
if (call.toolName === "delegate" &&
|
|
2667
|
+
(spec.tools === null || spec.tools.includes("delegate")) &&
|
|
2668
|
+
optionsOf(spec).depth < maxDelegationDepth) {
|
|
2669
|
+
const before = { ...consumed };
|
|
2670
|
+
const started = yield* ctx.step(`delegate/${step}/${call.toolCallId}`, ToolOutcome, () => R("delegation")(startChild(spec, step, call, before)));
|
|
2671
|
+
if (started.kind === "started") {
|
|
2672
|
+
const decision = yield* ctx.waitForSignal(started.signal, Decision);
|
|
2673
|
+
if (decision.kind === "cancel")
|
|
2674
|
+
return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled");
|
|
2675
|
+
const child = decision.kind === "child" ? decision : { status: "failed", result: null };
|
|
2676
|
+
tool = yield* ctx.step(name, ToolOutcome, () => R("delegation result")(Effect.gen(function* () {
|
|
2677
|
+
const spentByChild = yield* childConsumed(spec, started.childRunId);
|
|
2678
|
+
const persisted = yield* persistResult(spec, step, call, { ok: true, output: { runId: started.childRunId, status: child.status, result: child.result } }, spentByChild);
|
|
2679
|
+
return yield* processTool(spec, step, call, persisted);
|
|
2680
|
+
})));
|
|
2681
|
+
}
|
|
2682
|
+
else
|
|
2683
|
+
tool = started;
|
|
2684
|
+
}
|
|
2685
|
+
else if (call.toolName === TEAM &&
|
|
2686
|
+
(spec.tools === null || spec.tools.includes(TEAM) || optionsOf(spec).seat !== undefined)) {
|
|
2687
|
+
const ledger = {
|
|
2688
|
+
seen: { ...team.seen },
|
|
2689
|
+
collected: [...team.collected],
|
|
2690
|
+
reserved: { ...team.reserved },
|
|
2691
|
+
};
|
|
2692
|
+
if (call.input?.action === "spawn") {
|
|
2693
|
+
const before = { ...consumed };
|
|
2694
|
+
tool = yield* ctx.step(`team/${step}/${call.toolCallId}`, ToolOutcome, () => R("team")((spawnsSeats(spec, maxDelegationDepth)
|
|
2695
|
+
? startChild(spec, step, call, before, true)
|
|
2696
|
+
: persistResult(spec, step, call, refused("ToolNotAllowed", "This run may not start seats (it was not given the team tool, or the delegation depth is reached)", { tool: TEAM }))).pipe(Effect.flatMap((o) => processTool(spec, step, call, o)))));
|
|
2697
|
+
}
|
|
2698
|
+
else {
|
|
2699
|
+
for (let k = 0;; k++) {
|
|
2700
|
+
const outcome = yield* ctx.step(`team/${step}/${call.toolCallId}/${k}`, TeamOutcome, () => R("team")(teamCall(spec, step, call, k, ledger).pipe(Effect.flatMap((o) => o.kind === "team-wait" ? Effect.succeed(o) : processTool(spec, step, call, o)))));
|
|
2701
|
+
if (outcome.kind !== "team-wait") {
|
|
2702
|
+
tool = outcome;
|
|
2703
|
+
break;
|
|
2704
|
+
}
|
|
2705
|
+
const woken = yield* ctx.waitForSignal(outcome.signal, Decision);
|
|
2706
|
+
if (woken.kind === "cancel")
|
|
2707
|
+
return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled");
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
if (tool.kind === "result" && tool.result.ok) {
|
|
2711
|
+
const output = (tool.result.output ?? {});
|
|
2712
|
+
if (output.seat !== undefined && output.limits !== undefined) {
|
|
2713
|
+
team.reserved[output.seat] = { calls: output.limits.maxSteps, tokens: output.limits.maxTokens };
|
|
2714
|
+
}
|
|
2715
|
+
for (const seat of output.finished ?? [])
|
|
2716
|
+
team.collected.push(seat.seat);
|
|
2717
|
+
for (const message of output.messages ?? []) {
|
|
2718
|
+
team.seen[message.sender] = Math.max(team.seen[message.sender] ?? -1, message.seq);
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
else {
|
|
2723
|
+
tool = yield* ctx.step(name, ToolOutcome, (key) => R("tool call")(toolStep(spec, step, call, key, offered).pipe(Effect.flatMap((o) => processTool(spec, step, call, o)))));
|
|
2724
|
+
}
|
|
2725
|
+
if (tool.kind === "consent") {
|
|
2726
|
+
const decision = tool.decided ?? (yield* ctx.waitForSignal(tool.signal, Decision));
|
|
2727
|
+
if (decision.kind === "cancel")
|
|
2728
|
+
return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled");
|
|
2729
|
+
const consentId = tool.consentId;
|
|
2730
|
+
tool = yield* ctx.step(`${name}/decided`, ToolOutcome, (key) => R("consented tool call")(afterConsent(spec, step, call, decision, consentId, key).pipe(Effect.flatMap((o) => processTool(spec, step, call, o)))));
|
|
2731
|
+
}
|
|
2732
|
+
if (tool.kind === "cancelled")
|
|
2733
|
+
return yield* finish("cancelled", "cancelled", last || null, "The run was cancelled");
|
|
2734
|
+
if (tool.kind === "result" && tool.consumed !== undefined) {
|
|
2735
|
+
consumed.calls += tool.consumed.calls;
|
|
2736
|
+
consumed.tokens += tool.consumed.tokens;
|
|
2737
|
+
}
|
|
2738
|
+
if (tool.kind === "result") {
|
|
2739
|
+
const result = tool.result;
|
|
2740
|
+
if (result.ok && result.receipt !== undefined) {
|
|
2741
|
+
receipts.push({ tool: call.toolName, receipt: Schema.decodeUnknownSync(WriteReceipt)(result.receipt) });
|
|
2742
|
+
}
|
|
2743
|
+
if (result.ok && call.toolName === TOOL_SEARCH) {
|
|
2744
|
+
const found = result.output;
|
|
2745
|
+
for (const name of found.loaded ?? [])
|
|
2746
|
+
loaded.add(name);
|
|
2747
|
+
for (const name of found.removed ?? [])
|
|
2748
|
+
loaded.delete(name);
|
|
2749
|
+
}
|
|
2750
|
+
if (tool.tripped !== undefined) {
|
|
2751
|
+
return yield* finish("stopped", "processor", last || null, trippedStop(tool.tripped).message);
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
});
|
|
2757
|
+
// A step that failed (after its retries) ends the run as failed, so its record and stream say so.
|
|
2758
|
+
return yield* loop.pipe(Effect.catchTag("WorkflowFailed", (failure) => finish("failed", "error", last || null, failure.message)));
|
|
2759
|
+
}),
|
|
2760
|
+
// Anything else that fails the execution (its start, its finish, a defect) still ends the run `failed`.
|
|
2761
|
+
onFailure: ({ runId }, failure, ctx) => failRun(runId, ctx.identity.orgId, `The run's execution failed (${failure.tag}): ${failure.message}`),
|
|
2762
|
+
});
|
|
2763
|
+
// --- reactions ---------------------------------------------------------------------------------------------------------
|
|
2764
|
+
const RunPayload = Schema.Struct({ runId: Schema.String });
|
|
2765
|
+
const FinishedPayload = Schema.Struct({
|
|
2766
|
+
runId: Schema.String,
|
|
2767
|
+
parentRunId: Schema.String,
|
|
2768
|
+
status: Schema.String,
|
|
2769
|
+
result: Schema.NullOr(Schema.String),
|
|
2770
|
+
});
|
|
2771
|
+
const ConsentPayload = Schema.Struct({ id: Schema.String, status: Schema.Literals(["approved", "rejected"]) });
|
|
2772
|
+
/**
|
|
2773
|
+
* The kernel reactions that drive runs from outbox events: start a run's execution when it is requested (by
|
|
2774
|
+
* `agent.send` or a delegation), wake a waiting run when it is cancelled, when the person decides a consent it
|
|
2775
|
+
* waits on, or when its sub-agent finishes.
|
|
2776
|
+
*/
|
|
2777
|
+
/** Signal a run waiting on something (its recorded `wait`), with what happened; nothing if it does not wait. */
|
|
2778
|
+
const wakeRun = (workflows, sql) => (orgId, runId, value) => Effect.gen(function* () {
|
|
2779
|
+
const [run] = yield* inAgent(sql, orgId, sql `SELECT wait FROM eloxiv_agent.run WHERE id = ${runId}`).pipe(Effect.orDie);
|
|
2780
|
+
const signal = run?.wait?.signal;
|
|
2781
|
+
if (signal === undefined)
|
|
2782
|
+
return;
|
|
2783
|
+
yield* workflows.signal({
|
|
2784
|
+
executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, runId),
|
|
2785
|
+
signal,
|
|
2786
|
+
value,
|
|
2787
|
+
});
|
|
2788
|
+
});
|
|
2789
|
+
/**
|
|
2790
|
+
* Wake a run waiting on its team (a `team` wait, `wait.team`): one of its seats finished, or a message arrived for it.
|
|
2791
|
+
* Nothing for a run that waits on anything else (a consent, a device turn) or not at all; a wake for a wait already
|
|
2792
|
+
* over finds the next one (if any), which looks again and waits on.
|
|
2793
|
+
*/
|
|
2794
|
+
const wakeTeam = (workflows, sql) => (orgId, runId) => Effect.gen(function* () {
|
|
2795
|
+
const [run] = yield* inAgent(sql, orgId, sql `SELECT wait FROM eloxiv_agent.run WHERE id = ${runId}`).pipe(Effect.orDie);
|
|
2796
|
+
if (run?.wait?.team !== true || run.wait.signal === undefined)
|
|
2797
|
+
return;
|
|
2798
|
+
yield* workflows.signal({
|
|
2799
|
+
executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, runId),
|
|
2800
|
+
signal: run.wait.signal,
|
|
2801
|
+
value: { kind: "team" },
|
|
2802
|
+
});
|
|
2803
|
+
});
|
|
2804
|
+
/**
|
|
2805
|
+
* A device turn settled (the kernel's `devices.settled` reaction): wake the agent run it executes for, if any
|
|
2806
|
+
* (its parent run, recorded by the run when it sent the turn).
|
|
2807
|
+
*/
|
|
2808
|
+
export const wakeRunForTurn = (workflows, sql) => (settled) => Effect.gen(function* () {
|
|
2809
|
+
const [turn] = yield* sql
|
|
2810
|
+
.withTransaction(asSystem(sql, "devices", settled.orgId, sql `SELECT parent_run_id AS "parentRunId" FROM eloxiv_devices.turn
|
|
2811
|
+
WHERE id = ${settled.turnId}`))
|
|
2812
|
+
.pipe(Effect.orDie);
|
|
2813
|
+
if (turn?.parentRunId == null)
|
|
2814
|
+
return;
|
|
2815
|
+
yield* wakeRun(workflows, sql)(settled.orgId, turn.parentRunId, { kind: "device", status: settled.status });
|
|
2816
|
+
});
|
|
2817
|
+
export const agentReactions = (workflows, sql) => {
|
|
2818
|
+
const wake = wakeRun(workflows, sql);
|
|
2819
|
+
const wakeLead = wakeTeam(workflows, sql);
|
|
2820
|
+
return [
|
|
2821
|
+
{
|
|
2822
|
+
id: "agent.start",
|
|
2823
|
+
event: "agent.runRequested",
|
|
2824
|
+
handle: (event) => Effect.gen(function* () {
|
|
2825
|
+
const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload);
|
|
2826
|
+
const [run] = yield* inAgent(sql, event.orgId, sql `SELECT user_id AS "userId" FROM eloxiv_agent.run WHERE id = ${runId}`).pipe(Effect.orDie);
|
|
2827
|
+
if (run === undefined)
|
|
2828
|
+
return;
|
|
2829
|
+
yield* workflows.start({
|
|
2830
|
+
workflow: AGENT_RUN_WORKFLOW,
|
|
2831
|
+
key: runId,
|
|
2832
|
+
identity: run.userId === SYSTEM_ACTOR
|
|
2833
|
+
? { kind: "system", orgId: event.orgId }
|
|
2834
|
+
: { kind: "user", userId: run.userId, orgId: event.orgId },
|
|
2835
|
+
input: { runId },
|
|
2836
|
+
});
|
|
2837
|
+
}),
|
|
2838
|
+
},
|
|
2839
|
+
{
|
|
2840
|
+
id: "agent.cancel",
|
|
2841
|
+
event: "agent.cancelRequested",
|
|
2842
|
+
handle: (event) => Effect.gen(function* () {
|
|
2843
|
+
const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload);
|
|
2844
|
+
// Its whole subtree is cancelled with it (each sub-agent reads every ancestor's flag too, from the moment it
|
|
2845
|
+
// commits): the flag is recorded on each, at any depth, and each is woken if it waits.
|
|
2846
|
+
const children = yield* inAgent(sql, event.orgId, sql `WITH RECURSIVE subtree (id) AS (
|
|
2847
|
+
SELECT id FROM eloxiv_agent.run WHERE parent_run_id = ${runId}
|
|
2848
|
+
UNION ALL
|
|
2849
|
+
SELECT r.id FROM eloxiv_agent.run r JOIN subtree t ON r.parent_run_id = t.id
|
|
2850
|
+
)
|
|
2851
|
+
UPDATE eloxiv_agent.run SET cancel_requested_at = coalesce(cancel_requested_at, now())
|
|
2852
|
+
WHERE id IN (SELECT id FROM subtree) AND finished_at IS NULL RETURNING id`).pipe(Effect.orDie);
|
|
2853
|
+
for (const child of children)
|
|
2854
|
+
yield* wake(event.orgId, child.id, { kind: "cancel" });
|
|
2855
|
+
yield* wake(event.orgId, runId, { kind: "cancel" });
|
|
2856
|
+
}),
|
|
2857
|
+
},
|
|
2858
|
+
{
|
|
2859
|
+
id: "agent.consent",
|
|
2860
|
+
event: "consent.decided",
|
|
2861
|
+
handle: (event) => Effect.gen(function* () {
|
|
2862
|
+
const { id, status } = yield* Schema.decodeUnknownEffect(ConsentPayload)(event.payload);
|
|
2863
|
+
const waiting = yield* inAgent(sql, event.orgId, sql `SELECT id FROM eloxiv_agent.run WHERE wait->>'consentId' = ${id} AND finished_at IS NULL`).pipe(Effect.orDie);
|
|
2864
|
+
for (const run of waiting)
|
|
2865
|
+
yield* wake(event.orgId, run.id, { kind: "consent", status });
|
|
2866
|
+
}),
|
|
2867
|
+
},
|
|
2868
|
+
{
|
|
2869
|
+
id: "agent.child",
|
|
2870
|
+
event: "agent.runFinished",
|
|
2871
|
+
handle: (event) => Effect.gen(function* () {
|
|
2872
|
+
const payload = yield* Schema.decodeUnknownEffect(FinishedPayload)(event.payload);
|
|
2873
|
+
// A seat's lead never waits for this one child: it may wait on its team, and is woken only for that. (Every
|
|
2874
|
+
// signal a run is sent is one it awaits: the engine resumes a run for each, and one it never awaits kept a
|
|
2875
|
+
// lead replaying without end.)
|
|
2876
|
+
const [child] = yield* inAgent(sql, event.orgId, sql `SELECT options ? 'seat' AS seat FROM eloxiv_agent.run WHERE id = ${payload.runId}`).pipe(Effect.orDie);
|
|
2877
|
+
if (child?.seat === true)
|
|
2878
|
+
return yield* wakeLead(event.orgId, payload.parentRunId);
|
|
2879
|
+
yield* workflows.signal({
|
|
2880
|
+
executionId: yield* workflows.executionIdFor(AGENT_RUN_WORKFLOW, payload.parentRunId),
|
|
2881
|
+
signal: `child/${payload.runId}`,
|
|
2882
|
+
value: { kind: "child", status: payload.status, result: payload.result },
|
|
2883
|
+
});
|
|
2884
|
+
}),
|
|
2885
|
+
},
|
|
2886
|
+
{
|
|
2887
|
+
id: "agent.team",
|
|
2888
|
+
event: "agent.teamWake",
|
|
2889
|
+
handle: (event) => Effect.gen(function* () {
|
|
2890
|
+
const { runId } = yield* Schema.decodeUnknownEffect(RunPayload)(event.payload);
|
|
2891
|
+
yield* wakeLead(event.orgId, runId);
|
|
2892
|
+
}),
|
|
2893
|
+
},
|
|
2894
|
+
];
|
|
2895
|
+
};
|
|
2896
|
+
//# sourceMappingURL=Run.js.map
|