@systemfsoftware/agent 0.0.0-stage → 0.1.0-beta.192
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/dist/ActivityStore-CEy3oY41.mjs +90 -0
- package/dist/ActivityStore-CEy3oY41.mjs.map +1 -0
- package/dist/ActivityStore-CPXWRHGz.d.mts +91 -0
- package/dist/Admin-BcQDrWKY.mjs +329 -0
- package/dist/Admin-BcQDrWKY.mjs.map +1 -0
- package/dist/Admin-BfolLkHj.d.mts +5678 -0
- package/dist/Agent-Bn3zMhDH.mjs +60 -0
- package/dist/Agent-Bn3zMhDH.mjs.map +1 -0
- package/dist/Agent-DSVEpq4e.d.mts +219 -0
- package/dist/AgentError-RkUaetX8.d.mts +128 -0
- package/dist/AgentError-yFdnS9bl.mjs +141 -0
- package/dist/AgentError-yFdnS9bl.mjs.map +1 -0
- package/dist/AgentPolicy-CI7LRBQa.mjs +116 -0
- package/dist/AgentPolicy-CI7LRBQa.mjs.map +1 -0
- package/dist/AgentPolicy-D-GmZQex.d.mts +128 -0
- package/dist/AgentRegistration-Dg53p6du.mjs +14 -0
- package/dist/AgentRegistration-Dg53p6du.mjs.map +1 -0
- package/dist/AgentRuntime-CoGy_5dm.d.mts +751 -0
- package/dist/AgentRuntime-CzP4I4RB.mjs +5249 -0
- package/dist/AgentRuntime-CzP4I4RB.mjs.map +1 -0
- package/dist/AgentUpdates-7xT0It_R.d.mts +54 -0
- package/dist/AgentUpdates-BS_6gR5K.mjs +66 -0
- package/dist/AgentUpdates-BS_6gR5K.mjs.map +1 -0
- package/dist/BrowserUse-C9vict2M.d.mts +196 -0
- package/dist/BrowserUse-DjEyFDLZ.mjs +156 -0
- package/dist/BrowserUse-DjEyFDLZ.mjs.map +1 -0
- package/dist/Budget-CXh_ChFJ.d.mts +112 -0
- package/dist/Budget-j1UkthgY.mjs +351 -0
- package/dist/Budget-j1UkthgY.mjs.map +1 -0
- package/dist/CodeExecutor-B_Vt1Ghy.mjs +281 -0
- package/dist/CodeExecutor-B_Vt1Ghy.mjs.map +1 -0
- package/dist/CodeExecutor-D5-Rda75.d.mts +198 -0
- package/dist/CodeMode-B7JvfKAD.d.mts +159 -0
- package/dist/CodeMode-BI7WhUkr.mjs +555 -0
- package/dist/CodeMode-BI7WhUkr.mjs.map +1 -0
- package/dist/CommittedActivity-DXyCKCtX.mjs +146 -0
- package/dist/CommittedActivity-DXyCKCtX.mjs.map +1 -0
- package/dist/CommittedActivity-LWOKXqdi.d.mts +62 -0
- package/dist/Compaction-C0hWAmOG.mjs +15 -0
- package/dist/Compaction-C0hWAmOG.mjs.map +1 -0
- package/dist/Compaction-e5cNeFmY.d.mts +5 -0
- package/dist/ContextCompactor-Chm9BLrD.d.mts +165 -0
- package/dist/ContextCompactor-DV4NOQvg.mjs +134 -0
- package/dist/ContextCompactor-DV4NOQvg.mjs.map +1 -0
- package/dist/ContextHistory-C80rW5M7.mjs +76 -0
- package/dist/ContextHistory-C80rW5M7.mjs.map +1 -0
- package/dist/ContextHistory-akQ1Td7a.d.mts +65 -0
- package/dist/ContextTools-917r7gpv.d.mts +186 -0
- package/dist/ContextTools-p8JDPo-W.mjs +88 -0
- package/dist/ContextTools-p8JDPo-W.mjs.map +1 -0
- package/dist/ContextWindow-BJZI4MMt.d.mts +61 -0
- package/dist/ContextWindow-kbFcs1IF.mjs +63 -0
- package/dist/ContextWindow-kbFcs1IF.mjs.map +1 -0
- package/dist/Digest-BDToAbaX.d.mts +25 -0
- package/dist/Digest-CU6IWj-2.mjs +106 -0
- package/dist/Digest-CU6IWj-2.mjs.map +1 -0
- package/dist/DurableAgentRuntime-BHXo8GPJ.mjs +8432 -0
- package/dist/DurableAgentRuntime-BHXo8GPJ.mjs.map +1 -0
- package/dist/DurableFailpoint-BD5nowNl.mjs +98 -0
- package/dist/DurableFailpoint-BD5nowNl.mjs.map +1 -0
- package/dist/DurableFailpoint-Cqi5tyof.d.mts +42 -0
- package/dist/DurableStep-CzVIho7y.mjs +54 -0
- package/dist/DurableStep-CzVIho7y.mjs.map +1 -0
- package/dist/DurableStep-cI_Ho_rU.d.mts +109 -0
- package/dist/EventSource-BwZVkEQi.mjs +66 -0
- package/dist/EventSource-BwZVkEQi.mjs.map +1 -0
- package/dist/EventSource-C0TCBeIf.d.mts +52 -0
- package/dist/FailureDiagnostic-DdHV2eFs.mjs +304 -0
- package/dist/FailureDiagnostic-DdHV2eFs.mjs.map +1 -0
- package/dist/FailureDiagnostic-DpzYNI8f.d.mts +232 -0
- package/dist/IdGenerator-BCzwV0ZI.mjs +29 -0
- package/dist/IdGenerator-BCzwV0ZI.mjs.map +1 -0
- package/dist/IdGenerator-BY8NH74o.d.mts +26 -0
- package/dist/Identifiers-LWd4837I.mjs +41 -0
- package/dist/Identifiers-LWd4837I.mjs.map +1 -0
- package/dist/Identifiers-qafW4EP0.d.mts +38 -0
- package/dist/InMemory-BrTm6XEO.mjs +57 -0
- package/dist/InMemory-BrTm6XEO.mjs.map +1 -0
- package/dist/InMemory-C3qXFT5k.d.mts +46 -0
- package/dist/InMemory.d.mts +2 -0
- package/dist/InMemory.mjs +1 -0
- package/dist/InteractiveBrowser-B-hlNJy5.mjs +237 -0
- package/dist/InteractiveBrowser-B-hlNJy5.mjs.map +1 -0
- package/dist/InteractiveBrowser-nnML0r7w.d.mts +258 -0
- package/dist/LifecyclePublication-BDc_ug5v.mjs +204 -0
- package/dist/LifecyclePublication-BDc_ug5v.mjs.map +1 -0
- package/dist/Memory-CT5bDZqi.d.mts +57 -0
- package/dist/Memory-Dl9ecPpm.mjs +204 -0
- package/dist/Memory-Dl9ecPpm.mjs.map +1 -0
- package/dist/MemoryNamespace-BtnlH_E6.d.mts +35 -0
- package/dist/MemoryNamespace-DZSpjLj9.mjs +116 -0
- package/dist/MemoryNamespace-DZSpjLj9.mjs.map +1 -0
- package/dist/MemoryNotes-4CRzkPBD.d.mts +425 -0
- package/dist/MemoryNotes-i41TsH11.mjs +132 -0
- package/dist/MemoryNotes-i41TsH11.mjs.map +1 -0
- package/dist/MemoryReference-Dd3KSMa7.d.mts +77 -0
- package/dist/MemoryReference-RFU0HQJG.mjs +108 -0
- package/dist/MemoryReference-RFU0HQJG.mjs.map +1 -0
- package/dist/MemoryRevalidation--aAh_Pfq.mjs +136 -0
- package/dist/MemoryRevalidation--aAh_Pfq.mjs.map +1 -0
- package/dist/MemoryRevalidation-FsJ8E61W.d.mts +64 -0
- package/dist/MemoryStore-Bg5RunTk.d.mts +187 -0
- package/dist/MemoryStore-E0J99hb2.mjs +245 -0
- package/dist/MemoryStore-E0J99hb2.mjs.map +1 -0
- package/dist/MessageDelivery-BE2Yf3FC.mjs +615 -0
- package/dist/MessageDelivery-BE2Yf3FC.mjs.map +1 -0
- package/dist/MessageDelivery-Dh6GZBt_.d.mts +1129 -0
- package/dist/Messaging-BqWHYf93.d.mts +216 -0
- package/dist/Messaging-DgSiv4f4.mjs +154 -0
- package/dist/Messaging-DgSiv4f4.mjs.map +1 -0
- package/dist/Messaging-DhM-APnP.d.mts +1074 -0
- package/dist/MessagingHost-Bm5e-kAX.mjs +117 -0
- package/dist/MessagingHost-Bm5e-kAX.mjs.map +1 -0
- package/dist/MessagingHost-CubWeYKN.d.mts +80 -0
- package/dist/OperationAuthorizer-VSiHCC2S.mjs +72 -0
- package/dist/OperationAuthorizer-VSiHCC2S.mjs.map +1 -0
- package/dist/OperationAuthorizer-y-F-Ox_Q.d.mts +62 -0
- package/dist/Output-DQ8mWcgf.mjs +7 -0
- package/dist/Output-DQ8mWcgf.mjs.map +1 -0
- package/dist/Output-SbOdlBFL.d.mts +22 -0
- package/dist/PageCapture-BfRURUOA.mjs +275 -0
- package/dist/PageCapture-BfRURUOA.mjs.map +1 -0
- package/dist/PageCapture-C_mE72Sd.d.mts +216 -0
- package/dist/PageScreenshot-BJTASs4o.mjs +53 -0
- package/dist/PageScreenshot-BJTASs4o.mjs.map +1 -0
- package/dist/PageScreenshot-CaoaH7mc.d.mts +48 -0
- package/dist/PersistentHistory-BrtZ0g2j.d.mts +14 -0
- package/dist/PersistentHistory-CTAVhHKH.mjs +147 -0
- package/dist/PersistentHistory-CTAVhHKH.mjs.map +1 -0
- package/dist/PreparedInputAdmission-Ci18uY4s.d.mts +973 -0
- package/dist/PreparedInputAdmission-adqVJJa6.mjs +95 -0
- package/dist/PreparedInputAdmission-adqVJJa6.mjs.map +1 -0
- package/dist/ProvisionalText-BcKpPYKQ.d.mts +70 -0
- package/dist/ProvisionalText-DXddTK4c.mjs +47 -0
- package/dist/ProvisionalText-DXddTK4c.mjs.map +1 -0
- package/dist/Receipt-B-FlCaNH.mjs +35 -0
- package/dist/Receipt-B-FlCaNH.mjs.map +1 -0
- package/dist/Receipt-B4feBxMY.d.mts +31 -0
- package/dist/RecordFormat-DoNh-AFe.mjs +79 -0
- package/dist/RecordFormat-DoNh-AFe.mjs.map +1 -0
- package/dist/RecordFormat-ZMus8Dx8.d.mts +52 -0
- package/dist/Records-C645aQks.mjs +1145 -0
- package/dist/Records-C645aQks.mjs.map +1 -0
- package/dist/Records-C9I1nCL9.d.mts +1423 -0
- package/dist/Recovery-zWy_kmZq.mjs +736 -0
- package/dist/Recovery-zWy_kmZq.mjs.map +1 -0
- package/dist/Redaction-C0zLBAn6.d.mts +28 -0
- package/dist/Redaction-CtyCBMEj.mjs +116 -0
- package/dist/Redaction-CtyCBMEj.mjs.map +1 -0
- package/dist/RememberingStore-BO-OnCgP.mjs +23 -0
- package/dist/RememberingStore-BO-OnCgP.mjs.map +1 -0
- package/dist/RememberingStore-DgqXmILx.d.mts +14 -0
- package/dist/RunContinuation-BVAHoYlN.d.mts +127 -0
- package/dist/RunContinuation-Bpfp087i.mjs +1060 -0
- package/dist/RunContinuation-Bpfp087i.mjs.map +1 -0
- package/dist/RunEvent-CwgDzXcH.d.mts +465 -0
- package/dist/RunEvent-DJxENnJi.mjs +345 -0
- package/dist/RunEvent-DJxENnJi.mjs.map +1 -0
- package/dist/RunEventSink-B8uM8bw2.mjs +22 -0
- package/dist/RunEventSink-B8uM8bw2.mjs.map +1 -0
- package/dist/RunEventSink-f-T4jbNB.d.mts +105 -0
- package/dist/RunHooks-Bob22Bcj.d.mts +40 -0
- package/dist/RunHooks-DWuLBVdU.mjs +60 -0
- package/dist/RunHooks-DWuLBVdU.mjs.map +1 -0
- package/dist/RunJournal-C_1eqQdr.mjs +1107 -0
- package/dist/RunJournal-C_1eqQdr.mjs.map +1 -0
- package/dist/RunOptions-BVSa3BO2.d.mts +560 -0
- package/dist/RunOptions-COEUCrx4.mjs +61 -0
- package/dist/RunOptions-COEUCrx4.mjs.map +1 -0
- package/dist/RunPolicyUsage-B-JXRZYO.mjs +25 -0
- package/dist/RunPolicyUsage-B-JXRZYO.mjs.map +1 -0
- package/dist/RunPolicyUsage-jvJo0vJp.d.mts +21 -0
- package/dist/RunStorage-CsQQ0Y5u.mjs +304 -0
- package/dist/RunStorage-CsQQ0Y5u.mjs.map +1 -0
- package/dist/Sandbox-37vXP0BV.d.mts +24 -0
- package/dist/Sandbox-Bze6pHYc.mjs +30 -0
- package/dist/Sandbox-Bze6pHYc.mjs.map +1 -0
- package/dist/Schedule-BY0lzbij.mjs +336 -0
- package/dist/Schedule-BY0lzbij.mjs.map +1 -0
- package/dist/ScheduleTransition-CjVP48I8.d.mts +22 -0
- package/dist/ScheduleTransition-DtNzlN9k.mjs +180 -0
- package/dist/ScheduleTransition-DtNzlN9k.mjs.map +1 -0
- package/dist/Scheduling-BpJN9E1j.mjs +699 -0
- package/dist/Scheduling-BpJN9E1j.mjs.map +1 -0
- package/dist/Scheduling-DYTM29s9.d.mts +57 -0
- package/dist/SemanticMemory-BRV0cuWg.mjs +300 -0
- package/dist/SemanticMemory-BRV0cuWg.mjs.map +1 -0
- package/dist/SemanticMemory-rgWlhW87.d.mts +431 -0
- package/dist/SemanticMemoryIndex-D7yNEWpt.d.mts +826 -0
- package/dist/SemanticMemoryIndex-godQDjNx.mjs +186 -0
- package/dist/SemanticMemoryIndex-godQDjNx.mjs.map +1 -0
- package/dist/SemanticMemoryRevalidation-Bm3_pfsI.d.mts +44 -0
- package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs +179 -0
- package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs.map +1 -0
- package/dist/Subagent-CSIRUgUo.mjs +1315 -0
- package/dist/Subagent-CSIRUgUo.mjs.map +1 -0
- package/dist/Subagent-CXEI5YZ8.d.mts +2368 -0
- package/dist/SubagentContract-B7vQPueI.d.mts +176 -0
- package/dist/SubagentContract-C-7AxTm_.mjs +187 -0
- package/dist/SubagentContract-C-7AxTm_.mjs.map +1 -0
- package/dist/SubagentHost-BEnICu7g.mjs +70 -0
- package/dist/SubagentHost-BEnICu7g.mjs.map +1 -0
- package/dist/SubagentHost-CKhz1vbH.d.mts +167 -0
- package/dist/SubagentReservations-BYNAHPpm.mjs +465 -0
- package/dist/SubagentReservations-BYNAHPpm.mjs.map +1 -0
- package/dist/SubagentReservations-WrmIVzO5.d.mts +185 -0
- package/dist/SubmissionLedger-WG0beEyt.mjs +921 -0
- package/dist/SubmissionLedger-WG0beEyt.mjs.map +1 -0
- package/dist/SubmissionStatus-CPZsOM5a.mjs +17 -0
- package/dist/SubmissionStatus-CPZsOM5a.mjs.map +1 -0
- package/dist/Subscription-BhQbmUD-.mjs +340 -0
- package/dist/Subscription-BhQbmUD-.mjs.map +1 -0
- package/dist/Subscription-CC--_OnU.d.mts +815 -0
- package/dist/SubscriptionInput-BEeB0Cj8.d.mts +42 -0
- package/dist/SubscriptionInput-Xcd4JjEs.mjs +53 -0
- package/dist/SubscriptionInput-Xcd4JjEs.mjs.map +1 -0
- package/dist/SubscriptionTransition-CWt9UVH0.d.mts +23 -0
- package/dist/SubscriptionTransition-lrf733c8.mjs +154 -0
- package/dist/SubscriptionTransition-lrf733c8.mjs.map +1 -0
- package/dist/Subscriptions-4K_qu_2f.mjs +638 -0
- package/dist/Subscriptions-4K_qu_2f.mjs.map +1 -0
- package/dist/Subscriptions-BF3aSf8X.d.mts +75 -0
- package/dist/Thread-B8JApGHa.mjs +283 -0
- package/dist/Thread-B8JApGHa.mjs.map +1 -0
- package/dist/Thread-BnAtkJl4.d.mts +116 -0
- package/dist/ThreadArchiveRange-1PMdjpdJ.mjs +64 -0
- package/dist/ThreadArchiveRange-1PMdjpdJ.mjs.map +1 -0
- package/dist/ThreadContextHistory-BSStMOLX.mjs +211 -0
- package/dist/ThreadContextHistory-BSStMOLX.mjs.map +1 -0
- package/dist/ThreadContextHistory-lTZ8Ftq1.d.mts +33 -0
- package/dist/ThreadContextHistoryProjection-Cp7_RR6V.d.mts +59 -0
- package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs +149 -0
- package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs.map +1 -0
- package/dist/ThreadHistory-BkyGfv5E.d.mts +76 -0
- package/dist/ThreadHistory-Blt_W31N.mjs +69 -0
- package/dist/ThreadHistory-Blt_W31N.mjs.map +1 -0
- package/dist/ThreadImport-C8Tqiezd.mjs +491 -0
- package/dist/ThreadImport-C8Tqiezd.mjs.map +1 -0
- package/dist/ThreadImport-DaSmrlRi.d.mts +843 -0
- package/dist/ThreadInvariants-DyPhMeo-.d.mts +23 -0
- package/dist/ThreadInvariants-fniroLRY.mjs +154 -0
- package/dist/ThreadInvariants-fniroLRY.mjs.map +1 -0
- package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs +37 -0
- package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs.map +1 -0
- package/dist/ThreadProjectionMaintenance-DjUy7kCa.d.mts +51 -0
- package/dist/ThreadStore-BMUAp5Ta.mjs +937 -0
- package/dist/ThreadStore-BMUAp5Ta.mjs.map +1 -0
- package/dist/ThreadTransfer-B3NkyO_y.mjs +154 -0
- package/dist/ThreadTransfer-B3NkyO_y.mjs.map +1 -0
- package/dist/ThreadTransfer-BM02cbOo.d.mts +63 -0
- package/dist/ThreadWork-C-xa2Boi.mjs +484 -0
- package/dist/ThreadWork-C-xa2Boi.mjs.map +1 -0
- package/dist/ToolBroker-DkoVyx6T.mjs +42 -0
- package/dist/ToolBroker-DkoVyx6T.mjs.map +1 -0
- package/dist/ToolBroker-Dy2xM6ht.d.mts +134 -0
- package/dist/ToolDiscovery-DHySvLQd.mjs +211 -0
- package/dist/ToolDiscovery-DHySvLQd.mjs.map +1 -0
- package/dist/ToolDiscovery-VjamzX3q.d.mts +119 -0
- package/dist/ToolExposure-Cn7xETn5.d.mts +6 -0
- package/dist/ToolExposure-D7id9Gt5.d.mts +37 -0
- package/dist/ToolExposure-DCvQWFIa.mjs +9 -0
- package/dist/ToolExposure-DCvQWFIa.mjs.map +1 -0
- package/dist/ToolExposure-DNME8BkG.d.mts +44 -0
- package/dist/ToolExposure-DPnq8Won.mjs +30 -0
- package/dist/ToolExposure-DPnq8Won.mjs.map +1 -0
- package/dist/ToolExposure-DaGaF5tj.mjs +20 -0
- package/dist/ToolExposure-DaGaF5tj.mjs.map +1 -0
- package/dist/ToolExposure.d.mts +4 -0
- package/dist/ToolExposure.mjs +4 -0
- package/dist/ToolReconciler-6bb7xlip.d.mts +81 -0
- package/dist/ToolReconciler-DJQd3SZA.mjs +87 -0
- package/dist/ToolReconciler-DJQd3SZA.mjs.map +1 -0
- package/dist/ToolResult-By5KAje4.d.mts +79 -0
- package/dist/ToolResult-DwZxjlHw.mjs +160 -0
- package/dist/ToolResult-DwZxjlHw.mjs.map +1 -0
- package/dist/ToolResultStorage-BmoRewhh.mjs +46 -0
- package/dist/ToolResultStorage-BmoRewhh.mjs.map +1 -0
- package/dist/ToolResultStorage-Bp5fm0do.d.mts +49 -0
- package/dist/ToolResults-C4-HsMCp.d.mts +33 -0
- package/dist/ToolResults-nCgBlTp2.mjs +45 -0
- package/dist/ToolResults-nCgBlTp2.mjs.map +1 -0
- package/dist/Usage-B0xgME5f.mjs +340 -0
- package/dist/Usage-B0xgME5f.mjs.map +1 -0
- package/dist/Usage-Bc-jXe_9.d.mts +128 -0
- package/dist/WakeScheduler-DVYj66C-.mjs +74 -0
- package/dist/WakeScheduler-DVYj66C-.mjs.map +1 -0
- package/dist/WakeScheduler-SFqj67Sk.d.mts +74 -0
- package/dist/WebCapture-CA4ZarW2.mjs +64 -0
- package/dist/WebCapture-CA4ZarW2.mjs.map +1 -0
- package/dist/WebCapture-pzIeUJ5W.d.mts +49 -0
- package/dist/WebSearch-CD0V--qh.d.mts +18 -0
- package/dist/WebSearch-DnbOzRL_.mjs +30 -0
- package/dist/WebSearch-DnbOzRL_.mjs.map +1 -0
- package/dist/Worker-CQu8Qp1j.mjs +267 -0
- package/dist/Worker-CQu8Qp1j.mjs.map +1 -0
- package/dist/Worker-xxucY_0b.d.mts +468 -0
- package/dist/WorkerAdmission-BhFjx86s.mjs +162 -0
- package/dist/WorkerAdmission-BhFjx86s.mjs.map +1 -0
- package/dist/WorkerAdmission-BnRuXLWF.d.mts +171 -0
- package/dist/WorkerHost-DtYzi54D.d.mts +150 -0
- package/dist/WorkerHost-DuQug9Bq.mjs +73 -0
- package/dist/WorkerHost-DuQug9Bq.mjs.map +1 -0
- package/dist/agent-registration-CNs2twrr.mjs +262 -0
- package/dist/agent-registration-CNs2twrr.mjs.map +1 -0
- package/dist/capabilities/BrowserUse.d.mts +2 -0
- package/dist/capabilities/BrowserUse.mjs +1 -0
- package/dist/capabilities/Budget.d.mts +2 -0
- package/dist/capabilities/Budget.mjs +1 -0
- package/dist/capabilities/CodeMode.d.mts +2 -0
- package/dist/capabilities/CodeMode.mjs +1 -0
- package/dist/capabilities/ContextTools.d.mts +2 -0
- package/dist/capabilities/ContextTools.mjs +1 -0
- package/dist/capabilities/MemoryNotes.d.mts +2 -0
- package/dist/capabilities/MemoryNotes.mjs +1 -0
- package/dist/capabilities/Messaging.d.mts +3 -0
- package/dist/capabilities/Messaging.mjs +4 -0
- package/dist/capabilities/Redaction.d.mts +2 -0
- package/dist/capabilities/Redaction.mjs +1 -0
- package/dist/capabilities/RunHooks.d.mts +2 -0
- package/dist/capabilities/RunHooks.mjs +1 -0
- package/dist/capabilities/SemanticMemory.d.mts +2 -0
- package/dist/capabilities/SemanticMemory.mjs +1 -0
- package/dist/capabilities/Subagent.d.mts +4 -0
- package/dist/capabilities/Subagent.mjs +6 -0
- package/dist/capabilities/SubagentReservations.d.mts +2 -0
- package/dist/capabilities/SubagentReservations.mjs +1 -0
- package/dist/capabilities/ToolDiscovery.d.mts +2 -0
- package/dist/capabilities/ToolDiscovery.mjs +1 -0
- package/dist/capabilities/ToolResults.d.mts +2 -0
- package/dist/capabilities/ToolResults.mjs +1 -0
- package/dist/capabilities/WebCapture.d.mts +2 -0
- package/dist/capabilities/WebCapture.mjs +1 -0
- package/dist/capabilities/WebSearch.d.mts +2 -0
- package/dist/capabilities/WebSearch.mjs +1 -0
- package/dist/compaction-C3hXuO4Z.mjs +539 -0
- package/dist/compaction-C3hXuO4Z.mjs.map +1 -0
- package/dist/completion-B_WDnSg-.d.mts +11 -0
- package/dist/core/Agent.d.mts +2 -0
- package/dist/core/Agent.mjs +1 -0
- package/dist/core/AgentError.d.mts +2 -0
- package/dist/core/AgentError.mjs +1 -0
- package/dist/core/AgentPolicy.d.mts +2 -0
- package/dist/core/AgentPolicy.mjs +1 -0
- package/dist/core/AgentUpdates.d.mts +2 -0
- package/dist/core/AgentUpdates.mjs +1 -0
- package/dist/core/FailureDiagnostic.d.mts +2 -0
- package/dist/core/FailureDiagnostic.mjs +1 -0
- package/dist/core/IdGenerator.d.mts +2 -0
- package/dist/core/IdGenerator.mjs +1 -0
- package/dist/core/Identifiers.d.mts +2 -0
- package/dist/core/Identifiers.mjs +1 -0
- package/dist/core/Memory.d.mts +2 -0
- package/dist/core/Memory.mjs +1 -0
- package/dist/core/MemoryNamespace.d.mts +2 -0
- package/dist/core/MemoryNamespace.mjs +1 -0
- package/dist/core/MemoryReference.d.mts +2 -0
- package/dist/core/MemoryReference.mjs +1 -0
- package/dist/core/MemoryRevalidation.d.mts +2 -0
- package/dist/core/MemoryRevalidation.mjs +1 -0
- package/dist/core/MemoryStore.d.mts +2 -0
- package/dist/core/MemoryStore.mjs +1 -0
- package/dist/core/ProvisionalText.d.mts +2 -0
- package/dist/core/ProvisionalText.mjs +1 -0
- package/dist/core/Receipt.d.mts +2 -0
- package/dist/core/Receipt.mjs +1 -0
- package/dist/core/RememberingStore.d.mts +2 -0
- package/dist/core/RememberingStore.mjs +1 -0
- package/dist/core/RunEvent.d.mts +3 -0
- package/dist/core/RunEvent.mjs +1 -0
- package/dist/core/RunPolicyUsage.d.mts +2 -0
- package/dist/core/RunPolicyUsage.mjs +1 -0
- package/dist/core/SemanticMemoryIndex.d.mts +2 -0
- package/dist/core/SemanticMemoryIndex.mjs +1 -0
- package/dist/core/SemanticMemoryRevalidation.d.mts +2 -0
- package/dist/core/SemanticMemoryRevalidation.mjs +1 -0
- package/dist/core/SubagentContract.d.mts +2 -0
- package/dist/core/SubagentContract.mjs +1 -0
- package/dist/core/Thread.d.mts +2 -0
- package/dist/core/Thread.mjs +1 -0
- package/dist/core/ToolResult.d.mts +2 -0
- package/dist/core/ToolResult.mjs +1 -0
- package/dist/core/ToolResultStorage.d.mts +2 -0
- package/dist/core/ToolResultStorage.mjs +1 -0
- package/dist/core/Usage.d.mts +2 -0
- package/dist/core/Usage.mjs +1 -0
- package/dist/core/Worker.d.mts +3 -0
- package/dist/core/Worker.mjs +3 -0
- package/dist/durable/ActivityStore.d.mts +2 -0
- package/dist/durable/ActivityStore.mjs +1 -0
- package/dist/durable/Admin.d.mts +2 -0
- package/dist/durable/Admin.mjs +1 -0
- package/dist/durable/AgentRegistration.d.mts +3 -0
- package/dist/durable/AgentRegistration.mjs +2 -0
- package/dist/durable/CommittedActivity.d.mts +2 -0
- package/dist/durable/CommittedActivity.mjs +1 -0
- package/dist/durable/Digest.d.mts +2 -0
- package/dist/durable/Digest.mjs +3 -0
- package/dist/durable/DurableAgentRuntime.d.mts +3 -0
- package/dist/durable/DurableAgentRuntime.mjs +4 -0
- package/dist/durable/DurableFailpoint.d.mts +2 -0
- package/dist/durable/DurableFailpoint.mjs +1 -0
- package/dist/durable/DurableFailpointTestControl.d.mts +14 -0
- package/dist/durable/DurableFailpointTestControl.mjs +21 -0
- package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
- package/dist/durable/EventSource.d.mts +2 -0
- package/dist/durable/EventSource.mjs +1 -0
- package/dist/durable/LifecyclePublication.d.mts +2 -0
- package/dist/durable/LifecyclePublication.mjs +1 -0
- package/dist/durable/MessageDelivery.d.mts +2 -0
- package/dist/durable/MessageDelivery.mjs +1 -0
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +401 -0
- package/dist/durable/MessageDeliveryStoreConformance.mjs +273 -0
- package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
- package/dist/durable/OperationAuthorizer.d.mts +2 -0
- package/dist/durable/OperationAuthorizer.mjs +1 -0
- package/dist/durable/PersistentHistory.d.mts +2 -0
- package/dist/durable/PersistentHistory.mjs +1 -0
- package/dist/durable/PreparedInputAdmission.d.mts +2 -0
- package/dist/durable/PreparedInputAdmission.mjs +1 -0
- package/dist/durable/RecordFormat.d.mts +2 -0
- package/dist/durable/RecordFormat.mjs +1 -0
- package/dist/durable/Records.d.mts +2 -0
- package/dist/durable/Records.mjs +1 -0
- package/dist/durable/Recovery.d.mts +2 -0
- package/dist/durable/Recovery.mjs +1 -0
- package/dist/durable/RunContinuation.d.mts +4 -0
- package/dist/durable/RunContinuation.mjs +4 -0
- package/dist/durable/RunJournal.d.mts +2 -0
- package/dist/durable/RunJournal.mjs +1 -0
- package/dist/durable/RunStorage.d.mts +2 -0
- package/dist/durable/RunStorage.mjs +1 -0
- package/dist/durable/Schedule.d.mts +2 -0
- package/dist/durable/Schedule.mjs +1 -0
- package/dist/durable/ScheduleStoreConformance.d.mts +16 -0
- package/dist/durable/ScheduleStoreConformance.mjs +421 -0
- package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
- package/dist/durable/ScheduleTransition.d.mts +2 -0
- package/dist/durable/ScheduleTransition.mjs +1 -0
- package/dist/durable/Scheduling.d.mts +2 -0
- package/dist/durable/Scheduling.mjs +1 -0
- package/dist/durable/SettlementPublisher.d.mts +2 -0
- package/dist/durable/SettlementPublisher.mjs +99 -0
- package/dist/durable/SettlementPublisher.mjs.map +1 -0
- package/dist/durable/SqlMemoryStore.d.mts +729 -0
- package/dist/durable/SqlMemoryStore.mjs +626 -0
- package/dist/durable/SqlMemoryStore.mjs.map +1 -0
- package/dist/durable/SqlStorageOwner.d.mts +18 -0
- package/dist/durable/SqlStorageOwner.mjs +6 -0
- package/dist/durable/SqlStorageOwner.mjs.map +1 -0
- package/dist/durable/SubmissionLedger.d.mts +3 -0
- package/dist/durable/SubmissionLedger.mjs +3 -0
- package/dist/durable/SubmissionLedgerConformance.d.mts +31 -0
- package/dist/durable/SubmissionLedgerConformance.mjs +2090 -0
- package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
- package/dist/durable/SubmissionStatus.d.mts +2 -0
- package/dist/durable/SubmissionStatus.mjs +1 -0
- package/dist/durable/Subscription.d.mts +2 -0
- package/dist/durable/Subscription.mjs +1 -0
- package/dist/durable/SubscriptionInput.d.mts +2 -0
- package/dist/durable/SubscriptionInput.mjs +1 -0
- package/dist/durable/SubscriptionStoreConformance.d.mts +15 -0
- package/dist/durable/SubscriptionStoreConformance.mjs +816 -0
- package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
- package/dist/durable/SubscriptionTransition.d.mts +2 -0
- package/dist/durable/SubscriptionTransition.mjs +1 -0
- package/dist/durable/Subscriptions.d.mts +2 -0
- package/dist/durable/Subscriptions.mjs +1 -0
- package/dist/durable/ThreadArchiveRange.d.mts +2 -0
- package/dist/durable/ThreadArchiveRange.mjs +1 -0
- package/dist/durable/ThreadContextHistory.d.mts +2 -0
- package/dist/durable/ThreadContextHistory.mjs +1 -0
- package/dist/durable/ThreadContextHistoryProjection.d.mts +2 -0
- package/dist/durable/ThreadContextHistoryProjection.mjs +1 -0
- package/dist/durable/ThreadImport.d.mts +2 -0
- package/dist/durable/ThreadImport.mjs +1 -0
- package/dist/durable/ThreadInvariants.d.mts +2 -0
- package/dist/durable/ThreadInvariants.mjs +1 -0
- package/dist/durable/ThreadProjectionMaintenance.d.mts +2 -0
- package/dist/durable/ThreadProjectionMaintenance.mjs +1 -0
- package/dist/durable/ThreadReader.d.mts +2 -0
- package/dist/durable/ThreadReader.mjs +1 -0
- package/dist/durable/ThreadStore.d.mts +3 -0
- package/dist/durable/ThreadStore.mjs +3 -0
- package/dist/durable/ThreadStoreConformance.d.mts +53 -0
- package/dist/durable/ThreadStoreConformance.mjs +402 -0
- package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
- package/dist/durable/ThreadTransfer.d.mts +2 -0
- package/dist/durable/ThreadTransfer.mjs +1 -0
- package/dist/durable/ThreadWork.d.mts +2 -0
- package/dist/durable/ThreadWork.mjs +1 -0
- package/dist/durable/ToolReconciler.d.mts +2 -0
- package/dist/durable/ToolReconciler.mjs +1 -0
- package/dist/durable/WakeScheduler.d.mts +2 -0
- package/dist/durable/WakeScheduler.mjs +1 -0
- package/dist/durable/WorkerAdmission.d.mts +2 -0
- package/dist/durable/WorkerAdmission.mjs +1 -0
- package/dist/durable/WorkerHost.d.mts +2 -0
- package/dist/durable/WorkerHost.mjs +1 -0
- package/dist/engine/AgentRuntime.d.mts +2 -0
- package/dist/engine/AgentRuntime.mjs +1 -0
- package/dist/engine/Compaction.d.mts +4 -0
- package/dist/engine/Compaction.mjs +2 -0
- package/dist/engine/ContextCompactor.d.mts +2 -0
- package/dist/engine/ContextCompactor.mjs +1 -0
- package/dist/engine/ContextHistory.d.mts +2 -0
- package/dist/engine/ContextHistory.mjs +1 -0
- package/dist/engine/ContextWindow.d.mts +2 -0
- package/dist/engine/ContextWindow.mjs +1 -0
- package/dist/engine/DurableStep.d.mts +2 -0
- package/dist/engine/DurableStep.mjs +3 -0
- package/dist/engine/MessagingHost.d.mts +2 -0
- package/dist/engine/MessagingHost.mjs +1 -0
- package/dist/engine/Output.d.mts +3 -0
- package/dist/engine/Output.mjs +2 -0
- package/dist/engine/RunEventSink.d.mts +2 -0
- package/dist/engine/RunEventSink.mjs +1 -0
- package/dist/engine/RunOptions.d.mts +2 -0
- package/dist/engine/RunOptions.mjs +1 -0
- package/dist/engine/SubagentHost.d.mts +2 -0
- package/dist/engine/SubagentHost.mjs +1 -0
- package/dist/engine/ThreadHistory.d.mts +2 -0
- package/dist/engine/ThreadHistory.mjs +1 -0
- package/dist/engine/ToolBroker.d.mts +2 -0
- package/dist/engine/ToolBroker.mjs +1 -0
- package/dist/index.d.mts +90 -0
- package/dist/index.mjs +101 -0
- package/dist/output-contract-CYA4oBhe.mjs +128 -0
- package/dist/output-contract-CYA4oBhe.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/dist/run-context-reader-CHox63hg.d.mts +17 -0
- package/dist/sandbox/CodeExecutor.d.mts +2 -0
- package/dist/sandbox/CodeExecutor.mjs +1 -0
- package/dist/sandbox/InteractiveBrowser.d.mts +2 -0
- package/dist/sandbox/InteractiveBrowser.mjs +1 -0
- package/dist/sandbox/PageCapture.d.mts +2 -0
- package/dist/sandbox/PageCapture.mjs +1 -0
- package/dist/sandbox/PageScreenshot.d.mts +2 -0
- package/dist/sandbox/PageScreenshot.mjs +1 -0
- package/dist/sandbox/Sandbox.d.mts +2 -0
- package/dist/sandbox/Sandbox.mjs +1 -0
- package/dist/subagent-policy-xRJhrc0a.mjs +133 -0
- package/dist/subagent-policy-xRJhrc0a.mjs.map +1 -0
- package/dist/tool-execution-Cl7v8fXU.mjs +16 -0
- package/dist/tool-execution-Cl7v8fXU.mjs.map +1 -0
- package/dist/tool-operations-CauPonM8.mjs +84 -0
- package/dist/tool-operations-CauPonM8.mjs.map +1 -0
- package/dist/utf8-Bl0ZhhGe.mjs +27 -0
- package/dist/utf8-Bl0ZhhGe.mjs.map +1 -0
- package/package.json +491 -3
- package/src/InMemory.ts +79 -0
- package/src/ToolExposure.ts +2 -0
- package/src/capabilities/BrowserUse.ts +212 -0
- package/src/capabilities/Budget.ts +544 -0
- package/src/capabilities/CodeMode.ts +1129 -0
- package/src/capabilities/ContextTools.ts +131 -0
- package/src/capabilities/MemoryNotes.ts +177 -0
- package/src/capabilities/Messaging.ts +260 -0
- package/src/capabilities/Redaction.ts +163 -0
- package/src/capabilities/RunHooks.ts +116 -0
- package/src/capabilities/SemanticMemory.ts +402 -0
- package/src/capabilities/Subagent.ts +2343 -0
- package/src/capabilities/SubagentReservations.ts +807 -0
- package/src/capabilities/ToolDiscovery.ts +291 -0
- package/src/capabilities/ToolResults.ts +50 -0
- package/src/capabilities/WebCapture.ts +64 -0
- package/src/capabilities/WebSearch.ts +45 -0
- package/src/capabilities/internal/subagent-background.ts +1137 -0
- package/src/capabilities/internal/subagent-contract.ts +92 -0
- package/src/capabilities/internal/subagent-policy.ts +205 -0
- package/src/capabilities/internal/subagent-reporting.ts +152 -0
- package/src/core/Agent.ts +528 -0
- package/src/core/AgentError.ts +189 -0
- package/src/core/AgentPolicy.ts +194 -0
- package/src/core/AgentUpdates.ts +104 -0
- package/src/core/FailureDiagnostic.ts +392 -0
- package/src/core/IdGenerator.ts +42 -0
- package/src/core/Identifiers.ts +64 -0
- package/src/core/Memory.ts +283 -0
- package/src/core/MemoryNamespace.ts +202 -0
- package/src/core/MemoryReference.ts +120 -0
- package/src/core/MemoryRevalidation.ts +151 -0
- package/src/core/MemoryStore.ts +371 -0
- package/src/core/Messaging.ts +72 -0
- package/src/core/ProvisionalText.ts +53 -0
- package/src/core/Receipt.ts +42 -0
- package/src/core/RememberingStore.ts +22 -0
- package/src/core/RunEvent.ts +345 -0
- package/src/core/RunPolicyUsage.ts +19 -0
- package/src/core/SemanticMemoryIndex.ts +259 -0
- package/src/core/SemanticMemoryRevalidation.ts +220 -0
- package/src/core/SubagentContract.ts +263 -0
- package/src/core/Thread.ts +447 -0
- package/src/core/ToolExposure.ts +75 -0
- package/src/core/ToolResult.ts +204 -0
- package/src/core/ToolResultStorage.ts +56 -0
- package/src/core/Usage.ts +562 -0
- package/src/core/Worker.ts +236 -0
- package/src/core/internal/agent-updates.ts +42 -0
- package/src/core/internal/completion.ts +33 -0
- package/src/core/internal/json.ts +17 -0
- package/src/core/internal/memory-document.ts +39 -0
- package/src/core/internal/message-status.ts +60 -0
- package/src/core/internal/strict-schema.ts +14 -0
- package/src/core/internal/tool-execution.ts +33 -0
- package/src/core/internal/utf8.ts +32 -0
- package/src/durable/ActivityStore.ts +131 -0
- package/src/durable/Admin.ts +504 -0
- package/src/durable/AgentRegistration.ts +16 -0
- package/src/durable/CommittedActivity.ts +262 -0
- package/src/durable/Digest.ts +57 -0
- package/src/durable/DurableAgentRuntime.ts +12758 -0
- package/src/durable/DurableFailpoint.ts +108 -0
- package/src/durable/DurableFailpointTestControl.ts +39 -0
- package/src/durable/EventSource.ts +179 -0
- package/src/durable/LifecyclePublication.ts +343 -0
- package/src/durable/MessageDelivery.ts +949 -0
- package/src/durable/MessageDeliveryStoreConformance.ts +407 -0
- package/src/durable/OperationAuthorizer.ts +89 -0
- package/src/durable/PersistentHistory.ts +322 -0
- package/src/durable/PreparedInputAdmission.ts +128 -0
- package/src/durable/RecordFormat.ts +113 -0
- package/src/durable/Records.ts +1396 -0
- package/src/durable/Recovery.ts +1022 -0
- package/src/durable/RunContinuation.ts +1946 -0
- package/src/durable/RunJournal.ts +1926 -0
- package/src/durable/RunStorage.ts +533 -0
- package/src/durable/Schedule.ts +445 -0
- package/src/durable/ScheduleStoreConformance.ts +642 -0
- package/src/durable/ScheduleTransition.ts +267 -0
- package/src/durable/Scheduling.ts +1031 -0
- package/src/durable/SettlementPublisher.ts +172 -0
- package/src/durable/SqlMemoryStore.ts +1042 -0
- package/src/durable/SqlStorageOwner.ts +25 -0
- package/src/durable/SubmissionLedger.ts +1247 -0
- package/src/durable/SubmissionLedgerConformance.ts +4695 -0
- package/src/durable/SubmissionStatus.ts +14 -0
- package/src/durable/Subscription.ts +527 -0
- package/src/durable/SubscriptionInput.ts +145 -0
- package/src/durable/SubscriptionStoreConformance.ts +1275 -0
- package/src/durable/SubscriptionTransition.ts +330 -0
- package/src/durable/Subscriptions.ts +1245 -0
- package/src/durable/ThreadArchiveRange.ts +91 -0
- package/src/durable/ThreadContextHistory.ts +338 -0
- package/src/durable/ThreadContextHistoryProjection.ts +219 -0
- package/src/durable/ThreadImport.ts +1199 -0
- package/src/durable/ThreadInvariants.ts +312 -0
- package/src/durable/ThreadProjectionMaintenance.ts +72 -0
- package/src/durable/ThreadReader.ts +21 -0
- package/src/durable/ThreadStore.ts +1258 -0
- package/src/durable/ThreadStoreConformance.ts +877 -0
- package/src/durable/ThreadTransfer.ts +263 -0
- package/src/durable/ThreadWork.ts +713 -0
- package/src/durable/ToolReconciler.ts +112 -0
- package/src/durable/WakeScheduler.ts +125 -0
- package/src/durable/WorkerAdmission.ts +98 -0
- package/src/durable/WorkerHost.ts +204 -0
- package/src/durable/internal/StorageOwner.ts +181 -0
- package/src/durable/internal/agent-registration.ts +713 -0
- package/src/durable/internal/agent-updates.ts +338 -0
- package/src/durable/internal/canonical-json.ts +110 -0
- package/src/durable/internal/evidence.ts +29 -0
- package/src/durable/internal/foreign-diagnostic.ts +48 -0
- package/src/durable/internal/history-prompt.ts +87 -0
- package/src/durable/internal/initial-context.ts +215 -0
- package/src/durable/internal/journal-metadata.ts +188 -0
- package/src/durable/internal/message-status.ts +18 -0
- package/src/durable/internal/messaging-host.ts +615 -0
- package/src/durable/internal/prompt-footprint.ts +47 -0
- package/src/durable/internal/prompt-history-cache.ts +604 -0
- package/src/durable/internal/record-encoding.ts +258 -0
- package/src/durable/internal/record-ownership.ts +68 -0
- package/src/durable/internal/run-context-reader.ts +51 -0
- package/src/durable/internal/run-context.ts +211 -0
- package/src/durable/internal/schedule-time.ts +304 -0
- package/src/durable/internal/thread-import-reader.ts +85 -0
- package/src/durable/internal/thread-initialization.ts +181 -0
- package/src/durable/internal/thread-transfer-source.ts +7 -0
- package/src/durable/internal/tool-operations.ts +138 -0
- package/src/durable/internal/transfer-dependencies.ts +40 -0
- package/src/durable/internal/usage-totals.ts +36 -0
- package/src/durable/internal/worker-host.ts +4041 -0
- package/src/durable/internal/worker-runtime.ts +10 -0
- package/src/engine/AgentRuntime.ts +100 -0
- package/src/engine/Compaction.ts +11 -0
- package/src/engine/ContextCompactor.ts +302 -0
- package/src/engine/ContextHistory.ts +75 -0
- package/src/engine/ContextWindow.ts +81 -0
- package/src/engine/DurableStep.ts +115 -0
- package/src/engine/MessagingHost.ts +118 -0
- package/src/engine/Output.ts +2 -0
- package/src/engine/RunEventSink.ts +124 -0
- package/src/engine/RunOptions.ts +664 -0
- package/src/engine/SubagentHost.ts +231 -0
- package/src/engine/ThreadHistory.ts +125 -0
- package/src/engine/ToolBroker.ts +159 -0
- package/src/engine/ToolExposure.ts +49 -0
- package/src/engine/internal/agent-runtime.ts +11137 -0
- package/src/engine/internal/bounded-value.ts +312 -0
- package/src/engine/internal/compaction.ts +673 -0
- package/src/engine/internal/error-diagnostic.ts +39 -0
- package/src/engine/internal/image-tokens.ts +61 -0
- package/src/engine/internal/interpreter-options.ts +569 -0
- package/src/engine/internal/output-contract.ts +226 -0
- package/src/engine/internal/primitive-delta.ts +103 -0
- package/src/engine/internal/provider-result-staging.ts +211 -0
- package/src/engine/internal/provisional-text.ts +107 -0
- package/src/engine/internal/tool-derivative.ts +47 -0
- package/src/engine/internal/tool-exposure.ts +228 -0
- package/src/engine/internal/tool-telemetry.ts +488 -0
- package/src/index.ts +100 -0
- package/src/sandbox/CodeExecutor.ts +352 -0
- package/src/sandbox/InteractiveBrowser.ts +343 -0
- package/src/sandbox/PageCapture.ts +391 -0
- package/src/sandbox/PageScreenshot.ts +83 -0
- package/src/sandbox/Sandbox.ts +29 -0
- package/README.md +0 -3
|
@@ -0,0 +1,4041 @@
|
|
|
1
|
+
import * as Cause from 'effect/Cause'
|
|
2
|
+
import * as Clock from 'effect/Clock'
|
|
3
|
+
import * as Context from 'effect/Context'
|
|
4
|
+
import * as CryptoDigest from 'effect/crypto/Digest'
|
|
5
|
+
import * as DateTime from 'effect/DateTime'
|
|
6
|
+
import * as Duration from 'effect/Duration'
|
|
7
|
+
import * as Effect from 'effect/Effect'
|
|
8
|
+
import * as Option from 'effect/Option'
|
|
9
|
+
import * as Schema from 'effect/Schema'
|
|
10
|
+
import * as Stream from 'effect/Stream'
|
|
11
|
+
|
|
12
|
+
import { resolveSubagentPolicy } from '../../capabilities/internal/subagent-policy'
|
|
13
|
+
import type * as Agent from '../../core/Agent'
|
|
14
|
+
import { AgentPolicy } from '../../core/AgentPolicy'
|
|
15
|
+
import { Update, UpdateError } from '../../core/AgentUpdates'
|
|
16
|
+
import { type AgentId, type SubmissionId, ThreadId } from '../../core/Identifiers'
|
|
17
|
+
import { MessageRef, type MessageStatus } from '../../core/Messaging'
|
|
18
|
+
import { IdempotencyKey, Receipt } from '../../core/Receipt'
|
|
19
|
+
import {
|
|
20
|
+
SubagentBudgetReservation,
|
|
21
|
+
SubagentDelegationCaps,
|
|
22
|
+
SubagentGrant,
|
|
23
|
+
SubagentPolicy,
|
|
24
|
+
} from '../../core/SubagentContract'
|
|
25
|
+
import {
|
|
26
|
+
FrameworkMessage,
|
|
27
|
+
type WorkerBudgetScope,
|
|
28
|
+
WorkerCompletion,
|
|
29
|
+
type WorkerContext,
|
|
30
|
+
WorkerError,
|
|
31
|
+
WorkerHistoryEntry,
|
|
32
|
+
WorkerRef,
|
|
33
|
+
type WorkerStarted,
|
|
34
|
+
WorkerStop,
|
|
35
|
+
type WorkerSummary,
|
|
36
|
+
WorkerUpdate,
|
|
37
|
+
} from '../../core/Worker'
|
|
38
|
+
import {
|
|
39
|
+
type DeferredFollowUpWorkerRequest,
|
|
40
|
+
type DeferredStartWorkerRequest,
|
|
41
|
+
type FollowUpWorkerRequest,
|
|
42
|
+
type StartWorkerRequest,
|
|
43
|
+
type SubagentHost,
|
|
44
|
+
type WorkerObservation,
|
|
45
|
+
type WorkerReceiptRequest,
|
|
46
|
+
type WorkerRunReport,
|
|
47
|
+
} from '../../engine/SubagentHost'
|
|
48
|
+
import { digestJson } from '../Digest'
|
|
49
|
+
import type {
|
|
50
|
+
DurableAbortFailure,
|
|
51
|
+
DurableAwaitFailure,
|
|
52
|
+
DurableSubmitFailure,
|
|
53
|
+
DurableSubmitOptions,
|
|
54
|
+
} from '../DurableAgentRuntime'
|
|
55
|
+
import { DurableRuntimeFailpoint, type DurableRuntimeFailpointLocation } from '../DurableFailpoint'
|
|
56
|
+
import {
|
|
57
|
+
MessageDeliveryDriver,
|
|
58
|
+
type MessageDeliveryRecord,
|
|
59
|
+
MessageDeliveryStore,
|
|
60
|
+
prepareMessageDelivery,
|
|
61
|
+
} from '../MessageDelivery'
|
|
62
|
+
import {
|
|
63
|
+
PreparedInput,
|
|
64
|
+
PreparedInputAdmission,
|
|
65
|
+
type PreparedInputFailure,
|
|
66
|
+
PreparedInputRefused,
|
|
67
|
+
PreparedInputRetryable,
|
|
68
|
+
} from '../PreparedInputAdmission'
|
|
69
|
+
import {
|
|
70
|
+
BatchId,
|
|
71
|
+
CanonicalBatch,
|
|
72
|
+
type CanonicalRecordEnvelope,
|
|
73
|
+
CanonicalSequence,
|
|
74
|
+
type DeploymentId,
|
|
75
|
+
type Digest,
|
|
76
|
+
MAX_RUN_EVIDENCE_BYTES,
|
|
77
|
+
MAX_RUN_EVIDENCE_RECORDS,
|
|
78
|
+
MAX_RUN_TERMINAL_BYTES,
|
|
79
|
+
PersistedJson,
|
|
80
|
+
type ProducerId,
|
|
81
|
+
RecordEnvelope,
|
|
82
|
+
RecordId,
|
|
83
|
+
SubtreeBudgetReserved,
|
|
84
|
+
WorkerAdmission,
|
|
85
|
+
WorkerContinuation,
|
|
86
|
+
WorkerInputCompleted,
|
|
87
|
+
WorkerInputRefused,
|
|
88
|
+
WorkerInputRequested,
|
|
89
|
+
WorkerOrigin,
|
|
90
|
+
WorkerReportingIntent,
|
|
91
|
+
WorkerReportPrepared,
|
|
92
|
+
WorkerReportRefused,
|
|
93
|
+
WorkerStopRequested,
|
|
94
|
+
WorkHandoffCompleted,
|
|
95
|
+
} from '../Records'
|
|
96
|
+
import { canonicalRecordBytes, readRunEvidenceSnapshot, reference } from '../RunContinuation'
|
|
97
|
+
import {
|
|
98
|
+
agentUpdateRecordId,
|
|
99
|
+
firstWorkerInputRecordId,
|
|
100
|
+
runIdForSubmission,
|
|
101
|
+
workerInputRecordId,
|
|
102
|
+
workerOriginRecordId,
|
|
103
|
+
workerReportRecordId,
|
|
104
|
+
} from '../RunJournal'
|
|
105
|
+
import {
|
|
106
|
+
AbortCommand,
|
|
107
|
+
type AbortIntent,
|
|
108
|
+
FundingOwnerRequest,
|
|
109
|
+
LedgerError,
|
|
110
|
+
type Principal,
|
|
111
|
+
type Settlement,
|
|
112
|
+
SubmissionLedger,
|
|
113
|
+
SubmissionLookupById,
|
|
114
|
+
SubmissionLookupByKey,
|
|
115
|
+
submissionSettlementRecordId,
|
|
116
|
+
type SubmissionSnapshot,
|
|
117
|
+
WorkerLedgerState,
|
|
118
|
+
} from '../SubmissionLedger'
|
|
119
|
+
import type { SubmissionStatus } from '../SubmissionStatus'
|
|
120
|
+
import {
|
|
121
|
+
AppendRequest,
|
|
122
|
+
getRecord,
|
|
123
|
+
getRunInput,
|
|
124
|
+
readWorkerState as readNativeWorkerState,
|
|
125
|
+
type ThreadIdentity,
|
|
126
|
+
ThreadIdentityRequest,
|
|
127
|
+
ThreadRead,
|
|
128
|
+
ThreadReader,
|
|
129
|
+
ThreadStore,
|
|
130
|
+
ThreadStoreError,
|
|
131
|
+
ThreadTailRequest,
|
|
132
|
+
type ThreadWorkerCapacity,
|
|
133
|
+
} from '../ThreadStore'
|
|
134
|
+
import { deliveryPredecessor, workId } from '../ThreadWork'
|
|
135
|
+
import { WakeScheduler } from '../WakeScheduler'
|
|
136
|
+
import {
|
|
137
|
+
WorkerBudgetAuthorizer,
|
|
138
|
+
WorkerConcurrencyLimit,
|
|
139
|
+
WorkerConcurrencyResolver,
|
|
140
|
+
WorkerHostAuthorizer,
|
|
141
|
+
WorkerHostConfig,
|
|
142
|
+
WorkerPolicyResolver,
|
|
143
|
+
type WorkerPolicyTarget,
|
|
144
|
+
type WorkerStartAdmission,
|
|
145
|
+
} from '../WorkerHost'
|
|
146
|
+
import { definitionDigestsEqual, type ResolvedBinding, resolveDefinitionBinding } from './agent-registration'
|
|
147
|
+
import { messageStatus } from './message-status'
|
|
148
|
+
import { ensureWorkerOrigin } from './thread-initialization'
|
|
149
|
+
import { unresolvedToolOperations } from './tool-operations'
|
|
150
|
+
|
|
151
|
+
const failure = (
|
|
152
|
+
operation: WorkerError['operation'],
|
|
153
|
+
reason: WorkerError['reason'],
|
|
154
|
+
cause?: unknown,
|
|
155
|
+
) => WorkerError.make({ operation, reason, ...(cause === undefined ? {} : { cause }) })
|
|
156
|
+
|
|
157
|
+
const storageFailure = (operation: WorkerError['operation']) => (cause: unknown) => failure(operation, 'storage', cause)
|
|
158
|
+
|
|
159
|
+
const decode = <S extends Schema.Top>(
|
|
160
|
+
schema: S,
|
|
161
|
+
value: unknown,
|
|
162
|
+
operation: WorkerError['operation'],
|
|
163
|
+
) =>
|
|
164
|
+
Schema.decodeUnknownEffect(Schema.toType(schema))(value).pipe(
|
|
165
|
+
Effect.mapError((cause) => failure(operation, 'corrupt', cause)),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
const sameOrigin = Schema.toEquivalence(WorkerOrigin)
|
|
169
|
+
const sameAdmission = Schema.toEquivalence(WorkerAdmission)
|
|
170
|
+
const sameReporting = Schema.toEquivalence(Schema.UndefinedOr(WorkerReportingIntent))
|
|
171
|
+
const sameJson = Schema.toEquivalence(PersistedJson)
|
|
172
|
+
const sameCaps = Schema.toEquivalence(SubagentDelegationCaps)
|
|
173
|
+
const samePolicy = Schema.toEquivalence(AgentPolicy)
|
|
174
|
+
|
|
175
|
+
const amountCaps = [
|
|
176
|
+
['turns', 'maxTurns'],
|
|
177
|
+
['toolCalls', 'maxToolCalls'],
|
|
178
|
+
['durationMillis', 'maxDurationMillis'],
|
|
179
|
+
['inputTokens', 'maxInputTokens'],
|
|
180
|
+
['outputTokens', 'maxOutputTokens'],
|
|
181
|
+
['costMicrousd', 'maxCostMicrousd'],
|
|
182
|
+
['resultBytes', 'maxResultBytes'],
|
|
183
|
+
] as const
|
|
184
|
+
|
|
185
|
+
const sourceCaps = (policy: AgentPolicy): SubagentDelegationCaps =>
|
|
186
|
+
SubagentDelegationCaps.make({
|
|
187
|
+
...(Number.isFinite(policy.maxToolCalls)
|
|
188
|
+
? {
|
|
189
|
+
maxTotalChildInvocations: policy.maxToolCalls,
|
|
190
|
+
maxToolCalls: policy.maxToolCalls,
|
|
191
|
+
maxResultBytes: Math.min(
|
|
192
|
+
Number.MAX_SAFE_INTEGER,
|
|
193
|
+
policy.toolResultBounds.maxBytes * policy.maxToolCalls,
|
|
194
|
+
),
|
|
195
|
+
}
|
|
196
|
+
: {}),
|
|
197
|
+
maxConcurrentChildren: policy.toolConcurrency,
|
|
198
|
+
...(Number.isFinite(policy.maxTurns) ? { maxTurns: policy.maxTurns } : {}),
|
|
199
|
+
maxDurationMillis: Math.ceil(Duration.toMillis(policy.maxDuration)),
|
|
200
|
+
...(policy.tokenBudget === undefined
|
|
201
|
+
? {}
|
|
202
|
+
: { maxInputTokens: policy.tokenBudget, maxOutputTokens: policy.tokenBudget }),
|
|
203
|
+
...(policy.costBudgetMicrousd === undefined
|
|
204
|
+
? {}
|
|
205
|
+
: { maxCostMicrousd: policy.costBudgetMicrousd }),
|
|
206
|
+
})
|
|
207
|
+
|
|
208
|
+
const withinPolicy = (origin: WorkerOrigin, source: AgentPolicy, target: AgentPolicy): boolean => {
|
|
209
|
+
const policy = origin.policy
|
|
210
|
+
const allocation = origin.budget.allocation
|
|
211
|
+
const caps = origin.budget.caps
|
|
212
|
+
const ceilings = sourceCaps(source)
|
|
213
|
+
|
|
214
|
+
for (const [, name] of origin.budgetScope === 'worker-run' ? [] : amountCaps) {
|
|
215
|
+
if (caps[name] !== undefined && ceilings[name] !== undefined && caps[name] > ceilings[name]) {
|
|
216
|
+
return false
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (
|
|
220
|
+
origin.budgetScope !== 'worker-run' &&
|
|
221
|
+
((caps.maxTotalChildInvocations !== undefined &&
|
|
222
|
+
caps.maxTotalChildInvocations > source.maxToolCalls) ||
|
|
223
|
+
(caps.maxConcurrentChildren !== undefined &&
|
|
224
|
+
caps.maxConcurrentChildren > source.toolConcurrency))
|
|
225
|
+
) {
|
|
226
|
+
return false
|
|
227
|
+
}
|
|
228
|
+
const tokenCeiling = Math.min(source.tokenBudget ?? Infinity, target.tokenBudget ?? Infinity)
|
|
229
|
+
|
|
230
|
+
const costCeiling = Math.min(
|
|
231
|
+
source.costBudgetMicrousd ?? Infinity,
|
|
232
|
+
target.costBudgetMicrousd ?? Infinity,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
return (
|
|
236
|
+
policy.maxTurns <= Math.min(allocation.turns, source.maxTurns, target.maxTurns) &&
|
|
237
|
+
policy.maxToolCalls <=
|
|
238
|
+
Math.min(allocation.toolCalls, source.maxToolCalls, target.maxToolCalls) &&
|
|
239
|
+
Duration.toMillis(policy.maxDuration) <=
|
|
240
|
+
Math.min(
|
|
241
|
+
allocation.durationMillis,
|
|
242
|
+
Duration.toMillis(source.maxDuration),
|
|
243
|
+
Duration.toMillis(target.maxDuration),
|
|
244
|
+
) &&
|
|
245
|
+
policy.toolConcurrency <= Math.min(source.toolConcurrency, target.toolConcurrency) &&
|
|
246
|
+
policy.toolResultBounds.maxBytes <=
|
|
247
|
+
Math.min(source.toolResultBounds.maxBytes, target.toolResultBounds.maxBytes) &&
|
|
248
|
+
(tokenCeiling === Infinity ||
|
|
249
|
+
(policy.tokenBudget !== undefined && policy.tokenBudget <= tokenCeiling)) &&
|
|
250
|
+
(costCeiling === Infinity ||
|
|
251
|
+
(policy.costBudgetMicrousd !== undefined && policy.costBudgetMicrousd <= costCeiling)) &&
|
|
252
|
+
(source.tokenBudget === undefined ||
|
|
253
|
+
(allocation.inputTokens > 0 &&
|
|
254
|
+
allocation.outputTokens > 0 &&
|
|
255
|
+
policy.tokenBudget !== undefined &&
|
|
256
|
+
policy.tokenBudget <= allocation.inputTokens + allocation.outputTokens)) &&
|
|
257
|
+
(source.costBudgetMicrousd === undefined ||
|
|
258
|
+
(policy.costBudgetMicrousd !== undefined &&
|
|
259
|
+
policy.costBudgetMicrousd <= allocation.costMicrousd))
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface WorkerRuntimeOptions {
|
|
264
|
+
readonly bindings: ReadonlyArray<ResolvedBinding>
|
|
265
|
+
readonly deploymentId: DeploymentId
|
|
266
|
+
readonly producerId: ProducerId
|
|
267
|
+
readonly settlementPollInterval: Duration.Duration
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Admission and cancellation enter the owning runtime, never the raw ledger. */
|
|
271
|
+
export class WorkerInputControl extends Context.Service<
|
|
272
|
+
WorkerInputControl,
|
|
273
|
+
{
|
|
274
|
+
readonly submit: (envelope: PreparedInput) => Effect.Effect<Receipt, DurableSubmitFailure>
|
|
275
|
+
readonly status: (
|
|
276
|
+
receipt: Receipt,
|
|
277
|
+
) => Effect.Effect<SubmissionStatus, DurableAwaitFailure | PreparedInputFailure>
|
|
278
|
+
readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>
|
|
279
|
+
}
|
|
280
|
+
>()('@effect-agent/thread/internal/WorkerInputControl') {}
|
|
281
|
+
|
|
282
|
+
const CurrentStartDelivery = Context.Reference<
|
|
283
|
+
| {
|
|
284
|
+
readonly authorization: WorkerStartAdmission
|
|
285
|
+
readonly admission: WorkerAdmission
|
|
286
|
+
readonly inputDigest: Digest
|
|
287
|
+
}
|
|
288
|
+
| undefined
|
|
289
|
+
>('@effect-agent/thread/internal/CurrentStartDelivery', { defaultValue: () => undefined })
|
|
290
|
+
|
|
291
|
+
/** No in-memory ownership: every mutation is reserved in source canonical history with CAS. */
|
|
292
|
+
export const makeWorkerRuntime = Effect.fnUntraced(function*(options: WorkerRuntimeOptions) {
|
|
293
|
+
const control = yield* WorkerInputControl
|
|
294
|
+
// A routed read may belong to another owner; capture it before exposing worker operations.
|
|
295
|
+
const admission = yield* Effect.serviceOption(PreparedInputAdmission)
|
|
296
|
+
|
|
297
|
+
const deps = {
|
|
298
|
+
...options,
|
|
299
|
+
...control,
|
|
300
|
+
store: yield* ThreadStore,
|
|
301
|
+
ledger: yield* SubmissionLedger,
|
|
302
|
+
deliveries: yield* Effect.serviceOption(MessageDeliveryStore),
|
|
303
|
+
crypto: yield* CryptoDigest.Digest,
|
|
304
|
+
authorizer: yield* WorkerHostAuthorizer,
|
|
305
|
+
budgetAuthorizer: yield* WorkerBudgetAuthorizer,
|
|
306
|
+
policyResolver: yield* WorkerPolicyResolver,
|
|
307
|
+
concurrencyResolver: yield* WorkerConcurrencyResolver,
|
|
308
|
+
limits: yield* WorkerHostConfig,
|
|
309
|
+
failpoint: yield* DurableRuntimeFailpoint,
|
|
310
|
+
wake: yield* Effect.serviceOption(WakeScheduler),
|
|
311
|
+
status: Option.getOrUndefined(admission)?.submissionStatus ?? control.status,
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const readWorkerCapacity = deps.store.readWorkerCapacity?.bind(deps.store)
|
|
315
|
+
|
|
316
|
+
if (readWorkerCapacity === undefined) {
|
|
317
|
+
return yield* ThreadStoreError.make({
|
|
318
|
+
operation: 'construct worker runtime',
|
|
319
|
+
message: 'The storage adapter has no worker-capacity port',
|
|
320
|
+
})
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const withCrypto = <A, E>(effect: Effect.Effect<A, E, CryptoDigest.Digest>) =>
|
|
324
|
+
Effect.provideService(effect, CryptoDigest.Digest, deps.crypto)
|
|
325
|
+
|
|
326
|
+
const currentStart = Effect.fnUntraced(function*(
|
|
327
|
+
admission: WorkerStartAdmission | undefined,
|
|
328
|
+
sourceThreadId: ThreadId,
|
|
329
|
+
sourceSubmissionId: SubmissionId | undefined,
|
|
330
|
+
principal: Principal,
|
|
331
|
+
targetAgentId: AgentId,
|
|
332
|
+
continuationOf: WorkerContinuation | undefined,
|
|
333
|
+
) {
|
|
334
|
+
if (
|
|
335
|
+
admission === undefined ||
|
|
336
|
+
admission.sourceThreadId !== sourceThreadId ||
|
|
337
|
+
admission.sourceSubmissionId !== sourceSubmissionId ||
|
|
338
|
+
(admission.principal !== principal && admission.requestedPrincipal !== principal) ||
|
|
339
|
+
admission.targetAgentId !== targetAgentId ||
|
|
340
|
+
!Schema.toEquivalence(Schema.UndefinedOr(WorkerContinuation))(
|
|
341
|
+
admission.continuationOf,
|
|
342
|
+
continuationOf,
|
|
343
|
+
)
|
|
344
|
+
) {
|
|
345
|
+
return undefined
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const tail = yield* deps.store
|
|
349
|
+
.inspectTail(ThreadTailRequest.make({ threadId: sourceThreadId }))
|
|
350
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
351
|
+
|
|
352
|
+
return tail.tailSequence === admission.tailSequence ? admission : undefined
|
|
353
|
+
})
|
|
354
|
+
|
|
355
|
+
const authorizeBudget = Effect.fnUntraced(function*(
|
|
356
|
+
origin: WorkerOrigin,
|
|
357
|
+
principal: Principal,
|
|
358
|
+
admission?: WorkerStartAdmission,
|
|
359
|
+
) {
|
|
360
|
+
yield* verifyContinuation(origin)
|
|
361
|
+
if (origin.budgetScope !== 'worker-run') return
|
|
362
|
+
// Independence changes accounting ownership, never delegation generations.
|
|
363
|
+
if (origin.depth !== 1) return yield* failure('start', 'denied')
|
|
364
|
+
|
|
365
|
+
yield* deps.budgetAuthorizer.authorize({
|
|
366
|
+
...(admission === undefined ? {} : { admission }),
|
|
367
|
+
source: origin.source,
|
|
368
|
+
principal,
|
|
369
|
+
worker: origin.worker,
|
|
370
|
+
...(origin.continuationOf === undefined ? {} : { continuationOf: origin.continuationOf }),
|
|
371
|
+
policy: origin.policy,
|
|
372
|
+
budget: origin.budget,
|
|
373
|
+
})
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
const exactRecord = (
|
|
377
|
+
threadId: ThreadId,
|
|
378
|
+
recordId: RecordId,
|
|
379
|
+
operation: WorkerError['operation'],
|
|
380
|
+
) =>
|
|
381
|
+
getRecord({ threadId, recordId }).pipe(
|
|
382
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
383
|
+
Effect.mapError(storageFailure(operation)),
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
const readStop = Effect.fnUntraced(function*(
|
|
387
|
+
threadId: ThreadId,
|
|
388
|
+
workerThreadId: ThreadId,
|
|
389
|
+
throughSequence: CanonicalSequence,
|
|
390
|
+
) {
|
|
391
|
+
const page = yield* Stream.runCollect(
|
|
392
|
+
deps.store.read({
|
|
393
|
+
threadId,
|
|
394
|
+
selection: { _tag: 'WorkerStop', workerThreadId, throughSequence },
|
|
395
|
+
page: { limit: 1 },
|
|
396
|
+
}),
|
|
397
|
+
).pipe(Effect.mapError(storageFailure('stop')))
|
|
398
|
+
|
|
399
|
+
const entry = page[0]
|
|
400
|
+
|
|
401
|
+
if (
|
|
402
|
+
page.length > 1 ||
|
|
403
|
+
(entry !== undefined &&
|
|
404
|
+
(entry.threadId !== threadId ||
|
|
405
|
+
entry.sequence > throughSequence ||
|
|
406
|
+
entry.record.payload._tag !== 'WorkerStopRequested' ||
|
|
407
|
+
entry.record.payload.command.worker.threadId !== workerThreadId))
|
|
408
|
+
) {
|
|
409
|
+
return yield* failure('stop', 'corrupt')
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return entry
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
/** One worker Receipt and its exact joined host, without the unrelated Thread transcript. */
|
|
416
|
+
const readSubmission = Effect.fnUntraced(function*(submission: SubmissionSnapshot) {
|
|
417
|
+
const threadId = submission.threadId
|
|
418
|
+
|
|
419
|
+
const tail = yield* deps.store
|
|
420
|
+
.inspectTail(ThreadTailRequest.make({ threadId }))
|
|
421
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
422
|
+
|
|
423
|
+
const identity = yield* deps.store
|
|
424
|
+
.readIdentity(ThreadIdentityRequest.make({ threadId }))
|
|
425
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
426
|
+
|
|
427
|
+
const selected = [submission.submissionId]
|
|
428
|
+
|
|
429
|
+
const settled = Option.getOrUndefined(
|
|
430
|
+
yield* exactRecord(
|
|
431
|
+
threadId,
|
|
432
|
+
submissionSettlementRecordId(submission.submissionId),
|
|
433
|
+
'inspect',
|
|
434
|
+
),
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
if (
|
|
438
|
+
settled?.record.payload._tag === 'SubmissionSettled' &&
|
|
439
|
+
settled.record.payload.runId !== undefined &&
|
|
440
|
+
settled.record.payload.runId !== runIdForSubmission(submission.submissionId)
|
|
441
|
+
) {
|
|
442
|
+
const original = yield* getRunInput({ threadId, runId: settled.record.payload.runId }).pipe(
|
|
443
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
444
|
+
Effect.mapError(storageFailure('inspect')),
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
const input = Option.getOrUndefined(original)?.record.payload
|
|
448
|
+
|
|
449
|
+
if (input?._tag !== 'UserInputRecorded' || input.submissionId === undefined) {
|
|
450
|
+
return yield* failure('inspect', 'corrupt')
|
|
451
|
+
}
|
|
452
|
+
selected.push(input.submissionId)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const byId = new Map(
|
|
456
|
+
identity.records
|
|
457
|
+
.filter((entry) => entry.sequence <= tail.tailSequence)
|
|
458
|
+
.map((entry) => [entry.record.recordId, entry]),
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
let bytes = 0
|
|
462
|
+
|
|
463
|
+
for (const submissionId of selected) {
|
|
464
|
+
const records = yield* readRunEvidenceSnapshot(
|
|
465
|
+
threadId,
|
|
466
|
+
submissionId,
|
|
467
|
+
tail.tailSequence,
|
|
468
|
+
).pipe(
|
|
469
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
470
|
+
Effect.provideService(CryptoDigest.Digest, deps.crypto),
|
|
471
|
+
Effect.mapError(storageFailure('inspect')),
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
for (const entry of records) {
|
|
475
|
+
if (!byId.has(entry.record.recordId)) bytes += canonicalRecordBytes(entry.record)
|
|
476
|
+
if (bytes > MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES) {
|
|
477
|
+
return yield* failure('inspect', 'capacity')
|
|
478
|
+
}
|
|
479
|
+
byId.set(entry.record.recordId, entry)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return {
|
|
484
|
+
...tail,
|
|
485
|
+
records: [...byId.values()].sort((left, right) => left.sequence - right.sequence),
|
|
486
|
+
}
|
|
487
|
+
})
|
|
488
|
+
|
|
489
|
+
const completedContinuation = Effect.fnUntraced(function*(
|
|
490
|
+
source: WorkerContext['source'],
|
|
491
|
+
worker: WorkerRef,
|
|
492
|
+
targetAgentId: AgentId,
|
|
493
|
+
delegationId: WorkerRef['delegationId'],
|
|
494
|
+
expected?: WorkerContinuation,
|
|
495
|
+
) {
|
|
496
|
+
const selected = yield* decode(WorkerRef, worker, 'start')
|
|
497
|
+
|
|
498
|
+
if (
|
|
499
|
+
selected.targetAgentId !== targetAgentId ||
|
|
500
|
+
selected.delegationId !== delegationId ||
|
|
501
|
+
selected.threadId === source.threadId ||
|
|
502
|
+
deps.ledger.inspectWorker === undefined
|
|
503
|
+
) {
|
|
504
|
+
return yield* failure('start', 'worker-mismatch')
|
|
505
|
+
}
|
|
506
|
+
const sourceState = yield* readIdentity(source.threadId, 'start')
|
|
507
|
+
|
|
508
|
+
if (yield* readStop(source.threadId, selected.threadId, sourceState.tailSequence)) {
|
|
509
|
+
return yield* failure('start', 'denied')
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
const first = Option.getOrUndefined(
|
|
513
|
+
yield* exactRecord(source.threadId, firstWorkerInputRecordId(selected), 'start'),
|
|
514
|
+
)?.record.payload
|
|
515
|
+
|
|
516
|
+
const origin = first?._tag === 'WorkerInputRequested' ? first.admission.origin : undefined
|
|
517
|
+
|
|
518
|
+
if (
|
|
519
|
+
origin === undefined ||
|
|
520
|
+
origin.lifecycle !== 'assignment' ||
|
|
521
|
+
!Schema.toEquivalence(WorkerRef)(origin.worker, selected) ||
|
|
522
|
+
origin.source.threadId !== source.threadId ||
|
|
523
|
+
origin.source.agentId !== source.agentId ||
|
|
524
|
+
first?._tag !== 'WorkerInputRequested' ||
|
|
525
|
+
first.admission.messageId !== origin.firstMessageId
|
|
526
|
+
) {
|
|
527
|
+
return yield* failure('start', 'worker-mismatch')
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const recorded = Option.getOrUndefined(
|
|
531
|
+
yield* exactRecord(selected.threadId, workerOriginRecordId(selected.threadId), 'start'),
|
|
532
|
+
)?.record.payload
|
|
533
|
+
|
|
534
|
+
if (recorded?._tag !== 'WorkerOriginRecorded' || !sameOrigin(recorded.origin, origin)) {
|
|
535
|
+
return yield* failure('start', 'worker-mismatch')
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const control = yield* deps.ledger
|
|
539
|
+
.inspectWorker(selected.threadId)
|
|
540
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
541
|
+
|
|
542
|
+
if (control.terminal !== 'completed' || !control.stopped || control.active !== null) {
|
|
543
|
+
return yield* failure('start', 'denied')
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const tail = yield* deps.store
|
|
547
|
+
.inspectTail(ThreadTailRequest.make({ threadId: selected.threadId }))
|
|
548
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
549
|
+
|
|
550
|
+
const execution = yield* deps.store
|
|
551
|
+
.read({
|
|
552
|
+
threadId: selected.threadId,
|
|
553
|
+
selection: {
|
|
554
|
+
_tag: 'WorkerExecution',
|
|
555
|
+
expectedTailSequence: tail.tailSequence,
|
|
556
|
+
},
|
|
557
|
+
page: { limit: 2 },
|
|
558
|
+
})
|
|
559
|
+
.pipe(Stream.runCollect, Effect.mapError(storageFailure('start')))
|
|
560
|
+
|
|
561
|
+
const run = execution.find(({ record }) => record.payload._tag === 'SubmissionSettled')?.record
|
|
562
|
+
.payload
|
|
563
|
+
|
|
564
|
+
if (run?._tag !== 'SubmissionSettled' || run.runId === undefined) {
|
|
565
|
+
return yield* failure('start', 'corrupt')
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const input = Option.getOrUndefined(
|
|
569
|
+
yield* getRunInput({ threadId: selected.threadId, runId: run.runId }).pipe(
|
|
570
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
571
|
+
Effect.mapError(storageFailure('start')),
|
|
572
|
+
),
|
|
573
|
+
)?.record.payload
|
|
574
|
+
|
|
575
|
+
if (input?._tag !== 'UserInputRecorded' || input.submissionId === undefined) {
|
|
576
|
+
return yield* failure('start', 'corrupt')
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const found = yield* deps.ledger
|
|
580
|
+
.lookup(SubmissionLookupById.make({ submissionId: input.submissionId }))
|
|
581
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
582
|
+
|
|
583
|
+
const row = Option.getOrUndefined(found)
|
|
584
|
+
|
|
585
|
+
const settlement = Option.getOrUndefined(
|
|
586
|
+
yield* exactRecord(
|
|
587
|
+
selected.threadId,
|
|
588
|
+
submissionSettlementRecordId(input.submissionId),
|
|
589
|
+
'start',
|
|
590
|
+
),
|
|
591
|
+
)?.record.payload
|
|
592
|
+
|
|
593
|
+
if (
|
|
594
|
+
row === undefined ||
|
|
595
|
+
row.threadId !== selected.threadId ||
|
|
596
|
+
row.state !== 'settled' ||
|
|
597
|
+
row.settledOutcome !== 'completed' ||
|
|
598
|
+
row.workerAdmission === undefined ||
|
|
599
|
+
!sameOrigin(row.workerAdmission.origin, origin) ||
|
|
600
|
+
settlement?._tag !== 'SubmissionSettled' ||
|
|
601
|
+
settlement.outcome !== 'completed' ||
|
|
602
|
+
settlement.runDisposition !== 'completed' ||
|
|
603
|
+
settlement.finishReason !== undefined ||
|
|
604
|
+
settlement.runId !== run.runId ||
|
|
605
|
+
settlement.submissionId !== row.submissionId ||
|
|
606
|
+
settlement.receiptId !== row.receiptId
|
|
607
|
+
) {
|
|
608
|
+
return yield* failure('start', 'denied')
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const evidence = WorkerContinuation.make({
|
|
612
|
+
worker: selected,
|
|
613
|
+
receipt: Receipt.make({
|
|
614
|
+
threadId: row.threadId,
|
|
615
|
+
submissionId: row.submissionId,
|
|
616
|
+
receiptId: row.receiptId,
|
|
617
|
+
queueSequence: row.queueSequence,
|
|
618
|
+
}),
|
|
619
|
+
settlementId: settlement.settlementId,
|
|
620
|
+
})
|
|
621
|
+
|
|
622
|
+
if (expected !== undefined && !Schema.toEquivalence(WorkerContinuation)(expected, evidence)) {
|
|
623
|
+
return yield* failure('start', 'worker-mismatch')
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
return { evidence, origin }
|
|
627
|
+
})
|
|
628
|
+
|
|
629
|
+
const verifyContinuation = Effect.fnUntraced(function*(origin: WorkerOrigin) {
|
|
630
|
+
if (origin.continuationOf === undefined) return
|
|
631
|
+
|
|
632
|
+
const previous = yield* completedContinuation(
|
|
633
|
+
origin.source,
|
|
634
|
+
origin.continuationOf.worker,
|
|
635
|
+
origin.worker.targetAgentId,
|
|
636
|
+
origin.worker.delegationId,
|
|
637
|
+
origin.continuationOf,
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
if (
|
|
641
|
+
origin.worker.threadId === previous.origin.worker.threadId ||
|
|
642
|
+
origin.lifecycle !== 'assignment' ||
|
|
643
|
+
!samePolicy(origin.policy, previous.origin.policy) ||
|
|
644
|
+
!Schema.toEquivalence(WorkerOrigin.fields.budget)(origin.budget, previous.origin.budget) ||
|
|
645
|
+
!Schema.toEquivalence(SubagentGrant)(origin.grant, previous.origin.grant) ||
|
|
646
|
+
origin.budgetScope !== previous.origin.budgetScope ||
|
|
647
|
+
origin.depth !== previous.origin.depth ||
|
|
648
|
+
origin.toolCallAllowance !== previous.origin.toolCallAllowance ||
|
|
649
|
+
origin.expiresAtMillis > previous.origin.expiresAtMillis
|
|
650
|
+
) {
|
|
651
|
+
return yield* failure('start', 'denied')
|
|
652
|
+
}
|
|
653
|
+
})
|
|
654
|
+
|
|
655
|
+
const readIdentity = (threadId: ThreadId, operation: WorkerError['operation']) =>
|
|
656
|
+
deps.store
|
|
657
|
+
.readIdentity(ThreadIdentityRequest.make({ threadId }))
|
|
658
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
659
|
+
|
|
660
|
+
const readWorkerState = (
|
|
661
|
+
threadId: ThreadId,
|
|
662
|
+
operation: WorkerError['operation'],
|
|
663
|
+
sourceSubmissionId: SubmissionId,
|
|
664
|
+
) =>
|
|
665
|
+
readNativeWorkerState({
|
|
666
|
+
threadId,
|
|
667
|
+
limit: MAX_RUN_EVIDENCE_RECORDS,
|
|
668
|
+
sourceSubmissionId,
|
|
669
|
+
}).pipe(
|
|
670
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
671
|
+
Effect.mapError(storageFailure(operation)),
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
const hit = (location: DurableRuntimeFailpointLocation, operation: WorkerError['operation']) =>
|
|
675
|
+
deps.failpoint.hit(location).pipe(Effect.mapError(storageFailure(operation)))
|
|
676
|
+
|
|
677
|
+
const append = Effect.fnUntraced(
|
|
678
|
+
function*(
|
|
679
|
+
threadId: ThreadId,
|
|
680
|
+
id: string,
|
|
681
|
+
payload:
|
|
682
|
+
| WorkerStopRequested
|
|
683
|
+
| WorkHandoffCompleted
|
|
684
|
+
| WorkerInputRequested
|
|
685
|
+
| WorkerInputRefused
|
|
686
|
+
| WorkerInputCompleted
|
|
687
|
+
| WorkerReportPrepared
|
|
688
|
+
| WorkerReportRefused
|
|
689
|
+
| SubtreeBudgetReserved,
|
|
690
|
+
current: Pick<ThreadIdentity, 'tailSequence' | 'records'>,
|
|
691
|
+
phase: 'source' | 'completion' | 'subtree' | 'report' | 'stop',
|
|
692
|
+
) {
|
|
693
|
+
const operation = 'start'
|
|
694
|
+
|
|
695
|
+
// The owner's transaction checks the exact prefix used for this decision.
|
|
696
|
+
yield* hit(`worker:before-${phase}-append`, operation)
|
|
697
|
+
|
|
698
|
+
const result = yield* deps.store
|
|
699
|
+
.append(
|
|
700
|
+
AppendRequest.make({
|
|
701
|
+
threadId,
|
|
702
|
+
expectedTailSequence: current.tailSequence,
|
|
703
|
+
|
|
704
|
+
batch: CanonicalBatch.make({
|
|
705
|
+
batchId: yield* Schema.decodeEffect(BatchId)(id).pipe(Effect.orDie),
|
|
706
|
+
producerId: deps.producerId,
|
|
707
|
+
records: [
|
|
708
|
+
RecordEnvelope.make({
|
|
709
|
+
recordId: yield* Schema.decodeEffect(RecordId)(id).pipe(Effect.orDie),
|
|
710
|
+
family: 'thread',
|
|
711
|
+
schemaVersion: 1,
|
|
712
|
+
createdAt: DateTime.makeUnsafe(
|
|
713
|
+
payload._tag === 'WorkerInputRequested'
|
|
714
|
+
? payload.admission.createdAtMillis
|
|
715
|
+
: payload._tag === 'WorkerInputCompleted'
|
|
716
|
+
? payload.completedAtMillis
|
|
717
|
+
: yield* Clock.currentTimeMillis,
|
|
718
|
+
),
|
|
719
|
+
deploymentId: deps.deploymentId,
|
|
720
|
+
payload,
|
|
721
|
+
}),
|
|
722
|
+
],
|
|
723
|
+
}),
|
|
724
|
+
}),
|
|
725
|
+
)
|
|
726
|
+
.pipe(
|
|
727
|
+
Effect.as(true),
|
|
728
|
+
Effect.catchTag('AppendConflict', () => Effect.succeed(false)),
|
|
729
|
+
)
|
|
730
|
+
|
|
731
|
+
if (result) yield* hit(`worker:after-${phase}-append`, operation)
|
|
732
|
+
|
|
733
|
+
return result
|
|
734
|
+
},
|
|
735
|
+
Effect.mapError(storageFailure('start')),
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
const completedMessageIds = (records: ReadonlyArray<CanonicalRecordEnvelope>) =>
|
|
739
|
+
new Set<string>(
|
|
740
|
+
records.flatMap(({ record }) =>
|
|
741
|
+
(record.payload._tag === 'WorkerInputCompleted' && record.payload.effectsResolved) ||
|
|
742
|
+
record.payload._tag === 'WorkerInputRefused'
|
|
743
|
+
? [record.payload.messageId]
|
|
744
|
+
: []
|
|
745
|
+
),
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
const reportIntent = Effect.fnUntraced(function*(
|
|
749
|
+
source: ResolvedBinding,
|
|
750
|
+
target: ResolvedBinding,
|
|
751
|
+
delegationId: WorkerRef['delegationId'],
|
|
752
|
+
authority: Effect.Success<ReturnType<typeof sourceAuthority>>,
|
|
753
|
+
): Effect.fn.Return<WorkerOrigin['reporting'], WorkerError> {
|
|
754
|
+
const reports = source.reporting?.filter((entry) => entry.delegationId === delegationId) ?? []
|
|
755
|
+
const report = reports[0]
|
|
756
|
+
|
|
757
|
+
if (report === undefined) return undefined
|
|
758
|
+
if (reports.length !== 1 || !Object.is(report.target, target.definition)) {
|
|
759
|
+
return yield* failure('start', 'declaration-unavailable')
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
const submission = authority.submission
|
|
763
|
+
|
|
764
|
+
if (
|
|
765
|
+
submission === undefined ||
|
|
766
|
+
(authority.depth !== 0 && submission.workerAdmission === undefined)
|
|
767
|
+
) {
|
|
768
|
+
return yield* failure('start', 'denied')
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const retained = submission.workerAdmission === undefined
|
|
772
|
+
? undefined
|
|
773
|
+
: yield* Schema.encodeEffect(WorkerAdmission)(submission.workerAdmission).pipe(
|
|
774
|
+
Effect.flatMap(Schema.decodeEffect(PersistedJson)),
|
|
775
|
+
Effect.mapError(storageFailure('start')),
|
|
776
|
+
)
|
|
777
|
+
|
|
778
|
+
return {
|
|
779
|
+
sourceDigests: source.digests,
|
|
780
|
+
mode: 'standard',
|
|
781
|
+
returnAddress: {
|
|
782
|
+
input: submission.inputPayload,
|
|
783
|
+
principal: submission.principal,
|
|
784
|
+
policy: authority.policy,
|
|
785
|
+
depth: authority.depth,
|
|
786
|
+
...(authority.grant === undefined ? {} : { grant: authority.grant }),
|
|
787
|
+
...(retained === undefined ? {} : { workerAdmission: retained }),
|
|
788
|
+
},
|
|
789
|
+
}
|
|
790
|
+
})
|
|
791
|
+
|
|
792
|
+
const currentBinding = (agentId: AgentId): ResolvedBinding | undefined => {
|
|
793
|
+
const matches = deps.bindings.filter((entry) => entry.agentId === agentId)
|
|
794
|
+
|
|
795
|
+
return matches.length === 1 ? matches[0] : undefined
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const sourceAuthority = Effect.fnUntraced(function*(
|
|
799
|
+
threadId: ThreadId,
|
|
800
|
+
submissionId?: SubmissionId,
|
|
801
|
+
reservations = false,
|
|
802
|
+
) {
|
|
803
|
+
let ownerSubmission: SubmissionSnapshot | undefined
|
|
804
|
+
|
|
805
|
+
if (submissionId !== undefined) {
|
|
806
|
+
if (deps.ledger.resolveFundingOwner === undefined) {
|
|
807
|
+
return yield* failure('start', 'unavailable')
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const funding = yield* deps.ledger
|
|
811
|
+
.resolveFundingOwner(FundingOwnerRequest.make({ threadId, submissionId }))
|
|
812
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
813
|
+
|
|
814
|
+
if (
|
|
815
|
+
funding.selected.submissionId !== submissionId ||
|
|
816
|
+
funding.selected.threadId !== threadId ||
|
|
817
|
+
funding.owner.threadId !== threadId
|
|
818
|
+
) {
|
|
819
|
+
return yield* failure('start', 'denied')
|
|
820
|
+
}
|
|
821
|
+
ownerSubmission = funding.owner
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const current = yield* reservations && ownerSubmission !== undefined
|
|
825
|
+
? readWorkerState(threadId, 'start', ownerSubmission.submissionId)
|
|
826
|
+
: readIdentity(threadId, 'start')
|
|
827
|
+
|
|
828
|
+
const created = current.records[0]?.record.payload
|
|
829
|
+
|
|
830
|
+
if (created?._tag !== 'ThreadCreated' || current.records[0]?.sequence !== 1) {
|
|
831
|
+
return yield* failure('start', 'not-found')
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const binding = currentBinding(created.agentId)
|
|
835
|
+
|
|
836
|
+
const worker = current.records.find(
|
|
837
|
+
({ record }) => record.payload._tag === 'WorkerOriginRecorded',
|
|
838
|
+
)?.record.payload
|
|
839
|
+
|
|
840
|
+
const attached = current.records.find(
|
|
841
|
+
({ record }) => record.payload._tag === 'SubagentLineageRecorded',
|
|
842
|
+
)?.record.payload
|
|
843
|
+
|
|
844
|
+
const nested = worker?._tag === 'WorkerOriginRecorded' || attached?._tag === 'SubagentLineageRecorded'
|
|
845
|
+
|
|
846
|
+
if (nested && ownerSubmission === undefined) return yield* failure('start', 'denied')
|
|
847
|
+
if (ownerSubmission !== undefined) {
|
|
848
|
+
if (nested && ownerSubmission.agentId !== created.agentId) {
|
|
849
|
+
return yield* failure('start', 'denied')
|
|
850
|
+
}
|
|
851
|
+
if (
|
|
852
|
+
worker?._tag === 'WorkerOriginRecorded' &&
|
|
853
|
+
(ownerSubmission.workerAdmission === undefined ||
|
|
854
|
+
!sameOrigin(ownerSubmission.workerAdmission.origin, worker.origin))
|
|
855
|
+
) {
|
|
856
|
+
return yield* failure('start', 'denied')
|
|
857
|
+
}
|
|
858
|
+
if (
|
|
859
|
+
attached?._tag === 'SubagentLineageRecorded' &&
|
|
860
|
+
(ownerSubmission.parentLinkage?.parentSubmissionId !== attached.parentSubmissionId ||
|
|
861
|
+
ownerSubmission.parentLinkage.parentToolCallId !== attached.parentLink.parentToolCallId)
|
|
862
|
+
) {
|
|
863
|
+
return yield* failure('start', 'denied')
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const ownerBinding = ownerSubmission === undefined ? undefined : currentBinding(ownerSubmission.agentId)
|
|
868
|
+
|
|
869
|
+
const selectedBinding = ownerBinding ?? binding
|
|
870
|
+
|
|
871
|
+
if (worker?._tag === 'WorkerOriginRecorded') {
|
|
872
|
+
return {
|
|
873
|
+
current,
|
|
874
|
+
binding: selectedBinding,
|
|
875
|
+
submission: ownerSubmission,
|
|
876
|
+
policyOverride: Option.none<AgentPolicy>(),
|
|
877
|
+
policy: worker.origin.policy,
|
|
878
|
+
budget: worker.origin.budget,
|
|
879
|
+
budgetScope: worker.origin.budgetScope,
|
|
880
|
+
grant: worker.origin.grant,
|
|
881
|
+
depth: worker.origin.depth,
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
if (attached?._tag === 'SubagentLineageRecorded') {
|
|
885
|
+
if (
|
|
886
|
+
attached.policy === undefined ||
|
|
887
|
+
attached.budget === undefined ||
|
|
888
|
+
attached.grant === undefined
|
|
889
|
+
) {
|
|
890
|
+
return yield* failure('start', 'denied')
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
return {
|
|
894
|
+
current,
|
|
895
|
+
binding: selectedBinding,
|
|
896
|
+
submission: ownerSubmission,
|
|
897
|
+
policyOverride: Option.none<AgentPolicy>(),
|
|
898
|
+
policy: attached.policy,
|
|
899
|
+
budget: attached.budget,
|
|
900
|
+
budgetScope: undefined,
|
|
901
|
+
grant: attached.grant,
|
|
902
|
+
depth: attached.parentLink.depth,
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
const changedRootAgent = ownerSubmission !== undefined && ownerSubmission.agentId !== created.agentId
|
|
907
|
+
|
|
908
|
+
// A root conversation may admit a new registered Agent after deployment.
|
|
909
|
+
// Its immutable owner input selects authority; child lineage never changes.
|
|
910
|
+
if (selectedBinding === undefined || (changedRootAgent && ownerBinding === undefined)) {
|
|
911
|
+
return yield* failure('start', 'declaration-unavailable')
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
const selected = yield* deps.policyResolver.resolveSource({
|
|
915
|
+
threadId,
|
|
916
|
+
definition: selectedBinding.definition,
|
|
917
|
+
definitions: ownerSubmission?.agentDigests ?? selectedBinding.digests,
|
|
918
|
+
...(ownerSubmission === undefined ? {} : { submission: ownerSubmission }),
|
|
919
|
+
})
|
|
920
|
+
|
|
921
|
+
if (Option.isSome(selected) && ownerSubmission !== undefined && ownerBinding === undefined) {
|
|
922
|
+
return yield* failure('start', 'declaration-unavailable')
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
const effectiveBinding = Option.isSome(selected) || changedRootAgent || binding === undefined
|
|
926
|
+
? selectedBinding
|
|
927
|
+
: binding
|
|
928
|
+
|
|
929
|
+
if (effectiveBinding === undefined) return yield* failure('start', 'declaration-unavailable')
|
|
930
|
+
|
|
931
|
+
const policy = Option.isNone(selected)
|
|
932
|
+
? effectiveBinding.definition.policy
|
|
933
|
+
: yield* decode(AgentPolicy, selected.value, 'start')
|
|
934
|
+
|
|
935
|
+
return {
|
|
936
|
+
current,
|
|
937
|
+
binding: effectiveBinding,
|
|
938
|
+
submission: ownerSubmission,
|
|
939
|
+
policyOverride: Option.map(selected, () => policy),
|
|
940
|
+
policy,
|
|
941
|
+
budget: undefined,
|
|
942
|
+
budgetScope: undefined,
|
|
943
|
+
grant: undefined,
|
|
944
|
+
depth: 0,
|
|
945
|
+
}
|
|
946
|
+
})
|
|
947
|
+
|
|
948
|
+
const resolveTargetPolicy = Effect.fnUntraced(function*(request: WorkerPolicyTarget) {
|
|
949
|
+
const selected = yield* deps.policyResolver.resolveTarget(request)
|
|
950
|
+
|
|
951
|
+
if (Option.isNone(selected)) return selected
|
|
952
|
+
const policy = yield* decode(AgentPolicy, selected.value, 'start')
|
|
953
|
+
|
|
954
|
+
if (request._tag === 'RetainedWorker' && !samePolicy(policy, request.origin.policy)) {
|
|
955
|
+
return yield* failure('start', 'worker-mismatch')
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
return Option.some(policy)
|
|
959
|
+
})
|
|
960
|
+
|
|
961
|
+
const reserveSubtree = Effect.fnUntraced(function*(
|
|
962
|
+
sourceThreadId: ThreadId,
|
|
963
|
+
requested: SubtreeBudgetReserved,
|
|
964
|
+
): Effect.fn.Return<void, WorkerError> {
|
|
965
|
+
const decoded = yield* decode(SubtreeBudgetReserved, requested, 'start')
|
|
966
|
+
|
|
967
|
+
if (decoded.sourceSubmissionId === undefined) return yield* failure('start', 'denied')
|
|
968
|
+
const funding = yield* sourceAuthority(sourceThreadId, decoded.sourceSubmissionId)
|
|
969
|
+
|
|
970
|
+
if (funding.submission === undefined) return yield* failure('start', 'denied')
|
|
971
|
+
|
|
972
|
+
const payload = SubtreeBudgetReserved.make({
|
|
973
|
+
...decoded,
|
|
974
|
+
sourceSubmissionId: funding.submission.submissionId,
|
|
975
|
+
})
|
|
976
|
+
|
|
977
|
+
const recordId = `subtree:${payload.reservationId}`
|
|
978
|
+
|
|
979
|
+
let repairs = 64
|
|
980
|
+
|
|
981
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
982
|
+
const source = yield* sourceAuthority(sourceThreadId, payload.sourceSubmissionId, true)
|
|
983
|
+
|
|
984
|
+
const previous = Option.getOrUndefined(
|
|
985
|
+
yield* exactRecord(sourceThreadId, RecordId.make(recordId), 'start'),
|
|
986
|
+
)?.record.payload
|
|
987
|
+
|
|
988
|
+
if (previous !== undefined) {
|
|
989
|
+
if (
|
|
990
|
+
previous._tag !== 'SubtreeBudgetReserved' ||
|
|
991
|
+
!Schema.toEquivalence(SubtreeBudgetReserved)(previous, payload)
|
|
992
|
+
) {
|
|
993
|
+
return yield* failure('start', 'idempotency-conflict')
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
return
|
|
997
|
+
}
|
|
998
|
+
if (
|
|
999
|
+
Option.isSome(
|
|
1000
|
+
yield* exactRecord(
|
|
1001
|
+
sourceThreadId,
|
|
1002
|
+
RecordId.make(`worker-input-refused:${payload.reservationId}`),
|
|
1003
|
+
'start',
|
|
1004
|
+
),
|
|
1005
|
+
)
|
|
1006
|
+
) {
|
|
1007
|
+
return yield* failure('start', 'denied')
|
|
1008
|
+
}
|
|
1009
|
+
if (payload.depth !== source.depth + 1 || payload.depth > payload.grant.maxDepth) {
|
|
1010
|
+
return yield* failure('start', 'denied')
|
|
1011
|
+
}
|
|
1012
|
+
const inherited = source.grant
|
|
1013
|
+
const lifetimes = inherited?.childLifetimes
|
|
1014
|
+
|
|
1015
|
+
if (
|
|
1016
|
+
inherited !== undefined &&
|
|
1017
|
+
(payload.depth > inherited.maxDepth ||
|
|
1018
|
+
payload.grant.maxDepth > inherited.maxDepth ||
|
|
1019
|
+
(lifetimes !== undefined && !lifetimes.includes(payload.lifetime)) ||
|
|
1020
|
+
payload.grant.allowedToolNames.some(
|
|
1021
|
+
(name) => !inherited.allowedToolNames.includes(name),
|
|
1022
|
+
) ||
|
|
1023
|
+
(lifetimes !== undefined &&
|
|
1024
|
+
(payload.grant.childLifetimes ?? ['attached', 'background']).some(
|
|
1025
|
+
(lifetime) => !lifetimes.includes(lifetime),
|
|
1026
|
+
)))
|
|
1027
|
+
) {
|
|
1028
|
+
return yield* failure('start', 'denied')
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
const rows = source.current.records.flatMap(({ record }) =>
|
|
1032
|
+
record.payload._tag === 'SubtreeBudgetReserved' &&
|
|
1033
|
+
record.payload.sourceSubmissionId === payload.sourceSubmissionId
|
|
1034
|
+
? [record.payload]
|
|
1035
|
+
: []
|
|
1036
|
+
)
|
|
1037
|
+
|
|
1038
|
+
const caps = payload.budget.caps
|
|
1039
|
+
|
|
1040
|
+
if (rows.some((row) => !sameCaps(row.budget.caps, caps))) {
|
|
1041
|
+
return yield* failure('start', 'capacity')
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
const own = {
|
|
1045
|
+
turns: source.policy.maxTurns,
|
|
1046
|
+
toolCalls: source.policy.maxToolCalls,
|
|
1047
|
+
durationMillis: Math.ceil(Duration.toMillis(source.policy.maxDuration)),
|
|
1048
|
+
inputTokens: source.policy.tokenBudget ?? source.budget?.allocation.inputTokens ?? 0,
|
|
1049
|
+
outputTokens: source.policy.tokenBudget ?? source.budget?.allocation.outputTokens ?? 0,
|
|
1050
|
+
costMicrousd: source.policy.costBudgetMicrousd ?? source.budget?.allocation.costMicrousd ?? 0,
|
|
1051
|
+
resultBytes: source.policy.toolResultBounds.maxBytes,
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
const ceilings = sourceCaps(source.policy)
|
|
1055
|
+
const child = payload.policy
|
|
1056
|
+
const allocation = payload.budget.allocation
|
|
1057
|
+
|
|
1058
|
+
if (
|
|
1059
|
+
child.maxTurns > Math.min(source.policy.maxTurns, allocation.turns) ||
|
|
1060
|
+
child.maxToolCalls > Math.min(source.policy.maxToolCalls, allocation.toolCalls) ||
|
|
1061
|
+
Duration.toMillis(child.maxDuration) >
|
|
1062
|
+
Math.min(Duration.toMillis(source.policy.maxDuration), allocation.durationMillis) ||
|
|
1063
|
+
child.toolConcurrency > source.policy.toolConcurrency ||
|
|
1064
|
+
child.toolResultBounds.maxBytes > source.policy.toolResultBounds.maxBytes ||
|
|
1065
|
+
(source.policy.tokenBudget !== undefined &&
|
|
1066
|
+
(child.tokenBudget === undefined ||
|
|
1067
|
+
child.tokenBudget > source.policy.tokenBudget ||
|
|
1068
|
+
child.tokenBudget > allocation.inputTokens + allocation.outputTokens)) ||
|
|
1069
|
+
(source.policy.costBudgetMicrousd !== undefined &&
|
|
1070
|
+
(child.costBudgetMicrousd === undefined ||
|
|
1071
|
+
child.costBudgetMicrousd >
|
|
1072
|
+
Math.min(source.policy.costBudgetMicrousd, allocation.costMicrousd)))
|
|
1073
|
+
) {
|
|
1074
|
+
return yield* failure('start', 'capacity')
|
|
1075
|
+
}
|
|
1076
|
+
for (const [, cap] of amountCaps) {
|
|
1077
|
+
if (caps[cap] !== undefined && ceilings[cap] !== undefined && caps[cap] > ceilings[cap]) {
|
|
1078
|
+
return yield* failure('start', 'capacity')
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
if (
|
|
1082
|
+
(caps.maxTotalChildInvocations ?? 0) > source.policy.maxToolCalls ||
|
|
1083
|
+
(caps.maxConcurrentChildren ?? 0) > source.policy.toolConcurrency
|
|
1084
|
+
) {
|
|
1085
|
+
return yield* failure('start', 'capacity')
|
|
1086
|
+
}
|
|
1087
|
+
const slots = 1 + (payload.budget.descendantInvocations ?? 0)
|
|
1088
|
+
|
|
1089
|
+
const chargedSlots = rows.reduce(
|
|
1090
|
+
(sum, row) => sum + 1 + (row.budget.descendantInvocations ?? 0),
|
|
1091
|
+
slots,
|
|
1092
|
+
)
|
|
1093
|
+
|
|
1094
|
+
const slotLimit = Math.min(
|
|
1095
|
+
caps.maxTotalChildInvocations ?? Infinity,
|
|
1096
|
+
source.budget === undefined
|
|
1097
|
+
? source.policy.maxToolCalls
|
|
1098
|
+
: (source.budget.descendantInvocations ?? 0),
|
|
1099
|
+
)
|
|
1100
|
+
|
|
1101
|
+
if (chargedSlots > slotLimit) return yield* failure('start', 'capacity')
|
|
1102
|
+
for (const [amount, cap] of amountCaps) {
|
|
1103
|
+
// Zero is the encoded absence of an allocation when this dimension is unconfigured.
|
|
1104
|
+
// It must not become a new cumulative token or dollar ceiling in a descendant.
|
|
1105
|
+
if (
|
|
1106
|
+
source.budgetScope === 'worker-run' &&
|
|
1107
|
+
(amount === 'inputTokens' || amount === 'outputTokens' || amount === 'costMicrousd') &&
|
|
1108
|
+
source.budget !== undefined &&
|
|
1109
|
+
source.budget.caps[cap] === undefined &&
|
|
1110
|
+
source.budget.allocation[amount] === 0 &&
|
|
1111
|
+
ceilings[cap] === undefined
|
|
1112
|
+
) {
|
|
1113
|
+
const charged = rows.reduce(
|
|
1114
|
+
(sum, row) => sum + row.budget.allocation[amount],
|
|
1115
|
+
allocation[amount],
|
|
1116
|
+
)
|
|
1117
|
+
|
|
1118
|
+
if (charged > (caps[cap] ?? Infinity)) return yield* failure('start', 'capacity')
|
|
1119
|
+
continue
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
const residual = source.budget === undefined
|
|
1123
|
+
? (ceilings[cap] ?? Infinity)
|
|
1124
|
+
: Math.max(0, source.budget.allocation[amount] - own[amount])
|
|
1125
|
+
|
|
1126
|
+
const limit = Math.min(caps[cap] ?? Infinity, residual)
|
|
1127
|
+
|
|
1128
|
+
const charged = rows.reduce(
|
|
1129
|
+
(sum, row) => sum + row.budget.allocation[amount],
|
|
1130
|
+
payload.budget.allocation[amount],
|
|
1131
|
+
)
|
|
1132
|
+
|
|
1133
|
+
if (charged > limit) return yield* failure('start', 'capacity')
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// Include unreconciled reservations conservatively; only canonical completion frees an
|
|
1137
|
+
// active slot. A worker Thread consumes one slot even when multiple inputs safely join it.
|
|
1138
|
+
const completedAttached = new Set<string>(
|
|
1139
|
+
source.current.records.flatMap(({ record }) =>
|
|
1140
|
+
record.payload._tag === 'SubagentJoined' ? [record.payload.reservationId] : []
|
|
1141
|
+
),
|
|
1142
|
+
)
|
|
1143
|
+
|
|
1144
|
+
const activeLimit = Math.min(
|
|
1145
|
+
caps.maxConcurrentChildren ?? Infinity,
|
|
1146
|
+
source.policy.toolConcurrency,
|
|
1147
|
+
)
|
|
1148
|
+
|
|
1149
|
+
const hasSlot = (completed: ReadonlySet<string>, conservative = false) => {
|
|
1150
|
+
const active = new Set(
|
|
1151
|
+
rows
|
|
1152
|
+
.filter((row) =>
|
|
1153
|
+
row.lifetime === 'background'
|
|
1154
|
+
? !completed.has(row.reservationId)
|
|
1155
|
+
: !completedAttached.has(row.reservationId)
|
|
1156
|
+
)
|
|
1157
|
+
.map((row) => row.childThreadId),
|
|
1158
|
+
)
|
|
1159
|
+
|
|
1160
|
+
return active.has(payload.childThreadId)
|
|
1161
|
+
? !conservative || active.size <= activeLimit
|
|
1162
|
+
: active.size < activeLimit
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
const localCompletions = completedMessageIds(source.current.records)
|
|
1166
|
+
|
|
1167
|
+
if (!hasSlot(localCompletions, true)) {
|
|
1168
|
+
let changed = false
|
|
1169
|
+
|
|
1170
|
+
for (const entry of source.current.records) {
|
|
1171
|
+
const reserved = entry.record.payload
|
|
1172
|
+
|
|
1173
|
+
if (repairs === 0) break
|
|
1174
|
+
if (
|
|
1175
|
+
reserved._tag !== 'SubtreeBudgetReserved' ||
|
|
1176
|
+
reserved.lifetime !== 'background' ||
|
|
1177
|
+
localCompletions.has(reserved.reservationId)
|
|
1178
|
+
) {
|
|
1179
|
+
continue
|
|
1180
|
+
}
|
|
1181
|
+
repairs--
|
|
1182
|
+
|
|
1183
|
+
const input = Option.getOrUndefined(
|
|
1184
|
+
yield* exactRecord(
|
|
1185
|
+
sourceThreadId,
|
|
1186
|
+
workerInputRecordId(IdempotencyKey.make(reserved.reservationId)),
|
|
1187
|
+
'start',
|
|
1188
|
+
),
|
|
1189
|
+
)
|
|
1190
|
+
|
|
1191
|
+
if (
|
|
1192
|
+
input?.record.payload._tag === 'WorkerInputRequested'
|
|
1193
|
+
? (yield* repairInput(sourceThreadId, input.record.payload)) === 'repaired'
|
|
1194
|
+
: yield* repairReservation(sourceThreadId, entry)
|
|
1195
|
+
) {
|
|
1196
|
+
changed = true
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
if (changed) continue
|
|
1200
|
+
if (!hasSlot(localCompletions)) {
|
|
1201
|
+
return yield* WorkerError.make({
|
|
1202
|
+
operation: 'start',
|
|
1203
|
+
reason: 'capacity',
|
|
1204
|
+
retryable: true,
|
|
1205
|
+
})
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
if (yield* append(sourceThreadId, recordId, payload, source.current, 'subtree')) return
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
return yield* failure('start', 'storage')
|
|
1212
|
+
})
|
|
1213
|
+
|
|
1214
|
+
const repairCapacityPage = Effect.fnUntraced(function*(
|
|
1215
|
+
threadId: ThreadId,
|
|
1216
|
+
tail: ThreadWorkerCapacity,
|
|
1217
|
+
pressure: { remaining: number; after: CanonicalSequence; worker?: ThreadId },
|
|
1218
|
+
worker?: ThreadId,
|
|
1219
|
+
) {
|
|
1220
|
+
if (pressure.worker !== worker) {
|
|
1221
|
+
pressure.worker = worker
|
|
1222
|
+
pressure.after = CanonicalSequence.make(0)
|
|
1223
|
+
}
|
|
1224
|
+
if (pressure.remaining === 0) return { changed: false, incumbent: false, more: false }
|
|
1225
|
+
|
|
1226
|
+
const selected = yield* Stream.runCollect(
|
|
1227
|
+
deps.store.read({
|
|
1228
|
+
threadId,
|
|
1229
|
+
selection: {
|
|
1230
|
+
_tag: 'LiveWorkerInputs',
|
|
1231
|
+
throughSequence: tail.tailSequence,
|
|
1232
|
+
...(worker === undefined ? {} : { workerThreadId: worker }),
|
|
1233
|
+
},
|
|
1234
|
+
page: { afterSequence: pressure.after, limit: Math.min(64, pressure.remaining) },
|
|
1235
|
+
}),
|
|
1236
|
+
).pipe(
|
|
1237
|
+
Effect.asSome,
|
|
1238
|
+
Effect.catchTag('ThreadStoreError', (cause) =>
|
|
1239
|
+
deps.store
|
|
1240
|
+
.inspectTail(ThreadTailRequest.make({ threadId }))
|
|
1241
|
+
.pipe(
|
|
1242
|
+
Effect.flatMap((current) =>
|
|
1243
|
+
current.tailSequence !== tail.tailSequence
|
|
1244
|
+
? Effect.succeed(Option.none<ReadonlyArray<CanonicalRecordEnvelope>>())
|
|
1245
|
+
: Effect.fail(cause)
|
|
1246
|
+
),
|
|
1247
|
+
)),
|
|
1248
|
+
Effect.mapError(storageFailure('start')),
|
|
1249
|
+
)
|
|
1250
|
+
|
|
1251
|
+
if (Option.isNone(selected)) return { changed: true, incumbent: false, more: false }
|
|
1252
|
+
const entries = selected.value
|
|
1253
|
+
|
|
1254
|
+
const requests: Array<WorkerInputRequested> = []
|
|
1255
|
+
|
|
1256
|
+
for (const entry of entries) {
|
|
1257
|
+
if (
|
|
1258
|
+
entry.threadId !== threadId ||
|
|
1259
|
+
entry.sequence <= pressure.after ||
|
|
1260
|
+
entry.sequence > tail.tailSequence ||
|
|
1261
|
+
entry.record.payload._tag !== 'WorkerInputRequested' ||
|
|
1262
|
+
(worker !== undefined && entry.record.payload.admission.origin.worker.threadId !== worker)
|
|
1263
|
+
) {
|
|
1264
|
+
return yield* failure('start', 'corrupt')
|
|
1265
|
+
}
|
|
1266
|
+
pressure.after = entry.sequence
|
|
1267
|
+
pressure.remaining--
|
|
1268
|
+
requests.push(entry.record.payload)
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// Foreign reads stay concurrent under pressure; canonical acknowledgements retain source order.
|
|
1272
|
+
const completions = yield* Effect.forEach(
|
|
1273
|
+
requests,
|
|
1274
|
+
Effect.fnUntraced(function*(request) {
|
|
1275
|
+
return { request, completion: yield* readInputCompletion(request.admission) }
|
|
1276
|
+
}),
|
|
1277
|
+
{ concurrency: 8 },
|
|
1278
|
+
)
|
|
1279
|
+
|
|
1280
|
+
let changed = false
|
|
1281
|
+
let incumbent = false
|
|
1282
|
+
|
|
1283
|
+
for (const { request, completion } of completions) {
|
|
1284
|
+
if ((yield* repairInput(threadId, request, completion)) === 'repaired') changed = true
|
|
1285
|
+
else if (worker !== undefined) incumbent = true
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
return { changed, incumbent, more: entries.length > 0 && pressure.remaining > 0 }
|
|
1289
|
+
})
|
|
1290
|
+
|
|
1291
|
+
const reservation = Effect.fnUntraced(function*(
|
|
1292
|
+
admission: WorkerAdmission,
|
|
1293
|
+
inputDigest: Digest,
|
|
1294
|
+
input: PersistedJson,
|
|
1295
|
+
principal: Principal,
|
|
1296
|
+
retainedFrameworkInput: boolean,
|
|
1297
|
+
authorization?: WorkerStartAdmission,
|
|
1298
|
+
): Effect.fn.Return<void, WorkerError> {
|
|
1299
|
+
const origin = admission.origin
|
|
1300
|
+
|
|
1301
|
+
yield* verifyContinuation(origin)
|
|
1302
|
+
const id = workerInputRecordId(admission.messageId)
|
|
1303
|
+
|
|
1304
|
+
const pressure: { remaining: number; after: CanonicalSequence; worker?: ThreadId } = {
|
|
1305
|
+
remaining: 64,
|
|
1306
|
+
after: CanonicalSequence.make(0),
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
1310
|
+
const source = yield* sourceAuthority(origin.source.threadId, admission.sourceSubmissionId)
|
|
1311
|
+
|
|
1312
|
+
const current = source.current
|
|
1313
|
+
|
|
1314
|
+
if (
|
|
1315
|
+
origin.continuationOf !== undefined &&
|
|
1316
|
+
(yield* readStop(
|
|
1317
|
+
origin.source.threadId,
|
|
1318
|
+
origin.continuationOf.worker.threadId,
|
|
1319
|
+
current.tailSequence,
|
|
1320
|
+
))
|
|
1321
|
+
) {
|
|
1322
|
+
return yield* failure('start', 'denied')
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
const retained = Option.getOrUndefined(
|
|
1326
|
+
yield* exactRecord(origin.source.threadId, id, 'start'),
|
|
1327
|
+
)
|
|
1328
|
+
|
|
1329
|
+
if (retained !== undefined && retained.sequence > current.tailSequence) continue
|
|
1330
|
+
const existing = retained?.record.payload
|
|
1331
|
+
|
|
1332
|
+
if (
|
|
1333
|
+
Option.isSome(
|
|
1334
|
+
yield* exactRecord(
|
|
1335
|
+
origin.source.threadId,
|
|
1336
|
+
RecordId.make(`worker-input-refused:${admission.messageId}`),
|
|
1337
|
+
'start',
|
|
1338
|
+
),
|
|
1339
|
+
)
|
|
1340
|
+
) {
|
|
1341
|
+
return yield* failure('start', 'denied')
|
|
1342
|
+
}
|
|
1343
|
+
if (existing !== undefined) {
|
|
1344
|
+
if (
|
|
1345
|
+
existing._tag !== 'WorkerInputRequested' ||
|
|
1346
|
+
existing.inputDigest !== inputDigest ||
|
|
1347
|
+
!sameAdmission(existing.admission, admission)
|
|
1348
|
+
) {
|
|
1349
|
+
return yield* failure('start', 'idempotency-conflict')
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
const first = current.records[0]?.record.payload
|
|
1353
|
+
|
|
1354
|
+
if (first?._tag !== 'ThreadCreated') return yield* failure('start', 'denied')
|
|
1355
|
+
|
|
1356
|
+
const firstRequest = Option.getOrUndefined(
|
|
1357
|
+
yield* exactRecord(
|
|
1358
|
+
origin.source.threadId,
|
|
1359
|
+
workerInputRecordId(origin.firstMessageId),
|
|
1360
|
+
'start',
|
|
1361
|
+
),
|
|
1362
|
+
)
|
|
1363
|
+
|
|
1364
|
+
if (firstRequest !== undefined && firstRequest.sequence > current.tailSequence) continue
|
|
1365
|
+
if (firstRequest !== undefined && firstRequest.record.payload._tag !== 'WorkerInputRequested') {
|
|
1366
|
+
return yield* failure('start', 'corrupt')
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
const prior = firstRequest?.record.payload._tag === 'WorkerInputRequested'
|
|
1370
|
+
? firstRequest.record.payload.admission.origin
|
|
1371
|
+
: undefined
|
|
1372
|
+
|
|
1373
|
+
if (
|
|
1374
|
+
prior === undefined &&
|
|
1375
|
+
(source.submission?.agentId ?? first.agentId) !== origin.source.agentId
|
|
1376
|
+
) {
|
|
1377
|
+
return yield* failure('start', 'denied')
|
|
1378
|
+
}
|
|
1379
|
+
if (prior !== undefined && !sameOrigin(prior, origin)) {
|
|
1380
|
+
return yield* failure('start', 'worker-mismatch')
|
|
1381
|
+
}
|
|
1382
|
+
if (prior === undefined && admission.messageId !== origin.firstMessageId) {
|
|
1383
|
+
return yield* failure('start', 'not-found')
|
|
1384
|
+
}
|
|
1385
|
+
const caps = origin.budget.caps
|
|
1386
|
+
|
|
1387
|
+
const sourceBinding = source.binding
|
|
1388
|
+
|
|
1389
|
+
const targetBinding = currentBinding(origin.worker.targetAgentId)
|
|
1390
|
+
|
|
1391
|
+
if (sourceBinding === undefined || targetBinding === undefined) {
|
|
1392
|
+
return yield* failure('start', 'declaration-unavailable')
|
|
1393
|
+
}
|
|
1394
|
+
// Standard reports and updates retain the owner's original input bytes. Their
|
|
1395
|
+
// framework message carries the new information independently of the current input codec.
|
|
1396
|
+
if (!retainedFrameworkInput) {
|
|
1397
|
+
yield* Schema.decodeEffect(Schema.toEncoded(targetBinding.definition.input))(input).pipe(
|
|
1398
|
+
Effect.mapError((cause) => failure('start', 'corrupt', cause)),
|
|
1399
|
+
)
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
const targetRequest = {
|
|
1403
|
+
definition: targetBinding.definition,
|
|
1404
|
+
definitions: targetBinding.digests,
|
|
1405
|
+
source: origin.source,
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
const selected = yield* resolveTargetPolicy(
|
|
1409
|
+
admission.messageId === origin.firstMessageId
|
|
1410
|
+
? {
|
|
1411
|
+
...targetRequest,
|
|
1412
|
+
_tag: 'InitialInput',
|
|
1413
|
+
...(authorization === undefined || authorization.tailSequence !== current.tailSequence
|
|
1414
|
+
? {}
|
|
1415
|
+
: { admission: authorization }),
|
|
1416
|
+
...(origin.continuationOf === undefined
|
|
1417
|
+
? {}
|
|
1418
|
+
: { continuationOf: origin.continuationOf }),
|
|
1419
|
+
input,
|
|
1420
|
+
inputDigest,
|
|
1421
|
+
...(source.submission === undefined ? {} : { sourceSubmission: source.submission }),
|
|
1422
|
+
}
|
|
1423
|
+
: { ...targetRequest, _tag: 'RetainedWorker', origin: prior ?? origin },
|
|
1424
|
+
)
|
|
1425
|
+
|
|
1426
|
+
const independent = origin.budgetScope === 'worker-run'
|
|
1427
|
+
|
|
1428
|
+
const targetPolicy = Option.isSome(selected)
|
|
1429
|
+
? selected.value
|
|
1430
|
+
: independent
|
|
1431
|
+
? targetBinding.definition.policy
|
|
1432
|
+
: AgentPolicy.resolve(
|
|
1433
|
+
targetBinding.definition.policyOverrides ?? targetBinding.definition.policy,
|
|
1434
|
+
source.policy,
|
|
1435
|
+
)
|
|
1436
|
+
|
|
1437
|
+
// Captured authority is checked on replay too, before the retained reservation returns.
|
|
1438
|
+
// Static callers retain the old idempotent-return behavior.
|
|
1439
|
+
if (
|
|
1440
|
+
(existing === undefined || Option.isSome(selected)) &&
|
|
1441
|
+
!withinPolicy(origin, independent ? targetPolicy : source.policy, targetPolicy)
|
|
1442
|
+
) {
|
|
1443
|
+
return yield* failure('start', 'capacity')
|
|
1444
|
+
}
|
|
1445
|
+
if (existing !== undefined) return
|
|
1446
|
+
const now = yield* Clock.currentTimeMillis
|
|
1447
|
+
|
|
1448
|
+
if (now >= origin.expiresAtMillis) return yield* failure('start', 'capacity')
|
|
1449
|
+
if (
|
|
1450
|
+
prior === undefined &&
|
|
1451
|
+
!sameReporting(
|
|
1452
|
+
yield* reportIntent(sourceBinding, targetBinding, origin.worker.delegationId, source),
|
|
1453
|
+
origin.reporting,
|
|
1454
|
+
)
|
|
1455
|
+
) {
|
|
1456
|
+
return yield* failure('start', 'denied')
|
|
1457
|
+
}
|
|
1458
|
+
if (independent && source.depth !== 0) return yield* failure('start', 'denied')
|
|
1459
|
+
if (!independent && admission.sourceSubmissionId === undefined) {
|
|
1460
|
+
return yield* failure('start', 'denied')
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
// Resolve inside the source CAS loop: independently delivered starts must compete
|
|
1464
|
+
// against one canonical prefix. A conflict repeats both authority and capacity reads.
|
|
1465
|
+
const selectedConcurrency = yield* deps.concurrencyResolver.resolve({
|
|
1466
|
+
source: origin.source,
|
|
1467
|
+
worker: origin.worker,
|
|
1468
|
+
...(origin.continuationOf === undefined ? {} : { continuationOf: origin.continuationOf }),
|
|
1469
|
+
principal,
|
|
1470
|
+
...(source.submission === undefined ? {} : { sourceSubmission: source.submission }),
|
|
1471
|
+
})
|
|
1472
|
+
|
|
1473
|
+
const sourceConcurrency = Option.isSome(selectedConcurrency)
|
|
1474
|
+
? (yield* decode(WorkerConcurrencyLimit, selectedConcurrency.value, 'start'))
|
|
1475
|
+
.maxActiveWorkersPerSource
|
|
1476
|
+
: Infinity
|
|
1477
|
+
|
|
1478
|
+
const activeLimit = Math.min(
|
|
1479
|
+
sourceConcurrency,
|
|
1480
|
+
deps.limits.maxActiveWorkersPerSource ?? source.policy.toolConcurrency,
|
|
1481
|
+
independent
|
|
1482
|
+
? Infinity
|
|
1483
|
+
: Math.min(caps.maxConcurrentChildren ?? Infinity, source.policy.toolConcurrency),
|
|
1484
|
+
)
|
|
1485
|
+
|
|
1486
|
+
const pendingLimit = admission.reportKind === 'update'
|
|
1487
|
+
? (deps.limits.maxPendingUpdateInputsPerWorker ?? 32)
|
|
1488
|
+
: deps.limits.maxPendingInputsPerWorker
|
|
1489
|
+
|
|
1490
|
+
const capacity = yield* readWorkerCapacity({
|
|
1491
|
+
threadId: origin.source.threadId,
|
|
1492
|
+
workerThreadId: origin.worker.threadId,
|
|
1493
|
+
expectedTailSequence: current.tailSequence,
|
|
1494
|
+
|
|
1495
|
+
update: admission.reportKind === 'update',
|
|
1496
|
+
activeLimit,
|
|
1497
|
+
pendingLimit,
|
|
1498
|
+
}).pipe(
|
|
1499
|
+
Effect.asSome,
|
|
1500
|
+
Effect.catchTag('ThreadStoreError', (cause) =>
|
|
1501
|
+
deps.store
|
|
1502
|
+
.inspectTail(ThreadTailRequest.make({ threadId: origin.source.threadId }))
|
|
1503
|
+
.pipe(
|
|
1504
|
+
Effect.flatMap((tail) =>
|
|
1505
|
+
tail.tailSequence !== current.tailSequence
|
|
1506
|
+
? Effect.succeed(Option.none<ThreadWorkerCapacity>())
|
|
1507
|
+
: Effect.fail(cause)
|
|
1508
|
+
),
|
|
1509
|
+
)),
|
|
1510
|
+
Effect.mapError(storageFailure('start')),
|
|
1511
|
+
)
|
|
1512
|
+
|
|
1513
|
+
if (Option.isNone(capacity)) continue
|
|
1514
|
+
const live = capacity.value
|
|
1515
|
+
|
|
1516
|
+
if (live.threadId !== origin.source.threadId || live.tailSequence !== current.tailSequence) {
|
|
1517
|
+
return yield* failure('start', 'corrupt')
|
|
1518
|
+
}
|
|
1519
|
+
const pending = live.pendingInputs < pendingLimit
|
|
1520
|
+
|
|
1521
|
+
const slot = live.workerActive
|
|
1522
|
+
? live.activeWorkers <= activeLimit
|
|
1523
|
+
: live.activeWorkers < activeLimit
|
|
1524
|
+
|
|
1525
|
+
if (!pending || !slot) {
|
|
1526
|
+
const repaired = yield* repairCapacityPage(
|
|
1527
|
+
origin.source.threadId,
|
|
1528
|
+
live,
|
|
1529
|
+
pressure,
|
|
1530
|
+
!pending || live.workerActive ? origin.worker.threadId : undefined,
|
|
1531
|
+
)
|
|
1532
|
+
|
|
1533
|
+
if (repaired.changed) continue
|
|
1534
|
+
if (!(pending && live.workerActive && repaired.incumbent)) {
|
|
1535
|
+
if (repaired.more) continue
|
|
1536
|
+
|
|
1537
|
+
return yield* WorkerError.make({
|
|
1538
|
+
operation: 'start',
|
|
1539
|
+
reason: 'capacity',
|
|
1540
|
+
retryable: true,
|
|
1541
|
+
})
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
if (!independent) {
|
|
1545
|
+
yield* reserveSubtree(
|
|
1546
|
+
origin.source.threadId,
|
|
1547
|
+
SubtreeBudgetReserved.make({
|
|
1548
|
+
reservationId: yield* Schema.decodeEffect(SubtreeBudgetReserved.fields.reservationId)(
|
|
1549
|
+
admission.messageId,
|
|
1550
|
+
).pipe(Effect.orDie),
|
|
1551
|
+
executionRunId: admission.executionRunId,
|
|
1552
|
+
...(admission.sourceSubmissionId === undefined
|
|
1553
|
+
? {}
|
|
1554
|
+
: { sourceSubmissionId: admission.sourceSubmissionId }),
|
|
1555
|
+
childThreadId: origin.worker.threadId,
|
|
1556
|
+
lifetime: 'background',
|
|
1557
|
+
depth: origin.depth,
|
|
1558
|
+
policy: origin.policy,
|
|
1559
|
+
grant: origin.grant,
|
|
1560
|
+
budget: origin.budget,
|
|
1561
|
+
}),
|
|
1562
|
+
)
|
|
1563
|
+
}
|
|
1564
|
+
if (
|
|
1565
|
+
yield* append(
|
|
1566
|
+
origin.source.threadId,
|
|
1567
|
+
id,
|
|
1568
|
+
WorkerInputRequested.make({ admission, inputDigest }),
|
|
1569
|
+
current,
|
|
1570
|
+
'source',
|
|
1571
|
+
)
|
|
1572
|
+
) {
|
|
1573
|
+
return
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
return yield* failure('start', 'storage')
|
|
1578
|
+
})
|
|
1579
|
+
|
|
1580
|
+
const ensureOrigin = (origin: WorkerOrigin) =>
|
|
1581
|
+
ensureWorkerOrigin(
|
|
1582
|
+
{ producerId: deps.producerId, deploymentId: deps.deploymentId },
|
|
1583
|
+
origin,
|
|
1584
|
+
).pipe(
|
|
1585
|
+
Effect.provideService(ThreadStore, deps.store),
|
|
1586
|
+
Effect.provideService(DurableRuntimeFailpoint, deps.failpoint),
|
|
1587
|
+
)
|
|
1588
|
+
|
|
1589
|
+
const validateAdmission = Effect.fnUntraced(function*(
|
|
1590
|
+
unvalidated: WorkerAdmission,
|
|
1591
|
+
options: DurableSubmitOptions,
|
|
1592
|
+
agentId: Agent.AnyDefinition['id'],
|
|
1593
|
+
inputDigest: Digest,
|
|
1594
|
+
input: PersistedJson,
|
|
1595
|
+
) {
|
|
1596
|
+
const admission = yield* decode(WorkerAdmission, unvalidated, 'start')
|
|
1597
|
+
|
|
1598
|
+
if (admission.reportKind === 'update') {
|
|
1599
|
+
if (!Schema.is(WorkerUpdate)(options.messageAdmission)) {
|
|
1600
|
+
return yield* failure('start', 'denied')
|
|
1601
|
+
}
|
|
1602
|
+
yield* validateCompletion(options.messageAdmission, options, agentId, inputDigest)
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
yield* verifyContinuation(admission.origin)
|
|
1606
|
+
const delivery = yield* CurrentStartDelivery
|
|
1607
|
+
|
|
1608
|
+
const authorization = delivery !== undefined &&
|
|
1609
|
+
sameAdmission(delivery.admission, admission) &&
|
|
1610
|
+
delivery.inputDigest === inputDigest
|
|
1611
|
+
? yield* currentStart(
|
|
1612
|
+
delivery.authorization,
|
|
1613
|
+
admission.origin.source.threadId,
|
|
1614
|
+
admission.sourceSubmissionId,
|
|
1615
|
+
options.principal,
|
|
1616
|
+
agentId,
|
|
1617
|
+
admission.origin.continuationOf,
|
|
1618
|
+
)
|
|
1619
|
+
: undefined
|
|
1620
|
+
|
|
1621
|
+
yield* deps.authorizer.authorize({
|
|
1622
|
+
...(authorization === undefined ? {} : { admission: authorization }),
|
|
1623
|
+
sourceThreadId: admission.origin.source.threadId,
|
|
1624
|
+
...(admission.sourceSubmissionId === undefined
|
|
1625
|
+
? {}
|
|
1626
|
+
: { sourceSubmissionId: admission.sourceSubmissionId }),
|
|
1627
|
+
principal: options.principal,
|
|
1628
|
+
operation: 'start',
|
|
1629
|
+
access: 'send',
|
|
1630
|
+
worker: admission.origin.worker,
|
|
1631
|
+
...(admission.origin.continuationOf === undefined
|
|
1632
|
+
? {}
|
|
1633
|
+
: { continuationOf: admission.origin.continuationOf }),
|
|
1634
|
+
})
|
|
1635
|
+
yield* authorizeBudget(admission.origin, options.principal, authorization)
|
|
1636
|
+
if (
|
|
1637
|
+
admission.origin.worker.threadId !== options.threadId ||
|
|
1638
|
+
admission.origin.worker.targetAgentId !== agentId ||
|
|
1639
|
+
!definitionDigestsEqual(admission.origin.targetDigests, options.definitions) ||
|
|
1640
|
+
options.idempotencyKey !== admission.messageId ||
|
|
1641
|
+
(admission.deliveryPrincipal !== undefined &&
|
|
1642
|
+
admission.deliveryPrincipal !== options.principal)
|
|
1643
|
+
) {
|
|
1644
|
+
return yield* failure('start', 'worker-mismatch')
|
|
1645
|
+
}
|
|
1646
|
+
const retainedFrameworkInput = Schema.is(FrameworkMessage)(options.messageAdmission)
|
|
1647
|
+
|
|
1648
|
+
if (retainedFrameworkInput && admission.reportKind !== 'update') {
|
|
1649
|
+
yield* validateCompletion(options.messageAdmission, options, agentId, inputDigest)
|
|
1650
|
+
}
|
|
1651
|
+
yield* reservation(
|
|
1652
|
+
admission,
|
|
1653
|
+
inputDigest,
|
|
1654
|
+
input,
|
|
1655
|
+
options.principal,
|
|
1656
|
+
retainedFrameworkInput,
|
|
1657
|
+
authorization,
|
|
1658
|
+
)
|
|
1659
|
+
|
|
1660
|
+
return admission
|
|
1661
|
+
})
|
|
1662
|
+
|
|
1663
|
+
const prepareUpdate = Effect.fnUntraced(
|
|
1664
|
+
function*(update: Update, submission: SubmissionSnapshot, messageId: IdempotencyKey) {
|
|
1665
|
+
const origin = submission.workerAdmission?.origin
|
|
1666
|
+
const intent = origin?.reporting
|
|
1667
|
+
|
|
1668
|
+
if (origin === undefined || intent?.mode !== 'standard') return undefined
|
|
1669
|
+
if (update.threadId !== submission.threadId || update.agentId !== origin.worker.targetAgentId) {
|
|
1670
|
+
return yield* failure('followUp', 'worker-mismatch')
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
const destination = intent.returnAddress
|
|
1674
|
+
|
|
1675
|
+
if (destination === undefined) return yield* failure('followUp', 'corrupt')
|
|
1676
|
+
|
|
1677
|
+
const retained = destination.workerAdmission === undefined
|
|
1678
|
+
? undefined
|
|
1679
|
+
: yield* Schema.decodeUnknownEffect(WorkerAdmission)(destination.workerAdmission).pipe(
|
|
1680
|
+
Effect.mapError((cause) => failure('followUp', 'corrupt', cause)),
|
|
1681
|
+
)
|
|
1682
|
+
|
|
1683
|
+
const sourceBinding = currentBinding(origin.source.agentId)
|
|
1684
|
+
const targetBinding = currentBinding(origin.worker.targetAgentId)
|
|
1685
|
+
|
|
1686
|
+
const reports = sourceBinding?.reporting?.filter(
|
|
1687
|
+
(entry) => entry.delegationId === origin.worker.delegationId,
|
|
1688
|
+
) ?? []
|
|
1689
|
+
|
|
1690
|
+
if (
|
|
1691
|
+
sourceBinding === undefined ||
|
|
1692
|
+
targetBinding === undefined ||
|
|
1693
|
+
reports.length !== 1 ||
|
|
1694
|
+
reports[0] === undefined ||
|
|
1695
|
+
reports[0].target !== targetBinding.definition ||
|
|
1696
|
+
!definitionDigestsEqual(submission.agentDigests, origin.targetDigests)
|
|
1697
|
+
) {
|
|
1698
|
+
return yield* failure('followUp', 'declaration-unavailable')
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
const receivingOrigin = retained?.origin
|
|
1702
|
+
|
|
1703
|
+
if (destination.depth !== 0 && receivingOrigin === undefined) {
|
|
1704
|
+
return yield* failure('followUp', 'denied')
|
|
1705
|
+
}
|
|
1706
|
+
const now = yield* Clock.currentTimeMillis
|
|
1707
|
+
|
|
1708
|
+
const deadlineAtMillis = Math.min(
|
|
1709
|
+
origin.expiresAtMillis,
|
|
1710
|
+
receivingOrigin?.expiresAtMillis ?? Infinity,
|
|
1711
|
+
)
|
|
1712
|
+
|
|
1713
|
+
if (now >= deadlineAtMillis) return yield* failure('followUp', 'denied')
|
|
1714
|
+
if (reports[0].reportUpdate !== undefined && !reports[0].reportUpdate(update)) {
|
|
1715
|
+
return undefined
|
|
1716
|
+
}
|
|
1717
|
+
const input = destination.input
|
|
1718
|
+
|
|
1719
|
+
let workerAdmission: WorkerAdmission | undefined
|
|
1720
|
+
|
|
1721
|
+
if (retained !== undefined) {
|
|
1722
|
+
workerAdmission = {
|
|
1723
|
+
origin: retained.origin,
|
|
1724
|
+
executionRunId: null,
|
|
1725
|
+
reportKind: 'update',
|
|
1726
|
+
messageId,
|
|
1727
|
+
parameters: retained.parameters,
|
|
1728
|
+
createdAtMillis: now,
|
|
1729
|
+
...(retained.sourceSubmissionId === undefined
|
|
1730
|
+
? {}
|
|
1731
|
+
: { sourceSubmissionId: retained.sourceSubmissionId }),
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
const message = WorkerUpdate.make({
|
|
1736
|
+
_tag: 'WorkerUpdate',
|
|
1737
|
+
schemaVersion: 1,
|
|
1738
|
+
worker: origin.worker,
|
|
1739
|
+
update,
|
|
1740
|
+
})
|
|
1741
|
+
|
|
1742
|
+
const envelope: PreparedInput = {
|
|
1743
|
+
schemaVersion: 1,
|
|
1744
|
+
threadId: origin.source.threadId,
|
|
1745
|
+
deliveryPrincipal: destination.principal,
|
|
1746
|
+
agentId: origin.source.agentId,
|
|
1747
|
+
definitions: intent.sourceDigests,
|
|
1748
|
+
input,
|
|
1749
|
+
inputDigest: yield* withCrypto(digestJson(input)).pipe(
|
|
1750
|
+
Effect.mapError(storageFailure('followUp')),
|
|
1751
|
+
),
|
|
1752
|
+
admissionKey: messageId,
|
|
1753
|
+
authorization: { policyId: 'worker-report', decisionId: messageId },
|
|
1754
|
+
messageAdmission: message,
|
|
1755
|
+
...(workerAdmission === undefined
|
|
1756
|
+
? {}
|
|
1757
|
+
: { workerAdmission: { ...workerAdmission, deliveryPrincipal: destination.principal } }),
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1760
|
+
return {
|
|
1761
|
+
messageId,
|
|
1762
|
+
envelope: yield* Schema.encodeEffect(PreparedInput)(envelope).pipe(
|
|
1763
|
+
Effect.flatMap(Schema.decodeEffect(PersistedJson)),
|
|
1764
|
+
Effect.mapError(storageFailure('followUp')),
|
|
1765
|
+
),
|
|
1766
|
+
createdAtMillis: now,
|
|
1767
|
+
deadlineAtMillis,
|
|
1768
|
+
}
|
|
1769
|
+
},
|
|
1770
|
+
Effect.mapError((error) =>
|
|
1771
|
+
error.reason === 'storage' || error.reason === 'corrupt'
|
|
1772
|
+
? LedgerError.make({ operation: 'worker-update', message: error.reason, cause: error })
|
|
1773
|
+
: UpdateError.make({ reason: error.reason === 'denied' ? 'denied' : 'unavailable' })
|
|
1774
|
+
),
|
|
1775
|
+
)
|
|
1776
|
+
|
|
1777
|
+
const reportRun = Effect.fnUntraced(function*(
|
|
1778
|
+
submission: SubmissionSnapshot,
|
|
1779
|
+
history: Effect.Success<ReturnType<typeof readSubmission>>,
|
|
1780
|
+
): Effect.fn.Return<void, WorkerError> {
|
|
1781
|
+
const admission = submission.workerAdmission
|
|
1782
|
+
const intent = admission?.origin.reporting
|
|
1783
|
+
|
|
1784
|
+
if (admission === undefined || intent === undefined) return
|
|
1785
|
+
const origin = admission.origin
|
|
1786
|
+
|
|
1787
|
+
const member = history.records.find(
|
|
1788
|
+
({ record }) =>
|
|
1789
|
+
record.payload._tag === 'SubmissionSettled' &&
|
|
1790
|
+
record.payload.submissionId === submission.submissionId,
|
|
1791
|
+
)?.record.payload
|
|
1792
|
+
|
|
1793
|
+
if (member?._tag !== 'SubmissionSettled') return yield* failure('inspect', 'corrupt')
|
|
1794
|
+
if (member.runId === undefined) return // No actual Run means no fabricated report identity.
|
|
1795
|
+
const runId = member.runId
|
|
1796
|
+
|
|
1797
|
+
const host = history.records.find(
|
|
1798
|
+
({ record }) => record.payload._tag === 'SubmissionSettled' && record.payload.runId === runId,
|
|
1799
|
+
)?.record.payload
|
|
1800
|
+
|
|
1801
|
+
if (host?._tag !== 'SubmissionSettled') return yield* failure('inspect', 'corrupt')
|
|
1802
|
+
|
|
1803
|
+
const messageId = yield* withCrypto(
|
|
1804
|
+
digestJson(['worker-report', submission.threadId, runId]),
|
|
1805
|
+
).pipe(
|
|
1806
|
+
Effect.map((value) => Schema.decodeSync(IdempotencyKey)(`report:${value}`)),
|
|
1807
|
+
Effect.mapError(storageFailure('inspect')),
|
|
1808
|
+
)
|
|
1809
|
+
|
|
1810
|
+
const recordId = workerReportRecordId(messageId)
|
|
1811
|
+
|
|
1812
|
+
const prepare = Effect.fnUntraced(function*(): Effect.fn.Return<
|
|
1813
|
+
WorkerReportPrepared | WorkerReportRefused,
|
|
1814
|
+
WorkerError
|
|
1815
|
+
> {
|
|
1816
|
+
const refused = (reason: WorkerReportRefused['reason']) => WorkerReportRefused.make({ runId, messageId, reason })
|
|
1817
|
+
|
|
1818
|
+
if (intent.mode !== 'standard') return yield* failure('inspect', 'corrupt')
|
|
1819
|
+
|
|
1820
|
+
const selected = yield* deps.ledger
|
|
1821
|
+
.lookup(SubmissionLookupById.make({ submissionId: host.submissionId }))
|
|
1822
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
1823
|
+
|
|
1824
|
+
if (
|
|
1825
|
+
Option.isNone(selected) ||
|
|
1826
|
+
selected.value.threadId !== submission.threadId ||
|
|
1827
|
+
selected.value.receiptId !== host.receiptId ||
|
|
1828
|
+
selected.value.workerAdmission === undefined ||
|
|
1829
|
+
!sameOrigin(selected.value.workerAdmission.origin, origin)
|
|
1830
|
+
) {
|
|
1831
|
+
return yield* failure('inspect', 'corrupt')
|
|
1832
|
+
}
|
|
1833
|
+
const hostSubmission = selected.value
|
|
1834
|
+
const hostAdmission = selected.value.workerAdmission
|
|
1835
|
+
|
|
1836
|
+
const address = intent.returnAddress
|
|
1837
|
+
|
|
1838
|
+
if (address === undefined) return yield* failure('inspect', 'corrupt')
|
|
1839
|
+
|
|
1840
|
+
const retainedAdmission = address.workerAdmission === undefined
|
|
1841
|
+
? undefined
|
|
1842
|
+
: yield* Schema.decodeUnknownEffect(WorkerAdmission)(address.workerAdmission).pipe(
|
|
1843
|
+
Effect.mapError((cause) => failure('inspect', 'corrupt', cause)),
|
|
1844
|
+
)
|
|
1845
|
+
|
|
1846
|
+
const source = { ...address, admission: retainedAdmission }
|
|
1847
|
+
|
|
1848
|
+
const sourceBinding = currentBinding(origin.source.agentId)
|
|
1849
|
+
const targetBinding = currentBinding(origin.worker.targetAgentId)
|
|
1850
|
+
|
|
1851
|
+
const reports = sourceBinding?.reporting?.filter(
|
|
1852
|
+
(entry) => entry.delegationId === origin.worker.delegationId,
|
|
1853
|
+
) ?? []
|
|
1854
|
+
|
|
1855
|
+
const descriptor = reports[0]
|
|
1856
|
+
|
|
1857
|
+
if (
|
|
1858
|
+
sourceBinding === undefined ||
|
|
1859
|
+
targetBinding === undefined ||
|
|
1860
|
+
descriptor === undefined ||
|
|
1861
|
+
reports.length !== 1 ||
|
|
1862
|
+
!Object.is(descriptor.target, targetBinding.definition)
|
|
1863
|
+
) {
|
|
1864
|
+
return refused('declaration-unavailable')
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
const sourceOrigin = source.admission?.origin
|
|
1868
|
+
|
|
1869
|
+
if (source.depth !== 0 && sourceOrigin === undefined) return refused('destination')
|
|
1870
|
+
const now = yield* Clock.currentTimeMillis
|
|
1871
|
+
|
|
1872
|
+
const deadlineAtMillis = Math.min(
|
|
1873
|
+
origin.expiresAtMillis,
|
|
1874
|
+
sourceOrigin?.expiresAtMillis ?? Infinity,
|
|
1875
|
+
)
|
|
1876
|
+
|
|
1877
|
+
if (now >= deadlineAtMillis) return refused('expired')
|
|
1878
|
+
|
|
1879
|
+
const context: WorkerContext = {
|
|
1880
|
+
source: origin.source,
|
|
1881
|
+
policy: source.policy,
|
|
1882
|
+
depth: source.depth,
|
|
1883
|
+
...(source.grant === undefined ? {} : { grant: source.grant }),
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
const report: WorkerRunReport = {
|
|
1887
|
+
worker: origin.worker,
|
|
1888
|
+
context,
|
|
1889
|
+
observation: {
|
|
1890
|
+
_tag: 'Settled',
|
|
1891
|
+
receipt: Receipt.make({
|
|
1892
|
+
threadId: hostSubmission.threadId,
|
|
1893
|
+
submissionId: hostSubmission.submissionId,
|
|
1894
|
+
receiptId: hostSubmission.receiptId,
|
|
1895
|
+
queueSequence: hostSubmission.queueSequence,
|
|
1896
|
+
}),
|
|
1897
|
+
runId,
|
|
1898
|
+
settlementId: host.settlementId,
|
|
1899
|
+
outcome: host.outcome,
|
|
1900
|
+
encodedParameters: hostAdmission.parameters,
|
|
1901
|
+
encodedResult: host.result ?? null,
|
|
1902
|
+
...(host.outcome === 'failed' ? { diagnostic: host.result } : {}),
|
|
1903
|
+
budgetExhausted: host.finishReason === 'budget-exhausted',
|
|
1904
|
+
},
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
const projection = yield* Effect.suspend(() =>
|
|
1908
|
+
descriptor.reportCompletion?.(report) === false
|
|
1909
|
+
? Effect.as(Effect.void, undefined)
|
|
1910
|
+
: descriptor.prepare(report)
|
|
1911
|
+
).pipe(
|
|
1912
|
+
Effect.timeout(
|
|
1913
|
+
Math.min(deps.limits.reportPreparationTimeoutMillis ?? 5_000, deadlineAtMillis - now),
|
|
1914
|
+
),
|
|
1915
|
+
Effect.map((value) => ({ _tag: 'Prepared' as const, value })),
|
|
1916
|
+
Effect.catchTags({
|
|
1917
|
+
WorkerReportPreparationFailure: (error) => Effect.succeed(refused(error.stage)),
|
|
1918
|
+
TimeoutError: () => Effect.succeed(refused('timeout')),
|
|
1919
|
+
}),
|
|
1920
|
+
Effect.catchCauseIf(
|
|
1921
|
+
(cause) => !Cause.hasInterrupts(cause),
|
|
1922
|
+
() => Effect.succeed(refused('defect')),
|
|
1923
|
+
),
|
|
1924
|
+
)
|
|
1925
|
+
|
|
1926
|
+
if (projection._tag === 'WorkerReportRefused') return projection
|
|
1927
|
+
|
|
1928
|
+
if (projection.value === undefined) return refused('filtered')
|
|
1929
|
+
|
|
1930
|
+
const message = projection.value.message
|
|
1931
|
+
|
|
1932
|
+
if (!Schema.is(WorkerCompletion)(message)) return refused('input')
|
|
1933
|
+
if (
|
|
1934
|
+
!Schema.toEquivalence(WorkerRef)(message.report.worker, origin.worker) ||
|
|
1935
|
+
!Schema.toEquivalence(Receipt)(message.report.receipt, report.observation.receipt) ||
|
|
1936
|
+
message.report.runId !== runId ||
|
|
1937
|
+
message.report.settlementId !== host.settlementId ||
|
|
1938
|
+
message.report.outcome !== host.outcome ||
|
|
1939
|
+
message.budgetExhausted !== report.observation.budgetExhausted
|
|
1940
|
+
) {
|
|
1941
|
+
return refused('input')
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
const validated = yield* Schema.decodeEffect(PersistedJson)(source.input).pipe(Effect.option)
|
|
1945
|
+
|
|
1946
|
+
if (Option.isNone(validated)) return refused('input')
|
|
1947
|
+
const input = validated.value
|
|
1948
|
+
|
|
1949
|
+
const inputDigest = yield* withCrypto(digestJson(input)).pipe(
|
|
1950
|
+
Effect.mapError(storageFailure('inspect')),
|
|
1951
|
+
)
|
|
1952
|
+
|
|
1953
|
+
let workerAdmission: WorkerAdmission | undefined
|
|
1954
|
+
const principal = source.principal
|
|
1955
|
+
|
|
1956
|
+
if (sourceOrigin !== undefined) {
|
|
1957
|
+
const retained = source.admission
|
|
1958
|
+
|
|
1959
|
+
if (retained === undefined) return refused('destination')
|
|
1960
|
+
|
|
1961
|
+
const parameters = yield* Schema.decodeEffect(PersistedJson)(retained.parameters).pipe(
|
|
1962
|
+
Effect.option,
|
|
1963
|
+
)
|
|
1964
|
+
|
|
1965
|
+
if (Option.isNone(parameters)) return refused('destination')
|
|
1966
|
+
workerAdmission = {
|
|
1967
|
+
origin: sourceOrigin,
|
|
1968
|
+
executionRunId: null,
|
|
1969
|
+
messageId,
|
|
1970
|
+
parameters: parameters.value,
|
|
1971
|
+
createdAtMillis: now,
|
|
1972
|
+
...(retained.sourceSubmissionId === undefined
|
|
1973
|
+
? {}
|
|
1974
|
+
: { sourceSubmissionId: retained.sourceSubmissionId }),
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
// The destination reauthorizes standard messages through validateCompletion.
|
|
1979
|
+
const envelope: PreparedInput = {
|
|
1980
|
+
schemaVersion: 1,
|
|
1981
|
+
threadId: origin.source.threadId,
|
|
1982
|
+
deliveryPrincipal: principal,
|
|
1983
|
+
agentId: origin.source.agentId,
|
|
1984
|
+
definitions: intent.sourceDigests,
|
|
1985
|
+
input,
|
|
1986
|
+
inputDigest,
|
|
1987
|
+
admissionKey: messageId,
|
|
1988
|
+
authorization: { policyId: 'worker-report', decisionId: messageId },
|
|
1989
|
+
messageAdmission: message,
|
|
1990
|
+
...(workerAdmission === undefined
|
|
1991
|
+
? {}
|
|
1992
|
+
: { workerAdmission: { ...workerAdmission, deliveryPrincipal: principal } }),
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
const encoded = yield* Schema.encodeEffect(PreparedInput)(envelope).pipe(
|
|
1996
|
+
Effect.flatMap(Schema.decodeUnknownEffect(PersistedJson)),
|
|
1997
|
+
Effect.mapError(storageFailure('inspect')),
|
|
1998
|
+
)
|
|
1999
|
+
|
|
2000
|
+
const predecessor = yield* deliveryPredecessor(
|
|
2001
|
+
submission.threadId,
|
|
2002
|
+
history.tailSequence,
|
|
2003
|
+
).pipe(
|
|
2004
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
2005
|
+
Effect.mapError(storageFailure('inspect')),
|
|
2006
|
+
)
|
|
2007
|
+
|
|
2008
|
+
return WorkerReportPrepared.make({
|
|
2009
|
+
runId,
|
|
2010
|
+
messageId,
|
|
2011
|
+
envelope: encoded,
|
|
2012
|
+
createdAtMillis: now,
|
|
2013
|
+
deadlineAtMillis,
|
|
2014
|
+
...(predecessor === undefined ? {} : { predecessor }),
|
|
2015
|
+
})
|
|
2016
|
+
})
|
|
2017
|
+
|
|
2018
|
+
let decision: WorkerReportPrepared | WorkerReportRefused | undefined
|
|
2019
|
+
|
|
2020
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2021
|
+
const current = yield* readSubmission(submission)
|
|
2022
|
+
|
|
2023
|
+
const existing = current.records.find(({ record }) => record.recordId === recordId)?.record
|
|
2024
|
+
.payload
|
|
2025
|
+
|
|
2026
|
+
if (existing !== undefined) {
|
|
2027
|
+
if (
|
|
2028
|
+
(existing._tag !== 'WorkerReportPrepared' && existing._tag !== 'WorkerReportRefused') ||
|
|
2029
|
+
existing.runId !== runId ||
|
|
2030
|
+
existing.messageId !== messageId
|
|
2031
|
+
) {
|
|
2032
|
+
return yield* failure('inspect', 'corrupt')
|
|
2033
|
+
}
|
|
2034
|
+
decision = existing
|
|
2035
|
+
break
|
|
2036
|
+
}
|
|
2037
|
+
decision ??= yield* prepare()
|
|
2038
|
+
if (yield* append(submission.threadId, recordId, decision, current, 'report')) break
|
|
2039
|
+
if (attempt === 15) return yield* failure('inspect', 'storage')
|
|
2040
|
+
}
|
|
2041
|
+
// The decision and its outbox row are already committed together. The outbox's own
|
|
2042
|
+
// due index survives both child and source settlement, including Object eviction.
|
|
2043
|
+
})
|
|
2044
|
+
|
|
2045
|
+
const completeInput = Effect.fnUntraced(function*(submission: SubmissionSnapshot) {
|
|
2046
|
+
const admission = submission.workerAdmission
|
|
2047
|
+
|
|
2048
|
+
if (admission === undefined) return
|
|
2049
|
+
const child = yield* readSubmission(submission)
|
|
2050
|
+
|
|
2051
|
+
const settledEnvelope = child.records.find(
|
|
2052
|
+
({ record }) =>
|
|
2053
|
+
record.payload._tag === 'SubmissionSettled' &&
|
|
2054
|
+
record.payload.submissionId === submission.submissionId,
|
|
2055
|
+
)?.record
|
|
2056
|
+
|
|
2057
|
+
const settled = settledEnvelope?.payload
|
|
2058
|
+
|
|
2059
|
+
if (
|
|
2060
|
+
settled?._tag !== 'SubmissionSettled' ||
|
|
2061
|
+
settled.receiptId !== submission.receiptId ||
|
|
2062
|
+
settledEnvelope === undefined
|
|
2063
|
+
) {
|
|
2064
|
+
return yield* failure('inspect', 'corrupt')
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
const unresolved = new Set<string>()
|
|
2068
|
+
const declarationIds = new Set<string>()
|
|
2069
|
+
|
|
2070
|
+
for (const { record } of child.records) {
|
|
2071
|
+
const value = record.payload
|
|
2072
|
+
|
|
2073
|
+
if (value._tag === 'ModelResponseRecorded' && value.runId === settled.runId) {
|
|
2074
|
+
for (const operation of value.toolOperations) {
|
|
2075
|
+
if (declarationIds.has(operation.toolCallId)) return yield* failure('inspect', 'corrupt')
|
|
2076
|
+
declarationIds.add(operation.toolCallId)
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
if (value._tag === 'ToolCallUnknown' && value.runId === settled.runId) {
|
|
2080
|
+
unresolved.add(value.toolCallId)
|
|
2081
|
+
}
|
|
2082
|
+
if (value._tag === 'ToolCallSettled' && value.runId === settled.runId) {
|
|
2083
|
+
unresolved.delete(value.toolCallId)
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
if (unresolved.size > 0 || unresolvedToolOperations(child.records, settled.runId).length > 0) {
|
|
2087
|
+
yield* reportRun(submission, child)
|
|
2088
|
+
|
|
2089
|
+
return
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
const payload = WorkerInputCompleted.make({
|
|
2093
|
+
effectsResolved: true,
|
|
2094
|
+
messageId: admission.messageId,
|
|
2095
|
+
workerThreadId: submission.threadId,
|
|
2096
|
+
submissionId: submission.submissionId,
|
|
2097
|
+
receiptId: submission.receiptId,
|
|
2098
|
+
settlementId: settled.settlementId,
|
|
2099
|
+
completedAtMillis: DateTime.toEpochMillis(settledEnvelope.createdAt),
|
|
2100
|
+
})
|
|
2101
|
+
|
|
2102
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2103
|
+
const current = yield* readSubmission(submission)
|
|
2104
|
+
|
|
2105
|
+
const existing = Option.getOrUndefined(
|
|
2106
|
+
yield* exactRecord(
|
|
2107
|
+
submission.threadId,
|
|
2108
|
+
RecordId.make(`worker-effects-resolved:${admission.messageId}`),
|
|
2109
|
+
'inspect',
|
|
2110
|
+
),
|
|
2111
|
+
)?.record.payload
|
|
2112
|
+
|
|
2113
|
+
if (existing !== undefined) {
|
|
2114
|
+
if (
|
|
2115
|
+
existing._tag !== 'WorkerInputCompleted' ||
|
|
2116
|
+
!Schema.toEquivalence(WorkerInputCompleted)(
|
|
2117
|
+
{ ...existing, effectsResolved: true },
|
|
2118
|
+
payload,
|
|
2119
|
+
)
|
|
2120
|
+
) {
|
|
2121
|
+
return yield* failure('inspect', 'corrupt')
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
if (existing.effectsResolved) {
|
|
2125
|
+
yield* reportRun(submission, current)
|
|
2126
|
+
|
|
2127
|
+
return
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
if (
|
|
2131
|
+
yield* append(
|
|
2132
|
+
submission.threadId,
|
|
2133
|
+
`worker-effects-resolved:${admission.messageId}`,
|
|
2134
|
+
payload,
|
|
2135
|
+
current,
|
|
2136
|
+
'completion',
|
|
2137
|
+
)
|
|
2138
|
+
) {
|
|
2139
|
+
if (Option.isSome(deps.wake)) {
|
|
2140
|
+
yield* deps.wake.value
|
|
2141
|
+
.notify(admission.origin.source.threadId)
|
|
2142
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
yield* reportRun(submission, current)
|
|
2146
|
+
|
|
2147
|
+
return
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
return yield* failure('inspect', 'storage')
|
|
2152
|
+
})
|
|
2153
|
+
|
|
2154
|
+
/** Open refused inboxes remain owed until an operator stops them; funding charges never refund. */
|
|
2155
|
+
const repairReservation = Effect.fnUntraced(function*(
|
|
2156
|
+
sourceThreadId: ThreadId,
|
|
2157
|
+
reservation: CanonicalRecordEnvelope,
|
|
2158
|
+
): Effect.fn.Return<boolean, WorkerError> {
|
|
2159
|
+
const fact = reservation.record.payload
|
|
2160
|
+
|
|
2161
|
+
if (
|
|
2162
|
+
reservation.threadId !== sourceThreadId ||
|
|
2163
|
+
(fact._tag !== 'WorkerInputRequested' &&
|
|
2164
|
+
(fact._tag !== 'SubtreeBudgetReserved' || fact.lifetime !== 'background'))
|
|
2165
|
+
) {
|
|
2166
|
+
return yield* failure('inspect', 'corrupt')
|
|
2167
|
+
}
|
|
2168
|
+
if (fact._tag === 'SubtreeBudgetReserved') {
|
|
2169
|
+
const input = Option.getOrUndefined(
|
|
2170
|
+
yield* exactRecord(
|
|
2171
|
+
sourceThreadId,
|
|
2172
|
+
workerInputRecordId(IdempotencyKey.make(fact.reservationId)),
|
|
2173
|
+
'inspect',
|
|
2174
|
+
),
|
|
2175
|
+
)
|
|
2176
|
+
|
|
2177
|
+
if (input !== undefined) {
|
|
2178
|
+
if (input.record.payload._tag !== 'WorkerInputRequested') {
|
|
2179
|
+
return yield* failure('inspect', 'corrupt')
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
return (yield* repairInput(sourceThreadId, input.record.payload)) === 'repaired'
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
const messageId = fact._tag === 'WorkerInputRequested'
|
|
2187
|
+
? fact.admission.messageId
|
|
2188
|
+
: IdempotencyKey.make(fact.reservationId)
|
|
2189
|
+
|
|
2190
|
+
const workerThreadId = fact._tag === 'WorkerInputRequested'
|
|
2191
|
+
? fact.admission.origin.worker.threadId
|
|
2192
|
+
: fact.childThreadId
|
|
2193
|
+
|
|
2194
|
+
const id = RecordId.make(`worker-input-refused:${messageId}`)
|
|
2195
|
+
|
|
2196
|
+
if (Option.isNone(deps.deliveries) || deps.ledger.inspectWorker === undefined) {
|
|
2197
|
+
return yield* failure('inspect', 'unavailable')
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
const delivery = yield* deps.deliveries.value
|
|
2201
|
+
.get({ ownerThreadId: sourceThreadId, messageId })
|
|
2202
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2203
|
+
|
|
2204
|
+
if (delivery === null) return false
|
|
2205
|
+
const admission = delivery.envelope.workerAdmission
|
|
2206
|
+
|
|
2207
|
+
if (
|
|
2208
|
+
admission === undefined ||
|
|
2209
|
+
delivery.envelope.threadId !== workerThreadId ||
|
|
2210
|
+
admission.messageId !== messageId ||
|
|
2211
|
+
delivery.envelope.admissionKey !== messageId ||
|
|
2212
|
+
admission.origin.source.threadId !== sourceThreadId ||
|
|
2213
|
+
admission.origin.worker.threadId !== workerThreadId ||
|
|
2214
|
+
(fact._tag === 'WorkerInputRequested'
|
|
2215
|
+
? !sameAdmission(admission, fact.admission) ||
|
|
2216
|
+
delivery.envelope.inputDigest !== fact.inputDigest
|
|
2217
|
+
: !Schema.toEquivalence(SubtreeBudgetReserved)(
|
|
2218
|
+
fact,
|
|
2219
|
+
SubtreeBudgetReserved.make({
|
|
2220
|
+
reservationId: fact.reservationId,
|
|
2221
|
+
executionRunId: admission.executionRunId,
|
|
2222
|
+
...(admission.sourceSubmissionId === undefined
|
|
2223
|
+
? {}
|
|
2224
|
+
: { sourceSubmissionId: admission.sourceSubmissionId }),
|
|
2225
|
+
childThreadId: workerThreadId,
|
|
2226
|
+
lifetime: 'background',
|
|
2227
|
+
depth: admission.origin.depth,
|
|
2228
|
+
policy: admission.origin.policy,
|
|
2229
|
+
grant: admission.origin.grant,
|
|
2230
|
+
budget: admission.origin.budget,
|
|
2231
|
+
}),
|
|
2232
|
+
))
|
|
2233
|
+
) {
|
|
2234
|
+
return yield* failure('inspect', 'corrupt')
|
|
2235
|
+
}
|
|
2236
|
+
if (delivery.status !== 'refused' || delivery.receipt !== null) return false
|
|
2237
|
+
|
|
2238
|
+
const ref = yield* withCrypto(reference(reservation.record)).pipe(
|
|
2239
|
+
Effect.mapError(storageFailure('inspect')),
|
|
2240
|
+
)
|
|
2241
|
+
|
|
2242
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2243
|
+
const existing = Option.getOrUndefined(yield* exactRecord(sourceThreadId, id, 'inspect'))
|
|
2244
|
+
?.record.payload
|
|
2245
|
+
|
|
2246
|
+
if (existing !== undefined) {
|
|
2247
|
+
if (
|
|
2248
|
+
existing._tag !== 'WorkerInputRefused' ||
|
|
2249
|
+
existing.messageId !== messageId ||
|
|
2250
|
+
existing.workerThreadId !== workerThreadId ||
|
|
2251
|
+
existing.reservation.recordId !== ref.recordId ||
|
|
2252
|
+
existing.receiver.threadId !== workerThreadId ||
|
|
2253
|
+
existing.receiver.principal !== delivery.envelope.deliveryPrincipal ||
|
|
2254
|
+
existing.receiver.idempotencyKey !== delivery.envelope.admissionKey ||
|
|
2255
|
+
existing.receiver.inputDigest !== delivery.envelope.inputDigest ||
|
|
2256
|
+
existing.envelopeDigest !== delivery.envelopeDigest ||
|
|
2257
|
+
existing.deliveryVersion !== delivery.version
|
|
2258
|
+
) {
|
|
2259
|
+
return yield* failure('inspect', 'corrupt')
|
|
2260
|
+
}
|
|
2261
|
+
|
|
2262
|
+
const stop = Option.getOrUndefined(
|
|
2263
|
+
yield* exactRecord(sourceThreadId, existing.stop.recordId, 'inspect'),
|
|
2264
|
+
)
|
|
2265
|
+
|
|
2266
|
+
if (
|
|
2267
|
+
stop?.record.payload._tag !== 'WorkerStopRequested' ||
|
|
2268
|
+
!Schema.toEquivalence(WorkerRef)(
|
|
2269
|
+
stop.record.payload.command.worker,
|
|
2270
|
+
admission.origin.worker,
|
|
2271
|
+
)
|
|
2272
|
+
) {
|
|
2273
|
+
return yield* failure('inspect', 'corrupt')
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
return true
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
const tail = yield* deps.store
|
|
2280
|
+
.inspectTail(ThreadTailRequest.make({ threadId: sourceThreadId }))
|
|
2281
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2282
|
+
|
|
2283
|
+
// A source reservation can advance to an input while this repair yields. Close its
|
|
2284
|
+
// current exact owner, with the tail below fencing any later transition.
|
|
2285
|
+
if (fact._tag === 'SubtreeBudgetReserved') {
|
|
2286
|
+
const input = Option.getOrUndefined(
|
|
2287
|
+
yield* exactRecord(sourceThreadId, workerInputRecordId(messageId), 'inspect'),
|
|
2288
|
+
)
|
|
2289
|
+
|
|
2290
|
+
if (input !== undefined) {
|
|
2291
|
+
if (input.sequence > tail.tailSequence) continue
|
|
2292
|
+
if (input.record.payload._tag !== 'WorkerInputRequested') {
|
|
2293
|
+
return yield* failure('inspect', 'corrupt')
|
|
2294
|
+
}
|
|
2295
|
+
|
|
2296
|
+
return (yield* repairInput(sourceThreadId, input.record.payload)) === 'repaired'
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
const stop = yield* readStop(sourceThreadId, workerThreadId, tail.tailSequence)
|
|
2301
|
+
|
|
2302
|
+
if (stop === undefined) return false
|
|
2303
|
+
if (
|
|
2304
|
+
stop.record.payload._tag !== 'WorkerStopRequested' ||
|
|
2305
|
+
!Schema.toEquivalence(WorkerRef)(
|
|
2306
|
+
stop.record.payload.command.worker,
|
|
2307
|
+
admission.origin.worker,
|
|
2308
|
+
)
|
|
2309
|
+
) {
|
|
2310
|
+
return yield* failure('inspect', 'corrupt')
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
const receiver = yield* deps.ledger
|
|
2314
|
+
.inspectWorker(workerThreadId)
|
|
2315
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2316
|
+
|
|
2317
|
+
if (!receiver.stopped) return false
|
|
2318
|
+
|
|
2319
|
+
const key = SubmissionLookupByKey.make({
|
|
2320
|
+
threadId: workerThreadId,
|
|
2321
|
+
principal: delivery.envelope.deliveryPrincipal,
|
|
2322
|
+
idempotencyKey: delivery.envelope.admissionKey,
|
|
2323
|
+
})
|
|
2324
|
+
|
|
2325
|
+
const resolution = yield* deps.ledger
|
|
2326
|
+
.resolveAdmission(key)
|
|
2327
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2328
|
+
|
|
2329
|
+
if (resolution._tag !== 'NotAdmitted') return false
|
|
2330
|
+
|
|
2331
|
+
const payload = WorkerInputRefused.make({
|
|
2332
|
+
messageId,
|
|
2333
|
+
workerThreadId,
|
|
2334
|
+
reservation: ref,
|
|
2335
|
+
stop: yield* withCrypto(reference(stop.record)).pipe(
|
|
2336
|
+
Effect.mapError(storageFailure('inspect')),
|
|
2337
|
+
),
|
|
2338
|
+
deliveryVersion: delivery.version,
|
|
2339
|
+
envelopeDigest: delivery.envelopeDigest,
|
|
2340
|
+
receiver: {
|
|
2341
|
+
...key,
|
|
2342
|
+
inputDigest: delivery.envelope.inputDigest,
|
|
2343
|
+
stopped: true,
|
|
2344
|
+
resolution: 'NotAdmitted',
|
|
2345
|
+
},
|
|
2346
|
+
})
|
|
2347
|
+
|
|
2348
|
+
if (yield* append(sourceThreadId, id, payload, { ...tail, records: [] }, 'completion')) {
|
|
2349
|
+
return true
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
return yield* failure('inspect', 'storage')
|
|
2354
|
+
})
|
|
2355
|
+
|
|
2356
|
+
const readInputCompletion = (admission: WorkerAdmission) =>
|
|
2357
|
+
getRecord({
|
|
2358
|
+
threadId: admission.origin.worker.threadId,
|
|
2359
|
+
recordId: RecordId.make(`worker-effects-resolved:${admission.messageId}`),
|
|
2360
|
+
}).pipe(
|
|
2361
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
2362
|
+
Effect.catchTag('ThreadNotMaterialized', () => Effect.succeedNone),
|
|
2363
|
+
Effect.mapError(storageFailure('inspect')),
|
|
2364
|
+
)
|
|
2365
|
+
|
|
2366
|
+
/** Copy an exact factual child acknowledgement into source accounting, even after its Run ends. */
|
|
2367
|
+
const repairInput = Effect.fnUntraced(function*(
|
|
2368
|
+
sourceThreadId: ThreadId,
|
|
2369
|
+
request: WorkerInputRequested,
|
|
2370
|
+
completion?: Option.Option<CanonicalRecordEnvelope>,
|
|
2371
|
+
): Effect.fn.Return<'repaired' | 'delivery-owned' | 'awaiting-effects', WorkerError> {
|
|
2372
|
+
const admission = request.admission
|
|
2373
|
+
|
|
2374
|
+
const reserved = Option.getOrUndefined(
|
|
2375
|
+
yield* exactRecord(sourceThreadId, workerInputRecordId(admission.messageId), 'inspect'),
|
|
2376
|
+
)
|
|
2377
|
+
|
|
2378
|
+
if (
|
|
2379
|
+
reserved === undefined ||
|
|
2380
|
+
reserved.record.payload._tag !== 'WorkerInputRequested' ||
|
|
2381
|
+
!sameAdmission(reserved.record.payload.admission, admission) ||
|
|
2382
|
+
reserved.record.payload.inputDigest !== request.inputDigest
|
|
2383
|
+
) {
|
|
2384
|
+
return yield* failure('inspect', 'corrupt')
|
|
2385
|
+
}
|
|
2386
|
+
if (yield* repairReservation(sourceThreadId, reserved)) return 'repaired'
|
|
2387
|
+
const id = RecordId.make(`worker-effects-resolved:${admission.messageId}`)
|
|
2388
|
+
|
|
2389
|
+
if (Option.isNone(deps.deliveries)) return yield* failure('inspect', 'unavailable')
|
|
2390
|
+
|
|
2391
|
+
const delivery = yield* deps.deliveries.value
|
|
2392
|
+
.get({ ownerThreadId: sourceThreadId, messageId: admission.messageId })
|
|
2393
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2394
|
+
|
|
2395
|
+
if (delivery === null) return yield* failure('inspect', 'unavailable')
|
|
2396
|
+
if (
|
|
2397
|
+
delivery.key.ownerThreadId !== sourceThreadId ||
|
|
2398
|
+
delivery.key.messageId !== admission.messageId ||
|
|
2399
|
+
delivery.envelope.threadId !== admission.origin.worker.threadId ||
|
|
2400
|
+
delivery.envelope.inputDigest !== request.inputDigest ||
|
|
2401
|
+
delivery.envelope.workerAdmission === undefined ||
|
|
2402
|
+
!sameAdmission(delivery.envelope.workerAdmission, admission)
|
|
2403
|
+
) {
|
|
2404
|
+
return yield* failure('inspect', 'corrupt')
|
|
2405
|
+
}
|
|
2406
|
+
// A parked delivery may already have a factual effects-resolved acknowledgement.
|
|
2407
|
+
// Settlement alone cannot release capacity; the exact child fact below can.
|
|
2408
|
+
// The delivery driver owns settlement polling. Normal maintenance waits for its local
|
|
2409
|
+
// observation; capacity pressure supplies an exact foreign read without polling live Runs.
|
|
2410
|
+
if (completion === undefined && delivery.settlement === null) return 'delivery-owned'
|
|
2411
|
+
|
|
2412
|
+
const child = Option.getOrUndefined(completion ?? (yield* readInputCompletion(admission)))
|
|
2413
|
+
|
|
2414
|
+
// Only the child storage owner publishes factual acknowledgements. Its native WorkerEffects
|
|
2415
|
+
// obligation survives settlement and operation closure; source recovery copies that evidence.
|
|
2416
|
+
if (child === undefined) return 'awaiting-effects'
|
|
2417
|
+
const payload = child.record.payload
|
|
2418
|
+
|
|
2419
|
+
if (
|
|
2420
|
+
payload._tag !== 'WorkerInputCompleted' ||
|
|
2421
|
+
payload.effectsResolved !== true ||
|
|
2422
|
+
payload.messageId !== admission.messageId ||
|
|
2423
|
+
payload.workerThreadId !== admission.origin.worker.threadId ||
|
|
2424
|
+
(delivery.receipt !== null &&
|
|
2425
|
+
(payload.submissionId !== delivery.receipt.submissionId ||
|
|
2426
|
+
payload.receiptId !== delivery.receipt.receiptId))
|
|
2427
|
+
) {
|
|
2428
|
+
return yield* failure('inspect', 'corrupt')
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
const origin = Option.getOrUndefined(
|
|
2432
|
+
yield* exactRecord(
|
|
2433
|
+
admission.origin.worker.threadId,
|
|
2434
|
+
workerOriginRecordId(admission.origin.worker.threadId),
|
|
2435
|
+
'inspect',
|
|
2436
|
+
),
|
|
2437
|
+
)?.record.payload
|
|
2438
|
+
|
|
2439
|
+
if (origin?._tag !== 'WorkerOriginRecorded' || !sameOrigin(origin.origin, admission.origin)) {
|
|
2440
|
+
return yield* failure('inspect', 'corrupt')
|
|
2441
|
+
}
|
|
2442
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2443
|
+
const existing = Option.getOrUndefined(yield* exactRecord(sourceThreadId, id, 'inspect'))
|
|
2444
|
+
?.record.payload
|
|
2445
|
+
|
|
2446
|
+
if (existing !== undefined) {
|
|
2447
|
+
if (
|
|
2448
|
+
existing._tag !== 'WorkerInputCompleted' ||
|
|
2449
|
+
!Schema.toEquivalence(WorkerInputCompleted)(existing, payload)
|
|
2450
|
+
) {
|
|
2451
|
+
return yield* failure('inspect', 'corrupt')
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
return 'repaired'
|
|
2455
|
+
}
|
|
2456
|
+
|
|
2457
|
+
const tail = yield* deps.store
|
|
2458
|
+
.inspectTail(ThreadTailRequest.make({ threadId: sourceThreadId }))
|
|
2459
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2460
|
+
|
|
2461
|
+
if (yield* append(sourceThreadId, id, payload, { ...tail, records: [] }, 'completion')) {
|
|
2462
|
+
return 'repaired'
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
return yield* failure('inspect', 'storage')
|
|
2467
|
+
})
|
|
2468
|
+
|
|
2469
|
+
const completeHandoff = Effect.fnUntraced(function*(
|
|
2470
|
+
threadId: ThreadId,
|
|
2471
|
+
preparationId: RecordId,
|
|
2472
|
+
ownerId: string,
|
|
2473
|
+
operation: 'inspect' | 'stop',
|
|
2474
|
+
) {
|
|
2475
|
+
const id = RecordId.make(`work-handoff-completed:${preparationId}`)
|
|
2476
|
+
|
|
2477
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2478
|
+
const prior = Option.getOrUndefined(yield* exactRecord(threadId, id, operation))?.record
|
|
2479
|
+
.payload
|
|
2480
|
+
|
|
2481
|
+
if (prior !== undefined) {
|
|
2482
|
+
if (
|
|
2483
|
+
prior._tag !== 'WorkHandoffCompleted' ||
|
|
2484
|
+
prior.preparationId !== preparationId ||
|
|
2485
|
+
prior.ownerId !== ownerId
|
|
2486
|
+
) {
|
|
2487
|
+
return yield* failure(operation, 'corrupt')
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
return
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
const tail = yield* deps.store
|
|
2494
|
+
.inspectTail(ThreadTailRequest.make({ threadId }))
|
|
2495
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
2496
|
+
|
|
2497
|
+
if (
|
|
2498
|
+
yield* append(
|
|
2499
|
+
threadId,
|
|
2500
|
+
id,
|
|
2501
|
+
WorkHandoffCompleted.make({ preparationId, ownerId }),
|
|
2502
|
+
{ ...tail, records: [] },
|
|
2503
|
+
operation === 'stop' ? 'stop' : 'completion',
|
|
2504
|
+
)
|
|
2505
|
+
) {
|
|
2506
|
+
return
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
|
|
2510
|
+
return yield* failure(operation, 'storage')
|
|
2511
|
+
})
|
|
2512
|
+
|
|
2513
|
+
/** A retained command preserves its original principal and input owner; discovery grants neither. */
|
|
2514
|
+
const repairStop = Effect.fnUntraced(function*(
|
|
2515
|
+
sourceThreadId: ThreadId,
|
|
2516
|
+
preparationId: RecordId,
|
|
2517
|
+
request: WorkerStopRequested,
|
|
2518
|
+
) {
|
|
2519
|
+
if (deps.ledger.stopWorker === undefined) return yield* failure('stop', 'unavailable')
|
|
2520
|
+
|
|
2521
|
+
const first = Option.getOrUndefined(
|
|
2522
|
+
yield* exactRecord(sourceThreadId, firstWorkerInputRecordId(request.command.worker), 'stop'),
|
|
2523
|
+
)?.record.payload
|
|
2524
|
+
|
|
2525
|
+
const retained = first === undefined && Option.isSome(deps.deliveries)
|
|
2526
|
+
? yield* deps.deliveries.value
|
|
2527
|
+
.get({
|
|
2528
|
+
ownerThreadId: sourceThreadId,
|
|
2529
|
+
messageId: IdempotencyKey.make(request.command.worker.threadId),
|
|
2530
|
+
})
|
|
2531
|
+
.pipe(Effect.mapError(storageFailure('stop')))
|
|
2532
|
+
: null
|
|
2533
|
+
|
|
2534
|
+
const origin = first?._tag === 'WorkerInputRequested'
|
|
2535
|
+
? first.admission.origin
|
|
2536
|
+
: retained?.envelope.workerAdmission?.origin
|
|
2537
|
+
|
|
2538
|
+
if (
|
|
2539
|
+
origin === undefined ||
|
|
2540
|
+
origin.source.threadId !== sourceThreadId ||
|
|
2541
|
+
origin.firstMessageId !== IdempotencyKey.make(request.command.worker.threadId) ||
|
|
2542
|
+
!Schema.toEquivalence(WorkerRef)(origin.worker, request.command.worker) ||
|
|
2543
|
+
(retained !== null &&
|
|
2544
|
+
(retained.key.ownerThreadId !== sourceThreadId ||
|
|
2545
|
+
retained.key.messageId !== origin.firstMessageId ||
|
|
2546
|
+
retained.envelope.workerAdmission?.messageId !== origin.firstMessageId ||
|
|
2547
|
+
retained.envelope.agentId !== origin.worker.targetAgentId ||
|
|
2548
|
+
retained.envelope.threadId !== origin.worker.threadId ||
|
|
2549
|
+
retained.envelope.admissionKey !== origin.firstMessageId))
|
|
2550
|
+
) {
|
|
2551
|
+
return yield* failure('stop', 'worker-mismatch')
|
|
2552
|
+
}
|
|
2553
|
+
|
|
2554
|
+
const principal = yield* deps.authorizer.authorize({
|
|
2555
|
+
sourceThreadId,
|
|
2556
|
+
principal: request.principal,
|
|
2557
|
+
operation: 'stop',
|
|
2558
|
+
access: 'control',
|
|
2559
|
+
worker: request.command.worker,
|
|
2560
|
+
...(request.sourceSubmissionId === undefined
|
|
2561
|
+
? {}
|
|
2562
|
+
: { sourceSubmissionId: request.sourceSubmissionId }),
|
|
2563
|
+
})
|
|
2564
|
+
|
|
2565
|
+
if (principal !== request.principal) return yield* failure('stop', 'denied')
|
|
2566
|
+
|
|
2567
|
+
const owned = yield* deps.ledger
|
|
2568
|
+
.stopWorker({ threadId: request.command.worker.threadId, author: principal })
|
|
2569
|
+
.pipe(Effect.mapError(storageFailure('stop')))
|
|
2570
|
+
|
|
2571
|
+
if (owned !== 0) return false
|
|
2572
|
+
yield* completeHandoff(sourceThreadId, preparationId, workId('handoff', preparationId), 'stop')
|
|
2573
|
+
|
|
2574
|
+
return true
|
|
2575
|
+
})
|
|
2576
|
+
|
|
2577
|
+
const facet = (
|
|
2578
|
+
context: WorkerContext,
|
|
2579
|
+
principal: Principal,
|
|
2580
|
+
sourceSubmissionId?: SubmissionId,
|
|
2581
|
+
): SubagentHost['Service'] => {
|
|
2582
|
+
const requestedPrincipal = principal
|
|
2583
|
+
|
|
2584
|
+
const authorize = (
|
|
2585
|
+
operation: WorkerError['operation'],
|
|
2586
|
+
access: 'context' | 'read' | 'send' | 'control',
|
|
2587
|
+
worker?: WorkerRef,
|
|
2588
|
+
continuationOf?: WorkerContinuation,
|
|
2589
|
+
admission?: WorkerStartAdmission,
|
|
2590
|
+
) =>
|
|
2591
|
+
deps.authorizer.authorize({
|
|
2592
|
+
...(admission === undefined ? {} : { admission }),
|
|
2593
|
+
sourceThreadId: context.source.threadId,
|
|
2594
|
+
...(sourceSubmissionId === undefined ? {} : { sourceSubmissionId }),
|
|
2595
|
+
principal,
|
|
2596
|
+
operation,
|
|
2597
|
+
access,
|
|
2598
|
+
...(worker === undefined ? {} : { worker }),
|
|
2599
|
+
...(continuationOf === undefined ? {} : { continuationOf }),
|
|
2600
|
+
})
|
|
2601
|
+
|
|
2602
|
+
const binding = (target: Agent.AnyDefinition, operation: WorkerError['operation']) =>
|
|
2603
|
+
resolveDefinitionBinding(deps.bindings, target).pipe(
|
|
2604
|
+
Effect.mapError((cause) => failure(operation, 'declaration-unavailable', cause)),
|
|
2605
|
+
)
|
|
2606
|
+
|
|
2607
|
+
const deliveryStatus = (row: MessageDeliveryRecord, operation: WorkerError['operation']) =>
|
|
2608
|
+
messageStatus(row).pipe(Effect.mapError((cause) => failure(operation, 'corrupt', cause)))
|
|
2609
|
+
|
|
2610
|
+
const preparedTarget = Effect.fnUntraced(function*(
|
|
2611
|
+
target: Agent.AnyDefinition,
|
|
2612
|
+
encodedInput: unknown,
|
|
2613
|
+
continuationOf?: WorkerContinuation,
|
|
2614
|
+
authorization?: WorkerStartAdmission,
|
|
2615
|
+
) {
|
|
2616
|
+
const resolved = yield* binding(target, 'start')
|
|
2617
|
+
|
|
2618
|
+
yield* Schema.decodeUnknownEffect(Schema.toEncoded(target.input))(encodedInput).pipe(
|
|
2619
|
+
Effect.mapError((cause) => failure('start', 'corrupt', cause)),
|
|
2620
|
+
)
|
|
2621
|
+
const input = yield* decode(PersistedJson, encodedInput, 'start')
|
|
2622
|
+
|
|
2623
|
+
const inputDigest = yield* withCrypto(digestJson(input)).pipe(
|
|
2624
|
+
Effect.mapError(storageFailure('start')),
|
|
2625
|
+
)
|
|
2626
|
+
|
|
2627
|
+
const source = yield* sourceAuthority(context.source.threadId, sourceSubmissionId)
|
|
2628
|
+
|
|
2629
|
+
const admission = yield* currentStart(
|
|
2630
|
+
authorization,
|
|
2631
|
+
context.source.threadId,
|
|
2632
|
+
sourceSubmissionId,
|
|
2633
|
+
principal,
|
|
2634
|
+
target.id,
|
|
2635
|
+
continuationOf,
|
|
2636
|
+
)
|
|
2637
|
+
|
|
2638
|
+
const policy = yield* resolveTargetPolicy({
|
|
2639
|
+
_tag: 'InitialInput',
|
|
2640
|
+
...(admission === undefined ? {} : { admission }),
|
|
2641
|
+
...(continuationOf === undefined ? {} : { continuationOf }),
|
|
2642
|
+
definition: resolved.definition,
|
|
2643
|
+
definitions: resolved.digests,
|
|
2644
|
+
source: context.source,
|
|
2645
|
+
...(source.submission === undefined ? {} : { sourceSubmission: source.submission }),
|
|
2646
|
+
input,
|
|
2647
|
+
inputDigest,
|
|
2648
|
+
})
|
|
2649
|
+
|
|
2650
|
+
return { resolved, source, policy }
|
|
2651
|
+
})
|
|
2652
|
+
|
|
2653
|
+
const findOrigin = Effect.fnUntraced(function*(
|
|
2654
|
+
worker: WorkerRef,
|
|
2655
|
+
target: Agent.AnyDefinition,
|
|
2656
|
+
operation: WorkerError['operation'],
|
|
2657
|
+
) {
|
|
2658
|
+
yield* binding(target, operation)
|
|
2659
|
+
|
|
2660
|
+
if (worker.targetAgentId !== target.id) return yield* failure(operation, 'worker-mismatch')
|
|
2661
|
+
|
|
2662
|
+
const first = Option.getOrUndefined(
|
|
2663
|
+
yield* exactRecord(context.source.threadId, firstWorkerInputRecordId(worker), operation),
|
|
2664
|
+
)?.record.payload
|
|
2665
|
+
|
|
2666
|
+
const origin = first?._tag === 'WorkerInputRequested' ? first.admission.origin : undefined
|
|
2667
|
+
|
|
2668
|
+
if (origin === undefined) {
|
|
2669
|
+
const retained = Option.isNone(deps.deliveries)
|
|
2670
|
+
? null
|
|
2671
|
+
: yield* deps.deliveries.value
|
|
2672
|
+
.get({
|
|
2673
|
+
ownerThreadId: context.source.threadId,
|
|
2674
|
+
messageId: yield* Schema.decodeEffect(IdempotencyKey)(worker.threadId).pipe(
|
|
2675
|
+
Effect.orDie,
|
|
2676
|
+
),
|
|
2677
|
+
})
|
|
2678
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
2679
|
+
|
|
2680
|
+
const pendingOrigin = retained?.envelope.workerAdmission?.origin
|
|
2681
|
+
|
|
2682
|
+
if (pendingOrigin === undefined) return yield* failure(operation, 'not-found')
|
|
2683
|
+
if (
|
|
2684
|
+
!Schema.toEquivalence(WorkerRef)(pendingOrigin.worker, worker) ||
|
|
2685
|
+
pendingOrigin.firstMessageId !== retained?.key.messageId ||
|
|
2686
|
+
pendingOrigin.source.threadId !== context.source.threadId
|
|
2687
|
+
) {
|
|
2688
|
+
return yield* failure(operation, 'worker-mismatch')
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
return pendingOrigin
|
|
2692
|
+
}
|
|
2693
|
+
if (
|
|
2694
|
+
!Schema.toEquivalence(WorkerRef)(origin.worker, worker) ||
|
|
2695
|
+
first?._tag !== 'WorkerInputRequested' ||
|
|
2696
|
+
first.admission.messageId !== origin.firstMessageId ||
|
|
2697
|
+
workerInputRecordId(origin.firstMessageId) !== firstWorkerInputRecordId(worker)
|
|
2698
|
+
) {
|
|
2699
|
+
return yield* failure(operation, 'worker-mismatch')
|
|
2700
|
+
}
|
|
2701
|
+
|
|
2702
|
+
return origin
|
|
2703
|
+
})
|
|
2704
|
+
|
|
2705
|
+
const receiptInput = Effect.fnUntraced(function*(
|
|
2706
|
+
request: WorkerReceiptRequest,
|
|
2707
|
+
operation: WorkerError['operation'],
|
|
2708
|
+
) {
|
|
2709
|
+
const origin = yield* findOrigin(request.worker, request.target, operation)
|
|
2710
|
+
const receipt = request.receipt
|
|
2711
|
+
|
|
2712
|
+
const snapshot = yield* deps.ledger
|
|
2713
|
+
.lookup(SubmissionLookupById.make({ submissionId: receipt.submissionId }))
|
|
2714
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
2715
|
+
|
|
2716
|
+
if (Option.isNone(snapshot)) return yield* failure(operation, 'not-found')
|
|
2717
|
+
const row = snapshot.value
|
|
2718
|
+
|
|
2719
|
+
if (
|
|
2720
|
+
row.threadId !== request.worker.threadId ||
|
|
2721
|
+
row.threadId !== receipt.threadId ||
|
|
2722
|
+
row.receiptId !== receipt.receiptId ||
|
|
2723
|
+
row.queueSequence !== receipt.queueSequence ||
|
|
2724
|
+
row.workerAdmission === undefined ||
|
|
2725
|
+
!sameOrigin(row.workerAdmission.origin, origin)
|
|
2726
|
+
) {
|
|
2727
|
+
return yield* failure(operation, 'receipt-mismatch')
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2730
|
+
return row.workerAdmission
|
|
2731
|
+
})
|
|
2732
|
+
|
|
2733
|
+
const observation = Effect.fnUntraced(function*(
|
|
2734
|
+
request: WorkerReceiptRequest,
|
|
2735
|
+
admission: WorkerAdmission,
|
|
2736
|
+
settlement: Settlement,
|
|
2737
|
+
): Effect.fn.Return<WorkerObservation, WorkerError> {
|
|
2738
|
+
const selected = yield* deps.ledger
|
|
2739
|
+
.lookup(SubmissionLookupById.make({ submissionId: settlement.submissionId }))
|
|
2740
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
2741
|
+
|
|
2742
|
+
if (Option.isNone(selected) || selected.value.threadId !== request.worker.threadId) {
|
|
2743
|
+
return yield* failure('inspect', 'corrupt')
|
|
2744
|
+
}
|
|
2745
|
+
const history = yield* readSubmission(selected.value)
|
|
2746
|
+
|
|
2747
|
+
const record = history.records.find(
|
|
2748
|
+
({ record }) =>
|
|
2749
|
+
record.payload._tag === 'SubmissionSettled' &&
|
|
2750
|
+
record.payload.submissionId === settlement.submissionId,
|
|
2751
|
+
)?.record.payload
|
|
2752
|
+
|
|
2753
|
+
if (
|
|
2754
|
+
record?._tag !== 'SubmissionSettled' ||
|
|
2755
|
+
record.settlementId !== settlement.settlementId ||
|
|
2756
|
+
record.receiptId !== request.receipt.receiptId ||
|
|
2757
|
+
record.outcome !== settlement.outcome
|
|
2758
|
+
) {
|
|
2759
|
+
return yield* failure('inspect', 'corrupt')
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
const input = history.records.find(
|
|
2763
|
+
({ record }) =>
|
|
2764
|
+
record.payload._tag === 'UserInputRecorded' &&
|
|
2765
|
+
record.payload.submissionId === settlement.submissionId,
|
|
2766
|
+
)?.record.payload
|
|
2767
|
+
|
|
2768
|
+
const inputRunId = input?._tag === 'UserInputRecorded' ? input.runId : undefined
|
|
2769
|
+
|
|
2770
|
+
if (inputRunId !== undefined && record.runId !== undefined && inputRunId !== record.runId) {
|
|
2771
|
+
return yield* failure('inspect', 'corrupt')
|
|
2772
|
+
}
|
|
2773
|
+
const runId = record.runId ?? inputRunId
|
|
2774
|
+
|
|
2775
|
+
// The host settlement precedes the joined members and carries the Run's actual output.
|
|
2776
|
+
// Both identities come from canonical history; no foreign recovery or finalization is needed.
|
|
2777
|
+
const host = runId === undefined
|
|
2778
|
+
? undefined
|
|
2779
|
+
: history.records.find(
|
|
2780
|
+
({ record }) => record.payload._tag === 'SubmissionSettled' && record.payload.runId === runId,
|
|
2781
|
+
)?.record.payload
|
|
2782
|
+
|
|
2783
|
+
const result = host?._tag === 'SubmissionSettled' ? host : record
|
|
2784
|
+
|
|
2785
|
+
if (result.outcome !== record.outcome) return yield* failure('inspect', 'corrupt')
|
|
2786
|
+
|
|
2787
|
+
return {
|
|
2788
|
+
_tag: 'Settled',
|
|
2789
|
+
receipt: request.receipt,
|
|
2790
|
+
settlementId: settlement.settlementId,
|
|
2791
|
+
...(result.runId === undefined ? {} : { runId: result.runId }),
|
|
2792
|
+
outcome: settlement.outcome,
|
|
2793
|
+
encodedParameters: admission.parameters,
|
|
2794
|
+
encodedResult: result.result ?? null,
|
|
2795
|
+
...(result.outcome === 'failed' ? { diagnostic: result.result } : {}),
|
|
2796
|
+
budgetExhausted: result.finishReason === 'budget-exhausted',
|
|
2797
|
+
}
|
|
2798
|
+
})
|
|
2799
|
+
|
|
2800
|
+
const send = Effect.fnUntraced(function*(
|
|
2801
|
+
origin: WorkerOrigin,
|
|
2802
|
+
messageId: IdempotencyKey,
|
|
2803
|
+
encodedInput: unknown,
|
|
2804
|
+
encodedParameters: unknown,
|
|
2805
|
+
principal: Principal,
|
|
2806
|
+
operation: 'start' | 'followUp',
|
|
2807
|
+
authorization?: WorkerStartAdmission,
|
|
2808
|
+
) {
|
|
2809
|
+
if (Option.isNone(deps.deliveries)) return yield* failure(operation, 'unavailable')
|
|
2810
|
+
const deliveries = deps.deliveries.value
|
|
2811
|
+
const input = yield* decode(PersistedJson, encodedInput, operation)
|
|
2812
|
+
const parameters = yield* decode(PersistedJson, encodedParameters, operation)
|
|
2813
|
+
|
|
2814
|
+
const inputDigest = yield* withCrypto(digestJson(input)).pipe(
|
|
2815
|
+
Effect.mapError(storageFailure(operation)),
|
|
2816
|
+
)
|
|
2817
|
+
|
|
2818
|
+
const key = { ownerThreadId: context.source.threadId, messageId }
|
|
2819
|
+
const saved = yield* deliveries.get(key).pipe(Effect.mapError(storageFailure(operation)))
|
|
2820
|
+
|
|
2821
|
+
if (saved !== null) {
|
|
2822
|
+
const metadata = saved.envelope.workerAdmission
|
|
2823
|
+
|
|
2824
|
+
if (
|
|
2825
|
+
metadata === undefined ||
|
|
2826
|
+
!sameOrigin(metadata.origin, origin) ||
|
|
2827
|
+
!sameJson(metadata.parameters, parameters) ||
|
|
2828
|
+
saved.envelope.inputDigest !== inputDigest ||
|
|
2829
|
+
!sameJson(saved.envelope.input, input)
|
|
2830
|
+
) {
|
|
2831
|
+
return yield* failure(operation, 'idempotency-conflict')
|
|
2832
|
+
}
|
|
2833
|
+
if (saved.receipt !== null) return yield* deliveryStatus(saved, operation)
|
|
2834
|
+
} else {
|
|
2835
|
+
const now = yield* Clock.currentTimeMillis
|
|
2836
|
+
|
|
2837
|
+
if (now >= origin.expiresAtMillis) return yield* failure(operation, 'capacity')
|
|
2838
|
+
|
|
2839
|
+
const funding = sourceSubmissionId === undefined
|
|
2840
|
+
? undefined
|
|
2841
|
+
: yield* sourceAuthority(context.source.threadId, sourceSubmissionId)
|
|
2842
|
+
|
|
2843
|
+
const envelope: PreparedInput = {
|
|
2844
|
+
schemaVersion: 1,
|
|
2845
|
+
threadId: origin.worker.threadId,
|
|
2846
|
+
deliveryPrincipal: principal,
|
|
2847
|
+
agentId: origin.worker.targetAgentId,
|
|
2848
|
+
definitions: origin.targetDigests,
|
|
2849
|
+
input,
|
|
2850
|
+
inputDigest,
|
|
2851
|
+
admissionKey: messageId,
|
|
2852
|
+
authorization: { policyId: 'worker-host', decisionId: messageId },
|
|
2853
|
+
workerAdmission: {
|
|
2854
|
+
origin,
|
|
2855
|
+
// Freeze the first sender's execution owner; replay reuses this whole envelope.
|
|
2856
|
+
executionRunId: context.source._tag === 'tool' ? context.source.runId : null,
|
|
2857
|
+
messageId,
|
|
2858
|
+
parameters,
|
|
2859
|
+
createdAtMillis: now,
|
|
2860
|
+
deliveryPrincipal: principal,
|
|
2861
|
+
...(funding?.submission === undefined
|
|
2862
|
+
? {}
|
|
2863
|
+
: { sourceSubmissionId: funding.submission.submissionId }),
|
|
2864
|
+
},
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
const prepared = yield* withCrypto(
|
|
2868
|
+
prepareMessageDelivery({
|
|
2869
|
+
key,
|
|
2870
|
+
envelope,
|
|
2871
|
+
createdAtMillis: now,
|
|
2872
|
+
deadlineAtMillis: origin.expiresAtMillis,
|
|
2873
|
+
}),
|
|
2874
|
+
).pipe(Effect.mapError(storageFailure(operation)))
|
|
2875
|
+
|
|
2876
|
+
yield* deliveries
|
|
2877
|
+
.insert(prepared)
|
|
2878
|
+
.pipe(
|
|
2879
|
+
Effect.mapError((error) =>
|
|
2880
|
+
failure(
|
|
2881
|
+
operation,
|
|
2882
|
+
error._tag === 'MessageDeliveryError' && error.reason === 'capacity'
|
|
2883
|
+
? 'capacity'
|
|
2884
|
+
: 'storage',
|
|
2885
|
+
error,
|
|
2886
|
+
)
|
|
2887
|
+
),
|
|
2888
|
+
)
|
|
2889
|
+
}
|
|
2890
|
+
|
|
2891
|
+
// Direct callers and automatic pumps run the same claim/accept/refuse protocol. A
|
|
2892
|
+
// conclusive refusal is retained before it becomes visible to this caller.
|
|
2893
|
+
const processed = yield* MessageDeliveryDriver.pipe(
|
|
2894
|
+
Effect.flatMap((driver) => driver.process(key)),
|
|
2895
|
+
Effect.provide(MessageDeliveryDriver.layer({ batchSize: 1, concurrency: 1 })),
|
|
2896
|
+
Effect.provideService(MessageDeliveryStore, deliveries),
|
|
2897
|
+
Effect.provideService(PreparedInputAdmission, {
|
|
2898
|
+
submit: (prepared) =>
|
|
2899
|
+
deps.submit(prepared).pipe(
|
|
2900
|
+
Effect.provideService(
|
|
2901
|
+
CurrentStartDelivery,
|
|
2902
|
+
authorization !== undefined &&
|
|
2903
|
+
prepared.workerAdmission !== undefined &&
|
|
2904
|
+
prepared.admissionKey === messageId &&
|
|
2905
|
+
prepared.inputDigest === inputDigest &&
|
|
2906
|
+
sameOrigin(prepared.workerAdmission.origin, origin)
|
|
2907
|
+
? { authorization, admission: prepared.workerAdmission, inputDigest }
|
|
2908
|
+
: undefined,
|
|
2909
|
+
),
|
|
2910
|
+
Effect.mapError((error) =>
|
|
2911
|
+
error._tag === 'AdmissionConflict' || error._tag === 'AgentInputError'
|
|
2912
|
+
? PreparedInputRefused.make({ code: error._tag, cause: error })
|
|
2913
|
+
: error._tag === 'AdmissionPolicyError' && error.reason === 'refused'
|
|
2914
|
+
? PreparedInputRefused.make({ code: error.code, cause: error })
|
|
2915
|
+
: PreparedInputRetryable.make({ reason: 'storage', cause: error })
|
|
2916
|
+
),
|
|
2917
|
+
),
|
|
2918
|
+
submissionStatus: (receipt) =>
|
|
2919
|
+
deps
|
|
2920
|
+
.status(receipt)
|
|
2921
|
+
.pipe(
|
|
2922
|
+
Effect.mapError((error) => PreparedInputRetryable.make({ reason: 'storage', cause: error })),
|
|
2923
|
+
),
|
|
2924
|
+
}),
|
|
2925
|
+
Effect.provideService(CryptoDigest.Digest, deps.crypto),
|
|
2926
|
+
Effect.mapError(storageFailure(operation)),
|
|
2927
|
+
)
|
|
2928
|
+
|
|
2929
|
+
return yield* deliveryStatus(processed, operation)
|
|
2930
|
+
})
|
|
2931
|
+
|
|
2932
|
+
const messageIdFor = (parts: ReadonlyArray<string>) =>
|
|
2933
|
+
withCrypto(digestJson(parts)).pipe(
|
|
2934
|
+
Effect.map((digest) => Schema.decodeSync(IdempotencyKey)(`worker:${digest}`)),
|
|
2935
|
+
Effect.mapError(storageFailure('start')),
|
|
2936
|
+
)
|
|
2937
|
+
|
|
2938
|
+
const summarize = Effect.fnUntraced(function*(
|
|
2939
|
+
origin: WorkerOrigin,
|
|
2940
|
+
operation: 'list' | 'inspect',
|
|
2941
|
+
): Effect.fn.Return<WorkerSummary, WorkerError> {
|
|
2942
|
+
yield* authorize(operation, 'read', origin.worker)
|
|
2943
|
+
if (deps.ledger.inspectWorker === undefined || Option.isNone(deps.deliveries)) {
|
|
2944
|
+
return yield* failure(operation, 'unavailable')
|
|
2945
|
+
}
|
|
2946
|
+
const threadId = origin.worker.threadId
|
|
2947
|
+
const deliveries = deps.deliveries.value
|
|
2948
|
+
|
|
2949
|
+
const pending = () =>
|
|
2950
|
+
deliveries
|
|
2951
|
+
.list({ ownerThreadId: context.source.threadId, pendingWorker: threadId, limit: 1 })
|
|
2952
|
+
.pipe(
|
|
2953
|
+
Effect.mapError(storageFailure(operation)),
|
|
2954
|
+
Effect.map((page) => page.items[0]),
|
|
2955
|
+
)
|
|
2956
|
+
|
|
2957
|
+
const tail = () =>
|
|
2958
|
+
deps.store.inspectTail(ThreadTailRequest.make({ threadId })).pipe(
|
|
2959
|
+
Effect.catchTag('ThreadNotMaterialized', () => Effect.as(Effect.void, undefined)),
|
|
2960
|
+
Effect.mapError(storageFailure(operation)),
|
|
2961
|
+
)
|
|
2962
|
+
|
|
2963
|
+
const receipt = (row: SubmissionSnapshot): Receipt => ({
|
|
2964
|
+
threadId: row.threadId,
|
|
2965
|
+
submissionId: row.submissionId,
|
|
2966
|
+
receiptId: row.receiptId,
|
|
2967
|
+
queueSequence: row.queueSequence,
|
|
2968
|
+
})
|
|
2969
|
+
|
|
2970
|
+
const input = (row: SubmissionSnapshot) => {
|
|
2971
|
+
if (row.workerAdmission === undefined || !sameOrigin(row.workerAdmission.origin, origin)) {
|
|
2972
|
+
return failure(operation, 'corrupt')
|
|
2973
|
+
}
|
|
2974
|
+
|
|
2975
|
+
return Effect.succeed({ receipt: receipt(row), messageId: row.workerAdmission.messageId })
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
const submission = (submissionId: SubmissionId) =>
|
|
2979
|
+
deps.ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(
|
|
2980
|
+
Effect.mapError(storageFailure(operation)),
|
|
2981
|
+
Effect.flatMap((row) => Option.isNone(row) ? failure(operation, 'corrupt') : Effect.succeed(row.value)),
|
|
2982
|
+
)
|
|
2983
|
+
|
|
2984
|
+
// Native pages and exact lookups only. Retry changing watermarks instead of combining
|
|
2985
|
+
// acceptance, application and completion facts that never coexisted.
|
|
2986
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
2987
|
+
const delivery = yield* pending()
|
|
2988
|
+
|
|
2989
|
+
const control = yield* deps.ledger
|
|
2990
|
+
.inspectWorker(threadId)
|
|
2991
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
2992
|
+
|
|
2993
|
+
const current = yield* tail()
|
|
2994
|
+
|
|
2995
|
+
const records = current === undefined
|
|
2996
|
+
? []
|
|
2997
|
+
: yield* deps.store
|
|
2998
|
+
.read({
|
|
2999
|
+
threadId,
|
|
3000
|
+
selection: {
|
|
3001
|
+
_tag: 'WorkerExecution',
|
|
3002
|
+
expectedTailSequence: current.tailSequence,
|
|
3003
|
+
},
|
|
3004
|
+
page: { limit: 2 },
|
|
3005
|
+
})
|
|
3006
|
+
.pipe(
|
|
3007
|
+
Stream.runCollect,
|
|
3008
|
+
Effect.mapError(storageFailure(operation)),
|
|
3009
|
+
Effect.catch((error) =>
|
|
3010
|
+
Effect.gen(function*() {
|
|
3011
|
+
// An unavailable recheck cannot justify discarding the original error.
|
|
3012
|
+
const after = yield* tail().pipe(Effect.orElseSucceed(() => current))
|
|
3013
|
+
|
|
3014
|
+
if (after !== undefined && current.tailSequence !== after.tailSequence) {
|
|
3015
|
+
return undefined
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
return yield* error
|
|
3019
|
+
})
|
|
3020
|
+
),
|
|
3021
|
+
)
|
|
3022
|
+
|
|
3023
|
+
if (records === undefined) continue
|
|
3024
|
+
|
|
3025
|
+
const applied = records.find((entry) => entry.record.payload._tag === 'UserInputRecorded')
|
|
3026
|
+
|
|
3027
|
+
const appliedRunId = applied?.record.payload._tag === 'UserInputRecorded'
|
|
3028
|
+
? applied.record.payload.runId
|
|
3029
|
+
: undefined
|
|
3030
|
+
|
|
3031
|
+
const execution = appliedRunId === undefined
|
|
3032
|
+
? undefined
|
|
3033
|
+
: Option.getOrUndefined(
|
|
3034
|
+
yield* deps.store
|
|
3035
|
+
.readExecution({ threadId, runId: appliedRunId })
|
|
3036
|
+
.pipe(Effect.mapError(storageFailure(operation))),
|
|
3037
|
+
)
|
|
3038
|
+
|
|
3039
|
+
const started = execution?.operational.find(
|
|
3040
|
+
(record) => record.payload._tag === 'RunStarted',
|
|
3041
|
+
)?.payload
|
|
3042
|
+
|
|
3043
|
+
const settled = records.find((entry) => entry.record.payload._tag === 'SubmissionSettled')
|
|
3044
|
+
?.record.payload
|
|
3045
|
+
|
|
3046
|
+
const latestRunId = started?._tag === 'RunStarted'
|
|
3047
|
+
? started.runId
|
|
3048
|
+
: settled?._tag === 'SubmissionSettled'
|
|
3049
|
+
? settled.runId
|
|
3050
|
+
: undefined
|
|
3051
|
+
|
|
3052
|
+
const acceptedInput = control.latest === null ? null : yield* input(control.latest)
|
|
3053
|
+
let appliedInput: WorkerSummary['appliedInput'] = null
|
|
3054
|
+
let run: WorkerSummary['run'] = null
|
|
3055
|
+
|
|
3056
|
+
if (applied?.record.payload._tag === 'UserInputRecorded') {
|
|
3057
|
+
const value = applied.record.payload
|
|
3058
|
+
|
|
3059
|
+
if (value.submissionId === undefined || value.runId === undefined) {
|
|
3060
|
+
return yield* failure(operation, 'corrupt')
|
|
3061
|
+
}
|
|
3062
|
+
appliedInput = {
|
|
3063
|
+
...(yield* input(yield* submission(value.submissionId))),
|
|
3064
|
+
runId: value.runId,
|
|
3065
|
+
sequence: applied.sequence,
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
if (latestRunId !== undefined) {
|
|
3069
|
+
const initial = Option.getOrUndefined(
|
|
3070
|
+
yield* getRunInput({ threadId, runId: latestRunId }).pipe(
|
|
3071
|
+
Effect.provideService(ThreadReader, ThreadReader.fromStore(deps.store)),
|
|
3072
|
+
Effect.mapError(storageFailure(operation)),
|
|
3073
|
+
),
|
|
3074
|
+
)?.record.payload
|
|
3075
|
+
|
|
3076
|
+
if (initial?._tag !== 'UserInputRecorded' || initial.submissionId === undefined) {
|
|
3077
|
+
return yield* failure(operation, 'corrupt')
|
|
3078
|
+
}
|
|
3079
|
+
const host = yield* input(yield* submission(initial.submissionId))
|
|
3080
|
+
|
|
3081
|
+
const terminal = Option.getOrUndefined(
|
|
3082
|
+
yield* exactRecord(
|
|
3083
|
+
threadId,
|
|
3084
|
+
submissionSettlementRecordId(initial.submissionId),
|
|
3085
|
+
operation,
|
|
3086
|
+
),
|
|
3087
|
+
)?.record.payload
|
|
3088
|
+
|
|
3089
|
+
if (
|
|
3090
|
+
terminal !== undefined &&
|
|
3091
|
+
(terminal._tag !== 'SubmissionSettled' || terminal.runId !== latestRunId)
|
|
3092
|
+
) {
|
|
3093
|
+
return yield* failure(operation, 'corrupt')
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
run = {
|
|
3097
|
+
runId: latestRunId,
|
|
3098
|
+
hostReceipt: host.receipt,
|
|
3099
|
+
outcome: terminal?.outcome ?? null,
|
|
3100
|
+
disposition: terminal?.runDisposition ?? null,
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
const after = yield* deps.ledger
|
|
3105
|
+
.inspectWorker(threadId)
|
|
3106
|
+
.pipe(Effect.mapError(storageFailure(operation)))
|
|
3107
|
+
|
|
3108
|
+
const afterTail = yield* tail()
|
|
3109
|
+
const afterDelivery = yield* pending()
|
|
3110
|
+
|
|
3111
|
+
const afterExecution = appliedRunId === undefined
|
|
3112
|
+
? undefined
|
|
3113
|
+
: Option.getOrUndefined(
|
|
3114
|
+
yield* deps.store
|
|
3115
|
+
.readExecution({ threadId, runId: appliedRunId })
|
|
3116
|
+
.pipe(Effect.mapError(storageFailure(operation))),
|
|
3117
|
+
)
|
|
3118
|
+
|
|
3119
|
+
if (
|
|
3120
|
+
!Schema.toEquivalence(WorkerLedgerState)(control, after) ||
|
|
3121
|
+
current?.tailSequence !== afterTail?.tailSequence ||
|
|
3122
|
+
execution?.progress.revision !== afterExecution?.progress.revision ||
|
|
3123
|
+
delivery?.key.messageId !== afterDelivery?.key.messageId ||
|
|
3124
|
+
delivery?.version !== afterDelivery?.version
|
|
3125
|
+
) {
|
|
3126
|
+
continue
|
|
3127
|
+
}
|
|
3128
|
+
|
|
3129
|
+
return {
|
|
3130
|
+
worker: origin.worker,
|
|
3131
|
+
latestReceipt: acceptedInput?.receipt ?? null,
|
|
3132
|
+
state: control.terminal ??
|
|
3133
|
+
(control.stopped
|
|
3134
|
+
? control.active === null
|
|
3135
|
+
? 'stopped'
|
|
3136
|
+
: 'stopping'
|
|
3137
|
+
: control.active !== null
|
|
3138
|
+
? control.active.state === 'unknown'
|
|
3139
|
+
? 'unknown'
|
|
3140
|
+
: 'active'
|
|
3141
|
+
: delivery !== undefined
|
|
3142
|
+
? 'starting'
|
|
3143
|
+
: 'idle'),
|
|
3144
|
+
acceptedInput,
|
|
3145
|
+
appliedInput,
|
|
3146
|
+
run,
|
|
3147
|
+
pendingDelivery: delivery === undefined ? null : yield* deliveryStatus(delivery, operation),
|
|
3148
|
+
watermark: {
|
|
3149
|
+
canonicalSequence: current?.tailSequence ?? 0,
|
|
3150
|
+
acceptedQueueSequence: control.latest?.queueSequence ?? 0,
|
|
3151
|
+
pendingDeliveryVersion: delivery?.version ?? null,
|
|
3152
|
+
},
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
|
|
3156
|
+
return yield* failure(operation, 'storage')
|
|
3157
|
+
})
|
|
3158
|
+
|
|
3159
|
+
return {
|
|
3160
|
+
context: Effect.gen(function*() {
|
|
3161
|
+
yield* authorize('context', 'context')
|
|
3162
|
+
if (context.depth !== 0) return context
|
|
3163
|
+
const source = yield* sourceAuthority(context.source.threadId, sourceSubmissionId)
|
|
3164
|
+
|
|
3165
|
+
return {
|
|
3166
|
+
...context,
|
|
3167
|
+
policy: Option.getOrElse(source.policyOverride, () => context.policy),
|
|
3168
|
+
}
|
|
3169
|
+
}),
|
|
3170
|
+
start: Effect.fnUntraced(function*<E = never, R = never>(
|
|
3171
|
+
command: StartWorkerRequest | DeferredStartWorkerRequest<E, R>,
|
|
3172
|
+
): Effect.fn.Return<WorkerStarted, WorkerError | E, R> {
|
|
3173
|
+
const effectiveScope: WorkerBudgetScope = command.budgetScope ??
|
|
3174
|
+
(context.source._tag === 'programmatic' && sourceSubmissionId === undefined
|
|
3175
|
+
? 'worker-run'
|
|
3176
|
+
: 'source-subtree')
|
|
3177
|
+
|
|
3178
|
+
if (effectiveScope === 'source-subtree' && sourceSubmissionId === undefined) {
|
|
3179
|
+
return yield* failure('start', 'denied')
|
|
3180
|
+
}
|
|
3181
|
+
|
|
3182
|
+
const previous = command.continuationOf === undefined
|
|
3183
|
+
? undefined
|
|
3184
|
+
: yield* completedContinuation(
|
|
3185
|
+
context.source,
|
|
3186
|
+
command.continuationOf,
|
|
3187
|
+
command.target.id,
|
|
3188
|
+
command.delegationId,
|
|
3189
|
+
)
|
|
3190
|
+
|
|
3191
|
+
// Bind the decision to the tail before authorization. If it changes while the
|
|
3192
|
+
// authorizer reads current state, currentStart rejects reuse of this decision.
|
|
3193
|
+
const tail = yield* deps.store
|
|
3194
|
+
.inspectTail(ThreadTailRequest.make({ threadId: context.source.threadId }))
|
|
3195
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
3196
|
+
|
|
3197
|
+
const principal = yield* authorize('start', 'send', undefined, previous?.evidence)
|
|
3198
|
+
|
|
3199
|
+
const startAdmission: WorkerStartAdmission = {
|
|
3200
|
+
sourceThreadId: context.source.threadId,
|
|
3201
|
+
...(sourceSubmissionId === undefined ? {} : { sourceSubmissionId }),
|
|
3202
|
+
requestedPrincipal,
|
|
3203
|
+
principal,
|
|
3204
|
+
targetAgentId: command.target.id,
|
|
3205
|
+
...(previous === undefined ? {} : { continuationOf: previous.evidence }),
|
|
3206
|
+
access: 'send',
|
|
3207
|
+
tailSequence: tail.tailSequence,
|
|
3208
|
+
}
|
|
3209
|
+
|
|
3210
|
+
if (context.depth !== 0 && sourceSubmissionId === undefined) {
|
|
3211
|
+
return yield* failure('start', 'denied')
|
|
3212
|
+
}
|
|
3213
|
+
|
|
3214
|
+
const grant = yield* Schema.decodeUnknownEffect(SubagentGrant)(command.encodedGrant).pipe(
|
|
3215
|
+
Effect.mapError((cause) => failure('start', 'corrupt', cause)),
|
|
3216
|
+
)
|
|
3217
|
+
|
|
3218
|
+
const parameters = yield* decode(PersistedJson, command.encodedParameters, 'start')
|
|
3219
|
+
|
|
3220
|
+
const messageId = yield* messageIdFor([
|
|
3221
|
+
context.source.threadId,
|
|
3222
|
+
command.delegationId,
|
|
3223
|
+
command.idempotencyKey,
|
|
3224
|
+
])
|
|
3225
|
+
|
|
3226
|
+
if (Option.isNone(deps.deliveries)) return yield* failure('start', 'unavailable')
|
|
3227
|
+
const deliveries = deps.deliveries.value
|
|
3228
|
+
|
|
3229
|
+
const retained = () =>
|
|
3230
|
+
deliveries
|
|
3231
|
+
.get({ ownerThreadId: context.source.threadId, messageId })
|
|
3232
|
+
.pipe(Effect.mapError(storageFailure('start')))
|
|
3233
|
+
|
|
3234
|
+
const replay = Effect.fnUntraced(function*(saved: MessageDeliveryRecord) {
|
|
3235
|
+
const currentPrevious = command.continuationOf === undefined
|
|
3236
|
+
? undefined
|
|
3237
|
+
: yield* completedContinuation(
|
|
3238
|
+
context.source,
|
|
3239
|
+
command.continuationOf,
|
|
3240
|
+
command.target.id,
|
|
3241
|
+
command.delegationId,
|
|
3242
|
+
previous?.evidence,
|
|
3243
|
+
)
|
|
3244
|
+
|
|
3245
|
+
const replayPrincipal = yield* authorize(
|
|
3246
|
+
'start',
|
|
3247
|
+
'send',
|
|
3248
|
+
undefined,
|
|
3249
|
+
currentPrevious?.evidence,
|
|
3250
|
+
)
|
|
3251
|
+
|
|
3252
|
+
yield* binding(command.target, 'start')
|
|
3253
|
+
const metadata = saved.envelope.workerAdmission
|
|
3254
|
+
|
|
3255
|
+
if (metadata === undefined) return yield* failure('start', 'idempotency-conflict')
|
|
3256
|
+
const origin = metadata.origin
|
|
3257
|
+
|
|
3258
|
+
if (
|
|
3259
|
+
!Schema.toEquivalence(Schema.UndefinedOr(WorkerContinuation))(
|
|
3260
|
+
origin.continuationOf,
|
|
3261
|
+
currentPrevious?.evidence,
|
|
3262
|
+
) ||
|
|
3263
|
+
origin.firstMessageId !== messageId ||
|
|
3264
|
+
metadata.messageId !== messageId ||
|
|
3265
|
+
origin.source.threadId !== context.source.threadId ||
|
|
3266
|
+
origin.worker.delegationId !== command.delegationId ||
|
|
3267
|
+
origin.worker.targetAgentId !== command.target.id ||
|
|
3268
|
+
!sameJson(metadata.parameters, parameters) ||
|
|
3269
|
+
!Schema.toEquivalence(SubagentGrant)(origin.grant, grant) ||
|
|
3270
|
+
origin.budgetScope !== effectiveScope ||
|
|
3271
|
+
origin.depth !== context.depth + 1 ||
|
|
3272
|
+
(!('prepare' in command) &&
|
|
3273
|
+
(!samePolicy(origin.policy, command.policy) ||
|
|
3274
|
+
!Schema.toEquivalence(WorkerOrigin.fields.budget)(origin.budget, command.budget) ||
|
|
3275
|
+
origin.toolCallAllowance !== command.toolCallAllowance))
|
|
3276
|
+
) {
|
|
3277
|
+
return yield* failure('start', 'idempotency-conflict')
|
|
3278
|
+
}
|
|
3279
|
+
|
|
3280
|
+
yield* verifyContinuation(origin)
|
|
3281
|
+
|
|
3282
|
+
return {
|
|
3283
|
+
worker: origin.worker,
|
|
3284
|
+
delivery: yield* send(
|
|
3285
|
+
origin,
|
|
3286
|
+
messageId,
|
|
3287
|
+
'prepare' in command ? saved.envelope.input : command.encodedInput,
|
|
3288
|
+
parameters,
|
|
3289
|
+
replayPrincipal,
|
|
3290
|
+
'start',
|
|
3291
|
+
),
|
|
3292
|
+
}
|
|
3293
|
+
})
|
|
3294
|
+
|
|
3295
|
+
const existing = yield* retained()
|
|
3296
|
+
|
|
3297
|
+
if (existing !== null) return yield* replay(existing)
|
|
3298
|
+
|
|
3299
|
+
return yield* Effect.gen(function*() {
|
|
3300
|
+
const encodedInput = 'prepare' in command ? (yield* command.prepare).encodedInput : command.encodedInput
|
|
3301
|
+
|
|
3302
|
+
const currentPrevious = command.continuationOf === undefined
|
|
3303
|
+
? undefined
|
|
3304
|
+
: yield* completedContinuation(
|
|
3305
|
+
context.source,
|
|
3306
|
+
command.continuationOf,
|
|
3307
|
+
command.target.id,
|
|
3308
|
+
command.delegationId,
|
|
3309
|
+
previous?.evidence,
|
|
3310
|
+
)
|
|
3311
|
+
|
|
3312
|
+
if ('prepare' in command || currentPrevious !== undefined) {
|
|
3313
|
+
const preparedPrincipal = yield* authorize(
|
|
3314
|
+
'start',
|
|
3315
|
+
'send',
|
|
3316
|
+
undefined,
|
|
3317
|
+
currentPrevious?.evidence,
|
|
3318
|
+
yield* currentStart(
|
|
3319
|
+
startAdmission,
|
|
3320
|
+
context.source.threadId,
|
|
3321
|
+
sourceSubmissionId,
|
|
3322
|
+
principal,
|
|
3323
|
+
command.target.id,
|
|
3324
|
+
currentPrevious?.evidence,
|
|
3325
|
+
),
|
|
3326
|
+
)
|
|
3327
|
+
|
|
3328
|
+
if (preparedPrincipal !== principal) return yield* failure('start', 'denied')
|
|
3329
|
+
}
|
|
3330
|
+
|
|
3331
|
+
const prepared = yield* preparedTarget(
|
|
3332
|
+
command.target,
|
|
3333
|
+
encodedInput,
|
|
3334
|
+
currentPrevious?.evidence,
|
|
3335
|
+
startAdmission,
|
|
3336
|
+
)
|
|
3337
|
+
|
|
3338
|
+
const resolved = prepared.resolved
|
|
3339
|
+
|
|
3340
|
+
const sourcePolicy = Option.getOrElse(
|
|
3341
|
+
prepared.source.policyOverride,
|
|
3342
|
+
() => context.policy,
|
|
3343
|
+
)
|
|
3344
|
+
|
|
3345
|
+
const targetPolicy = Option.getOrElse(prepared.policy, () =>
|
|
3346
|
+
effectiveScope === 'worker-run'
|
|
3347
|
+
? resolved.definition.policy
|
|
3348
|
+
: AgentPolicy.resolve(
|
|
3349
|
+
resolved.definition.policyOverrides ?? resolved.definition.policy,
|
|
3350
|
+
sourcePolicy,
|
|
3351
|
+
))
|
|
3352
|
+
|
|
3353
|
+
const prepareWorkerRequest = Effect.fnUntraced(function*(
|
|
3354
|
+
deferred: Extract<typeof command, { prepare: unknown }>,
|
|
3355
|
+
) {
|
|
3356
|
+
const declarationPolicy = deferred.declarationPolicy === undefined
|
|
3357
|
+
? undefined
|
|
3358
|
+
: yield* decode(SubagentPolicy, deferred.declarationPolicy, 'start')
|
|
3359
|
+
|
|
3360
|
+
const limits = resolveSubagentPolicy(
|
|
3361
|
+
{ target: resolved.definition, policy: declarationPolicy },
|
|
3362
|
+
effectiveScope === 'worker-run' ? targetPolicy : sourcePolicy,
|
|
3363
|
+
undefined,
|
|
3364
|
+
effectiveScope === 'worker-run' ? 'root-attached' : 'conserved',
|
|
3365
|
+
targetPolicy,
|
|
3366
|
+
)
|
|
3367
|
+
|
|
3368
|
+
if (limits === undefined) return yield* failure('start', 'denied')
|
|
3369
|
+
|
|
3370
|
+
return {
|
|
3371
|
+
...deferred,
|
|
3372
|
+
encodedInput,
|
|
3373
|
+
policy: limits.childPolicy,
|
|
3374
|
+
budget: SubagentBudgetReservation.make({
|
|
3375
|
+
caps: limits.caps,
|
|
3376
|
+
allocation: limits.allocation,
|
|
3377
|
+
...(limits.policy.descendantInvocations === undefined
|
|
3378
|
+
? {}
|
|
3379
|
+
: { descendantInvocations: limits.policy.descendantInvocations }),
|
|
3380
|
+
}),
|
|
3381
|
+
toolCallAllowance: limits.childPolicy.maxToolCalls,
|
|
3382
|
+
}
|
|
3383
|
+
})
|
|
3384
|
+
|
|
3385
|
+
const request: StartWorkerRequest = 'prepare' in command ? yield* prepareWorkerRequest(command) : command
|
|
3386
|
+
|
|
3387
|
+
const now = yield* Clock.currentTimeMillis
|
|
3388
|
+
const sourceBinding = prepared.source.binding
|
|
3389
|
+
|
|
3390
|
+
if (sourceBinding === undefined) {
|
|
3391
|
+
return yield* failure('start', 'declaration-unavailable')
|
|
3392
|
+
}
|
|
3393
|
+
|
|
3394
|
+
const reporting = yield* reportIntent(
|
|
3395
|
+
sourceBinding,
|
|
3396
|
+
resolved,
|
|
3397
|
+
request.delegationId,
|
|
3398
|
+
prepared.source,
|
|
3399
|
+
)
|
|
3400
|
+
|
|
3401
|
+
if (reporting?.mode === 'standard' && sourceSubmissionId === undefined) {
|
|
3402
|
+
return yield* failure('start', 'denied')
|
|
3403
|
+
}
|
|
3404
|
+
|
|
3405
|
+
const origin = yield* decode(
|
|
3406
|
+
WorkerOrigin,
|
|
3407
|
+
{
|
|
3408
|
+
worker: {
|
|
3409
|
+
schemaVersion: 1,
|
|
3410
|
+
delegationId: request.delegationId,
|
|
3411
|
+
targetAgentId: request.target.id,
|
|
3412
|
+
threadId: yield* Schema.decodeEffect(ThreadId)(messageId).pipe(Effect.orDie),
|
|
3413
|
+
},
|
|
3414
|
+
source: context.source,
|
|
3415
|
+
...(currentPrevious === undefined
|
|
3416
|
+
? {}
|
|
3417
|
+
: { continuationOf: currentPrevious.evidence }),
|
|
3418
|
+
...(resolved.definition.runDisposition?.workerLifecycle === 'assignment'
|
|
3419
|
+
? { lifecycle: 'assignment' }
|
|
3420
|
+
: {}),
|
|
3421
|
+
targetDigests: resolved.digests,
|
|
3422
|
+
policy: request.policy,
|
|
3423
|
+
budget: request.budget,
|
|
3424
|
+
budgetScope: effectiveScope,
|
|
3425
|
+
grant,
|
|
3426
|
+
depth: context.depth + 1,
|
|
3427
|
+
firstMessageId: messageId,
|
|
3428
|
+
createdAtMillis: now,
|
|
3429
|
+
expiresAtMillis: Math.min(
|
|
3430
|
+
now + deps.limits.lifetimeMillis,
|
|
3431
|
+
currentPrevious?.origin.expiresAtMillis ?? Infinity,
|
|
3432
|
+
),
|
|
3433
|
+
...(reporting === undefined ? {} : { reporting }),
|
|
3434
|
+
...(request.toolCallAllowance === undefined
|
|
3435
|
+
? {}
|
|
3436
|
+
: { toolCallAllowance: request.toolCallAllowance }),
|
|
3437
|
+
},
|
|
3438
|
+
'start',
|
|
3439
|
+
)
|
|
3440
|
+
|
|
3441
|
+
yield* authorizeBudget(
|
|
3442
|
+
origin,
|
|
3443
|
+
principal,
|
|
3444
|
+
yield* currentStart(
|
|
3445
|
+
startAdmission,
|
|
3446
|
+
context.source.threadId,
|
|
3447
|
+
sourceSubmissionId,
|
|
3448
|
+
principal,
|
|
3449
|
+
request.target.id,
|
|
3450
|
+
currentPrevious?.evidence,
|
|
3451
|
+
),
|
|
3452
|
+
)
|
|
3453
|
+
|
|
3454
|
+
if (
|
|
3455
|
+
!withinPolicy(
|
|
3456
|
+
origin,
|
|
3457
|
+
origin.budgetScope === 'worker-run' ? targetPolicy : sourcePolicy,
|
|
3458
|
+
targetPolicy,
|
|
3459
|
+
)
|
|
3460
|
+
) {
|
|
3461
|
+
return yield* failure('start', 'capacity')
|
|
3462
|
+
}
|
|
3463
|
+
|
|
3464
|
+
const delivery = yield* send(
|
|
3465
|
+
origin,
|
|
3466
|
+
messageId,
|
|
3467
|
+
request.encodedInput,
|
|
3468
|
+
request.encodedParameters,
|
|
3469
|
+
principal,
|
|
3470
|
+
'start',
|
|
3471
|
+
startAdmission,
|
|
3472
|
+
)
|
|
3473
|
+
|
|
3474
|
+
return { worker: origin.worker, delivery }
|
|
3475
|
+
}).pipe(
|
|
3476
|
+
Effect.catch((error) =>
|
|
3477
|
+
Effect.gen(function*() {
|
|
3478
|
+
if (!('prepare' in command)) return yield* Effect.fail(error)
|
|
3479
|
+
// A concurrent first writer may have retained the command during preparation or insert.
|
|
3480
|
+
// Only its exact declared arguments permit replay; absent proof preserves the failure.
|
|
3481
|
+
const saved = yield* retained()
|
|
3482
|
+
|
|
3483
|
+
return saved === null ? yield* Effect.fail(error) : yield* replay(saved)
|
|
3484
|
+
})
|
|
3485
|
+
),
|
|
3486
|
+
)
|
|
3487
|
+
}),
|
|
3488
|
+
followUp: Effect.fnUntraced(function*<E = never, R = never>(
|
|
3489
|
+
command: FollowUpWorkerRequest | DeferredFollowUpWorkerRequest<E, R>,
|
|
3490
|
+
): Effect.fn.Return<MessageStatus, WorkerError | E, R> {
|
|
3491
|
+
const principal = yield* authorize('followUp', 'send', command.worker)
|
|
3492
|
+
const origin = yield* findOrigin(command.worker, command.target, 'followUp')
|
|
3493
|
+
|
|
3494
|
+
const currentPolicy = resolveTargetPolicy({
|
|
3495
|
+
_tag: 'RetainedWorker',
|
|
3496
|
+
definition: command.target,
|
|
3497
|
+
definitions: origin.targetDigests,
|
|
3498
|
+
source: origin.source,
|
|
3499
|
+
origin,
|
|
3500
|
+
})
|
|
3501
|
+
|
|
3502
|
+
yield* currentPolicy
|
|
3503
|
+
|
|
3504
|
+
const messageId = yield* messageIdFor([
|
|
3505
|
+
context.source.threadId,
|
|
3506
|
+
command.worker.threadId,
|
|
3507
|
+
'followUp',
|
|
3508
|
+
command.idempotencyKey,
|
|
3509
|
+
])
|
|
3510
|
+
|
|
3511
|
+
if (Option.isNone(deps.deliveries)) return yield* failure('followUp', 'unavailable')
|
|
3512
|
+
const deliveries = deps.deliveries.value
|
|
3513
|
+
|
|
3514
|
+
const retained = () =>
|
|
3515
|
+
deliveries
|
|
3516
|
+
.get({ ownerThreadId: context.source.threadId, messageId })
|
|
3517
|
+
.pipe(Effect.mapError(storageFailure('followUp')))
|
|
3518
|
+
|
|
3519
|
+
const replay = Effect.fnUntraced(function*(saved: MessageDeliveryRecord) {
|
|
3520
|
+
const replayPrincipal = yield* authorize('followUp', 'send', command.worker)
|
|
3521
|
+
|
|
3522
|
+
yield* currentPolicy
|
|
3523
|
+
|
|
3524
|
+
return yield* send(
|
|
3525
|
+
origin,
|
|
3526
|
+
messageId,
|
|
3527
|
+
saved.envelope.input,
|
|
3528
|
+
command.encodedParameters,
|
|
3529
|
+
replayPrincipal,
|
|
3530
|
+
'followUp',
|
|
3531
|
+
)
|
|
3532
|
+
})
|
|
3533
|
+
|
|
3534
|
+
const existing = 'prepare' in command ? yield* retained() : null
|
|
3535
|
+
|
|
3536
|
+
if (existing !== null) return yield* replay(existing)
|
|
3537
|
+
|
|
3538
|
+
return yield* Effect.gen(function*() {
|
|
3539
|
+
const request = 'prepare' in command ? { ...(yield* command.prepare), ...command } : command
|
|
3540
|
+
|
|
3541
|
+
yield* Schema.decodeUnknownEffect(Schema.toEncoded(request.target.input))(
|
|
3542
|
+
request.encodedInput,
|
|
3543
|
+
).pipe(Effect.mapError((cause) => failure('followUp', 'corrupt', cause)))
|
|
3544
|
+
|
|
3545
|
+
let sendPrincipal = principal
|
|
3546
|
+
|
|
3547
|
+
if ('prepare' in command) {
|
|
3548
|
+
// Preparation can yield while authority changes, even when another writer saves equal input.
|
|
3549
|
+
sendPrincipal = yield* authorize('followUp', 'send', command.worker)
|
|
3550
|
+
yield* currentPolicy
|
|
3551
|
+
}
|
|
3552
|
+
|
|
3553
|
+
return yield* send(
|
|
3554
|
+
origin,
|
|
3555
|
+
messageId,
|
|
3556
|
+
request.encodedInput,
|
|
3557
|
+
request.encodedParameters,
|
|
3558
|
+
sendPrincipal,
|
|
3559
|
+
'followUp',
|
|
3560
|
+
)
|
|
3561
|
+
}).pipe(
|
|
3562
|
+
Effect.catch((error) =>
|
|
3563
|
+
Effect.gen(function*() {
|
|
3564
|
+
if (!('prepare' in command)) return yield* Effect.fail(error)
|
|
3565
|
+
// A concurrent first writer can retain the original correction during preparation.
|
|
3566
|
+
// Replay rechecks current authority before reusing its immutable envelope.
|
|
3567
|
+
const saved = yield* retained()
|
|
3568
|
+
|
|
3569
|
+
return saved === null ? yield* Effect.fail(error) : yield* replay(saved)
|
|
3570
|
+
})
|
|
3571
|
+
),
|
|
3572
|
+
)
|
|
3573
|
+
}),
|
|
3574
|
+
inspect: Effect.fnUntraced(function*(request) {
|
|
3575
|
+
yield* authorize('inspect', 'read', request.worker)
|
|
3576
|
+
|
|
3577
|
+
if ('message' in request) {
|
|
3578
|
+
const message = yield* Schema.decodeEffect(MessageRef)(request.message).pipe(
|
|
3579
|
+
Effect.mapError((cause) => failure('inspect', 'message-mismatch', cause)),
|
|
3580
|
+
)
|
|
3581
|
+
|
|
3582
|
+
if (message.ownerThreadId !== context.source.threadId) {
|
|
3583
|
+
return yield* failure('inspect', 'denied')
|
|
3584
|
+
}
|
|
3585
|
+
yield* binding(request.target, 'inspect')
|
|
3586
|
+
if (request.worker.targetAgentId !== request.target.id) {
|
|
3587
|
+
return yield* failure('inspect', 'worker-mismatch')
|
|
3588
|
+
}
|
|
3589
|
+
if (Option.isNone(deps.deliveries)) return yield* failure('inspect', 'unavailable')
|
|
3590
|
+
|
|
3591
|
+
const row = yield* deps.deliveries.value
|
|
3592
|
+
.get(message)
|
|
3593
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
3594
|
+
|
|
3595
|
+
if (row === null) return yield* failure('inspect', 'not-found')
|
|
3596
|
+
const admission = row.envelope.workerAdmission
|
|
3597
|
+
|
|
3598
|
+
if (
|
|
3599
|
+
admission === undefined ||
|
|
3600
|
+
!Schema.toEquivalence(MessageRef)(row.key, message) ||
|
|
3601
|
+
admission.messageId !== message.messageId ||
|
|
3602
|
+
admission.origin.source.threadId !== context.source.threadId ||
|
|
3603
|
+
!Schema.toEquivalence(WorkerRef)(admission.origin.worker, request.worker) ||
|
|
3604
|
+
row.envelope.threadId !== request.worker.threadId ||
|
|
3605
|
+
row.envelope.agentId !== request.target.id ||
|
|
3606
|
+
row.envelope.admissionKey !== message.messageId
|
|
3607
|
+
) {
|
|
3608
|
+
return yield* failure('inspect', 'message-mismatch')
|
|
3609
|
+
}
|
|
3610
|
+
|
|
3611
|
+
// Retention precedes source reservation and child materialization. Read its own
|
|
3612
|
+
// evidence without requiring either execution journal or attempting delivery again.
|
|
3613
|
+
return yield* deliveryStatus(row, 'inspect')
|
|
3614
|
+
}
|
|
3615
|
+
|
|
3616
|
+
const admission = yield* receiptInput(request, 'inspect')
|
|
3617
|
+
|
|
3618
|
+
const status = yield* deps
|
|
3619
|
+
.status(request.receipt)
|
|
3620
|
+
.pipe(Effect.mapError(storageFailure('inspect')))
|
|
3621
|
+
|
|
3622
|
+
return status._tag === 'pending'
|
|
3623
|
+
? { _tag: 'Pending' as const, receipt: request.receipt }
|
|
3624
|
+
: yield* observation(request, admission, status.settlement)
|
|
3625
|
+
}),
|
|
3626
|
+
summary: Effect.fnUntraced(function*(request) {
|
|
3627
|
+
yield* authorize('inspect', 'read', request.worker)
|
|
3628
|
+
const origin = yield* findOrigin(request.worker, request.target, 'inspect')
|
|
3629
|
+
|
|
3630
|
+
return yield* summarize(origin, 'inspect')
|
|
3631
|
+
}),
|
|
3632
|
+
observe: (request) =>
|
|
3633
|
+
Stream.unwrap(
|
|
3634
|
+
Effect.gen(function*() {
|
|
3635
|
+
yield* authorize('observe', 'read', request.worker)
|
|
3636
|
+
yield* findOrigin(request.worker, request.target, 'observe')
|
|
3637
|
+
const after = request.after ?? 0
|
|
3638
|
+
|
|
3639
|
+
if (!Number.isSafeInteger(after) || after < 0) {
|
|
3640
|
+
return yield* failure('observe', 'corrupt')
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
const tail = yield* deps.store
|
|
3644
|
+
.inspectTail(ThreadTailRequest.make({ threadId: request.worker.threadId }))
|
|
3645
|
+
.pipe(Effect.mapError(storageFailure('observe')))
|
|
3646
|
+
|
|
3647
|
+
return Stream.paginate(after, (cursor) =>
|
|
3648
|
+
Effect.gen(function*() {
|
|
3649
|
+
if (cursor >= tail.tailSequence) return [[], Option.none<number>()] as const
|
|
3650
|
+
const limit = Math.min(256, tail.tailSequence - cursor)
|
|
3651
|
+
|
|
3652
|
+
const page = yield* deps.store
|
|
3653
|
+
.read(
|
|
3654
|
+
ThreadRead.make({
|
|
3655
|
+
threadId: request.worker.threadId,
|
|
3656
|
+
afterSequence: yield* Schema.decodeEffect(CanonicalSequence)(cursor).pipe(
|
|
3657
|
+
Effect.orDie,
|
|
3658
|
+
),
|
|
3659
|
+
limit,
|
|
3660
|
+
}),
|
|
3661
|
+
)
|
|
3662
|
+
.pipe(Stream.runCollect, Effect.mapError(storageFailure('observe')))
|
|
3663
|
+
|
|
3664
|
+
if (
|
|
3665
|
+
page.length === 0 ||
|
|
3666
|
+
page.length > limit ||
|
|
3667
|
+
page.some(
|
|
3668
|
+
(entry, index) =>
|
|
3669
|
+
entry.threadId !== request.worker.threadId ||
|
|
3670
|
+
entry.sequence !== cursor + index + 1,
|
|
3671
|
+
)
|
|
3672
|
+
) {
|
|
3673
|
+
return yield* failure('observe', 'corrupt')
|
|
3674
|
+
}
|
|
3675
|
+
|
|
3676
|
+
const entries = yield* Effect.forEach(page, (entry) =>
|
|
3677
|
+
Schema.encodeEffect(RecordEnvelope)(entry.record).pipe(
|
|
3678
|
+
Effect.flatMap((record) =>
|
|
3679
|
+
Schema.decodeEffect(WorkerHistoryEntry)({
|
|
3680
|
+
sequence: entry.sequence,
|
|
3681
|
+
recordId: entry.record.recordId,
|
|
3682
|
+
record,
|
|
3683
|
+
})
|
|
3684
|
+
),
|
|
3685
|
+
Effect.mapError((cause) => failure('observe', 'corrupt', cause)),
|
|
3686
|
+
))
|
|
3687
|
+
|
|
3688
|
+
const next = cursor + page.length
|
|
3689
|
+
|
|
3690
|
+
return [
|
|
3691
|
+
entries,
|
|
3692
|
+
next >= tail.tailSequence ? Option.none<number>() : Option.some(next),
|
|
3693
|
+
] as const
|
|
3694
|
+
}))
|
|
3695
|
+
}),
|
|
3696
|
+
),
|
|
3697
|
+
await: Effect.fnUntraced(function*(request) {
|
|
3698
|
+
yield* authorize('await', 'read', request.worker)
|
|
3699
|
+
const admission = yield* receiptInput(request, 'await')
|
|
3700
|
+
|
|
3701
|
+
while (true) {
|
|
3702
|
+
const status = yield* deps
|
|
3703
|
+
.status(request.receipt)
|
|
3704
|
+
.pipe(Effect.mapError(storageFailure('await')))
|
|
3705
|
+
|
|
3706
|
+
if (status._tag === 'settled') {
|
|
3707
|
+
return yield* observation(request, admission, status.settlement)
|
|
3708
|
+
}
|
|
3709
|
+
// Poll the same host-routed read used by inspect. Interruption stops only this wait.
|
|
3710
|
+
yield* Effect.sleep(deps.settlementPollInterval)
|
|
3711
|
+
}
|
|
3712
|
+
}),
|
|
3713
|
+
list: Effect.fnUntraced(function*(request) {
|
|
3714
|
+
yield* authorize('list', 'read')
|
|
3715
|
+
yield* binding(request.target, 'list')
|
|
3716
|
+
if (!Number.isSafeInteger(request.limit) || request.limit < 1 || request.limit > 100) {
|
|
3717
|
+
return yield* failure('list', 'capacity')
|
|
3718
|
+
}
|
|
3719
|
+
if (Option.isNone(deps.deliveries)) return yield* failure('list', 'unavailable')
|
|
3720
|
+
|
|
3721
|
+
const page = yield* deps.deliveries.value
|
|
3722
|
+
.list({
|
|
3723
|
+
ownerThreadId: context.source.threadId,
|
|
3724
|
+
limit: request.limit,
|
|
3725
|
+
workerStarts: { delegationId: request.delegationId, targetAgentId: request.target.id },
|
|
3726
|
+
...(request.after === undefined
|
|
3727
|
+
? {}
|
|
3728
|
+
: {
|
|
3729
|
+
after: yield* Schema.decodeEffect(IdempotencyKey)(request.after).pipe(
|
|
3730
|
+
Effect.orDie,
|
|
3731
|
+
),
|
|
3732
|
+
}),
|
|
3733
|
+
})
|
|
3734
|
+
.pipe(Effect.mapError(storageFailure('list')))
|
|
3735
|
+
|
|
3736
|
+
const items = yield* Effect.forEach(page.items, (row) => {
|
|
3737
|
+
const origin = row.envelope.workerAdmission?.origin
|
|
3738
|
+
|
|
3739
|
+
return origin === undefined || origin.firstMessageId !== row.key.messageId
|
|
3740
|
+
? failure('list', 'corrupt')
|
|
3741
|
+
: summarize(origin, 'list')
|
|
3742
|
+
})
|
|
3743
|
+
|
|
3744
|
+
return {
|
|
3745
|
+
items,
|
|
3746
|
+
next: page.next === null
|
|
3747
|
+
? null
|
|
3748
|
+
: yield* Schema.decodeEffect(ThreadId)(page.next).pipe(Effect.orDie),
|
|
3749
|
+
}
|
|
3750
|
+
}),
|
|
3751
|
+
stop: Effect.fnUntraced(function*(request) {
|
|
3752
|
+
const principal = yield* authorize('stop', 'control', request.worker)
|
|
3753
|
+
|
|
3754
|
+
yield* findOrigin(request.worker, request.target, 'stop')
|
|
3755
|
+
if (deps.ledger.stopWorker === undefined) return yield* failure('stop', 'unavailable')
|
|
3756
|
+
const command = yield* decode(WorkerStop, request, 'stop')
|
|
3757
|
+
|
|
3758
|
+
const id = yield* Schema.decodeEffect(RecordId)(
|
|
3759
|
+
`worker-stop:${yield* messageIdFor([context.source.threadId, request.idempotencyKey])}`,
|
|
3760
|
+
).pipe(Effect.orDie)
|
|
3761
|
+
|
|
3762
|
+
let retained = false
|
|
3763
|
+
|
|
3764
|
+
for (let attempt = 0; attempt < 16; attempt++) {
|
|
3765
|
+
const current = yield* deps.store
|
|
3766
|
+
.inspectTail(ThreadTailRequest.make({ threadId: context.source.threadId }))
|
|
3767
|
+
.pipe(Effect.mapError(storageFailure('stop')))
|
|
3768
|
+
|
|
3769
|
+
const prior = Option.getOrUndefined(
|
|
3770
|
+
yield* exactRecord(context.source.threadId, id, 'stop'),
|
|
3771
|
+
)?.record.payload
|
|
3772
|
+
|
|
3773
|
+
if (prior !== undefined) {
|
|
3774
|
+
if (
|
|
3775
|
+
prior._tag !== 'WorkerStopRequested' ||
|
|
3776
|
+
!Schema.toEquivalence(WorkerStop)(prior.command, command) ||
|
|
3777
|
+
prior.principal !== principal ||
|
|
3778
|
+
prior.sourceSubmissionId !== sourceSubmissionId
|
|
3779
|
+
) {
|
|
3780
|
+
return yield* failure('stop', 'idempotency-conflict')
|
|
3781
|
+
}
|
|
3782
|
+
retained = true
|
|
3783
|
+
break
|
|
3784
|
+
}
|
|
3785
|
+
if (
|
|
3786
|
+
yield* append(
|
|
3787
|
+
context.source.threadId,
|
|
3788
|
+
id,
|
|
3789
|
+
WorkerStopRequested.make({
|
|
3790
|
+
command,
|
|
3791
|
+
principal,
|
|
3792
|
+
...(sourceSubmissionId === undefined ? {} : { sourceSubmissionId }),
|
|
3793
|
+
}),
|
|
3794
|
+
{ ...current, records: [] },
|
|
3795
|
+
'stop',
|
|
3796
|
+
)
|
|
3797
|
+
) {
|
|
3798
|
+
retained = true
|
|
3799
|
+
break
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
if (!retained) return yield* failure('stop', 'storage')
|
|
3803
|
+
// The destination serializes this seal with admission. Replays retain every earlier
|
|
3804
|
+
// abort intent and wait for active handlers/finalizers, rather than acknowledging a hint.
|
|
3805
|
+
while (true) {
|
|
3806
|
+
yield* hit('worker:before-stop-seal', 'stop')
|
|
3807
|
+
|
|
3808
|
+
const owned = yield* deps.ledger
|
|
3809
|
+
.stopWorker({ threadId: request.worker.threadId, author: principal })
|
|
3810
|
+
.pipe(Effect.mapError(storageFailure('stop')))
|
|
3811
|
+
|
|
3812
|
+
yield* hit('worker:after-stop-seal', 'stop')
|
|
3813
|
+
if (owned === 0) {
|
|
3814
|
+
yield* completeHandoff(context.source.threadId, id, workId('handoff', id), 'stop')
|
|
3815
|
+
|
|
3816
|
+
return command
|
|
3817
|
+
}
|
|
3818
|
+
yield* Effect.sleep(deps.settlementPollInterval)
|
|
3819
|
+
}
|
|
3820
|
+
}),
|
|
3821
|
+
cancel: Effect.fnUntraced(function*(request) {
|
|
3822
|
+
const principal = yield* authorize('cancel', 'control', request.worker)
|
|
3823
|
+
|
|
3824
|
+
yield* receiptInput(request, 'cancel')
|
|
3825
|
+
yield* deps
|
|
3826
|
+
.abort(
|
|
3827
|
+
AbortCommand.make({
|
|
3828
|
+
submissionId: request.receipt.submissionId,
|
|
3829
|
+
author: principal,
|
|
3830
|
+
reason: 'Worker owner requested cancellation of this Receipt',
|
|
3831
|
+
}),
|
|
3832
|
+
)
|
|
3833
|
+
.pipe(
|
|
3834
|
+
Effect.mapError((error) => error._tag === 'JoinedToHost' ? error : failure('cancel', 'storage', error)),
|
|
3835
|
+
)
|
|
3836
|
+
}),
|
|
3837
|
+
}
|
|
3838
|
+
}
|
|
3839
|
+
|
|
3840
|
+
const validateCompletion = Effect.fnUntraced(function*(
|
|
3841
|
+
unvalidated: FrameworkMessage,
|
|
3842
|
+
options: DurableSubmitOptions,
|
|
3843
|
+
agentId: AgentId,
|
|
3844
|
+
inputDigest: Digest,
|
|
3845
|
+
) {
|
|
3846
|
+
const message = yield* Schema.decodeEffect(FrameworkMessage)(unvalidated).pipe(
|
|
3847
|
+
Effect.mapError((cause) => failure('followUp', 'corrupt', cause)),
|
|
3848
|
+
)
|
|
3849
|
+
|
|
3850
|
+
const childThreadId = message._tag === 'WorkerCompletion'
|
|
3851
|
+
? message.report.worker.threadId
|
|
3852
|
+
: message.worker.threadId
|
|
3853
|
+
|
|
3854
|
+
const proofId = message._tag === 'WorkerCompletion'
|
|
3855
|
+
? workerReportRecordId(options.idempotencyKey)
|
|
3856
|
+
: yield* withCrypto(
|
|
3857
|
+
agentUpdateRecordId(
|
|
3858
|
+
message.update.threadId,
|
|
3859
|
+
message.update.runId,
|
|
3860
|
+
message.update.updateId,
|
|
3861
|
+
),
|
|
3862
|
+
).pipe(Effect.mapError(storageFailure('followUp')))
|
|
3863
|
+
|
|
3864
|
+
const proof = Option.getOrUndefined(yield* exactRecord(childThreadId, proofId, 'followUp'))
|
|
3865
|
+
?.record.payload
|
|
3866
|
+
|
|
3867
|
+
const frozen = message._tag === 'WorkerCompletion'
|
|
3868
|
+
? proof?._tag === 'WorkerReportPrepared' &&
|
|
3869
|
+
proof.runId === message.report.runId &&
|
|
3870
|
+
proof.messageId === options.idempotencyKey
|
|
3871
|
+
? proof.envelope
|
|
3872
|
+
: undefined
|
|
3873
|
+
: proof?._tag === 'AgentUpdateEmitted' &&
|
|
3874
|
+
Schema.toEquivalence(Update)(proof.update, message.update)
|
|
3875
|
+
? proof.delivery?.envelope
|
|
3876
|
+
: undefined
|
|
3877
|
+
|
|
3878
|
+
if (frozen === undefined) return yield* failure('followUp', 'denied')
|
|
3879
|
+
|
|
3880
|
+
const envelope = yield* Schema.decodeUnknownEffect(PreparedInput)(frozen).pipe(
|
|
3881
|
+
Effect.mapError((cause) => failure('followUp', 'corrupt', cause)),
|
|
3882
|
+
)
|
|
3883
|
+
|
|
3884
|
+
if (
|
|
3885
|
+
!Schema.is(FrameworkMessage)(envelope.messageAdmission) ||
|
|
3886
|
+
!Schema.toEquivalence(FrameworkMessage)(envelope.messageAdmission, message) ||
|
|
3887
|
+
envelope.threadId !== options.threadId ||
|
|
3888
|
+
envelope.agentId !== agentId ||
|
|
3889
|
+
envelope.inputDigest !== inputDigest ||
|
|
3890
|
+
envelope.deliveryPrincipal !== options.principal ||
|
|
3891
|
+
envelope.admissionKey !== options.idempotencyKey ||
|
|
3892
|
+
!definitionDigestsEqual(envelope.definitions, options.definitions) ||
|
|
3893
|
+
!Schema.toEquivalence(Schema.UndefinedOr(WorkerAdmission))(
|
|
3894
|
+
envelope.workerAdmission,
|
|
3895
|
+
options.workerAdmission,
|
|
3896
|
+
)
|
|
3897
|
+
) {
|
|
3898
|
+
return yield* failure('followUp', 'denied')
|
|
3899
|
+
}
|
|
3900
|
+
|
|
3901
|
+
const recorded = Option.getOrUndefined(
|
|
3902
|
+
yield* exactRecord(childThreadId, workerOriginRecordId(childThreadId), 'followUp'),
|
|
3903
|
+
)?.record.payload
|
|
3904
|
+
|
|
3905
|
+
if (
|
|
3906
|
+
recorded?._tag !== 'WorkerOriginRecorded' ||
|
|
3907
|
+
recorded.origin.worker.threadId !== childThreadId ||
|
|
3908
|
+
recorded.origin.reporting?.mode !== 'standard'
|
|
3909
|
+
) {
|
|
3910
|
+
return yield* failure('followUp', 'denied')
|
|
3911
|
+
}
|
|
3912
|
+
const origin = recorded.origin
|
|
3913
|
+
|
|
3914
|
+
const first = Option.getOrUndefined(
|
|
3915
|
+
yield* exactRecord(
|
|
3916
|
+
origin.source.threadId,
|
|
3917
|
+
workerInputRecordId(origin.firstMessageId),
|
|
3918
|
+
'followUp',
|
|
3919
|
+
),
|
|
3920
|
+
)?.record.payload
|
|
3921
|
+
|
|
3922
|
+
if (
|
|
3923
|
+
first?._tag !== 'WorkerInputRequested' ||
|
|
3924
|
+
first.admission.messageId !== origin.firstMessageId ||
|
|
3925
|
+
!sameOrigin(first.admission.origin, origin)
|
|
3926
|
+
) {
|
|
3927
|
+
return yield* failure('followUp', 'denied')
|
|
3928
|
+
}
|
|
3929
|
+
const receiving = envelope.workerAdmission
|
|
3930
|
+
|
|
3931
|
+
const sourceSubmissionId = receiving === undefined
|
|
3932
|
+
? first.admission.sourceSubmissionId
|
|
3933
|
+
: receiving.sourceSubmissionId
|
|
3934
|
+
|
|
3935
|
+
// Emission only persists the child's outbound message. The receiving runtime
|
|
3936
|
+
// calls this before acceptance and checks live permission, including revocation.
|
|
3937
|
+
// A frozen return address never substitutes for destination authorization.
|
|
3938
|
+
const principal = yield* deps.authorizer.authorize({
|
|
3939
|
+
sourceThreadId: receiving?.origin.source.threadId ?? origin.source.threadId,
|
|
3940
|
+
...(sourceSubmissionId === undefined ? {} : { sourceSubmissionId }),
|
|
3941
|
+
principal: options.principal,
|
|
3942
|
+
operation: 'followUp',
|
|
3943
|
+
access: 'report',
|
|
3944
|
+
worker: receiving?.origin.worker ?? origin.worker,
|
|
3945
|
+
})
|
|
3946
|
+
|
|
3947
|
+
if (principal !== options.principal) return yield* failure('followUp', 'denied')
|
|
3948
|
+
|
|
3949
|
+
return message
|
|
3950
|
+
})
|
|
3951
|
+
|
|
3952
|
+
const acquire = Effect.fnUntraced(function*(request: {
|
|
3953
|
+
readonly sourceThreadId: ThreadId
|
|
3954
|
+
readonly principal: Principal
|
|
3955
|
+
readonly sourceSubmissionId?: SubmissionId
|
|
3956
|
+
}) {
|
|
3957
|
+
const { sourceThreadId, principal } = request
|
|
3958
|
+
|
|
3959
|
+
yield* deps.authorizer.authorize({
|
|
3960
|
+
sourceThreadId,
|
|
3961
|
+
...(request.sourceSubmissionId === undefined
|
|
3962
|
+
? {}
|
|
3963
|
+
: { sourceSubmissionId: request.sourceSubmissionId }),
|
|
3964
|
+
principal,
|
|
3965
|
+
operation: 'context',
|
|
3966
|
+
access: 'context',
|
|
3967
|
+
})
|
|
3968
|
+
const current = yield* readIdentity(sourceThreadId, 'context')
|
|
3969
|
+
const created = current.records[0]?.record.payload
|
|
3970
|
+
|
|
3971
|
+
if (created?._tag !== 'ThreadCreated') return yield* failure('context', 'not-found')
|
|
3972
|
+
|
|
3973
|
+
const selected = request.sourceSubmissionId === undefined
|
|
3974
|
+
? undefined
|
|
3975
|
+
: yield* sourceAuthority(sourceThreadId, request.sourceSubmissionId)
|
|
3976
|
+
|
|
3977
|
+
const resolved = selected === undefined ? currentBinding(created.agentId) : selected.binding
|
|
3978
|
+
|
|
3979
|
+
if (resolved === undefined) return yield* failure('context', 'declaration-unavailable')
|
|
3980
|
+
|
|
3981
|
+
const origin = current.records.find(
|
|
3982
|
+
({ record }) => record.payload._tag === 'WorkerOriginRecorded',
|
|
3983
|
+
)?.record.payload
|
|
3984
|
+
|
|
3985
|
+
const attached = current.records.find(
|
|
3986
|
+
({ record }) => record.payload._tag === 'SubagentLineageRecorded',
|
|
3987
|
+
)?.record.payload
|
|
3988
|
+
|
|
3989
|
+
const retained = origin?._tag === 'WorkerOriginRecorded'
|
|
3990
|
+
? origin.origin
|
|
3991
|
+
: attached?._tag === 'SubagentLineageRecorded'
|
|
3992
|
+
? attached
|
|
3993
|
+
: undefined
|
|
3994
|
+
|
|
3995
|
+
if (
|
|
3996
|
+
selected?.submission !== undefined &&
|
|
3997
|
+
selected.submission.submissionId !== request.sourceSubmissionId
|
|
3998
|
+
) {
|
|
3999
|
+
yield* deps.authorizer.authorize({
|
|
4000
|
+
sourceThreadId,
|
|
4001
|
+
sourceSubmissionId: selected.submission.submissionId,
|
|
4002
|
+
principal,
|
|
4003
|
+
operation: 'context',
|
|
4004
|
+
access: 'context',
|
|
4005
|
+
})
|
|
4006
|
+
}
|
|
4007
|
+
|
|
4008
|
+
return facet(
|
|
4009
|
+
{
|
|
4010
|
+
source: {
|
|
4011
|
+
_tag: 'programmatic',
|
|
4012
|
+
threadId: sourceThreadId,
|
|
4013
|
+
agentId: selected?.submission?.agentId ?? created.agentId,
|
|
4014
|
+
},
|
|
4015
|
+
policy: retained?.policy ?? selected?.binding?.definition.policy ?? resolved.definition.policy,
|
|
4016
|
+
depth: origin?._tag === 'WorkerOriginRecorded'
|
|
4017
|
+
? origin.origin.depth
|
|
4018
|
+
: attached?._tag === 'SubagentLineageRecorded'
|
|
4019
|
+
? attached.parentLink.depth
|
|
4020
|
+
: 0,
|
|
4021
|
+
...(retained?.grant === undefined ? {} : { grant: retained.grant }),
|
|
4022
|
+
},
|
|
4023
|
+
principal,
|
|
4024
|
+
selected?.submission?.submissionId,
|
|
4025
|
+
)
|
|
4026
|
+
})
|
|
4027
|
+
|
|
4028
|
+
return {
|
|
4029
|
+
facet,
|
|
4030
|
+
prepareUpdate,
|
|
4031
|
+
acquire,
|
|
4032
|
+
validateCompletion,
|
|
4033
|
+
validateAdmission,
|
|
4034
|
+
ensureOrigin,
|
|
4035
|
+
completeInput,
|
|
4036
|
+
repairInput,
|
|
4037
|
+
repairReservation,
|
|
4038
|
+
repairStop,
|
|
4039
|
+
reserveSubtree,
|
|
4040
|
+
}
|
|
4041
|
+
})
|