effect-agent 0.1.0-beta.164 → 0.1.0-beta.165
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/dist/{Admin-Vhz6NdaH.d.mts → Admin-CbwoQEm8.d.mts} +24 -24
- package/dist/{Agent-BMATXYsI.mjs → Agent-B0WrUcHy.mjs} +9 -9
- package/dist/Agent-B0WrUcHy.mjs.map +1 -0
- package/dist/{Agent-ZfnNCQXs.d.mts → Agent-D0fbFT2d.d.mts} +27 -24
- package/dist/{AgentError-Bn1ytXRD.d.mts → AgentError-BMqPzIVt.d.mts} +3 -3
- package/dist/{AgentPolicy-B4oH8TbG.d.mts → AgentPolicy-CclAEpHn.d.mts} +2 -2
- package/dist/{AgentRuntime-D1MmB_0z.d.mts → AgentRuntime-BM36roNi.d.mts} +44 -30
- package/dist/{AgentRuntime-Q50HloUc.mjs → AgentRuntime-BTfPyMXN.mjs} +91 -30
- package/dist/AgentRuntime-BTfPyMXN.mjs.map +1 -0
- package/dist/{AgentUpdates-DMJ-_xow.d.mts → AgentUpdates-DksV4D0A.d.mts} +6 -3
- package/dist/{ContextCompactor-BoKQOjr5.d.mts → ContextCompactor-DLpX-HUG.d.mts} +18 -12
- package/dist/{ContextWindow-DRQ5Mbm2.d.mts → ContextWindow-aGZOPIPq.d.mts} +24 -22
- package/dist/{Digest-COAt3Orl.d.mts → Digest-3l_02jaM.d.mts} +2 -2
- package/dist/{DurableAgentRuntime-BTMOgDl_.mjs → DurableAgentRuntime-CWmWREPj.mjs} +11 -11
- package/dist/{DurableAgentRuntime-BTMOgDl_.mjs.map → DurableAgentRuntime-CWmWREPj.mjs.map} +1 -1
- package/dist/{DurableStep-Cry_iol4.d.mts → DurableStep-CTqx6DOV.d.mts} +13 -11
- package/dist/{EventSource-CtS0RBM7.d.mts → EventSource-D29Jsj5U.d.mts} +3 -3
- package/dist/{FailureDiagnostic-BElLOoED.mjs → FailureDiagnostic-D9oW23Cn.mjs} +16 -10
- package/dist/FailureDiagnostic-D9oW23Cn.mjs.map +1 -0
- package/dist/{FailureDiagnostic-CaAkzGHL.d.mts → FailureDiagnostic-DvHruCSJ.d.mts} +10 -9
- package/dist/InMemory.d.mts +28 -5
- package/dist/InMemory.mjs +37 -4
- package/dist/InMemory.mjs.map +1 -1
- package/dist/{Messaging-CICd_CSi.d.mts → Messaging-BbuaphiQ.d.mts} +6 -6
- package/dist/{Messaging-7VXQnWI3.d.mts → Messaging-DF_IWnxV.d.mts} +5 -5
- package/dist/{MessagingHost-DXwWnrMh.d.mts → MessagingHost-Bfbfkx6f.d.mts} +13 -12
- package/dist/{MessagingHost-DfsbMPvq.mjs → MessagingHost-DJZJZILu.mjs} +4 -3
- package/dist/MessagingHost-DJZJZILu.mjs.map +1 -0
- package/dist/{Output-CY7NZByV.d.mts → Output-UsQKiPhz.d.mts} +4 -4
- package/dist/{PreparedInputAdmission-CS_zlCvD.d.mts → PreparedInputAdmission-DXvjTe4U.d.mts} +6 -6
- package/dist/{Receipt-BAHyigAF.d.mts → Receipt-BkM21Qiu.d.mts} +2 -2
- package/dist/{Records-Bm4Qt70a.d.mts → Records-CAQktL0z.d.mts} +8 -8
- package/dist/{RunEvent-D0aepYwN.d.mts → RunEvent-B3CRIqIC.d.mts} +5 -5
- package/dist/{RunEventSink-9CUdI9Ar.d.mts → RunEventSink-sDXDkrAl.d.mts} +9 -7
- package/dist/{RunJournal-D8Vvf_io.mjs → RunJournal-NRgq1PNe.mjs} +3 -3
- package/dist/{RunJournal-D8Vvf_io.mjs.map → RunJournal-NRgq1PNe.mjs.map} +1 -1
- package/dist/{RunOptions-BHmBa05n.d.mts → RunOptions-CkSZSuIh.d.mts} +87 -83
- package/dist/{RunPolicyUsage-CUudVtg_.d.mts → RunPolicyUsage-QmYVw9z8.d.mts} +2 -2
- package/dist/{Schedule-Bi_XVKLF.d.mts → Schedule-rEIiYnRq.d.mts} +4 -4
- package/dist/{Subagent-Cxvuaius.mjs → Subagent-C-fyHbcp.mjs} +5 -5
- package/dist/{Subagent-Cxvuaius.mjs.map → Subagent-C-fyHbcp.mjs.map} +1 -1
- package/dist/{Subagent-D59om8SR.d.mts → Subagent-t3pJDZMN.d.mts} +15 -15
- package/dist/{SubagentContract-tyN9v-Jv.d.mts → SubagentContract-DdPzxYQj.d.mts} +3 -2
- package/dist/{SubagentHost-VTyf_wEF.d.mts → SubagentHost-CXFlEpj0.d.mts} +19 -16
- package/dist/{Subscription-nbSNY6Hs.d.mts → Subscription-BJj-R-6V.d.mts} +8 -8
- package/dist/{SubscriptionInput-DbXnOMS2.d.mts → SubscriptionInput-DyQtODg2.d.mts} +3 -3
- package/dist/Thread-DT8RTLIQ.d.mts +117 -0
- package/dist/{ThreadHistory-FD-o4TsR.d.mts → ThreadHistory-DQ-IC1hU.d.mts} +12 -9
- package/dist/{ToolBroker-DWs4tZra.d.mts → ToolBroker-DXwv2aUT.d.mts} +14 -12
- package/dist/{ToolExposure-UCN12eCd.d.mts → ToolExposure-BsaSH15e.d.mts} +5 -4
- package/dist/{ToolExposure-r2eOWk4F.d.mts → ToolExposure-Ckg3-sTf.d.mts} +3 -2
- package/dist/{ToolExposure-9uF_Yo0T.mjs → ToolExposure-DBATXxmL.mjs} +2 -2
- package/dist/ToolExposure-DBATXxmL.mjs.map +1 -0
- package/dist/{ToolExposure-C93U1sPu.mjs → ToolExposure-hTJT2ekj.mjs} +3 -2
- package/dist/ToolExposure-hTJT2ekj.mjs.map +1 -0
- package/dist/ToolExposure.d.mts +2 -2
- package/dist/ToolExposure.mjs +2 -2
- package/dist/{ToolResult-BKdqWRff.d.mts → ToolResult-DqyEhJLF.d.mts} +2 -2
- package/dist/{Usage-BNjPR7Zr.d.mts → Usage-CzZJ6A2n.d.mts} +3 -2
- package/dist/{Worker-XEBYxRQv.d.mts → Worker-DH5SAVIK.d.mts} +7 -7
- package/dist/{Worker-CfwzMZEK.mjs → Worker-DZjdMjZn.mjs} +3 -3
- package/dist/Worker-DZjdMjZn.mjs.map +1 -0
- package/dist/{WorkerAdmission-BVbSB8_A.mjs → WorkerAdmission-DJ76C2b-.mjs} +4 -4
- package/dist/{WorkerAdmission-BVbSB8_A.mjs.map → WorkerAdmission-DJ76C2b-.mjs.map} +1 -1
- package/dist/{agent-registration-BIOzAej4.mjs → agent-registration-D1dWV7KK.mjs} +3 -3
- package/dist/{agent-registration-BIOzAej4.mjs.map → agent-registration-D1dWV7KK.mjs.map} +1 -1
- package/dist/capabilities/BrowserUse.d.mts +1 -1
- package/dist/capabilities/BrowserUse.mjs +1 -1
- package/dist/capabilities/CodeMode.d.mts +2 -2
- package/dist/capabilities/CodeMode.mjs +3 -3
- package/dist/capabilities/Commands.d.mts +1 -1
- package/dist/capabilities/ContextTools.d.mts +2 -2
- package/dist/capabilities/ContextTools.mjs +1 -1
- package/dist/capabilities/Mcp.d.mts +1 -1
- package/dist/capabilities/Mcp.mjs +1 -1
- package/dist/capabilities/McpClient.d.mts +1 -1
- package/dist/capabilities/McpClient.mjs +1 -1
- package/dist/capabilities/MemoryNotes.d.mts +2 -2
- package/dist/capabilities/MemoryNotes.mjs +1 -1
- package/dist/capabilities/Messaging.d.mts +2 -2
- package/dist/capabilities/Messaging.mjs +3 -3
- package/dist/capabilities/ModelContext.d.mts +1 -1
- package/dist/capabilities/Redaction.d.mts +1 -1
- package/dist/capabilities/RunHooks.d.mts +7 -6
- package/dist/capabilities/RunHooks.mjs +2 -1
- package/dist/capabilities/RunHooks.mjs.map +1 -1
- package/dist/capabilities/SemanticMemory.d.mts +1 -1
- package/dist/capabilities/SemanticMemory.mjs +1 -1
- package/dist/capabilities/Subagent.d.mts +3 -3
- package/dist/capabilities/Subagent.mjs +2 -2
- package/dist/capabilities/SubagentReservations.d.mts +64 -60
- package/dist/capabilities/SubagentReservations.mjs +6 -1
- package/dist/capabilities/SubagentReservations.mjs.map +1 -1
- package/dist/capabilities/ToolDiscovery.d.mts +2 -2
- package/dist/capabilities/ToolDiscovery.mjs +3 -3
- package/dist/capabilities/WebCapture.d.mts +1 -1
- package/dist/capabilities/WebCapture.mjs +1 -1
- package/dist/capabilities/WebSearch.d.mts +1 -1
- package/dist/capabilities/WebSearch.mjs +1 -1
- package/dist/{compaction-BQK4MUg3.mjs → compaction-FDJhjbzH.mjs} +4 -3
- package/dist/compaction-FDJhjbzH.mjs.map +1 -0
- package/dist/core/Agent.d.mts +1 -1
- package/dist/core/Agent.mjs +1 -1
- package/dist/core/AgentError.d.mts +1 -1
- package/dist/core/AgentError.mjs +4 -4
- package/dist/core/AgentError.mjs.map +1 -1
- package/dist/core/AgentPolicy.d.mts +1 -1
- package/dist/core/AgentUpdates.d.mts +1 -1
- package/dist/core/AgentUpdates.mjs +5 -1
- package/dist/core/AgentUpdates.mjs.map +1 -1
- package/dist/core/FailureDiagnostic.d.mts +1 -1
- package/dist/core/FailureDiagnostic.mjs +1 -1
- package/dist/core/IdGenerator.d.mts +3 -1
- package/dist/core/IdGenerator.mjs +8 -5
- package/dist/core/IdGenerator.mjs.map +1 -1
- package/dist/core/Receipt.d.mts +1 -1
- package/dist/core/Receipt.mjs +1 -1
- package/dist/core/Receipt.mjs.map +1 -1
- package/dist/core/RunEvent.d.mts +1 -1
- package/dist/core/RunEvent.mjs +2 -2
- package/dist/core/RunEvent.mjs.map +1 -1
- package/dist/core/RunPolicyUsage.d.mts +1 -1
- package/dist/core/RunPolicyUsage.mjs +1 -1
- package/dist/core/RunPolicyUsage.mjs.map +1 -1
- package/dist/core/SubagentContract.d.mts +1 -1
- package/dist/core/SubagentContract.mjs +2 -1
- package/dist/core/SubagentContract.mjs.map +1 -1
- package/dist/core/Thread.d.mts +2 -2
- package/dist/core/Thread.mjs +82 -33
- package/dist/core/Thread.mjs.map +1 -1
- package/dist/core/ToolResult.d.mts +1 -1
- package/dist/core/ToolResult.mjs +1 -1
- package/dist/core/ToolResult.mjs.map +1 -1
- package/dist/core/Usage.d.mts +1 -1
- package/dist/core/Usage.mjs +2 -1
- package/dist/core/Usage.mjs.map +1 -1
- package/dist/core/Worker.d.mts +2 -2
- package/dist/core/Worker.mjs +1 -1
- package/dist/durable/ActivityStore.d.mts +1 -1
- package/dist/durable/Admin.d.mts +1 -1
- package/dist/durable/AgentRegistration.d.mts +1 -1
- package/dist/durable/AgentRegistration.mjs +1 -1
- package/dist/durable/Certification.d.mts +1 -1
- package/dist/durable/CommittedActivity.d.mts +3 -3
- package/dist/durable/Digest.d.mts +1 -1
- package/dist/durable/DurableAgentRuntime.d.mts +2 -2
- package/dist/durable/DurableAgentRuntime.mjs +2 -2
- package/dist/durable/EventSource.d.mts +1 -1
- package/dist/durable/GitHubWorkflowSource.d.mts +4 -4
- package/dist/durable/GitHubWorkflowSource.mjs +1 -1
- package/dist/durable/LifecyclePublication.d.mts +1 -1
- package/dist/durable/LifecyclePublication.mjs +1 -1
- package/dist/durable/MessageDelivery.d.mts +9 -9
- package/dist/durable/MessageDelivery.mjs +2 -2
- package/dist/durable/MessageDeliveryStoreConformance.d.mts +28 -28
- package/dist/durable/MessageDeliveryStoreConformance.mjs +1 -1
- package/dist/durable/PersistentHistory.d.mts +2 -2
- package/dist/durable/PersistentHistory.mjs +2 -2
- package/dist/durable/PreparedInputAdmission.d.mts +1 -1
- package/dist/durable/PreparedInputAdmission.mjs +1 -1
- package/dist/durable/Records.d.mts +1 -1
- package/dist/durable/Records.mjs +5 -5
- package/dist/durable/Recovery.d.mts +1 -1
- package/dist/durable/RunJournal.d.mts +1 -1
- package/dist/durable/RunJournal.mjs +1 -1
- package/dist/durable/Schedule.d.mts +1 -1
- package/dist/durable/Schedule.mjs +1 -1
- package/dist/durable/ScheduleStoreConformance.d.mts +1 -1
- package/dist/durable/ScheduleTransition.d.mts +1 -1
- package/dist/durable/Scheduling.d.mts +4 -4
- package/dist/durable/SubmissionLedger.d.mts +2 -2
- package/dist/durable/SubmissionLedger.mjs +3 -3
- package/dist/durable/SubmissionLedgerConformance.d.mts +2 -2
- package/dist/durable/SubmissionLedgerConformance.mjs +3 -3
- package/dist/durable/SubmissionStatus.d.mts +1 -1
- package/dist/durable/Subscription.d.mts +1 -1
- package/dist/durable/Subscription.mjs +1 -1
- package/dist/durable/SubscriptionInput.d.mts +1 -1
- package/dist/durable/SubscriptionInput.mjs +1 -1
- package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
- package/dist/durable/SubscriptionTools.d.mts +7 -7
- package/dist/durable/SubscriptionTools.mjs +1 -1
- package/dist/durable/SubscriptionTransition.d.mts +1 -1
- package/dist/durable/Subscriptions.d.mts +7 -7
- package/dist/durable/ThreadContextHistory.d.mts +1 -1
- package/dist/durable/ThreadContextHistoryProjection.d.mts +1 -1
- package/dist/durable/ThreadContextHistoryProjection.mjs +2 -2
- package/dist/durable/ThreadInvariants.d.mts +2 -2
- package/dist/durable/ThreadInvariants.mjs +1 -1
- package/dist/durable/ThreadProjection.d.mts +1 -1
- package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
- package/dist/durable/ThreadStore.d.mts +1 -1
- package/dist/durable/ThreadStore.mjs +1 -1
- package/dist/durable/ThreadStoreConformance.d.mts +1 -1
- package/dist/durable/ThreadStoreConformance.mjs +1 -1
- package/dist/durable/WorkerAdmission.d.mts +6 -6
- package/dist/durable/WorkerAdmission.mjs +1 -1
- package/dist/durable/WorkerHost.d.mts +7 -7
- package/dist/durable/WorkerHost.mjs +1 -1
- package/dist/engine/AgentRuntime.d.mts +1 -1
- package/dist/engine/AgentRuntime.mjs +1 -1
- package/dist/engine/Compaction.d.mts +1 -1
- package/dist/engine/Compaction.mjs +1 -1
- package/dist/engine/ContextCompactor.d.mts +1 -1
- package/dist/engine/ContextCompactor.mjs +8 -3
- package/dist/engine/ContextCompactor.mjs.map +1 -1
- package/dist/engine/ContextWindow.d.mts +1 -1
- package/dist/engine/ContextWindow.mjs +3 -1
- package/dist/engine/ContextWindow.mjs.map +1 -1
- package/dist/engine/DurableStep.d.mts +1 -1
- package/dist/engine/DurableStep.mjs +2 -1
- package/dist/engine/DurableStep.mjs.map +1 -1
- package/dist/engine/MessagingHost.d.mts +1 -1
- package/dist/engine/MessagingHost.mjs +1 -1
- package/dist/engine/Output.d.mts +1 -1
- package/dist/engine/Output.mjs +1 -1
- package/dist/engine/RunEventSink.d.mts +1 -1
- package/dist/engine/RunEventSink.mjs +2 -1
- package/dist/engine/RunEventSink.mjs.map +1 -1
- package/dist/engine/RunOptions.d.mts +1 -1
- package/dist/engine/RunOptions.mjs +5 -2
- package/dist/engine/RunOptions.mjs.map +1 -1
- package/dist/engine/SubagentHost.d.mts +1 -1
- package/dist/engine/SubagentHost.mjs +4 -2
- package/dist/engine/SubagentHost.mjs.map +1 -1
- package/dist/engine/ThreadHistory.d.mts +1 -1
- package/dist/engine/ThreadHistory.mjs +12 -10
- package/dist/engine/ThreadHistory.mjs.map +1 -1
- package/dist/engine/ToolBroker.d.mts +1 -1
- package/dist/engine/ToolBroker.mjs +2 -1
- package/dist/engine/ToolBroker.mjs.map +1 -1
- package/dist/index.d.mts +34 -34
- package/dist/index.mjs +9 -9
- package/dist/{output-contract-DS-S8mTv.mjs → output-contract-DUNIO6as.mjs} +4 -3
- package/dist/output-contract-DUNIO6as.mjs.map +1 -0
- package/package.json +1 -1
- package/src/InMemory.ts +61 -2
- package/src/capabilities/RunHooks.ts +6 -3
- package/src/capabilities/SubagentReservations.ts +7 -1
- package/src/core/Agent.ts +3 -8
- package/src/core/AgentError.ts +1 -1
- package/src/core/AgentUpdates.ts +5 -1
- package/src/core/FailureDiagnostic.ts +6 -8
- package/src/core/IdGenerator.ts +5 -2
- package/src/core/Messaging.ts +1 -1
- package/src/core/Receipt.ts +1 -1
- package/src/core/RunEvent.ts +1 -1
- package/src/core/RunPolicyUsage.ts +1 -1
- package/src/core/SubagentContract.ts +2 -1
- package/src/core/Thread.ts +163 -61
- package/src/core/ToolExposure.ts +2 -1
- package/src/core/ToolResult.ts +1 -1
- package/src/core/Usage.ts +2 -1
- package/src/core/Worker.ts +1 -1
- package/src/core/internal/agent-updates.ts +3 -2
- package/src/core/internal/message-status.ts +1 -1
- package/src/core/internal/strict-schema.ts +3 -1
- package/src/engine/ContextCompactor.ts +8 -2
- package/src/engine/ContextWindow.ts +4 -1
- package/src/engine/DurableStep.ts +2 -1
- package/src/engine/MessagingHost.ts +2 -1
- package/src/engine/RunEventSink.ts +2 -1
- package/src/engine/RunOptions.ts +5 -1
- package/src/engine/SubagentHost.ts +3 -1
- package/src/engine/ThreadHistory.ts +20 -10
- package/src/engine/ToolBroker.ts +2 -1
- package/src/engine/ToolExposure.ts +2 -1
- package/src/engine/internal/agent-runtime.ts +41 -49
- package/src/engine/internal/bounded-value.ts +2 -1
- package/src/engine/internal/compaction.ts +3 -2
- package/src/engine/internal/output-contract.ts +3 -2
- package/src/engine/internal/primitive-delta.ts +51 -10
- package/src/engine/internal/tool-derivative.ts +5 -1
- package/src/engine/internal/tool-exposure.ts +5 -2
- package/src/engine/internal/tool-telemetry.ts +12 -13
- package/dist/Agent-BMATXYsI.mjs.map +0 -1
- package/dist/AgentRuntime-Q50HloUc.mjs.map +0 -1
- package/dist/FailureDiagnostic-BElLOoED.mjs.map +0 -1
- package/dist/MessagingHost-DfsbMPvq.mjs.map +0 -1
- package/dist/Thread-DOBQ0QUY.d.mts +0 -96
- package/dist/ToolExposure-9uF_Yo0T.mjs.map +0 -1
- package/dist/ToolExposure-C93U1sPu.mjs.map +0 -1
- package/dist/Worker-CfwzMZEK.mjs.map +0 -1
- package/dist/compaction-BQK4MUg3.mjs.map +0 -1
- package/dist/output-contract-DS-S8mTv.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"FailureDiagnostic-BElLOoED.mjs","names":["Context","EffectCause","Cause"],"sources":["../src/core/internal/strict-schema.ts","../src/core/FailureDiagnostic.ts"],"sourcesContent":["import { Schema, SchemaParser, SchemaTransformation } from \"effect\";\n\n/** Keep strict parsing on nested values even when an outer parser uses its defaults. */\nexport const strictSchema = <S extends Schema.Top>(schema: S) =>\n Schema.declareConstructor<S[\"Type\"], S[\"Encoded\"]>()(\n [schema],\n ([codec]) =>\n (value, _ast, options) =>\n SchemaParser.decodeUnknownEffect(codec)(value, { ...options, onExcessProperty: \"error\" }),\n {\n toCodecJson: ([codec]) =>\n Schema.link<S[\"Encoded\"]>()(codec, SchemaTransformation.passthrough()),\n },\n );\n","import {\n Cause as EffectCause,\n Exit,\n Predicate,\n Redacted,\n Schema,\n SchemaTransformation,\n} from \"effect\";\n\nimport { strictSchema } from \"./internal/strict-schema.ts\";\n\nconst Text = Schema.String.check(Schema.isMaxLength(16 * 1024));\nconst Name = Schema.String.check(Schema.isMaxLength(1_024));\nconst Scalar = Schema.Union([Text, Schema.Finite, Schema.Boolean, Schema.Null]);\n\n/** Correlation only: never include inputs, tool parameters, request bodies, or credentials. */\nexport const Context = Schema.Struct({\n agentId: Schema.optionalKey(Name),\n threadId: Schema.optionalKey(Name),\n runId: Schema.optionalKey(Name),\n submissionId: Schema.optionalKey(Name),\n attemptId: Schema.optionalKey(Name),\n turnId: Schema.optionalKey(Name),\n toolCallId: Schema.optionalKey(Name),\n toolName: Schema.optionalKey(Name),\n callId: Schema.optionalKey(Name),\n check: Schema.optionalKey(Name),\n operation: Schema.optionalKey(Name),\n}).pipe(strictSchema);\n\nexport type Context = typeof Context.Type;\n\ntype CauseReason =\n | { readonly _tag: \"Fail\"; readonly error: Diagnostic }\n | { readonly _tag: \"Die\"; readonly defect: Diagnostic }\n | { readonly _tag: \"Interrupt\"; readonly fiberId?: number };\n\n/** A private diagnostic projection, not a JavaScript error reconstruction or model response. */\nexport type Diagnostic =\n | {\n readonly _tag: \"Error\";\n readonly errorTag?: string;\n readonly name?: string;\n readonly message?: string;\n readonly stack?: string;\n readonly reason?: Diagnostic;\n readonly code?: string | number;\n readonly cause?: Diagnostic;\n readonly errors?: ReadonlyArray<Diagnostic>;\n readonly context?: Context;\n readonly omittedFields?: ReadonlyArray<string>;\n readonly truncated?: true;\n }\n | {\n readonly _tag: \"Cause\";\n readonly reasons: ReadonlyArray<CauseReason>;\n readonly truncated?: true;\n }\n | { readonly _tag: \"Value\"; readonly value: string | number | boolean | null }\n | { readonly _tag: \"Omitted\"; readonly reason: \"redacted\" | \"cycle\" | \"limit\" | \"unsupported\" };\n\nconst diagnosticSchema = <Nested extends Schema.Top>(nested: Nested) =>\n Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"Error\"),\n errorTag: Schema.optionalKey(Name),\n name: Schema.optionalKey(Name),\n message: Schema.optionalKey(Text),\n stack: Schema.optionalKey(Text),\n reason: Schema.optionalKey(nested),\n code: Schema.optionalKey(Schema.Union([Name, Schema.Finite])),\n cause: Schema.optionalKey(nested),\n errors: Schema.optionalKey(Schema.Array(nested).check(Schema.isMaxLength(128))),\n context: Schema.optionalKey(Context),\n omittedFields: Schema.optionalKey(Schema.Array(Name).check(Schema.isMaxLength(32))),\n truncated: Schema.optionalKey(Schema.Literal(true)),\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"Cause\"),\n reasons: Schema.Array(\n Schema.Union([\n Schema.Struct({ _tag: Schema.Literal(\"Fail\"), error: nested }),\n Schema.Struct({ _tag: Schema.Literal(\"Die\"), defect: nested }),\n Schema.Struct({\n _tag: Schema.Literal(\"Interrupt\"),\n fiberId: Schema.optionalKey(Schema.Finite),\n }),\n ]),\n ).check(Schema.isMaxLength(128)),\n truncated: Schema.optionalKey(Schema.Literal(true)),\n }),\n Schema.Struct({ _tag: Schema.Literal(\"Value\"), value: Scalar }),\n Schema.Struct({\n _tag: Schema.Literal(\"Omitted\"),\n reason: Schema.Literals([\"redacted\", \"cycle\", \"limit\", \"unsupported\"]),\n }),\n ]);\n\n/** Structured, allowlisted Error fields and ordered Effect Fail/Die/Interrupt reasons. */\nexport const Diagnostic: Schema.Codec<Diagnostic> = Schema.suspend(() =>\n diagnosticSchema(Diagnostic),\n).pipe(strictSchema);\n\n// Inspect one encoded node only; recursion must share capture's depth/node/text budgets.\nconst decodeDiagnosticNode = Schema.decodeUnknownExit(\n diagnosticSchema(Schema.Unknown).pipe(strictSchema),\n);\n\n/** Remove common credential forms; hosts must keep arbitrary private payloads out of error text. */\nexport const redactText = (text: string): string =>\n text\n .replace(/\\b(Bearer|Basic)\\s+[A-Za-z0-9._~+/=-]+/gi, \"$1 [REDACTED]\")\n .replace(/(https?:\\/\\/)[^\\s/@]+:[^\\s/@]+@/gi, \"$1[REDACTED]@\")\n .replace(\n /([?&](?:access_token|api_key|apikey|token|key|secret|password|signature)=)[^\\s&#]*/gi,\n \"$1[REDACTED]\",\n )\n .replace(\n /\\b((?:api[_-]?key|access[_-]?token|authorization|password|secret)\\s*[=:]\\s*)[^\\s,;}]+/gi,\n \"$1[REDACTED]\",\n );\n\n/**\n * Capture only diagnostic fields. Local values are never mutated. Cycles and exhausted limits\n * are explicit, not silently dropped; capture visits at most 1,024 nodes, with 56 JSON levels\n * and 128 KiB text. Inner causes have priority over outer stacks when the text budget is exhausted.\n * Text remains operator-private. No generic serializer can identify secrets embedded in arbitrary\n * prose: application error messages must exclude payloads, and hosts may supply stricter redaction.\n */\nexport const capture = (\n value: unknown,\n options?: { readonly redactText?: (text: string) => string },\n): Diagnostic => {\n const seen = new WeakSet<object>();\n let remainingNodes = 1_024;\n let remainingText = 128 * 1024;\n\n const text = (value: string, limit = 16 * 1024): string => {\n const safe = (options?.redactText ?? redactText)(value);\n const length = Math.max(0, Math.min(limit, remainingText));\n\n const marker = \"[truncated]\".slice(0, length);\n\n const result =\n safe.length <= length ? safe : `${safe.slice(0, length - marker.length)}${marker}`;\n\n remainingText -= result.length;\n\n return result;\n };\n\n const visit = (value: unknown, depth: number): Diagnostic => {\n if (remainingNodes <= 0 || depth >= 56) return { _tag: \"Omitted\", reason: \"limit\" };\n remainingNodes--;\n if (Redacted.isRedacted(value)) return { _tag: \"Omitted\", reason: \"redacted\" };\n if (Predicate.isString(value)) return { _tag: \"Value\", value: text(value) };\n if (\n value === null ||\n Predicate.isBoolean(value) ||\n (Predicate.isNumber(value) && Number.isFinite(value))\n )\n return { _tag: \"Value\", value };\n if (!Predicate.isObject(value)) return { _tag: \"Omitted\", reason: \"unsupported\" };\n if (seen.has(value)) return { _tag: \"Omitted\", reason: \"cycle\" };\n seen.add(value);\n const nested = (value: unknown) => visit(value, depth + 1);\n // Local errors retain their own tag, even when it happens to be \"Error\".\n const decoded = value instanceof Error ? undefined : decodeDiagnosticNode(value);\n const node = decoded !== undefined && Exit.isSuccess(decoded) ? decoded.value : undefined;\n\n if (node?._tag === \"Omitted\" || node?._tag === \"Value\") {\n seen.delete(value);\n\n return node._tag === \"Value\" && typeof node.value === \"string\"\n ? { _tag: \"Value\", value: text(node.value) }\n : node;\n }\n\n const originalReasons = EffectCause.isCause(value)\n ? value.reasons\n : node?._tag === \"Cause\"\n ? node.reasons\n : undefined;\n\n if (originalReasons !== undefined) {\n const reasons: Array<CauseReason> = [];\n\n for (const reason of originalReasons) {\n if (reasons.length >= 128 || remainingNodes <= 0) break;\n remainingNodes--;\n\n // reasons -> array item -> error/defect contributes three JSON levels.\n switch (reason._tag) {\n case \"Fail\":\n reasons.push({ _tag: \"Fail\", error: visit(reason.error, depth + 3) });\n break;\n case \"Die\":\n reasons.push({ _tag: \"Die\", defect: visit(reason.defect, depth + 3) });\n break;\n case \"Interrupt\":\n reasons.push({\n _tag: \"Interrupt\",\n ...(reason.fiberId === undefined ? {} : { fiberId: reason.fiberId }),\n });\n break;\n }\n }\n\n const result: Diagnostic = {\n _tag: \"Cause\",\n ...(originalReasons.length > reasons.length || (node?._tag === \"Cause\" && node.truncated)\n ? { truncated: true }\n : {}),\n reasons,\n };\n\n seen.delete(value);\n\n return result;\n }\n const retained = node?._tag === \"Error\" ? node : undefined;\n const omittedFields: Array<string> = [];\n\n const read = (key: string): unknown => {\n // A throwing accessor must not replace the original failure during diagnostic capture.\n try {\n return Reflect.get(value, key);\n } catch {\n omittedFields.push(key);\n\n return undefined;\n }\n };\n\n const tag = retained === undefined ? read(\"_tag\") : retained.errorTag;\n const name = read(\"name\");\n const message = read(\"message\");\n const stack = read(\"stack\");\n const reason = read(\"reason\");\n const code = read(\"code\");\n const cause = read(\"cause\");\n const errors = read(\"errors\");\n const capturedCause = cause === undefined ? undefined : nested(cause);\n const capturedReason = reason === undefined ? undefined : nested(reason);\n const capturedErrors: Array<Diagnostic> = [];\n\n if (Array.isArray(errors))\n for (const error of errors) {\n if (capturedErrors.length >= 128 || remainingNodes <= 0) break;\n capturedErrors.push(visit(error, depth + 2));\n }\n\n for (const field of retained?.omittedFields ?? []) omittedFields.push(text(field, 1_024));\n\n const context: Record<string, string> = {};\n\n for (const key of [\n \"agentId\",\n \"threadId\",\n \"runId\",\n \"submissionId\",\n \"attemptId\",\n \"turnId\",\n \"toolCallId\",\n \"toolName\",\n \"callId\",\n \"check\",\n \"operation\",\n ] as const) {\n const field = retained === undefined ? read(key) : retained.context?.[key];\n\n if (Predicate.isString(field)) context[key] = text(field, 1_024);\n }\n\n const result: Diagnostic = {\n _tag: \"Error\",\n ...(Predicate.isString(tag) ? { errorTag: text(tag, 1_024) } : {}),\n ...(Predicate.isString(name) ? { name: text(name, 1_024) } : {}),\n ...(Predicate.isString(message) ? { message: text(message) } : {}),\n ...(Predicate.isString(stack) ? { stack: text(stack) } : {}),\n ...(capturedReason === undefined ? {} : { reason: capturedReason }),\n ...(Predicate.isString(code)\n ? { code: text(code, 1_024) }\n : Predicate.isNumber(code) && Number.isFinite(code)\n ? { code }\n : {}),\n ...(capturedCause === undefined ? {} : { cause: capturedCause }),\n ...(Array.isArray(errors) ? { errors: capturedErrors } : {}),\n ...(Object.keys(context).length === 0 ? {} : { context }),\n ...(omittedFields.length === 0 ? {} : { omittedFields }),\n ...(retained?.truncated ||\n (Array.isArray(errors) && errors.length > capturedErrors.length) ||\n remainingText === 0\n ? { truncated: true }\n : {}),\n };\n\n seen.delete(value);\n\n return result;\n };\n\n return visit(value, 0);\n};\n\n/** Bound and redact a diagnostic copy; canonical identities stay in their owning records. */\nexport const captureContext = (context: Context): Context => {\n const diagnostic = capture(context);\n\n return diagnostic._tag === \"Error\" ? (diagnostic.context ?? {}) : {};\n};\n\n/**\n * Preserve the original value in-process; across JSON retain its structured diagnostic projection.\n * Decoding returns Diagnostic data, never claims to reconstruct an application error class.\n */\nexport const Value = Diagnostic.pipe(\n Schema.decodeTo(\n Schema.Unknown,\n SchemaTransformation.transform({\n decode: (diagnostic): unknown => diagnostic,\n encode: (value: unknown) => capture(value),\n }),\n ),\n);\n\n/** Original local Effect Cause; its JSON codec preserves ordered typed, defect and interrupt reasons. */\nexport const Cause = Schema.Cause(Value, Value).pipe(\n Schema.decodeTo(\n Schema.declare<EffectCause.Cause<unknown>>(EffectCause.isCause),\n SchemaTransformation.transform({ decode: (cause) => cause, encode: (cause) => cause }),\n ),\n);\n\n/** Safe summary plus optional operator-private causal evidence retained at a terminal boundary. */\nexport const Failure = Schema.Struct({\n errorTag: Schema.NonEmptyString.check(Schema.isMaxLength(256)),\n message: Text,\n diagnostic: Schema.optionalKey(Diagnostic),\n context: Schema.optionalKey(Context),\n}).pipe(strictSchema);\n\nexport type Failure = typeof Failure.Type;\n"],"mappings":";;;;AAGA,MAAa,gBAAsC,WACjD,OAAO,mBAA4C,CAAC,CAClD,CAAC,MAAM,IACN,CAAC,YACC,OAAO,MAAM,YACZ,aAAa,oBAAoB,KAAK,CAAC,CAAC,OAAO;CAAE,GAAG;CAAS,kBAAkB;AAAQ,CAAC,GAC5F,EACE,cAAc,CAAC,WACb,OAAO,KAAmB,CAAC,CAAC,OAAO,qBAAqB,YAAY,CAAC,EACzE,CACF;;;;;;;;;;;;;ACFF,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC;AAC9D,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO,YAAY,IAAK,CAAC;AAC1D,MAAM,SAAS,OAAO,MAAM;CAAC;CAAM,OAAO;CAAQ,OAAO;CAAS,OAAO;AAAI,CAAC;;AAG9E,MAAaA,YAAU,OAAO,OAAO;CACnC,SAAS,OAAO,YAAY,IAAI;C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AAe,UACzD,kBAAkB,IACd,EAAE,WAAW,KAAK,IAClB,CAAC;EACP;EAEA,KAAK,OAAO,KAAK;EAEjB,OAAO;CACT;CAEA,OAAO,MAAM,OAAO,CAAC;AACvB;;AAGA,MAAa,kBAAkB,YAA8B;CAC3D,MAAM,aAAa,QAAQ,OAAO;CAElC,OAAO,WAAW,SAAS,UAAW,WAAW,WAAW,CAAC,IAAK,CAAC;AACrE;;;;;AAMA,MAAa,QAAQ,WAAW,KAC9B,OAAO,SACL,OAAO,SACP,qBAAqB,UAAU;CAC7B,SAAS,eAAwB;CACjC,SAAS,UAAmB,QAAQ,KAAK;AAC3C,CAAC,CACH,CACF;;AAGA,MAAaC,UAAQ,OAAO,MAAM,OAAO,KAAK,CAAC,CAAC,KAC9C,OAAO,SACL,OAAO,QAAoCD,MAAY,OAAO,GAC9D,qBAAqB,UAAU;CAAE,SAAS,UAAU;CAAO,SAAS,UAAU;AAAM,CAAC,CACvF,CACF;;AAGA,MAAa,UAAU,OAAO,OAAO;CACnC,UAAU,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;CAC7D,SAAS;CACT,YAAY,OAAO,YAAY,UAAU;CACzC,SAAS,OAAO,YAAYD,SAAO;AACrC,CAAC,CAAC,CAAC,KAAK,YAAY"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MessagingHost-DfsbMPvq.mjs","names":[],"sources":["../src/core/Messaging.ts","../src/engine/MessagingHost.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\nimport { AgentId, ThreadId } from \"./Identifiers.ts\";\nimport { MessageRef } from \"./internal/message-status.ts\";\nimport { FrameworkMessage } from \"./Worker.ts\";\n\nexport { MessageRef, MessageStatus } from \"./internal/message-status.ts\";\n\n/** Application-chosen fixed route name; it never authorizes a destination by itself. */\nexport const PeerName = Schema.NonEmptyString.check(\n Schema.isMaxLength(64),\n Schema.isPattern(/^[a-zA-Z0-9_-]+$/u),\n);\n\nexport type PeerName = typeof PeerName.Type;\n\nexport const MessageAddress = Schema.Struct({ threadId: ThreadId, agentId: AgentId });\nexport type MessageAddress = typeof MessageAddress.Type;\n\n/** Host-authenticated provenance stored separately from destination-owned application input. */\nexport const MessageAdmission = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n message: MessageRef,\n peerName: PeerName,\n sender: MessageAddress,\n returnAddress: MessageAddress,\n inReplyTo: Schema.optionalKey(MessageRef),\n}).check(\n Schema.makeFilter(\n (value) =>\n value.message.ownerThreadId === value.sender.threadId &&\n value.sender.threadId === value.returnAddress.threadId &&\n value.sender.agentId === value.returnAddress.agentId,\n ),\n);\n\nexport type MessageAdmission = typeof MessageAdmission.Type;\n\nexport const InboxEntry = Schema.Struct({\n sequence: Schema.Natural.check(Schema.isGreaterThan(0)),\n admission: MessageAdmission,\n});\n\nexport type InboxEntry = typeof InboxEntry.Type;\n\nexport const InboxPage = Schema.Struct({\n items: Schema.Array(InboxEntry).check(Schema.isMaxLength(100)),\n next: Schema.NullOr(Schema.Natural),\n});\n\nexport type InboxPage = typeof InboxPage.Type;\n\nexport class MessagingError extends Schema.TaggedError<MessagingError>()(\"MessagingError\", {\n operation: Schema.Literals([\"context\", \"send\", \"reply\", \"inbox\", \"inspect\", \"retry\"]),\n reason: Schema.Literals([\n \"denied\",\n \"unavailable\",\n \"route-unavailable\",\n \"binding-mismatch\",\n \"invalid-input\",\n \"invalid-reference\",\n \"conflict\",\n \"capacity\",\n \"not-found\",\n \"storage\",\n \"corrupt\",\n ]),\n}) {}\n\n/** Canonical input provenance: peer input or a framework-owned completion message. */\nexport const InputMessage = Schema.Union([MessageAdmission, FrameworkMessage]);\nexport type InputMessage = typeof InputMessage.Type;\n","import { Context, type Effect } from \"effect\";\n\nimport type { AnyDefinition } from \"../core/Agent.ts\";\nimport type { ThreadId } from \"../core/Identifiers.ts\";\nimport {\n type InboxPage,\n type MessageAddress,\n type MessageRef,\n type MessageStatus,\n MessagingError,\n} from \"../core/Messaging.ts\";\nimport type { IdempotencyKey, Principal } from \"../core/Receipt.ts\";\nimport type { WorkerSource } from \"../core/Worker.ts\";\n\nexport interface PeerTarget {\n readonly name: string;\n readonly target: AnyDefinition;\n}\n\n/** A fixed declaration chooses the route. Caller input never selects a destination Thread. */\nexport interface SendPeerMessage extends PeerTarget {\n readonly encodedInput: unknown;\n readonly idempotencyKey: IdempotencyKey;\n /** Correlation on sends; replies additionally resolve and authorize the recorded return address. */\n readonly inReplyTo?: MessageRef;\n}\n\n/** Trusted per-invocation facet. It carries caller authority without exposing it in Tool schemas. */\nexport class MessagingHost extends Context.Service<\n MessagingHost,\n {\n readonly context: Effect.Effect<WorkerSource, MessagingError>;\n readonly send: (request: SendPeerMessage) => Effect.Effect<MessageStatus, MessagingError>;\n readonly reply: (\n request: SendPeerMessage & { readonly inReplyTo: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n readonly inbox: (\n request: PeerTarget & { readonly after?: number; readonly limit: number },\n ) => Effect.Effect<InboxPage, MessagingError>;\n readonly inspect: (\n request: PeerTarget & { readonly message: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n readonly retry: (\n request: PeerTarget & { readonly message: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n }\n>()(\"@effect-agent/engine/MessagingHost\") {\n static readonly unavailable: MessagingHost[\"Service\"] = {\n context: MessagingError.make({ operation: \"context\", reason: \"unavailable\" }),\n send: () => MessagingError.make({ operation: \"send\", reason: \"unavailable\" }),\n reply: () => MessagingError.make({ operation: \"reply\", reason: \"unavailable\" }),\n inbox: () => MessagingError.make({ operation: \"inbox\", reason: \"unavailable\" }),\n inspect: () => MessagingError.make({ operation: \"inspect\", reason: \"unavailable\" }),\n retry: () => MessagingError.make({ operation: \"retry\", reason: \"unavailable\" }),\n };\n\n /** Runtime-owned per-call binding. Unconfigured Runs deny peer operations. */\n static readonly forTool = Context.Reference<\n (source: Extract<WorkerSource, { readonly _tag: \"tool\" }>) => MessagingHost[\"Service\"]\n >(\"@effect-agent/engine/MessagingHost/forTool\", {\n defaultValue: () => () => MessagingHost.unavailable,\n });\n}\n\n/** Separate context, history, send and management grants; incoming messages grant none of them. */\nexport interface PeerAuthorizationRequest {\n readonly source: MessageAddress;\n readonly principal: Principal;\n readonly operation: MessagingError[\"operation\"];\n readonly access: \"context\" | \"read\" | \"send\" | \"control\";\n readonly peerName?: string;\n readonly destination?: MessageAddress;\n}\n\nexport const PeerAuthorizer = Context.Reference<{\n /** Return the stable delivery principal for sends. It is retained with the frozen envelope. */\n readonly authorize: (\n request: PeerAuthorizationRequest,\n ) => Effect.Effect<Principal, MessagingError>;\n}>(\"@effect-agent/thread/PeerAuthorizer\", {\n defaultValue: () => ({\n authorize: (request) => MessagingError.make({ operation: request.operation, reason: \"denied\" }),\n }),\n});\n\n/** Application-owned routing; the target Agent is resolved from the existing exact registrations. */\nexport const PeerRoutes = Context.Reference<{\n readonly resolve: (request: {\n readonly source: MessageAddress;\n readonly principal: Principal;\n readonly peerName: string;\n readonly targetAgentId: MessageAddress[\"agentId\"];\n }) => Effect.Effect<ThreadId, MessagingError>;\n}>(\"@effect-agent/thread/PeerRoutes\", {\n defaultValue: () => ({\n resolve: () => MessagingError.make({ operation: \"send\", reason: \"route-unavailable\" }),\n }),\n});\n\n/** Retry windows are finite; exhaustion parks the retained envelope for explicit authorized retry. */\nexport const PeerDeliveryLifetime = Context.Reference<number>(\n \"@effect-agent/thread/PeerDeliveryLifetime\",\n { defaultValue: () => 86_400_000 },\n);\n\n/** Bound canonical send intents across all peers and principals in one source Thread. */\nexport const PeerMessageCapacity = Context.Reference<number>(\n \"@effect-agent/thread/PeerMessageCapacity\",\n { defaultValue: () => 256 },\n);\n"],"mappings":";;;;;;AASA,MAAa,WAAW,OAAO,eAAe,MAC5C,OAAO,YAAY,EAAE,GACrB,OAAO,UAAU,mBAAmB,CACtC;AAIA,MAAa,iBAAiB,OAAO,OAAO;CAAE,UAAU;CAAU,SAAS;AAAQ,CAAC;;AAIpF,MAAa,mBAAm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E,eAAe,eAAe,KAAK;GAAE,WAAW;GAAW,QAAQ;EAAc,CAAC;EAClF,aAAa,eAAe,KAAK;GAAE,WAAW;GAAS,QAAQ;EAAc,CAAC;CAChF;;CAGA,OAAgB,UAAU,QAAQ,UAEhC,8CAA8C,EAC9C,0BAA0B,cAAc,YAC1C,CAAC;AACH;AAYA,MAAa,iBAAiB,QAAQ,UAKnC,uCAAuC,EACxC,qBAAqB,EACnB,YAAY,YAAY,eAAe,KAAK;CAAE,WAAW,QAAQ;CAAW,QAAQ;AAAS,CAAC,EAChG,GACF,CAAC;;AAGD,MAAa,aAAa,QAAQ,UAO/B,mCAAmC,EACpC,qBAAqB,EACnB,eAAe,eAAe,KAAK;CAAE,WAAW;CAAQ,QAAQ;AAAoB,CAAC,EACvF,GACF,CAAC;;AAGD,MAAa,uBAAuB,QAAQ,UAC1C,6CACA,EAAE,oBAAoB,MAAW,CACnC;;AAGA,MAAa,sBAAsB,QAAQ,UACzC,4CACA,EAAE,oBAAoB,IAAI,CAC5B"}
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import { s as RunId, u as ThreadId } from "./Identifiers-CN2s30fF.mjs";
|
|
2
|
-
import { Prompt } from "effect/unstable/ai";
|
|
3
|
-
import { Context, Effect, Layer, Schema } from "effect";
|
|
4
|
-
declare namespace Thread_d_exports {
|
|
5
|
-
export { Store, Thread, ThreadAppend, ThreadEncodingError, ThreadError, ThreadExport, ThreadHistoryDiverged, ThreadLimitExceeded, ThreadMessage, ThreadNotFound, ThreadText, layerMemory, toPrompt };
|
|
6
|
-
}
|
|
7
|
-
/** Bound applied to one text projection before it can enter a model context. */
|
|
8
|
-
declare const ThreadText: Schema.String;
|
|
9
|
-
declare const ThreadMessage_base: Schema.Class<ThreadMessage, Schema.Struct<{
|
|
10
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
11
|
-
readonly sequence: Schema.Natural;
|
|
12
|
-
readonly runId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "@effect-agent/core/RunId">>;
|
|
13
|
-
readonly message: Schema.Codec<Prompt.Message, Prompt.MessageEncoded, never, never>;
|
|
14
|
-
readonly encodedBytes: Schema.Natural;
|
|
15
|
-
readonly timestamp: Schema.DateTimeUtcFromString;
|
|
16
|
-
}>, {}>;
|
|
17
|
-
/** One append-only native Effect AI message in a conversation. */
|
|
18
|
-
declare class ThreadMessage extends ThreadMessage_base {}
|
|
19
|
-
declare const Thread_base: Schema.Class<Thread, Schema.Struct<{
|
|
20
|
-
readonly version: Schema.Literal<1>;
|
|
21
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
22
|
-
readonly nextSequence: Schema.Natural;
|
|
23
|
-
readonly contentBytes: Schema.Natural;
|
|
24
|
-
readonly messages: Schema.$Array<typeof ThreadMessage>;
|
|
25
|
-
}>, {}>;
|
|
26
|
-
/** An identified, ordered conversation snapshot. Storage and execution recovery are separate concerns. */
|
|
27
|
-
declare class Thread extends Thread_base {}
|
|
28
|
-
declare const ThreadExport_base: Schema.Class<ThreadExport, Schema.Struct<{
|
|
29
|
-
readonly format: Schema.Literal<"effect-agent/ephemeral-thread@1">;
|
|
30
|
-
readonly exportedAt: Schema.DateTimeUtcFromString;
|
|
31
|
-
readonly snapshot: typeof Thread;
|
|
32
|
-
}>, {}>;
|
|
33
|
-
/** Portable conversation snapshot. Its format is independent of the durable execution journal. */
|
|
34
|
-
declare class ThreadExport extends ThreadExport_base {}
|
|
35
|
-
declare const ThreadAppend_base: Schema.Class<ThreadAppend, Schema.Struct<{
|
|
36
|
-
readonly runId: Schema.optionalKey<Schema.brand<Schema.NonEmptyString, "@effect-agent/core/RunId">>;
|
|
37
|
-
readonly message: Schema.Codec<Prompt.Message, Prompt.MessageEncoded, never, never>;
|
|
38
|
-
}>, {}>;
|
|
39
|
-
/** Native message accepted by the append-only thread. */
|
|
40
|
-
declare class ThreadAppend extends ThreadAppend_base {}
|
|
41
|
-
declare const ThreadNotFound_base: Schema.Class<ThreadNotFound, Schema.TaggedStruct<"ThreadNotFound", {
|
|
42
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
43
|
-
}>, import("effect/Cause").YieldableError>;
|
|
44
|
-
/** The requested Thread has not been created in this store. */
|
|
45
|
-
declare class ThreadNotFound extends ThreadNotFound_base {}
|
|
46
|
-
declare const ThreadLimitExceeded_base: Schema.Class<ThreadLimitExceeded, Schema.TaggedStruct<"ThreadLimitExceeded", {
|
|
47
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
48
|
-
readonly limit: Schema.Literals<readonly ["messages", "content-bytes", "threads", "store-content-bytes"]>;
|
|
49
|
-
readonly limitValue: Schema.Natural;
|
|
50
|
-
readonly observedValue: Schema.Natural;
|
|
51
|
-
}>, import("effect/Cause").YieldableError>;
|
|
52
|
-
/** A process-local Thread store reached an explicit count or encoded-content bound. */
|
|
53
|
-
declare class ThreadLimitExceeded extends ThreadLimitExceeded_base {}
|
|
54
|
-
declare const ThreadHistoryDiverged_base: Schema.Class<ThreadHistoryDiverged, Schema.TaggedStruct<"ThreadHistoryDiverged", {
|
|
55
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
56
|
-
readonly message: Schema.String;
|
|
57
|
-
}>, import("effect/Cause").YieldableError>;
|
|
58
|
-
/** Engine history was not an append-only extension of the official snapshot. */
|
|
59
|
-
declare class ThreadHistoryDiverged extends ThreadHistoryDiverged_base {}
|
|
60
|
-
declare const ThreadEncodingError_base: Schema.Class<ThreadEncodingError, Schema.TaggedStruct<"ThreadEncodingError", {
|
|
61
|
-
readonly threadId: Schema.brand<Schema.NonEmptyString, "@effect-agent/core/ThreadId">;
|
|
62
|
-
readonly message: Schema.String;
|
|
63
|
-
}>, import("effect/Cause").YieldableError>;
|
|
64
|
-
/** Native Prompt encoding failed before a bounded state mutation. */
|
|
65
|
-
declare class ThreadEncodingError extends ThreadEncodingError_base {}
|
|
66
|
-
type ThreadError = ThreadNotFound | ThreadLimitExceeded | ThreadHistoryDiverged | ThreadEncodingError;
|
|
67
|
-
/** Reconstruct exact Effect AI Prompt history, including tools, reasoning, files, and options. */
|
|
68
|
-
declare const toPrompt: (snapshot: Thread) => Prompt.Prompt;
|
|
69
|
-
declare const Store_base: Context.ServiceClass<Store, "@effect-agent/capabilities/EphemeralThreads", {
|
|
70
|
-
readonly create: (threadId: ThreadId) => Effect.Effect<Thread, ThreadLimitExceeded>;
|
|
71
|
-
readonly append: (threadId: ThreadId, message: ThreadAppend) => Effect.Effect<Thread, ThreadNotFound | ThreadLimitExceeded | ThreadEncodingError>;
|
|
72
|
-
/**
|
|
73
|
-
* Record an engine-emitted full history only when it is an append-only
|
|
74
|
-
* extension of the exact official Prompt already stored. The entire
|
|
75
|
-
* suffix commits in one transaction or not at all: concurrent writers are
|
|
76
|
-
* serialized, a writer whose history no longer extends the committed
|
|
77
|
-
* official history fails with ThreadHistoryDiverged, and a limit
|
|
78
|
-
* failure inside the suffix records nothing. Earlier updates remain committed if the Run
|
|
79
|
-
* later fails or is interrupted; this transaction covers one update, not the whole Run.
|
|
80
|
-
*/
|
|
81
|
-
readonly recordHistory: (threadId: ThreadId, runId: RunId, history: Prompt.Prompt) => Effect.Effect<Thread, ThreadError>;
|
|
82
|
-
readonly snapshot: (threadId: ThreadId) => Effect.Effect<Thread, ThreadNotFound>;
|
|
83
|
-
readonly export: (threadId: ThreadId) => Effect.Effect<ThreadExport, ThreadNotFound>;
|
|
84
|
-
}>;
|
|
85
|
-
/**
|
|
86
|
-
* Process-local state for conversation history. Updates remain visible even
|
|
87
|
-
* when a Run later fails; this service has no successful-Run commit boundary or durable recovery.
|
|
88
|
-
* ThreadHistory.layer uses this store for ordinary Runs and interactive history.
|
|
89
|
-
* Scope closure releases all in-memory state.
|
|
90
|
-
*/
|
|
91
|
-
declare class Store extends Store_base {}
|
|
92
|
-
/** In-memory storage shared for the consumer's Scope; it does not survive process loss. */
|
|
93
|
-
declare const layerMemory: Layer.Layer<Store, never, never>;
|
|
94
|
-
//#endregion
|
|
95
|
-
export { ThreadError as a, ThreadLimitExceeded as c, ThreadText as d, Thread_d_exports as f, ThreadEncodingError as i, ThreadMessage as l, toPrompt as m, Thread as n, ThreadExport as o, layerMemory as p, ThreadAppend as r, ThreadHistoryDiverged as s, Store as t, ThreadNotFound as u };
|
|
96
|
-
//# sourceMappingURL=Thread-DOBQ0QUY.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ToolExposure-9uF_Yo0T.mjs","names":[],"sources":["../src/engine/ToolExposure.ts"],"sourcesContent":["import { Context, type Effect } from \"effect\";\nimport type { Tool } from \"effect/unstable/ai\";\n\nimport type { RunId, ThreadId } from \"../core/Identifiers.ts\";\n\nexport type CatalogEntry =\n | {\n readonly kind: \"native\";\n readonly tool: Tool.Any;\n readonly namespace?: string | undefined;\n readonly nativeToolName: string;\n }\n | {\n readonly kind: \"code-mode\";\n readonly tool: Tool.Any;\n readonly namespace: string;\n readonly method: string;\n readonly nativeToolName: string;\n };\n\n/** Engine-owned per-Turn snapshot. All candidates passed host visibility and inherited grants. */\nexport class CurrentToolCatalog extends Context.Service<\n CurrentToolCatalog,\n {\n readonly entries: ReadonlyArray<CatalogEntry>;\n }\n>()(\"@effect-agent/engine/ToolExposure/CurrentToolCatalog\") {}\n\n/** Host visibility is checked before a discovery Handler may inspect candidate documentation. */\nexport interface VisibilityRequest {\n readonly threadId: ThreadId;\n readonly runId: RunId;\n readonly turn: number;\n readonly input: unknown;\n /** Includes registered native names and explicitly advertised programmatic names. */\n readonly toolNames: ReadonlyArray<string>;\n}\n\n/** Resolve host dependencies when constructing the policy Layer. */\nexport interface VisibilityHook {\n readonly visible: (request: VisibilityRequest) => Effect.Effect<ReadonlyArray<string>>;\n}\n\n/** Optional host policy captured by durable runtimes; action authorization remains independent. */\nexport const RunToolVisibility = Context.Reference<VisibilityHook | undefined>(\n \"@effect-agent/engine/ToolExposure/RunToolVisibility\",\n { defaultValue: () => undefined },\n);\n"],"mappings":";;;AAqBA,IAAa,qBAAb,cAAwC,QAAQ,QAK9C,CAAC,CAAC,sDAAsD,CAAC,CAAC,CAAC;;AAkB7D,MAAa,oBAAoB,QAAQ,UACvC,uDACA,EAAE,oBAAoB,KAAA,EAAU,CAClC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ToolExposure-C93U1sPu.mjs","names":[],"sources":["../src/core/ToolExposure.ts"],"sourcesContent":["import { Context, Schema } from \"effect\";\nimport type { Tool } from \"effect/unstable/ai\";\n\n/** Registered native names only. Empty selection deliberately clears non-pinned Tools. */\nexport const ToolNames = Schema.Array(\n Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n).check(\n Schema.isMaxLength(1_024),\n Schema.makeFilter((names) => new Set(names).size === names.length, {\n title: \"Tool names are unique\",\n }),\n);\n\n/** One run-scoped replacement, independent of search and of model-visible result text. */\nexport class Selection extends Schema.Class<Selection>(\"@effect-agent/core/ToolExposure/Selection\")(\n {\n toolNames: ToolNames,\n },\n) {}\n\n/** Exact declarations used by one model request, with the selection that produced them. */\nexport class Snapshot extends Schema.Class<Snapshot>(\"@effect-agent/core/ToolExposure/Snapshot\")({\n exposedToolNames: ToolNames,\n selection: Schema.optionalKey(Selection),\n}) {}\n\nexport const Limits = Schema.Struct({\n maxTools: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n maxSchemaBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(4_194_304)),\n});\n\n/** Omission preserves eager exposure. Selection changes take effect only after a complete batch. */\nexport interface Configuration {\n readonly initialToolNames?: ReadonlyArray<string> | undefined;\n readonly maxTools?: number | undefined;\n readonly maxSchemaBytes?: number | undefined;\n}\n\n/** Trusted grouping metadata; never inferred from a Tool's name. */\nexport const ToolNamespace = Context.Reference<string | undefined>(\n \"@effect-agent/core/ToolExposure/ToolNamespace\",\n { defaultValue: () => undefined },\n);\n\n/** An ordinary readonly Tool whose successful result has a `toolNames` field of native names. */\nexport const DiscoveryTool = Context.Reference<boolean>(\n \"@effect-agent/core/ToolExposure/DiscoveryTool\",\n { defaultValue: () => false },\n);\n\n/** Remains selected while eligible. Host visibility and inherited grants may hide an explicit\n * pin without failing the Run; discovery, context rollover and required completion stay mandatory.\n */\nexport const PinnedTool = Context.Reference<boolean>(\"@effect-agent/core/ToolExposure/PinnedTool\", {\n defaultValue: () => false,\n});\n\n/** Extra documentation candidates executed through their owning native Tool, such as Code Mode. */\nexport interface AdditionalCatalogEntry {\n readonly tool: Tool.Any;\n readonly namespace: string;\n readonly method: string;\n}\n\nexport const AdditionalToolCatalog = Context.Reference<ReadonlyArray<AdditionalCatalogEntry>>(\n \"@effect-agent/core/ToolExposure/AdditionalToolCatalog\",\n { defaultValue: () => [] },\n);\n\n/** The owning Tool description embeds its complete additional catalogue. */\nexport const IncludesCatalogDocumentation = Context.Reference<boolean>(\n \"@effect-agent/core/ToolExposure/IncludesCatalogDocumentation\",\n { defaultValue: () => false },\n);\n"],"mappings":";;;AAIA,MAAa,YAAY,OAAO,MAC9B,OAAO,OAAO,MAAM,OAAO,YAAY,CAAC,GAAG,OAAO,YAAY,GAAG,CAAC,CACpE,CAAC,CAAC,MACA,OAAO,YAAY,IAAK,GACxB,OAAO,YAAY,UAAU,IAAI,IAAI,KAAK,CAAC,CAAC,SAAS,MAAM,QAAQ,EACjE,OAAO,wBACT,CAAC,CACH;;AAGA,IAAa,YAAb,cAA+B,OAAO,MAAiB,2CAA2C,CAAC,CACjG,EACE,WAAW,UACb,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,WAAb,cAA8B,OAAO,MAAgB,0CAA0C,CAAC,CAAC;CAC/F,kBAAkB;CAClB,WAAW,OAAO,YAAY,SAAS;AACzC,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,SAAS,OAAO,OAAO;CAClC,UAAU,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,IAAK,CAAC;CACrF,gBAAgB,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,OAAS,CAAC;AACjG,CAAC;;AAUD,MAAa,gBAAgB,QAAQ,UACnC,iDACA,EAAE,oBAAoB,KAAA,EAAU,CAClC;;AAGA,MAAa,gBAAgB,QAAQ,UACnC,iDACA,EAAE,oBAAoB,MAAM,CAC9B;;;;AAKA,MAAa,aAAa,QAAQ,UAAmB,8CAA8C,EACjG,oBAAoB,MACtB,CAAC;AASD,MAAa,wBAAwB,QAAQ,UAC3C,yDACA,EAAE,oBAAoB,CAAC,EAAE,CAC3B;;AAGA,MAAa,+BAA+B,QAAQ,UAClD,gEACA,EAAE,oBAAoB,MAAM,CAC9B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Worker-CfwzMZEK.mjs","names":["FailureDiagnostic.Value"],"sources":["../src/core/internal/message-status.ts","../src/core/Worker.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\nimport { SettlementId, ThreadId } from \"../Identifiers.ts\";\nimport { IdempotencyKey, Receipt } from \"../Receipt.ts\";\n\n/** A retained outbound delivery identity, not a destination Receipt or access grant. */\nexport const MessageRef = Schema.Struct({ ownerThreadId: ThreadId, messageId: IdempotencyKey });\nexport type MessageRef = typeof MessageRef.Type;\n\nconst Reason = Schema.NonEmptyString.check(Schema.isMaxLength(256));\nconst identity = { message: MessageRef };\n\n/**\n * Source-owned delivery evidence. Pending confirms retention only; accepted supplies the\n * destination Receipt, and processed supplies its canonical settlement. Neither retention nor\n * acceptance proves execution. Refused is a definite rejection; parked stops automatic retry\n * while retaining the same identity and any acceptance evidence. Inspect instead of resending.\n */\nexport const MessageStatus = Schema.Union([\n Schema.Struct({\n ...identity,\n status: Schema.Literal(\"pending\"),\n receipt: Schema.Null,\n settlement: Schema.Null,\n reason: Schema.NullOr(Reason),\n }),\n Schema.Struct({\n ...identity,\n status: Schema.Literal(\"accepted\"),\n receipt: Receipt,\n settlement: Schema.Null,\n reason: Schema.NullOr(Reason),\n }),\n Schema.Struct({\n ...identity,\n status: Schema.Literal(\"processed\"),\n receipt: Receipt,\n settlement: Schema.Struct({\n settlementId: SettlementId,\n outcome: Schema.Literals([\"completed\", \"failed\", \"aborted\"]),\n }),\n reason: Schema.Null,\n }),\n Schema.Struct({\n ...identity,\n status: Schema.Literal(\"refused\"),\n receipt: Schema.Null,\n settlement: Schema.Null,\n reason: Reason,\n }),\n Schema.Struct({\n ...identity,\n status: Schema.Literal(\"parked\"),\n receipt: Schema.NullOr(Receipt),\n settlement: Schema.Null,\n reason: Reason,\n }),\n]);\n\nexport type MessageStatus = typeof MessageStatus.Type;\n","import { Schema } from \"effect\";\n\nimport { AgentPolicy } from \"./AgentPolicy.ts\";\nimport { Update } from \"./AgentUpdates.ts\";\nimport * as FailureDiagnostic from \"./FailureDiagnostic.ts\";\nimport { AgentId, DelegationId, RunId, SettlementId, ThreadId, ToolCallId } from \"./Identifiers.ts\";\nimport { MessageStatus } from \"./internal/message-status.ts\";\nimport { IdempotencyKey, Receipt } from \"./Receipt.ts\";\nimport { SubagentExecutionFailure, SubagentGrant } from \"./SubagentContract.ts\";\n\n/** Assignment output selected through the Definition's runDisposition declaration. */\nexport const AssignmentDisposition = Schema.Literals([\"completed\", \"waiting\"]);\nexport type AssignmentDisposition = typeof AssignmentDisposition.Type;\n\n/** A permanent destination outcome; an ordinary Run completion does not imply this. */\nexport const AssignmentTerminal = Schema.Literals([\"completed\", \"failed\", \"cancelled\"]);\nexport type AssignmentTerminal = typeof AssignmentTerminal.Type;\n\n/** A reusable child Thread, correlated with its declaration. This value grants no authority. */\nexport const WorkerRef = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n delegationId: DelegationId,\n targetAgentId: AgentId,\n threadId: ThreadId,\n});\n\nexport type WorkerRef = typeof WorkerRef.Type;\n\n/** A continuing worker identity and retained first delivery, never an execution handle. */\nexport const WorkerStarted = Schema.Struct({\n worker: WorkerRef,\n delivery: MessageStatus,\n}).check(\n Schema.makeFilter(\n ({ worker, delivery }) =>\n delivery.receipt === null || worker.threadId === delivery.receipt.threadId,\n ),\n);\n\nexport type WorkerStarted = typeof WorkerStarted.Type;\n\n/** Stable owner command. Reusing its key for a different worker conflicts. */\nexport const WorkerStop = Schema.Struct({ worker: WorkerRef, idempotencyKey: IdempotencyKey });\nexport type WorkerStop = typeof WorkerStop.Type;\n\n/** The inbox is sealed and active execution has released ownership. External actions are not undone. */\nexport const WorkerStopped = WorkerStop;\nexport type WorkerStopped = typeof WorkerStopped.Type;\n\n/** A host-authorized Run allowance is independent of the immutable delegation lineage. */\nexport const WorkerBudgetScope = Schema.Literals([\"source-subtree\", \"worker-run\"]);\nexport type WorkerBudgetScope = typeof WorkerBudgetScope.Type;\n\n/** Host-bound caller metadata. Programmatic calls never fabricate Run or Tool Call identities. */\nexport const WorkerSource = Schema.Union([\n Schema.Struct({\n _tag: Schema.Literal(\"tool\"),\n agentId: AgentId,\n threadId: ThreadId,\n runId: RunId,\n toolCallId: ToolCallId,\n }),\n Schema.Struct({\n _tag: Schema.Literal(\"programmatic\"),\n agentId: AgentId,\n threadId: ThreadId,\n }),\n]);\n\nexport type WorkerSource = typeof WorkerSource.Type;\n\n/** The caller's effective policy and root-relative depth, resolved by its host. */\nexport const WorkerContext = Schema.Struct({\n source: WorkerSource,\n policy: AgentPolicy,\n depth: Schema.Natural,\n grant: Schema.optionalKey(SubagentGrant),\n});\n\nexport type WorkerContext = typeof WorkerContext.Type;\n\n/** Admission identity is distinct from canonical input application. */\nexport const WorkerInput = Schema.Struct({ receipt: Receipt, messageId: IdempotencyKey });\nexport type WorkerInput = typeof WorkerInput.Type;\n\nexport const WorkerAppliedInput = Schema.Struct({\n ...WorkerInput.fields,\n runId: RunId,\n sequence: Schema.Natural,\n});\n\n/** A Run outcome is not assignment completion. Interpret only a Definition's disposition. */\nexport const WorkerRun = Schema.Struct({\n runId: RunId,\n hostReceipt: Receipt,\n outcome: Schema.NullOr(Schema.Literals([\"completed\", \"failed\", \"aborted\"])),\n disposition: Schema.NullOr(Schema.Json),\n});\n\n/** Bounded durable listing data; a latest Receipt never substitutes for a requested Receipt. */\nexport const WorkerSummary = Schema.Struct({\n worker: WorkerRef,\n latestReceipt: Schema.NullOr(Receipt),\n /** stopping/stopped identify an owner-issued worker stop, never an ordinary Receipt abort. */\n state: Schema.Literals([\n \"starting\",\n \"active\",\n \"idle\",\n \"stopping\",\n \"stopped\",\n \"completed\",\n \"failed\",\n \"cancelled\",\n ]),\n acceptedInput: Schema.NullOr(WorkerInput),\n appliedInput: Schema.NullOr(WorkerAppliedInput),\n run: Schema.NullOr(WorkerRun),\n /** One retained unadmitted input, if any; its state is independent of destination execution. */\n pendingDelivery: Schema.NullOr(MessageStatus),\n /** Consistent destination facts; pending delivery has its own source-owned version. */\n watermark: Schema.Struct({\n canonicalSequence: Schema.Natural,\n acceptedQueueSequence: Schema.Natural,\n pendingDeliveryVersion: Schema.NullOr(Schema.Natural),\n }),\n});\n\nexport type WorkerSummary = typeof WorkerSummary.Type;\n\nexport const WorkerPage = Schema.Struct({\n items: Schema.Array(WorkerSummary).check(Schema.isMaxLength(100)),\n next: Schema.NullOr(ThreadId),\n});\n\nexport type WorkerPage = typeof WorkerPage.Type;\n\n/** Authorized canonical history, encoded independently of storage-adapter representations. */\nexport const WorkerHistoryEntry = Schema.Struct({\n sequence: Schema.Natural.check(Schema.isGreaterThan(0)),\n recordId: Schema.NonEmptyString.check(Schema.isMaxLength(1_024)),\n record: Schema.Json,\n});\n\nexport type WorkerHistoryEntry = typeof WorkerHistoryEntry.Type;\n\n/**\n * Closed host-boundary failures. Original causes stay private and survive diagnostic transport.\n * Retained delivery states are successful MessageStatus values, including pending and refused.\n * After a storage failure, keep the same idempotency key and parameters when reconciling.\n */\nexport class WorkerError extends Schema.TaggedError<WorkerError>()(\"WorkerError\", {\n cause: Schema.optionalKey(FailureDiagnostic.Value),\n stack: Schema.optionalKey(Schema.String),\n /** Concurrency pressure may clear without changing the request. */\n retryable: Schema.optionalKey(Schema.Literal(true)),\n operation: Schema.Literals([\n \"context\",\n \"start\",\n \"followUp\",\n \"inspect\",\n \"observe\",\n \"await\",\n \"list\",\n \"cancel\",\n \"stop\",\n ]),\n reason: Schema.Literals([\n \"denied\",\n \"declaration-unavailable\",\n \"worker-mismatch\",\n \"receipt-mismatch\",\n \"message-mismatch\",\n \"idempotency-conflict\",\n \"capacity\",\n \"not-found\",\n // Decode earlier failures without emitting them for retained deliveries.\n \"delivery-pending\",\n \"storage\",\n \"corrupt\",\n \"unavailable\",\n ]),\n}) {}\n\nexport { WorkerOperationTool } from \"./SubagentContract.ts\";\n\n/** One projected canonical Run outcome. Joined receipts share this identity. */\nexport const WorkerReport = <Success extends Schema.Top>(success: Success) => {\n const identity = {\n _tag: Schema.Literal(\"Settled\"),\n worker: WorkerRef,\n receipt: Receipt,\n runId: RunId,\n settlementId: SettlementId,\n };\n\n return Schema.Union([\n // Union preserves the Success codec while making the result field required.\n Schema.Struct({\n ...identity,\n outcome: Schema.Literal(\"completed\"),\n result: Schema.Union([success]),\n }),\n Schema.Struct({\n ...identity,\n outcome: Schema.Literals([\"failed\", \"aborted\"]),\n failure: SubagentExecutionFailure,\n }),\n ]);\n};\n\nexport type WorkerReport<Success extends Schema.Top> = ReturnType<\n typeof WorkerReport<Success>\n>[\"Type\"];\n\n/** Framework message stored separately from the parent's application input. */\nexport const WorkerCompletion = Schema.Struct({\n _tag: Schema.Literal(\"WorkerCompletion\"),\n budgetExhausted: Schema.Boolean,\n schemaVersion: Schema.Literal(1),\n report: WorkerReport(Schema.Json),\n}).check(Schema.makeFilter(({ report }) => report.worker.threadId === report.receipt.threadId));\n\nexport type WorkerCompletion = typeof WorkerCompletion.Type;\n\n/** Source-worker intermediate output, kept separate from application input. */\nexport const WorkerUpdate = Schema.Struct({\n _tag: Schema.Literal(\"WorkerUpdate\"),\n schemaVersion: Schema.Literal(1),\n worker: WorkerRef,\n update: Update,\n}).check(\n Schema.makeFilter(\n ({ worker, update }) =>\n worker.threadId === update.threadId && worker.targetAgentId === update.agentId,\n ),\n);\n\nexport type WorkerUpdate = typeof WorkerUpdate.Type;\nexport const FrameworkMessage = Schema.Union([WorkerCompletion, WorkerUpdate]);\nexport type FrameworkMessage = typeof FrameworkMessage.Type;\n"],"mappings":";;;;;;;;;;AAMA,MAAa,aAAa,OAAO,OAAO;CAAE,eAAe;CAAU,WAAW;AAAe,CAAC;AAG9F,MAAM,SAAS,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;AAClE,MAAM,WAAW,EAAE,SAAS,WAAW;;;;;;;AAQvC,MAAa,gBAAgB,OAAO,MAAM;CACxC,OAAO,OAAO;EACZ,GAAG;EACH,QAAQ,OAAO,QAAQ,SAAS;EAChC,SAAS,OAAO;EAChB,YAAY,OAAO;EACnB,QAAQ,OAAO,OAAO,MAAM;CAC9B,CAAC;CACD,OAAO,OAAO;EACZ,GAAG;EACH,QAAQ,OAAO,QAAQ,UAAU;EACjC,SAAS;EACT,YAAY,OAAO;EACnB,QAAQ,OAAO,OAAO,MAAM;CAC9B,CAAC;CACD,OAAO,OAAO;EACZ,GAAG;EACH,QAAQ,OAAO,QAAQ,WAAW;EAClC,SAAS;EACT,YAAY,OAAO,OAAO;GACxB,cAAc;GACd,SAAS,OAAO,SAAS;IAAC;IAAa;IAAU;GAAS,CAAC;EAC7D,CAAC;EACD,QAAQ,OAAO;CACjB,CAAC;CACD,OAAO,OAAO;EACZ,GAAG;EACH,QAAQ,OAAO,QAAQ,SAAS;EAChC,SAAS,OAAO;EAChB,YAAY,OAAO;EACnB,QAAQ;CACV,CAAC;CACD,OAAO,OAAO;EACZ,GAAG;EACH,QAAQ,OAAO,QAAQ,QAAQ;EAC/B,SAAS,OAAO,OAAO,OAAO;EAC9B,YAAY,OAAO;EACnB,QAAQ;CACV,CAAC;AACH,CAAC;;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,SAAS;EAC9B,QAAQ;EACR,SAAS;EACT,OAAO;EACP,cAAc;CAChB;CAEA,OAAO,OAAO,MAAM,CAElB,OAAO,OAAO;EACZ,GAAG;EACH,SAAS,OAAO,QAAQ,WAAW;EACnC,QAAQ,OAAO,MAAM,CAAC,OAAO,CAAC;CAChC,CAAC,GACD,OAAO,OAAO;EACZ,GAAG;EACH,SAAS,OAAO,SAAS,CAAC,UAAU,SAAS,CAAC;EAC9C,SAAS;CACX,CAAC,CACH,CAAC;AACH;;AAOA,MAAa,mBAAmB,OAAO,OAAO;CAC5C,MAAM,OAAO,QAAQ,kBAAkB;CACvC,iBAAiB,OAAO;CACxB,eAAe,OAAO,QAAQ,CAAC;CAC/B,QAAQ,aAAa,OAAO,IAAI;AAClC,CAAC,CAAC,CAAC,MAAM,OAAO,YAAY,EAAE,aAAa,OAAO,OAAO,aAAa,OAAO,QAAQ,QAAQ,CAAC;;AAK9F,MAAa,eAAe,OAAO,OAAO;CACxC,MAAM,OAAO,QAAQ,cAAc;CACnC,eAAe,OAAO,QAAQ,CAAC;CAC/B,QAAQ;CACR,QAAQ;AACV,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,EAAE,QAAQ,aACT,OAAO,aAAa,OAAO,YAAY,OAAO,kBAAkB,OAAO,OAC3E,CACF;AAGA,MAAa,mBAAmB,OAAO,MAAM,CAAC,kBAAkB,YAAY,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-BQK4MUg3.mjs","names":[],"sources":["../src/engine/internal/provider-result-staging.ts","../src/engine/internal/compaction.ts"],"sourcesContent":["import type { Schema } from \"effect\";\n\nconst MAX_JSON_DEPTH = 128;\n\nexport interface BoundedJsonSnapshot {\n readonly value: Schema.Json;\n readonly bytes: number;\n}\n\nconst FailedSnapshot = Symbol(\"@effect-agent/engine/FailedProviderResultSnapshot\");\n\n/**\n * @internal Normalize one untrusted JSON value into an owned, frozen snapshot while counting the\n * exact UTF-8 bytes of that same snapshot. The traversal never invokes `toJSON` or accessors,\n * rejects non-plain objects and excessive nesting, and stops as soon as the byte budget is spent.\n */\nconst snapshotJson = (\n root: unknown,\n maxBytes: number,\n maxDepth: number,\n rejectNonFiniteNumbers: boolean,\n): BoundedJsonSnapshot | undefined => {\n if (\n !Number.isSafeInteger(maxBytes) ||\n maxBytes < 0 ||\n !Number.isSafeInteger(maxDepth) ||\n maxDepth < 0\n ) {\n return undefined;\n }\n let total = 0;\n const ancestors = new WeakSet<object>();\n\n const add = (bytes: number): boolean => {\n if (bytes > maxBytes - total) return false;\n total += bytes;\n\n return true;\n };\n\n const addString = (value: string): boolean => {\n if (!add(2)) return false;\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n\n if (code === 0x22 || code === 0x5c) {\n if (!add(2)) return false;\n } else if (code <= 0x1f) {\n // Backspace, tab, newline, form-feed, and carriage-return use two-byte escapes; all other\n // control characters use a six-byte `\\\\u00xx` escape.\n if (!add(code >= 0x08 && code <= 0x0d && code !== 0x0b ? 2 : 6)) return false;\n } else if (code <= 0x7f) {\n if (!add(1)) return false;\n } else if (code <= 0x7ff) {\n if (!add(2)) return false;\n } else if (code >= 0xd800 && code <= 0xdbff) {\n const low = value.charCodeAt(index + 1);\n\n if (low >= 0xdc00 && low <= 0xdfff) {\n if (!add(4)) return false;\n index += 1;\n } else if (!add(6)) {\n return false;\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n if (!add(6)) return false;\n } else if (!add(3)) {\n return false;\n }\n }\n\n return true;\n };\n\n const visit = (value: unknown, depth: number): Schema.Json | typeof FailedSnapshot => {\n if (depth > maxDepth) return FailedSnapshot;\n if (value === null) return add(4) ? null : FailedSnapshot;\n switch (typeof value) {\n case \"string\":\n return addString(value) ? value : FailedSnapshot;\n case \"boolean\":\n return add(value ? 4 : 5) ? value : FailedSnapshot;\n case \"number\": {\n // JSON's numeric representation is inherently bounded for one IEEE-754 value. Retain the\n // wire-equivalent null for non-finite values so counting and later serialization agree.\n if (!Number.isFinite(value)) {\n return rejectNonFiniteNumbers ? FailedSnapshot : add(4) ? null : FailedSnapshot;\n }\n const encoded = JSON.stringify(value);\n\n return encoded !== undefined && add(encoded.length) ? value : FailedSnapshot;\n }\n case \"object\": {\n if (ancestors.has(value)) return FailedSnapshot;\n const isArray = Array.isArray(value);\n const prototype = Object.getPrototypeOf(value);\n\n if (prototype !== (isArray ? Array.prototype : Object.prototype) && prototype !== null) {\n return FailedSnapshot;\n }\n if (\n Object.getOwnPropertyDescriptor(value, \"toJSON\") !== undefined ||\n (prototype !== null && Object.getOwnPropertyDescriptor(prototype, \"toJSON\") !== undefined)\n ) {\n return FailedSnapshot;\n }\n ancestors.add(value);\n try {\n if (isArray) {\n const lengthDescriptor = Object.getOwnPropertyDescriptor(value, \"length\");\n\n if (\n lengthDescriptor === undefined ||\n !(\"value\" in lengthDescriptor) ||\n typeof lengthDescriptor.value !== \"number\" ||\n !Number.isSafeInteger(lengthDescriptor.value) ||\n lengthDescriptor.value < 0\n ) {\n return FailedSnapshot;\n }\n if (!add(1)) return FailedSnapshot;\n const snapshot: Array<Schema.Json> = [];\n\n for (let index = 0; index < lengthDescriptor.value; index += 1) {\n if (index > 0 && !add(1)) return FailedSnapshot;\n const descriptor = Object.getOwnPropertyDescriptor(value, index);\n\n if (descriptor === undefined) {\n if (!add(4)) return FailedSnapshot;\n snapshot.push(null);\n continue;\n }\n if (!(\"value\" in descriptor)) return FailedSnapshot;\n const item = visit(descriptor.value, depth + 1);\n\n if (item === FailedSnapshot) return FailedSnapshot;\n snapshot.push(item);\n }\n if (!add(1)) return FailedSnapshot;\n Object.setPrototypeOf(snapshot, null);\n\n return Object.freeze(snapshot);\n }\n if (!add(1)) return FailedSnapshot;\n const entries: Array<readonly [string, Schema.Json]> = [];\n let first = true;\n\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n\n if (descriptor === undefined || !descriptor.enumerable) continue;\n if (!(\"value\" in descriptor)) return FailedSnapshot;\n if (!first && !add(1)) return FailedSnapshot;\n first = false;\n if (!addString(key) || !add(1)) return FailedSnapshot;\n const item = visit(descriptor.value, depth + 1);\n\n if (item === FailedSnapshot) return FailedSnapshot;\n entries.push([key, item]);\n }\n if (!add(1)) return FailedSnapshot;\n const snapshot: Record<string, Schema.Json> = Object.fromEntries(entries);\n\n Object.setPrototypeOf(snapshot, null);\n\n return Object.freeze(snapshot);\n } finally {\n ancestors.delete(value);\n }\n }\n case \"bigint\":\n case \"function\":\n case \"symbol\":\n case \"undefined\":\n return FailedSnapshot;\n }\n\n return FailedSnapshot;\n };\n\n try {\n const value = visit(root, 0);\n\n return value === FailedSnapshot ? undefined : { value, bytes: total };\n } catch {\n // Revoked or adversarial proxies and reflection failures are protocol-invalid, never trusted.\n return undefined;\n }\n};\n\n/**\n * Normalize provider-owned JSON using JSON serialization's `NaN`/infinity to\n * `null` behavior. Provider events use this form so byte accounting matches\n * their eventual JSON representation.\n */\nexport const boundedJsonSnapshot = (\n root: unknown,\n maxBytes: number,\n maxDepth = MAX_JSON_DEPTH,\n): BoundedJsonSnapshot | undefined => snapshotJson(root, maxBytes, maxDepth, false);\n\n/**\n * Validate canonical JSON without repairing non-finite numbers. Recovery\n * inputs use this form because changing a recorded value would fabricate\n * history.\n */\nexport const boundedCanonicalJsonSnapshot = (\n root: unknown,\n maxBytes: number,\n maxDepth = MAX_JSON_DEPTH,\n): BoundedJsonSnapshot | undefined => snapshotJson(root, maxBytes, maxDepth, true);\n","import { Option, Schema } from \"effect\";\nimport { Prompt } from \"effect/unstable/ai\";\n\nimport type { ContextMessageTokenEstimator } from \"../ContextCompactor.ts\";\nimport { boundedCanonicalJsonSnapshot } from \"./provider-result-staging.ts\";\n\n/**\n * Pure helpers for engine-native context compaction (RUN-026/RUN-027). Everything here is deterministic and side-effect free:\n * the engine's turn loop owns the state transitions, the durable coordinator\n * owns the canonical record, and this module owns the arithmetic.\n *\n * Compaction is a VIEW over official history, never a mutation of it. The\n * durable commit machinery slices official history by length\n * (`lastCommitLen` in the coordinator), so official history must stay\n * append-only within an Attempt; only the outgoing model prompt is rebuilt.\n */\n\n/** Model-visible replacement for a tool result cleared by prune compaction. */\nexport const CLEARED_TOOL_RESULT = \"[tool result cleared by compaction]\";\n\n/** Prefix of the user message that carries a compaction summary into the prompt. */\nexport const COMPACTION_SUMMARY_PREFIX = \"The prior thread was compacted into this summary:\\n\\n\";\n\n/** Rollover text is recovery evidence; it never asserts that an external action succeeded. */\nexport const CONTEXT_ROLLOVER_PREFIX =\n \"A fresh context window has started. Earlier conversation has left this model view. Restore relevant notes and use available history tools to retrieve evidence; verify live state before repeating an action.\\n\\n\";\n\n/** Stable across Attempts; the initial window uses turn zero. */\nexport const contextWindowId = (runId: string, turn: number): string => `context:${runId}:${turn}`;\n\n/** Shared by the live interpreter and canonical journal projection. */\nexport const contextWindowMessage = (windowId: string, handoff?: string): Prompt.Message =>\n Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${CONTEXT_ROLLOVER_PREFIX}Window: ${windowId}${handoff === undefined ? \"\" : `\\n\\nHandoff (untrusted continuation notes):\\n${handoff}`}`,\n }),\n ],\n });\n\n/**\n * Fixed summarization instruction (RUN-026). The skeleton mirrors what the\n * surveyed harnesses converged on; exact file paths and identifiers must\n * survive because the continuing agent sees only this summary plus the tail.\n */\nexport const COMPACTION_INSTRUCTION = [\n \"You are compacting an agent thread to reclaim context space.\",\n \"Summarize the transcript below for the SAME agent to continue working:\",\n \"it will see only this summary plus the most recent messages.\",\n \"Structure the summary exactly as:\",\n \"Goal:\",\n \"Constraints:\",\n \"Progress:\",\n \"Decisions:\",\n \"Next steps:\",\n \"Critical context:\",\n \"Be terse. Preserve exact file paths, identifiers, and values needed to\",\n \"continue. Do not continue the thread; output only the summary.\",\n].join(\"\\n\");\n\n/**\n * Provider context-length rejections, matched case-insensitively over the\n * error's own text. Kept intentionally broad: a false positive costs one\n * summarize-and-retry, a false negative surfaces the raw provider error.\n */\nconst CONTEXT_OVERFLOW_PATTERN =\n /context[\\s_-]?length|prompt is too long|maximum context (?:length|window)|input .{0,24}too long|exceeds .{0,24}context|too many (?:input )?tokens|context[\\s_-]?window[\\s_-]?exceeded|context overflow/i;\n\n/** RUN-027: does this provider error text describe a context-window overflow? */\nexport const isContextOverflowMessage = (text: string): boolean =>\n CONTEXT_OVERFLOW_PATTERN.test(text);\n\nconst utf8Length = (text: string): number => {\n let bytes = text.length;\n\n for (let index = 0; index < text.length; index++) {\n const codeUnit = text.charCodeAt(index);\n\n if (codeUnit <= 0x7f) continue;\n if (codeUnit <= 0x7ff) {\n bytes++;\n continue;\n }\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff && index + 1 < text.length) {\n const next = text.charCodeAt(index + 1);\n\n if (next >= 0xdc00 && next <= 0xdfff) {\n // The two UTF-16 code units already contributed two of the four UTF-8 bytes.\n bytes += 2;\n index++;\n continue;\n }\n }\n bytes += 2;\n }\n\n return bytes;\n};\n\n/**\n * Deterministic UTF-8 bytes/4 token estimate over one message's structural JSON.\n * Conservative for prose, slightly generous for dense JSON — the estimate\n * only gates WHEN to compact, never what is preserved.\n */\nexport const estimateMessageTokens = (message: Prompt.Message): number => {\n let text: string | undefined;\n\n try {\n text = JSON.stringify(message);\n } catch {\n text = undefined;\n }\n\n return text === undefined ? 0 : Math.ceil(utf8Length(text) / 4);\n};\n\n/** Sum of `estimateMessageTokens` over a message array. */\nexport const estimatePromptTokens = (\n messages: ReadonlyArray<Prompt.Message>,\n estimate: (message: Prompt.Message) => number = estimateMessageTokens,\n): number => {\n let total = 0;\n\n for (const message of messages) {\n total += estimate(message);\n }\n\n return total;\n};\n\nconst isTokenEstimate = Schema.is(Schema.Natural);\n\n/** Validate each replacement at the Effect caller's boundary without throwing from arithmetic. */\nexport const evaluateMessageTokenEstimates = <A>(\n override: ContextMessageTokenEstimator | undefined,\n operation: (estimate: (message: Prompt.Message) => number) => A,\n): Option.Option<A> => {\n let valid = true;\n\n const value = operation((message) => {\n const replacement = override?.(message);\n const estimate = replacement === undefined ? estimateMessageTokens(message) : replacement;\n\n if (!isTokenEstimate(estimate)) valid = false;\n\n return estimate;\n });\n\n return valid ? Option.some(value) : Option.none();\n};\n\n/**\n * Mutable per-Run compaction state held on the engine's RunContext. Indices\n * are positions in the SOURCE prompt (the official-history basis handed to\n * each Turn). Ordinary history grows append-only. Prepared history must retain\n * content-equivalent covered prefixes or the engine rejects the next Turn.\n */\nexport interface ContextCompactionState {\n /**\n * Source-index bounds `[start, end)` of the protected instruction/input\n * block, mapped to prepared indices when necessary. `-1` before mapping;\n * an unmappable protected block fails before any compaction decision.\n */\n protectedStart: number;\n protectedEnd: number;\n /** Prepared prompts also retain application-added system instructions. */\n protectSystemMessages?: boolean;\n /** Tool messages at source index below this bound render as cleared. */\n clearedThrough: number;\n /**\n * Source messages below this bound (outside the protected block) are\n * replaced by a summary or a fresh-window marker. Absent before the first replacement.\n */\n replacement:\n | { readonly kind: \"summarize\"; readonly through: number; readonly summary: string }\n | {\n readonly kind: \"rollover\";\n readonly through: number;\n readonly windowId: string;\n readonly handoff?: string;\n }\n | undefined;\n /** Loop guard: at most one threshold compaction per Turn. */\n lastCompactionTurn: number;\n /** RUN-027 guard: at most one overflow compact-and-retry per Turn. */\n overflowRetryTurn: number;\n /**\n * View length at the last model call, the base of the provider-anchored\n * estimate. `-1` invalidates it (fresh Run or just compacted), forcing a\n * full-view estimate.\n */\n lastViewLength: number;\n}\n\n/** Fresh compaction state for a new Run. */\nexport const initialCompactionState = (): ContextCompactionState => ({\n protectedStart: -1,\n protectedEnd: -1,\n clearedThrough: 0,\n replacement: undefined,\n lastCompactionTurn: 0,\n overflowRetryTurn: 0,\n lastViewLength: -1,\n});\n\nconst isProtected = (\n state: ContextCompactionState,\n source: ReadonlyArray<Prompt.Message>,\n index: number,\n): boolean => {\n if (state.protectSystemMessages && source[index]?.role === \"system\") return true;\n if (state.protectedStart >= 0) {\n return index >= state.protectedStart && index < state.protectedEnd;\n }\n\n return source[index]?.role === \"system\";\n};\n\nconst clearedToolMessage = (message: Prompt.Message): Prompt.Message => {\n if (message.role !== \"tool\" || typeof message.content === \"string\") {\n return message;\n }\n\n // Structural rebuild keeps the message's pairing identity (same part ids\n // and names) while replacing only the result payloads the model would see.\n return Prompt.makeMessage(\"tool\", {\n content: message.content.map((part) =>\n part.type === \"tool-result\"\n ? Prompt.makePart(\"tool-result\", {\n id: part.id,\n name: part.name,\n result: CLEARED_TOOL_RESULT,\n isFailure: part.isFailure,\n providerExecuted: part.providerExecuted,\n })\n : part,\n ),\n });\n};\n\nconst renderMessage = (\n state: ContextCompactionState,\n message: Prompt.Message,\n index: number,\n): Prompt.Message =>\n index < state.clearedThrough && message.role === \"tool\" ? clearedToolMessage(message) : message;\n\nconst summaryMessage = (summary: string): Prompt.Message =>\n Prompt.makeMessage(\"user\", {\n content: [Prompt.makePart(\"text\", { text: `${COMPACTION_SUMMARY_PREFIX}${summary}` })],\n });\n\n/**\n * Build the model-visible view of the source prompt under the current\n * compaction state: protected block in place, covered span replaced by the\n * summary message, old tool results cleared. Identity when no compaction has\n * happened.\n */\nexport const buildCompactedView = (\n source: ReadonlyArray<Prompt.Message>,\n state: ContextCompactionState,\n): ReadonlyArray<Prompt.Message> => {\n if (state.replacement === undefined && state.clearedThrough === 0) {\n return source;\n }\n const view: Array<Prompt.Message> = [];\n\n if (state.replacement !== undefined && state.replacement.through > 0) {\n const protectedStart =\n state.protectedStart >= 0 && !state.protectSystemMessages ? state.protectedStart : 0;\n\n const protectedEnd =\n state.protectedStart >= 0 && !state.protectSystemMessages\n ? state.protectedEnd\n : (state.replacement?.through ?? 0);\n\n for (\n let index = protectedStart;\n index < Math.min(protectedEnd, state.replacement?.through ?? 0, source.length);\n index += 1\n ) {\n const message = source[index];\n\n if (message !== undefined && isProtected(state, source, index)) {\n view.push(renderMessage(state, message, index));\n }\n }\n view.push(\n state.replacement.kind === \"summarize\"\n ? summaryMessage(state.replacement.summary)\n : contextWindowMessage(state.replacement.windowId, state.replacement.handoff),\n );\n for (let index = state.replacement?.through ?? 0; index < source.length; index += 1) {\n const message = source[index];\n\n if (message !== undefined) {\n view.push(renderMessage(state, message, index));\n }\n }\n\n return view;\n }\n for (let index = 0; index < source.length; index += 1) {\n const message = source[index];\n\n if (message !== undefined) {\n view.push(renderMessage(state, message, index));\n }\n }\n\n return view;\n};\n\n/**\n * Prune selection: the new `clearedThrough` bound. Walks tool messages\n * newest→oldest, always protecting the most recent tool message (the model\n * has not reacted to it yet), then protecting older ones while their\n * estimates fit inside `keepRecentTokens`. If the whole view exceeds `targetTokens`,\n * clear more older results until it fits or only the newest result remains.\n * Replaced messages consume no retention budget. Never decreases the bound.\n */\nexport const choosePruneBound = (\n source: ReadonlyArray<Prompt.Message>,\n state: ContextCompactionState,\n keepRecentTokens: number,\n targetTokens?: number,\n estimate: (message: Prompt.Message) => number = estimateMessageTokens,\n): number => {\n const toolIndices: Array<number> = [];\n\n for (let index = 0; index < source.length; index += 1) {\n if (\n index >= (state.replacement?.through ?? 0) &&\n source[index]?.role === \"tool\" &&\n !isProtected(state, source, index)\n ) {\n toolIndices.push(index);\n }\n }\n if (toolIndices.length <= 1) {\n return state.clearedThrough;\n }\n let budget = keepRecentTokens;\n let newestCleared = -1;\n\n for (let position = toolIndices.length - 1; position >= 0; position -= 1) {\n const index = toolIndices[position];\n\n if (index === undefined) continue;\n const message = source[index];\n\n if (message === undefined) continue;\n if (position === toolIndices.length - 1) {\n budget -= estimate(message);\n continue;\n }\n const cost = estimate(message);\n\n if (budget - cost >= 0 && index >= state.clearedThrough) {\n budget -= cost;\n continue;\n }\n newestCleared = index;\n break;\n }\n\n let through =\n newestCleared === -1 ? state.clearedThrough : Math.max(state.clearedThrough, newestCleared + 1);\n\n if (targetTokens === undefined) return through;\n\n let estimated = estimatePromptTokens(\n buildCompactedView(source, { ...state, clearedThrough: through }),\n estimate,\n );\n\n for (\n let position = 0;\n position < toolIndices.length - 1 && estimated > targetTokens;\n position += 1\n ) {\n const index = toolIndices[position];\n\n if (index === undefined || index < through) continue;\n const message = source[index];\n\n if (message === undefined) continue;\n through = index + 1;\n estimated -= estimate(message) - estimate(clearedToolMessage(message));\n }\n\n return through;\n};\n\n/**\n * Summarize selection: the source cut index `C` — messages `[0, C)` outside\n * the protected block fold into the summary; `[C, …)` is the kept tail.\n * Walks newest→oldest accumulating view estimates until `keepRecentTokens`\n * is retained, then moves the cut down to keep leading user/system messages\n * with their assistant response and tool results with their declaring assistant.\n */\nexport const chooseSummarizeCut = (\n source: ReadonlyArray<Prompt.Message>,\n state: ContextCompactionState,\n keepRecentTokens: number,\n estimate: (message: Prompt.Message) => number = estimateMessageTokens,\n): number => {\n let kept = 0;\n let cut = 0;\n\n for (let index = source.length - 1; index >= 0; index -= 1) {\n const message = source[index];\n\n if (message === undefined) continue;\n kept += estimate(renderMessage(state, message, index));\n if (kept >= keepRecentTokens) {\n cut = index;\n break;\n }\n }\n // Durable responses commit pending input and the assistant reply together.\n while (\n cut > 0 &&\n (source[cut]?.role === \"tool\" ||\n source[cut - 1]?.role === \"user\" ||\n source[cut - 1]?.role === \"system\")\n ) {\n cut -= 1;\n }\n\n return Math.max(cut, state.replacement?.through ?? 0);\n};\n\n/**\n * The messages a cut NEWLY covers — from the prior replacement boundary to the\n * cut, protected block excluded, in order. Starting at the replacement boundary\n * keeps repeated compactions incremental: the previously covered span lives\n * on only through the previous summary, never as resubmitted raw history.\n */\nexport const collectCoveredMessages = (\n source: ReadonlyArray<Prompt.Message>,\n state: ContextCompactionState,\n cut: number,\n): ReadonlyArray<Prompt.Message> => {\n const covered: Array<Prompt.Message> = [];\n\n for (\n let index = Math.max(0, state.replacement?.through ?? 0);\n index < cut && index < source.length;\n index += 1\n ) {\n const message = source[index];\n\n if (message !== undefined && !isProtected(state, source, index)) {\n covered.push(message);\n }\n }\n\n return covered;\n};\n\nconst SUMMARY_TOOL_RESULT_CLIP = 2_000;\n\nconst jsonPreview = (value: unknown, limit: number): string => {\n if (typeof value === \"string\") return JSON.stringify(value.slice(0, limit)).slice(0, limit);\n const snapshot = boundedCanonicalJsonSnapshot(value, limit);\n\n return snapshot === undefined\n ? \"[omitted oversized or unsupported JSON]\"\n : JSON.stringify(snapshot.value);\n};\n\nconst partText = (part: Prompt.Message[\"content\"][number] | string): string => {\n if (typeof part === \"string\") return part;\n switch (part.type) {\n case \"text\": {\n return part.text;\n }\n case \"reasoning\": {\n return \"\";\n }\n case \"tool-call\": {\n return `[tool call ${part.name.slice(0, 500)} ${jsonPreview(part.params, 500)}]`;\n }\n case \"tool-result\": {\n return `[tool result ${part.name.slice(0, 500)}: ${jsonPreview(part.result, SUMMARY_TOOL_RESULT_CLIP)}]`;\n }\n default: {\n return `[${part.type}]`;\n }\n }\n};\n\n/**\n * Character budget for the complete default summarizer request, including\n * its instruction, transcript delimiters, previous summary, and elision marker.\n */\nexport const SUMMARY_INPUT_BUDGET = 80_000;\nexport const SUMMARY_MAX_LENGTH = 65_536;\nexport const SUMMARY_REQUEST_PREFIX = `${COMPACTION_INSTRUCTION}\\n\\n<transcript>\\n`;\nexport const SUMMARY_REQUEST_SUFFIX = \"\\n</transcript>\";\n\nconst SUMMARY_MESSAGE_CLIP = 2_000;\nconst SUMMARY_ELISION_RESERVE = 128;\n\nconst summaryBlock = (message: Prompt.Message): string => {\n let text = \"\";\n\n if (typeof message.content === \"string\") {\n text = message.content.slice(0, SUMMARY_MESSAGE_CLIP + 1);\n } else {\n for (const part of message.content) {\n const piece = partText(part);\n\n if (piece.length === 0) continue;\n if (text.length > 0) text += \"\\n\";\n text += piece.slice(0, SUMMARY_MESSAGE_CLIP + 1 - text.length);\n if (text.length > SUMMARY_MESSAGE_CLIP) break;\n }\n }\n if (text.length === 0) return \"\";\n\n return `[${message.role}]\\n${text.length > SUMMARY_MESSAGE_CLIP ? `${text.slice(0, SUMMARY_MESSAGE_CLIP)}…` : text}`;\n};\n\n/**\n * Deterministic emergency input record, not a progress summary. Keep recent user inputs and\n * the last, as-yet-unconsumed Tool batch. Clip before rendering large payloads, identify Tool\n * calls for archive lookup, and never recursively copy earlier recovery records.\n */\nexport const buildRolloverHandoff = (\n source: ReadonlyArray<Prompt.Message>,\n state: ContextCompactionState,\n targetTokens: number | undefined,\n through = source.length,\n estimate: (message: Prompt.Message) => number = estimateMessageTokens,\n): string | undefined => {\n const protectedTokens = estimatePromptTokens(\n source.filter((_, index) => index >= through || isProtected(state, source, index)),\n estimate,\n );\n\n const maxChars = Math.min(\n 5_000,\n Math.max(0, Math.floor(((targetTokens ?? 10_000) - protectedTokens - 200) * 2)),\n );\n\n if (maxChars < 160) return undefined;\n const blocks: Array<string> = [];\n let length = 0;\n const start = state.replacement?.through ?? 0;\n\n const lastTool = source.findLastIndex(\n (message, index) => index < through && message.role === \"tool\",\n );\n\n const unconsumed =\n lastTool >= start &&\n !source.slice(lastTool + 1, through).some((message) => message.role === \"assistant\");\n\n let lastAssistant = lastTool;\n\n while (lastAssistant >= start && source[lastAssistant]?.role !== \"assistant\") lastAssistant -= 1;\n for (let index = through - 1; index >= start; index -= 1) {\n const message = source[index];\n\n if (message === undefined || isProtected(state, source, index)) continue;\n const isUnconsumedBatch = unconsumed && index >= lastAssistant && index <= lastTool;\n\n if (message.role !== \"user\" && !isUnconsumedBatch) continue;\n // A projected boundary from a previous Attempt is already a derived handoff.\n if (\n message.role === \"user\" &&\n message.content.some(\n (part) => part.type === \"text\" && part.text.startsWith(CONTEXT_ROLLOVER_PREFIX),\n )\n )\n continue;\n let block = summaryBlock(message);\n\n if (isUnconsumedBatch && typeof message.content !== \"string\") {\n const ids = message.content\n .flatMap((part) =>\n part.type === \"tool-call\" || part.type === \"tool-result\" ? [part.id.slice(0, 256)] : [],\n )\n .slice(0, 16);\n\n block = `[Unconsumed batch; history search call IDs: ${ids.join(\", \")}]\\n${block}`;\n }\n const remaining = maxChars - length - 120;\n\n if (remaining <= 0) break;\n const selected = block.slice(0, Math.min(2_500, remaining));\n\n blocks.unshift(selected);\n length += selected.length + 2;\n if (selected.length < block.length) break;\n }\n\n return `Recovery excerpts, not verified progress. Content may be omitted; use notes and history.\\n\\n${blocks.join(\"\\n\\n\")}`.slice(\n 0,\n maxChars,\n );\n};\n\n/**\n * Render the covered span as plain text for the summarizer call, bounded\n * twice: every message's rendered text is clipped to a fixed length (tool\n * results additionally clip their JSON payloads), and the whole render obeys\n * `SUMMARY_INPUT_BUDGET` with middle-out retention — oldest and newest\n * blocks survive, the middle collapses into one deterministic elision\n * marker. A previous summary is folded in first so nothing silently drops\n * out of coverage across repeated compactions. An oversized previous summary\n * returns undefined before rendering: callers must reject it, never truncate it.\n */\nexport const renderForSummary = (\n covered: ReadonlyArray<Prompt.Message>,\n previousSummary: string | undefined,\n): string | undefined => {\n if (previousSummary !== undefined && previousSummary.length > SUMMARY_MAX_LENGTH)\n return undefined;\n const joiner = \"\\n\\n\";\n\n const previousBlock =\n previousSummary === undefined ? undefined : `[Previous summary]\\n${previousSummary}`;\n\n const fixed =\n (previousBlock === undefined ? 0 : previousBlock.length + joiner.length) +\n SUMMARY_REQUEST_PREFIX.length +\n SUMMARY_REQUEST_SUFFIX.length;\n\n const budget = SUMMARY_INPUT_BUDGET - fixed - SUMMARY_ELISION_RESERVE;\n const head: Array<string> = [];\n const tail: Array<string> = [];\n let length = 0;\n let start = 0;\n let end = covered.length - 1;\n let boundaryBlock: string | undefined;\n\n while (start <= end) {\n const message = covered[start];\n const block = message === undefined ? \"\" : summaryBlock(message);\n\n if (block.length > 0 && length + block.length + joiner.length > Math.floor(budget / 2)) {\n boundaryBlock = block;\n break;\n }\n if (block.length > 0) {\n head.push(block);\n length += block.length + joiner.length;\n }\n start += 1;\n }\n while (end >= start) {\n const message = covered[end];\n\n const block =\n end === start && boundaryBlock !== undefined\n ? boundaryBlock\n : message === undefined\n ? \"\"\n : summaryBlock(message);\n\n if (block.length > 0 && length + block.length + joiner.length > budget) break;\n if (block.length > 0) {\n tail.push(block);\n length += block.length + joiner.length;\n }\n end -= 1;\n }\n const omitted = end - start + 1;\n const lines: Array<string> = [];\n\n if (previousBlock !== undefined) {\n lines.push(previousBlock);\n }\n lines.push(...head);\n if (omitted > 0) lines.push(`[… ${omitted} messages omitted from summary input …]`);\n lines.push(...tail.reverse());\n\n return lines.join(joiner);\n};\n"],"mappings":";;;AAEA,MAAM,iBAAiB;AAOvB,MAAM,iBAAiB,OAAO,mDAAmD;;;;;;AAOjF,MAAM,gBACJ,MACA,UACA,UACA,2BACoC;CACpC,IACE,CAAC,OAAO,cAAc,QAAQ,KAC9B,WAAW,KACX,CAAC,OAAO,cAAc,QAAQ,KAC9B,WAAW,GAEX;CAEF,IAAI,QAAQ;CACZ,MAAM,4BAAY,IAAI,QAAgB;CAEtC,MAAM,OAAO,UAA2B;EACtC,IAAI,QAAQ,WAAW,OAAO,OAAO;EACrC,SAAS;EAET,OAAO;CACT;CAEA,MAAM,aAAa,UAA2B;EAC5C,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO;EACpB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;GACpD,MAAM,OAAO,MAAM,WAAW,KAAK;GAEnC,IAAI,SAAS,MAAQ,SAAS,IACxB;QAAA,CAAC,IAAI,CAAC,GAAG,OAAO;GAAA,OACf,IAAI,QAAQ,IAGb;QAAA,CAAC,IAAI,QAAQ,KAAQ,QAAQ,MAAQ,SAAS,KAAO,IAAI,CAAC,GAAG,OAAO;GAAA,OACnE,IAAI,QAAQ,KACb;QAAA,CAAC,IAAI,CAAC,GAAG,OAAO;GAAA,OACf,IAAI,QAAQ,MACb;QAAA,CAAC,IAAI,CAAC,GAAG,OAAO;GAAA,OACf,IAAI,QAAQ,SAAU,QAAQ,OAAQ;IAC3C,MAAM,MAAM,MAAM,WAAW,QAAQ,CAAC;IAEtC,IAAI,OAAO,SAAU,OAAO,OAAQ;KAClC,IAAI,CAAC,IAAI,CAAC,GAAG,OAAO;KACpB,SAAS;IACX,OAAO,IAAI,CAAC,IAAI,CAAC,GACf,OAAO;GAEX,OAA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A,aAAa,OAAO;EAE5B,IAAI,MAAM,SAAS,KAAK,SAAS,MAAM,SAAS,IAAgB,QAAQ;EACxE,IAAI,MAAM,SAAS,GAAG;GACpB,KAAK,KAAK,KAAK;GACf,UAAU,MAAM,SAAS;EAC3B;EACA,OAAO;CACT;CACA,MAAM,UAAU,MAAM,QAAQ;CAC9B,MAAM,QAAuB,CAAC;CAE9B,IAAI,kBAAkB,KAAA,GACpB,MAAM,KAAK,aAAa;CAE1B,MAAM,KAAK,GAAG,IAAI;CAClB,IAAI,UAAU,GAAG,MAAM,KAAK,MAAM,QAAQ,wCAAwC;CAClF,MAAM,KAAK,GAAG,KAAK,QAAQ,CAAC;CAE5B,OAAO,MAAM,KAAK,MAAM;AAC1B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"output-contract-DS-S8mTv.mjs","names":[],"sources":["../src/engine/internal/output-contract.ts"],"sourcesContent":["import { Schema } from \"effect\";\nimport { Prompt, Tool } from \"effect/unstable/ai\";\n\nimport type * as Agent from \"../../core/Agent.ts\";\n\nconst outputFormatAnnotation = \"@effect-agent/engine/Output/format\";\n\n/**\n * Declare ordinary assistant text as an Agent's final-output wire format. Apply this to the\n * complete output Schema after composing transformations. Its encoded type must be string;\n * decoding, checks, transformations, and service requirements remain owned by that Schema.\n * Text is preserved verbatim, including whitespace, quotes, and an empty reply when allowed.\n * Required completion Tools still take precedence. Unmarked Schemas use JSON final output.\n *\n * @example\n * ```ts\n * output: Output.text(Schema.String.check(Schema.isMaxLength(20_000)))\n * ```\n */\nexport const textOutput = <S extends Schema.Top & { readonly Encoded: string }>(\n schema: S,\n): S[\"Rebuild\"] => schema.annotate({ [outputFormatAnnotation]: \"text\" });\n\nexport const isTextOutput = (schema: Schema.Top): boolean =>\n Schema.resolveAnnotations(schema)?.[outputFormatAnnotation] === \"text\";\n\n/**\n * Model-visible final-output contract (RUN-028).\n *\n * For ordinary text completion, the interpreter's only output-conformance\n * point is `decodeFinalOutput`, which validates the final text after the\n * model has already finished. This module renders that Schema's wire contract\n * with the same Effect AI derivation the providers use for Tool parameters\n * and states it as one framework-owned system message on every model request.\n * A required completion Tool instead gets a native-tool directive: its Tool\n * parameter Schema is already carried by the provider request, and ordinary\n * final text is not an allowed completion path.\n *\n * The contract is a per-request projection of the immutable definition —\n * exactly like the Tool schemas the request already carries. It is inserted\n * at model-request materialization (after context preparation) and never\n * into official history, so canonical records, run events, and the committed\n * DN/DC golden are unchanged.\n *\n */\n\n/** Rendering outcome for one definition's output Schema. */\ntype OutputContract =\n | {\n readonly _tag: \"rendered\";\n /** The complete system-message text: directive plus the derived JSON Schema. */\n readonly message: string;\n readonly part: Prompt.SystemMessage;\n }\n | {\n readonly _tag: \"unrenderable\";\n /** Why Effect AI's JSON-Schema derivation rejected the output Schema. */\n readonly reason: string;\n };\n\nconst contractDirective = (definition: Agent.AnyDefinition): string =>\n definition.completion === undefined\n ? \"Final output contract: when the task is complete, the final assistant message must be only \" +\n \"JSON that is valid against this JSON Schema — no prose, no Markdown code fences, nothing \" +\n \"before or after the JSON.\"\n : `Final output contract: when the task is complete without calling the \"${definition.completion.tool}\" completion Tool, the final assistant message must be only ` +\n \"JSON that is valid against this JSON Schema — no prose, no Markdown code fences, nothing \" +\n `before or after the JSON. When calling the \"${definition.completion.tool}\" completion Tool, never place this private Agent output JSON in any Tool argument; follow the Tool's parameter schema instead. Call it as the sole application Tool Call, after receiving any other needed application Tool results. Completed provider Tool results may accompany it. The engine projects the successful completion Tool result into the Agent output.`;\n\nconst requiredCompletionDirective = (tool: string, hasAlternatives: boolean): string =>\n `Final output contract: ${hasAlternatives ? \"otherwise complete\" : \"complete only\"} by calling the required completion Tool ${JSON.stringify(tool)} ` +\n \"as the sole application Tool Call in its batch. Completed provider Tool results may accompany it. Do not emit an ordinary final assistant text answer. \" +\n \"The Tool's canonical parameters and successful result are projected and validated as the Agent output.\";\n\n/**\n * Render the model-visible final-output contract for one definition. The\n * derivation and message identity are stable for an immutable definition.\n * An output Schema the Effect AI derivation cannot represent is reported as\n * `unrenderable`; the caller falls back to the prior behavior — the contract\n * is guidance, and a Schema that decodes but does not render must not become\n * a new failure mode.\n */\nconst rendered = (message: string): OutputContract => ({\n _tag: \"rendered\",\n message,\n part: Prompt.makeMessage(\"system\", { content: message }),\n});\n\nconst renderOutputSchemaContract = (definition: Agent.AnyDefinition): OutputContract => {\n if (definition.completion?.required === true) {\n return rendered(\n requiredCompletionDirective(\n definition.completion.tool,\n (definition.completionFromTools?.length ?? 0) > 0,\n ),\n );\n }\n if (isTextOutput(definition.output)) {\n return rendered(\n \"Final output contract: write the final reply as ordinary assistant text, without JSON wrapping. \" +\n \"An empty reply is valid only when allowed by the output Schema and the task instructions.\" +\n (definition.completion === undefined\n ? \"\"\n : ` When calling the \"${definition.completion.tool}\" completion Tool, follow its parameter schema instead and call it as the sole application Tool Call, after receiving any other needed application Tool results; completed provider Tool results may accompany it; the engine projects its successful result into the Agent output.`),\n );\n }\n try {\n const jsonSchema = Tool.getJsonSchemaFromSchema(definition.output);\n\n return rendered(\n `${contractDirective(definition)}\\n\\n${JSON.stringify(jsonSchema, undefined, 2)}`,\n );\n } catch (cause) {\n return {\n _tag: \"unrenderable\",\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n};\n\n// Native incremental-response tracking recognizes message objects, not rendered text.\n// Weak keys retain neither discarded definitions nor their Schema graphs.\nconst outputContracts = new WeakMap<Agent.AnyDefinition, OutputContract>();\n\nexport const outputSchemaContract = (definition: Agent.AnyDefinition): OutputContract => {\n const cached = outputContracts.get(definition);\n\n if (cached !== undefined) return cached;\n const base = renderOutputSchemaContract(definition);\n const alternatives = definition.completionFromTools ?? [];\n\n const contract =\n base._tag === \"rendered\" && alternatives.length > 0\n ? rendered(\n `The following action Tools may complete the Run from their successful canonical result: ${alternatives.map((declaration) => JSON.stringify(declaration.tool)).join(\", \")}. ` +\n \"Call such a Tool as the sole application Tool Call, following its parameter schema. Completed provider Tool results may accompany it. It may complete the Run only when it satisfies the whole request. \" +\n \"An incomplete or pending result continues the Run. These actions are unavailable during finalization after budget exhaustion.\\n\\n\" +\n base.message,\n )\n : base;\n\n outputContracts.set(definition, contract);\n\n return contract;\n};\n\nconst sameSystemMessage = Schema.toEquivalence(Prompt.SystemMessage);\n\n/**\n * Keep supported system instructions in conversation order so changing late guidance\n * cannot invalidate the preceding user/tool cache prefix. Omit an exact repeat\n * only when no distinct system instruction intervened; returning to an earlier\n * instruction after a different one must preserve the new directive's precedence.\n * Anchor the immutable output contract after the initial system block.\n * Restore leading static instructions for caller-supplied conversation-only history.\n *\n * This runs after preparation and compaction. Canonical messages, protected\n * instruction/input spans and compaction coverage retain their original positions.\n * Adapters without this capability retain the grouped-system projection: keep the\n * last equivalent instruction with its native options, then the contract and\n * conversation. This prevents older Anthropic adapters from discarding system groups.\n */\nexport const prepareModelPrompt = (\n prompt: Prompt.Prompt,\n contract: Prompt.SystemMessage | undefined,\n systemMessagesInHistory: boolean,\n staticInstructions: Prompt.RawInput | undefined,\n): Prompt.Prompt => {\n if (systemMessagesInHistory) {\n const content: Array<Prompt.Message> = [];\n let lastSystem: Prompt.SystemMessage | undefined;\n let ordered = prompt.content;\n\n if (staticInstructions !== undefined) {\n const firstConversation = prompt.content.findIndex((message) => message.role !== \"system\");\n\n const leading = prompt.content.slice(\n 0,\n firstConversation === -1 ? prompt.content.length : firstConversation,\n );\n\n const restored: Array<Prompt.Message> = [];\n\n const instructions =\n typeof staticInstructions === \"string\"\n ? [Prompt.systemMessage({ content: staticInstructions })]\n : Prompt.make(staticInstructions).content;\n\n for (const message of instructions) {\n if (message.role !== \"system\") break;\n if (\n leading.some(\n (candidate) => candidate.role === \"system\" && sameSystemMessage(candidate, message),\n )\n )\n break;\n\n const original = prompt.content.find(\n (candidate) => candidate.role === \"system\" && sameSystemMessage(candidate, message),\n );\n\n if (original === undefined) break;\n restored.push(original);\n }\n if (restored.length > 0)\n ordered = [...leading, ...restored, ...prompt.content.slice(leading.length)];\n }\n\n for (const message of ordered) {\n if (message.role === \"system\") {\n if (lastSystem !== undefined && sameSystemMessage(lastSystem, message)) continue;\n lastSystem = message;\n }\n content.push(message);\n }\n if (contract !== undefined) {\n const firstConversation = content.findIndex((message) => message.role !== \"system\");\n\n content.splice(firstConversation === -1 ? content.length : firstConversation, 0, contract);\n }\n\n return Prompt.fromMessages(content);\n }\n\n const systems: Array<Prompt.SystemMessage> = [];\n const conversation: Array<Prompt.Message> = [];\n const seen = new Map<string, Array<Prompt.SystemMessage>>();\n\n for (let index = prompt.content.length - 1; index >= 0; index -= 1) {\n const message = prompt.content[index];\n\n if (message === undefined) continue;\n if (message.role !== \"system\") {\n conversation.push(message);\n continue;\n }\n const variants = seen.get(message.content);\n\n if (variants?.some((previous) => sameSystemMessage(previous, message))) continue;\n if (variants === undefined) seen.set(message.content, [message]);\n else variants.push(message);\n systems.push(message);\n }\n\n return Prompt.fromMessages([\n ...systems.reverse(),\n ...(contract === undefined ? [] : [contract]),\n ...conversation.reverse(),\n ]);\n};\n"],"mappings":";;;AAKA,MAAM,yBAAyB;;;;;;;;;;;;;AAc/B,MAAa,cACX,WACiB,OAAO,SAAS,GAAG,yBAAyB,OAAO,CAAC;AAEvE,MAAa,gBAAgB,WAC3B,OAAO,mBAAmB,MAAM,CAAC,GAAG,4BAA4B;AAoClE,MAAM,qBAAqB,eACzB,WAAW,eAAe,KAAA,IACtB,kNAGA,yEAAyE,WAAW,WAAW,KAAK,mMAErD,WAAW,WAAW,KAAK;AAEhF,MAAM,+BAA+B,MAAc,oBACjD,0BAA0B,kBAAkB,uBAAuB,gBAAgB,2CAA2C,KAAK,UAAU,IAAI,EAAE;;;;;;;;;AAYrJ,MAAM,YAAY,aAAqC;CACrD,MAAM;CACN;CACA,MAAM,OAAO,YAAY,UAAU,EAAE,SAAS,QAAQ,CAAC;AACzD;AAEA,MAAM,8BAA8B,eAAoD;CACtF,IAAI,WAAW,YAAY,aAAa,MACtC,OAAO,SACL,4BACE,WAAW,WAAW,OACrB,WAAW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