@effect-agent/testing 0.1.0-beta.9 → 0.1.0-beta.90

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.
Files changed (55) hide show
  1. package/dist/Certification.d.mts +106 -0
  2. package/dist/Certification.mjs +633 -0
  3. package/dist/Certification.mjs.map +1 -0
  4. package/dist/Chaos.d.mts +126 -0
  5. package/dist/Chaos.mjs +755 -0
  6. package/dist/Chaos.mjs.map +1 -0
  7. package/dist/CodeExecutorConformance.d.mts +33 -0
  8. package/dist/CodeExecutorConformance.mjs +231 -0
  9. package/dist/CodeExecutorConformance.mjs.map +1 -0
  10. package/dist/CodeExecutorSubstitute.d.mts +21 -0
  11. package/dist/CodeExecutorSubstitute.mjs +368 -0
  12. package/dist/CodeExecutorSubstitute.mjs.map +1 -0
  13. package/dist/DocsResearcher.d.mts +276 -0
  14. package/dist/DocsResearcher.mjs +490 -0
  15. package/dist/DocsResearcher.mjs.map +1 -0
  16. package/dist/ScriptedModel-DAvxIiud.d.mts +220 -0
  17. package/dist/ScriptedModel.d.mts +2 -0
  18. package/dist/ScriptedModel.mjs +155 -0
  19. package/dist/ScriptedModel.mjs.map +1 -0
  20. package/dist/TravelPlanner.d.mts +1680 -0
  21. package/dist/TravelPlanner.mjs +1963 -0
  22. package/dist/TravelPlanner.mjs.map +1 -0
  23. package/dist/deterministic-layers-D5owIoke.mjs +358 -0
  24. package/dist/deterministic-layers-D5owIoke.mjs.map +1 -0
  25. package/dist/index.d.mts +2 -3408
  26. package/dist/index.mjs +2 -4771
  27. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  28. package/package.json +1 -48
  29. package/src/{certification.ts → Certification.ts} +366 -171
  30. package/src/{chaos.ts → Chaos.ts} +241 -127
  31. package/src/{code-executor-conformance.ts → CodeExecutorConformance.ts} +30 -7
  32. package/src/{code-executor-substitute.ts → CodeExecutorSubstitute.ts} +113 -46
  33. package/src/{fixtures/docs-researcher/index.ts → DocsResearcher.ts} +68 -5
  34. package/src/{scripted-model.ts → ScriptedModel.ts} +25 -29
  35. package/src/TravelPlanner.ts +232 -0
  36. package/src/fixtures/docs-researcher/definition.ts +20 -11
  37. package/src/fixtures/docs-researcher/harness.ts +41 -34
  38. package/src/fixtures/docs-researcher/mcp.ts +49 -3
  39. package/src/fixtures/travel-planner/definition.ts +15 -2
  40. package/src/fixtures/travel-planner/deterministic-layers.ts +47 -4
  41. package/src/fixtures/travel-planner/phase2.ts +4 -3
  42. package/src/fixtures/travel-planner/phase3.ts +19 -42
  43. package/src/fixtures/travel-planner/phase4.ts +24 -37
  44. package/src/fixtures/travel-planner/phase5.ts +35 -42
  45. package/src/fixtures/travel-planner/phase6.ts +191 -88
  46. package/src/fixtures/travel-planner/phase7.ts +4 -102
  47. package/src/fixtures/travel-planner/scenarios.ts +3 -4
  48. package/src/fixtures/travel-planner/subagents-durable.ts +35 -61
  49. package/src/fixtures/travel-planner/subagents.ts +36 -14
  50. package/src/index.ts +1 -11
  51. package/src/internal/certification-report.ts +25 -0
  52. package/dist/index.mjs.map +0 -1
  53. package/src/code-executor-conformance.d.ts +0 -30
  54. package/src/fixtures/travel-planner/index.ts +0 -11
  55. package/src/fixtures/warehouse/index.ts +0 -412
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TravelPlanner.mjs","names":["digest","digest","decodeComparableJson","scriptedUsage","researcherLookupParts","researcherReportParts","digestOf","scriptedUsage","researcherLookupParts","researcherReportParts"],"sources":["../src/fixtures/travel-planner/phase2.ts","../src/fixtures/travel-planner/scenarios.ts","../src/fixtures/travel-planner/phase3.ts","../src/fixtures/travel-planner/phase4.ts","../src/fixtures/travel-planner/phase5.ts","../src/fixtures/travel-planner/subagents.ts","../src/fixtures/travel-planner/subagents-durable.ts","../src/fixtures/travel-planner/phase6.ts","../src/fixtures/travel-planner/phase7.ts"],"sourcesContent":["import { Context, Effect, Schema } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n FlightCatalog,\n LodgingCatalog,\n QuoteId,\n SearchActivities,\n SearchFlights,\n SearchLodging,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\n\nexport class ItineraryHoldRequest extends Schema.Class<ItineraryHoldRequest>(\n \"@effect-agent/testing/travel-planner/ItineraryHoldRequest\",\n)({\n quoteId: QuoteId,\n expiresInMinutes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(60)),\n}) {}\n\nexport class ItineraryHold extends Schema.Class<ItineraryHold>(\n \"@effect-agent/testing/travel-planner/ItineraryHold\",\n)({\n holdId: Schema.NonEmptyString,\n quoteId: QuoteId,\n status: Schema.Literal(\"held\"),\n}) {}\n\nexport class ItineraryHoldUnavailable extends Schema.TaggedError<ItineraryHoldUnavailable>()(\n \"ItineraryHoldUnavailable\",\n {\n quoteId: QuoteId,\n message: Schema.String,\n },\n) {}\n\nexport class ItineraryHoldGateway extends Context.Service<\n ItineraryHoldGateway,\n {\n readonly hold: (\n request: ItineraryHoldRequest,\n ) => Effect.Effect<ItineraryHold, ItineraryHoldUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ItineraryHoldGateway\") {}\n\n/**\n * The first mutating Travel Planner Tool. Effect AI marks it as approval-gated\n * so the engine must settle approval before acquiring a handler permit.\n */\nexport const HoldItinerary = Tool.make(\"hold_itinerary\", {\n parameters: ItineraryHoldRequest,\n success: ItineraryHold,\n failure: ItineraryHoldUnavailable,\n failureMode: \"error\",\n dependencies: [ItineraryHoldGateway],\n needsApproval: true,\n});\n\nexport const TravelPlannerPhase2Toolkit = Toolkit.make(\n SearchFlights,\n SearchLodging,\n SearchActivities,\n HoldItinerary,\n);\n\nexport const TravelPlannerPhase2ToolkitLayer = TravelPlannerPhase2Toolkit.toLayer({\n search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),\n search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),\n search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),\n hold_itinerary: (request) =>\n Effect.flatMap(ItineraryHoldGateway, (gateway) => gateway.hold(request)),\n});\n\nexport const TravelPlannerPhase2 = Agent.make(\"travel-planner-phase-2\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase2Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n tokenBudget: 4_096,\n }),\n description:\n \"Build a review-only itinerary and require approval before creating a temporary hold.\",\n metadata: { deploymentClass: \"E\", phase: \"P2\" },\n});\n","import { Schema } from \"effect\";\n\nimport type { ScriptedTurnInput } from \"../../ScriptedModel.ts\";\nimport { TravelPlan, TripRequest, type TravelPlan as TravelPlanValue } from \"./definition.ts\";\n\nconst usage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\nexport const phase1Trip = Schema.decodeSync(TripRequest)({\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n});\n\nexport const expectedTravelPlan: TravelPlanValue = Schema.decodeSync(TravelPlan)({\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284_000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n});\n\nexport const phase1HappyPathTurns = [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n] satisfies readonly [ScriptedTurnInput, ScriptedTurnInput];\n","import { Effect, Schema } from \"effect\";\nimport { AgentId, ThreadId, RunId, SubmissionId } from \"effect-agent/identifiers\";\nimport {\n BatchId,\n CanonicalBatch,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n RecordEnvelope,\n RecordId,\n} from \"effect-agent/records\";\nimport { ThreadProjection } from \"effect-agent/thread-projection\";\nimport { ThreadCheckpoint } from \"effect-agent/thread-store\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport { expectedTravelPlan, phase1Trip } from \"./scenarios.ts\";\n\nexport const phase3TravelPlannerThreadId = Schema.decodeSync(ThreadId)(\"travel-planner-p3-thread\");\n\nexport const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p3-producer\",\n);\n\nexport const phase3TravelPlannerRunId = Schema.decodeSync(RunId)(\"travel-planner-p3-run\");\n\nconst deploymentId = Schema.decodeSync(DeploymentId)(\"travel-planner-p3-scripted\");\nconst agentId = Schema.decodeSync(AgentId)(\"travel-planner\");\nconst submissionId = Schema.decodeSync(SubmissionId)(\"travel-planner-p3-submission\");\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase3TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"a\"),\n model: digest(\"b\"),\n tools: digest(\"c\"),\n});\n\nconst tripInput = Schema.encodeSync(TripRequest)(phase1Trip);\nconst travelPlanOutput = Schema.encodeSync(TravelPlan)(expectedTravelPlan);\n\nconst record = (recordId: string, createdAt: string, payload: unknown) =>\n Schema.decodeUnknownSync(RecordEnvelope)({\n recordId: Schema.decodeSync(RecordId)(recordId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt,\n deploymentId,\n payload,\n });\n\n/**\n * The first atomic append establishes the Thread and records its input.\n * Its encoded value is the redacted current-version persistence fixture.\n */\nexport const phase3TravelPlannerInitialBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-initial\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-created\", \"2026-09-01T00:00:00.000Z\", {\n _tag: \"ThreadCreated\",\n agentId,\n definitions: phase3TravelPlannerDefinitionDigests,\n }),\n record(\"travel-planner-p3-input\", \"2026-09-01T00:00:01.000Z\", {\n _tag: \"UserInputRecorded\",\n submissionId,\n kind: \"user\",\n runId: phase3TravelPlannerRunId,\n input: tripInput,\n }),\n ],\n});\n\n/** The second append records the Schema-decoded itinerary and terminal Run result. */\nexport const phase3TravelPlannerCompletionBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-completion\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-model\", \"2026-09-01T00:00:02.000Z\", {\n _tag: \"ModelCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n record(\"travel-planner-p3-completed\", \"2026-09-01T00:00:03.000Z\", {\n _tag: \"RunCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n ],\n});\n\nexport const phase3TravelPlannerBatches = [\n phase3TravelPlannerInitialBatch,\n phase3TravelPlannerCompletionBatch,\n] as const;\n\n/** Portable current-version fixture; it contains no passenger identity or credentials. */\nexport const phase3TravelPlannerEncodedFixture: ReadonlyArray<typeof CanonicalBatch.Encoded> =\n Schema.encodeSync(Schema.Array(CanonicalBatch))(phase3TravelPlannerBatches);\n\nexport class TravelPlannerProjectionError extends Schema.TaggedError<TravelPlannerProjectionError>()(\n \"TravelPlannerProjectionError\",\n { message: Schema.String },\n) {}\n\n/** Decode the itinerary projection rebuilt from canonical model-completion records. */\nexport const travelPlanFromProjection = (\n projection: ThreadProjection,\n): Effect.Effect<TravelPlan, TravelPlannerProjectionError> => {\n const output = projection.modelOutputs.at(-1);\n\n if (output === undefined) {\n return Effect.fail(\n TravelPlannerProjectionError.make({\n message: \"The canonical projection has no completed Travel Planner model output.\",\n }),\n );\n }\n\n return Schema.decodeUnknownEffect(TravelPlan)(output).pipe(\n Effect.mapError((error) => TravelPlannerProjectionError.make({ message: error.message })),\n );\n};\n\n/** Build a disposable checkpoint bound to a validated canonical prefix. */\nexport const makePhase3TravelPlannerCheckpoint = (projection: ThreadProjection): ThreadCheckpoint =>\n Schema.decodeSync(ThreadCheckpoint)({\n schemaVersion: 1,\n threadId: projection.threadId,\n throughSequence: projection.throughSequence,\n tailDigest: projection.tailDigest,\n state: Schema.encodeSync(ThreadProjection)(projection),\n createdAt: \"2026-09-01T00:00:04.000Z\",\n });\n","import { Effect, Layer, Schema } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport { type DurableSubmitOptions, type Receipt } from \"effect-agent/durable-agent-runtime\";\nimport { ToolExecutionClass } from \"effect-agent/durable-step\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport {\n CanonicalRecordEnvelope,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n} from \"effect-agent/records\";\nimport { Principal, type IdempotencyKey } from \"effect-agent/submission-ledger\";\nimport { Model, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { ScriptedModel, type ScriptedTurnInput } from \"../../ScriptedModel.ts\";\nimport {\n ActivityCatalog,\n ActivityQuery,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightQuery,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingQuery,\n LodgingUnavailable,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n TravelGuidanceLayer,\n} from \"./deterministic-layers.ts\";\nimport { phase1HappyPathTurns } from \"./scenarios.ts\";\n\nexport const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p4-deployment\",\n);\n\nexport const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p4-producer\",\n);\n\nexport const phase4TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p4-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase4TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"d\"),\n model: digest(\"e\"),\n tools: digest(\"f\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase4TravelPlannerSubmitOptions = (\n threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\n principal: phase4TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase4TravelPlannerDefinitionDigests,\n});\n\n/**\n * The P4 read-only search Tools, calling the same deterministic catalogs as the P1 toolkit.\n *\n * The plain-Struct parameter shape is a historical remnant of the P4 carry-in workaround: since\n * the P5 engine fix, official history carries Schema-ENCODED Tool-call parameters, so class-typed\n * parameter codecs persist canonically too — the Structs simply need no change here. The\n * `ToolExecutionClass` `readonly` annotation is the deliberate P5 migration (plan §4.3): these\n * Tools perform no external mutation, so a crash between start and settlement is a free re-run\n * and they never enter the prepared/settled uncertainty protocol — keeping the P4 canonical\n * history byte-stable (an unannotated Tool fails closed to `uncertain`).\n */\nexport const DurableSearchFlights = Tool.make(\"search_flights\", {\n parameters: Schema.Struct(FlightQuery.fields),\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const DurableSearchLodging = Tool.make(\"search_lodging\", {\n parameters: Schema.Struct(LodgingQuery.fields),\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const DurableSearchActivities = Tool.make(\"search_activities\", {\n parameters: Schema.Struct(ActivityQuery.fields),\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const TravelPlannerPhase4Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n);\n\nexport const TravelPlannerPhase4ToolkitLayer = TravelPlannerPhase4Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n});\n\n/**\n * The cumulative Travel Planner, Phase 4: the P1 planning behavior on the durable Node/SQLite\n * runtime. The searches are read-only and safe to repeat across Attempts (D6); supplier booking\n * is deliberately absent because DN does NOT claim replay-safe external mutation (P5 scope).\n */\nexport const TravelPlannerPhase4 = Agent.make(\"travel-planner-phase-4\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase4Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Durably plan one review-only itinerary from safe-to-repeat deterministic searches; supplier booking is not claimed safely replayable.\",\n metadata: { deploymentClass: \"DN\", phase: \"P4\" },\n});\n\n/**\n * The P4 Agent Binding: the durable Travel Planner definition bound to a finite scripted model.\n * The scripted Layer is rebuilt per Run, so every Run of one Binding replays the same\n * deterministic script.\n */\nexport const makePhase4TravelPlannerAgent = (\n turns: ReadonlyArray<ScriptedTurnInput> = phase1HappyPathTurns,\n) =>\n Agent.withModel(\n TravelPlannerPhase4,\n Model.make(\"scripted\", \"travel-planner-phase-4\", ScriptedModel.layer(turns)),\n );\n\n/**\n * Everything a durable worker needs beyond the runtime stack, reusing the deterministic P1\n * travel-service Layers. The durable coordinator supplies its own deterministic `IdGenerator`,\n * so this Layer deliberately provides none.\n */\nexport const phase4TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase4ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n\nexport class TravelPlannerDurableEvidenceError extends Schema.TaggedError<TravelPlannerDurableEvidenceError>()(\n \"TravelPlannerDurableEvidenceError\",\n { message: Schema.String },\n) {}\n\n/**\n * Decode the completed itinerary from the canonical `SubmissionSettled` record. Canonical history\n * is the outcome authority (DUR-015): the settled result — not any ledger cache — must decode\n * through the trip output schema.\n */\nexport const travelPlanFromDurableSettlement = Effect.fn(\n \"TravelPlannerPhase4.travelPlanFromDurableSettlement\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<TravelPlan, TravelPlannerDurableEvidenceError> {\n const settlements = records.flatMap((envelope) =>\n envelope.record.payload._tag === \"SubmissionSettled\" ? [envelope.record.payload] : [],\n );\n\n const settled = settlements.at(0);\n\n if (settled === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: \"The canonical Thread Log has no SubmissionSettled record.\",\n });\n }\n if (settled.outcome !== \"completed\" || settled.result === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: `The Submission settled ${settled.outcome} without a completed itinerary result.`,\n });\n }\n\n return yield* Schema.decodeUnknownEffect(TravelPlan)(settled.result).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `The settled result does not decode through the TravelPlan schema: ${error.message}`,\n }),\n ),\n );\n});\n\nconst encodeEvidence = Schema.encodeEffect(Schema.Array(CanonicalRecordEnvelope));\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/**\n * Project canonical evidence into a Submission-identity-independent comparable form: batch\n * identity, canonical sequence, and the full encoded record, with the ledger-minted\n * `submissionId`/`receiptId` (and every identity derived from them: run, turn, batch, record,\n * and settlement ids) replaced by stable placeholders. Two Threads whose normalized\n * evidence is equal took byte-equivalent canonical histories, so restart-equivalence can compare\n * a recovered run against an uninterrupted control run on a separate database.\n */\nexport const normalizeDurableTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase4.normalizeDurableTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const encoded = yield* encodeEvidence(records).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Canonical evidence failed to encode: ${error.message}`,\n }),\n ),\n );\n\n const comparable = encoded.map((envelope) => ({\n batchId: envelope.batchId,\n sequence: envelope.sequence,\n record: envelope.record,\n }));\n\n const substituted: unknown = JSON.parse(\n JSON.stringify(comparable)\n .replaceAll(receipt.submissionId, \"{submissionId}\")\n .replaceAll(receipt.receiptId, \"{receiptId}\"),\n );\n\n return yield* decodeComparableJson(substituted).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n","import { Effect, Layer, Option, Schema } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport { type DurableSubmitOptions } from \"effect-agent/durable-agent-runtime\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"effect-agent/durable-step\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n PersistedJson,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"effect-agent/records\";\nimport { Principal, type IdempotencyKey } from \"effect-agent/submission-ledger\";\nimport {\n ReconciliationCompleted,\n ReconciliationSafeToRetry,\n ReconciliationUncertain,\n ToolReconciler,\n ToolReconcilerError,\n} from \"effect-agent/tool-reconciler\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n ActivityQuery,\n AirportCode,\n FlightCatalog,\n FlightQuery,\n LodgingCatalog,\n LodgingQuery,\n QuoteId,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n BookingRef,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n SupplierBookingDesk,\n SupplierBookingRecord,\n SupplierUnavailable,\n} from \"./deterministic-layers.ts\";\nimport { DurableSearchActivities, DurableSearchFlights, DurableSearchLodging } from \"./phase4.ts\";\n\nexport const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p5-deployment\",\n);\n\nexport const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p5-producer\",\n);\n\nexport const phase5TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p5-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase5TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"1\"),\n model: digest(\"2\"),\n tools: digest(\"3\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase5TravelPlannerSubmitOptions = (\n threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\n principal: phase5TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase5TravelPlannerDefinitionDigests,\n});\n\nexport const TravelerRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/TravelerRef\"),\n);\n\nexport type TravelerRef = typeof TravelerRef.Type;\n\n/**\n * Class-shaped booking parameters with branded fields: since the P5 engine fix, official history\n * carries Schema-ENCODED Tool-call parameters, so class-typed parameter codecs persist\n * canonically end-to-end (the P4 Struct workaround is gone for new Tools).\n */\nexport class FlightBookingRequest extends Schema.Class<FlightBookingRequest>(\n \"FlightBookingRequest\",\n)({\n quoteId: QuoteId,\n travelerRef: TravelerRef,\n departOn: Schema.String,\n}) {}\n\nexport class SupplierBookingConfirmation extends Schema.Class<SupplierBookingConfirmation>(\n \"SupplierBookingConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"confirmed\"),\n detail: Schema.String,\n}) {}\n\nexport class CancelBookingRequest extends Schema.Class<CancelBookingRequest>(\n \"CancelBookingRequest\",\n)({\n bookingRef: BookingRef,\n travelerRef: TravelerRef,\n}) {}\n\nexport class CancellationConfirmation extends Schema.Class<CancellationConfirmation>(\n \"CancellationConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"cancelled\"),\n}) {}\n\nexport class ItineraryBookingRequest extends Schema.Class<ItineraryBookingRequest>(\n \"ItineraryBookingRequest\",\n)({\n quoteId: QuoteId,\n destination: AirportCode,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelerRef: TravelerRef,\n}) {}\n\nexport class ItineraryConfirmation extends Schema.Class<ItineraryConfirmation>(\n \"ItineraryConfirmation\",\n)({\n flightBookingRef: BookingRef,\n lodgingBookingRef: BookingRef,\n confirmationCode: Schema.String,\n}) {}\n\n/** The P5 Run output: a booked (or explicitly not-booked) trip report. */\nexport class TravelBookingReport extends Schema.Class<TravelBookingReport>(\"TravelBookingReport\")({\n summary: Schema.String,\n bookingRefs: Schema.Array(BookingRef),\n}) {}\n\n/**\n * Supplier idempotency-key derivations. The handler owns key derivation (the `idempotent` and\n * `uncertain` execution classes carry no key), and the reconciler MUST use the same derivations\n * to query external truth — both sides are exported so they cannot drift.\n */\nexport const bookFlightIdempotencyKey = (toolCallId: string): string => `book-flight:${toolCallId}`;\n\nexport const itineraryStepIdempotencyKey = (toolCallId: string, stepName: string): string =>\n `${toolCallId}:${stepName}`;\n\n/**\n * Approval-gated supplier booking, explicitly `uncertain`: a crash after the call may have\n * mutated supplier state without a recorded outcome, so recovery must reconcile or stop at an\n * Unknown Outcome — never replay automatically (DUR-009, ADR-0004).\n */\nexport const BookFlight = Tool.make(\"book_flight\", {\n parameters: FlightBookingRequest,\n success: SupplierBookingConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"uncertain\");\n\n/**\n * Approval-gated cancellation, annotated `idempotent`: the DECLARED external contract is that\n * cancellation is idempotent by `bookingRef` (the supplier desk enforces it), so recovery may\n * re-execute a prepared-but-unsettled cancel without reconciliation proof. Repeats stay\n * observable in the supplier call counters — the annotation never claims exactly-once execution.\n */\nexport const CancelBooking = Tool.make(\"cancel_booking\", {\n parameters: CancelBookingRequest,\n success: CancellationConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"idempotent\");\n\n/**\n * The Durable Tool: declaring `DurableStep` in `dependencies` is what makes it durable\n * (GLOSSARY.md). Its handler divides supplier mutation into three named Steps — `reserve-flight`,\n * `reserve-lodging`, `issue-confirmation` — each deriving its supplier idempotency key from\n * `(toolCallId, stepName)`, so re-entry after interruption replays recorded Step results and the\n * supplier dedupes any honestly-repeated call. The Tool itself carries no execution-class\n * annotation: it stays fail-closed `uncertain`, and `TravelSupplierReconcilerLayer` proves\n * re-entry safe from the keyed-Step construction instead.\n */\nexport const BookItinerary = Tool.make(\"book_itinerary\", {\n parameters: ItineraryBookingRequest,\n success: ItineraryConfirmation,\n failure: Schema.Union([SupplierUnavailable, DurableStepError]),\n failureMode: \"error\",\n dependencies: [DurableStep, SupplierBookingDesk],\n});\n\nexport const TravelPlannerPhase5Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n BookFlight,\n CancelBooking,\n BookItinerary,\n);\n\nconst requireToolCallId = (\n toolName: string,\n toolCallId: string | undefined,\n): Effect.Effect<string, SupplierUnavailable> =>\n toolCallId === undefined\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `${toolName} needs its stable Tool Call ID to derive the supplier idempotency key.`,\n }),\n )\n : Effect.succeed(toolCallId);\n\nexport const TravelPlannerPhase5ToolkitLayer = TravelPlannerPhase5Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n book_flight: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const toolCallId = yield* requireToolCallId(\"book_flight\", context.toolCallId);\n\n const record = yield* desk.book({\n operation: \"book-flight\",\n idempotencyKey: bookFlightIdempotencyKey(toolCallId),\n detail: `flight ${request.quoteId} for ${request.travelerRef} on ${request.departOn}`,\n });\n\n return SupplierBookingConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"confirmed\",\n detail: record.detail,\n });\n }),\n cancel_booking: (request) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const record = yield* desk.cancel(request.bookingRef);\n\n return CancellationConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"cancelled\",\n });\n }),\n book_itinerary: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const step = yield* DurableStep;\n const toolCallId = yield* requireToolCallId(\"book_itinerary\", context.toolCallId);\n\n const bookStep = (\n stepName: \"reserve-flight\" | \"reserve-lodging\" | \"issue-confirmation\",\n detail: string,\n ) =>\n step.do(\n stepName,\n SupplierBookingRecord,\n desk.book({\n operation: stepName,\n idempotencyKey: itineraryStepIdempotencyKey(toolCallId, stepName),\n detail,\n }),\n );\n\n const flight = yield* bookStep(\n \"reserve-flight\",\n `flight ${request.quoteId} for ${request.travelerRef}`,\n );\n\n const lodging = yield* bookStep(\n \"reserve-lodging\",\n `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`,\n );\n\n const confirmation = yield* bookStep(\n \"issue-confirmation\",\n `itinerary confirmation for ${request.travelerRef}`,\n );\n\n return ItineraryConfirmation.make({\n flightBookingRef: flight.bookingRef,\n lodgingBookingRef: lodging.bookingRef,\n confirmationCode: confirmation.bookingRef,\n });\n }),\n});\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodeConfirmation = Schema.encodeEffect(SupplierBookingConfirmation);\n\n/**\n * The application reconciliation policy (durability §10): a claim about EXTERNAL truth, queried\n * from the supplier desk by the same idempotency-key derivations the handlers use.\n *\n * - `book_flight`: a confirmed booking under `book-flight:{toolCallId}` is recovered supplier\n * truth — `CompletedWithResult` settles it canonically without executing anything. Absence is\n * NOT proof the call never started (a real supplier write could be in flight), so the desk\n * answer stays fail-closed `Uncertain`.\n * - `book_itinerary`: every external mutation inside is a named Step whose supplier idempotency\n * key derives from `(toolCallId, stepName)`, so re-entry is provably safe by construction —\n * `SafeToRetry`. Committed Steps replay from their records; repeated calls dedupe at the desk.\n * - `cancel_booking`: declared `idempotent`, so the coordinator re-executes without consulting\n * this policy; if ever asked, the bookingRef contract makes `SafeToRetry` honest.\n * - anything else: fail-closed `Uncertain` (AGENTS rule 11).\n */\nexport const TravelSupplierReconcilerLayer: Layer.Layer<\n ToolReconciler,\n never,\n SupplierBookingDesk\n> = Layer.effect(\n ToolReconciler,\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n\n return ToolReconciler.of({\n reconcile: (evidence) =>\n Effect.gen(function* () {\n switch (evidence.toolName) {\n case \"book_flight\": {\n const key = bookFlightIdempotencyKey(evidence.toolCallId);\n const booking = yield* desk.lookup(key);\n\n if (Option.isSome(booking) && booking.value.status === \"confirmed\") {\n const confirmation = yield* encodeConfirmation(\n SupplierBookingConfirmation.make({\n bookingRef: booking.value.bookingRef,\n status: \"confirmed\",\n detail: booking.value.detail,\n }),\n ).pipe(Effect.flatMap(decodePersistedJson));\n\n return ReconciliationCompleted.make({ result: confirmation, isFailure: false });\n }\n\n return ReconciliationUncertain.make({\n reason: `The supplier desk shows no confirmed booking under ${key}; a write may still be in flight.`,\n });\n }\n case \"book_itinerary\":\n return ReconciliationSafeToRetry.make();\n case \"cancel_booking\":\n return ReconciliationSafeToRetry.make();\n default:\n return ReconciliationUncertain.make({\n reason: `No supplier reconciliation exists for ${evidence.toolName}.`,\n });\n }\n }).pipe(\n Effect.mapError((error) =>\n ToolReconcilerError.make({\n toolCallId: evidence.toolCallId,\n message: `Supplier reconciliation failed: ${error.message}`,\n }),\n ),\n ),\n });\n }),\n);\n\n/**\n * The cumulative Travel Planner, Phase 5: the durable planner now performs consequential\n * supplier mutation under the full uncertainty protocol — approval-gated uncertain booking,\n * idempotent-by-contract cancellation, and one Durable Tool whose Steps carry supplier\n * idempotency keys.\n */\nexport const TravelPlannerPhase5 = Agent.make(\"travel-planner-phase-5\", {\n input: TripRequest,\n output: TravelBookingReport,\n instructions: [\n \"You are the Effect Agent Travel Planner P5 booking fixture.\",\n \"Search with the read-only tools, then book with book_flight, book_itinerary, or\",\n \"cancel_booking exactly as scripted. Every consequential mutation is approval-gated\",\n \"or Step-structured. Return only a JSON object with summary and bookingRefs.\",\n ].join(\" \"),\n toolkit: TravelPlannerPhase5Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 6,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n description:\n \"Durably book one itinerary with prepared/settled supplier records, Unknown Outcomes, named Steps, and joined traveler input.\",\n metadata: { deploymentClass: \"DN\", phase: \"P5\" },\n});\n\nexport class TravelPlannerBookingEvidenceError extends Schema.TaggedError<TravelPlannerBookingEvidenceError>()(\n \"TravelPlannerBookingEvidenceError\",\n { message: Schema.String },\n) {}\n\nconst bookingResultRefs = (result: unknown): ReadonlyArray<string> => {\n if (typeof result !== \"object\" || result === null) return [];\n const refs: Array<string> = [];\n\n for (const [field, value] of Object.entries(result)) {\n if (\n typeof value === \"string\" &&\n (field === \"bookingRef\" ||\n field === \"flightBookingRef\" ||\n field === \"lodgingBookingRef\" ||\n field === \"confirmationCode\")\n ) {\n refs.push(value);\n }\n }\n\n return refs;\n};\n\nconst bookingToolNames = new Set([\"book_flight\", \"cancel_booking\", \"book_itinerary\"]);\n\n/**\n * Never-fabricate assertion (ROADMAP P5 exit gate): every successfully settled booking result in\n * canonical history must reference a booking that actually exists in the supplier store. A\n * `ToolCallSettled` whose bookingRef the supplier cannot produce would be a fabricated result —\n * the exact lie the uncertainty protocol exists to prevent.\n */\nexport const assertSettledBookingsExistAtSupplier = Effect.fn(\n \"TravelPlannerPhase5.assertSettledBookingsExistAtSupplier\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<void, TravelPlannerBookingEvidenceError, SupplierBookingDesk> {\n const desk = yield* SupplierBookingDesk;\n const bookings = yield* desk.bookings;\n const knownRefs = new Set<string>(bookings.map((booking) => booking.bookingRef));\n\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\n if (\n payload._tag !== \"ToolCallSettled\" ||\n payload.isFailure ||\n !bookingToolNames.has(payload.toolName)\n ) {\n continue;\n }\n for (const ref of bookingResultRefs(payload.result)) {\n if (!knownRefs.has(ref)) {\n return yield* TravelPlannerBookingEvidenceError.make({\n message: `Canonical record ${envelope.record.recordId} settled bookingRef ${ref}, which the supplier store cannot produce — a fabricated result.`,\n });\n }\n }\n }\n});\n\n/**\n * Everything a durable P5 worker needs beyond the runtime stack and the supplier desk: the\n * booking toolkit plus the deterministic P1 travel-service Layers. `SupplierBookingDesk` is\n * deliberately NOT provided here — tests own the desk's lifetime so its counters, bookings, and\n * crash windows survive Tool-Layer rebuilds across Attempts.\n */\nexport const phase5TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase5ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n","import { Context, Deferred, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport { type RuntimeBinding } from \"effect-agent/agent-runtime\";\nimport * as Subagent from \"effect-agent/subagent\";\nimport { SubagentPolicy } from \"effect-agent/subagent\";\nimport { LanguageModel, Model, type Response, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport type { ScriptedTurnInput } from \"../../ScriptedModel.ts\";\nimport { AirportCode } from \"./definition.ts\";\nimport { CatalogLifecycle } from \"./deterministic-layers.ts\";\n\n// ---------------------------------------------------------------------------\n// Destination Researcher: the S1 specialist child Agent.\n// The researcher is a normal Agent with one deterministic\n// travel-service Tool; it never becomes a second child loop (SUB-001/003).\n// ---------------------------------------------------------------------------\n\nexport class DestinationQuery extends Schema.Class<DestinationQuery>(\"DestinationQuery\")({\n destination: AirportCode,\n}) {}\n\nexport class DestinationFacts extends Schema.Class<DestinationFacts>(\"DestinationFacts\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationGuideUnavailable extends Schema.TaggedError<DestinationGuideUnavailable>()(\n \"DestinationGuideUnavailable\",\n {\n destination: AirportCode,\n message: Schema.String,\n },\n) {}\n\nexport class DestinationGuide extends Context.Service<\n DestinationGuide,\n {\n readonly lookup: (\n query: DestinationQuery,\n ) => Effect.Effect<DestinationFacts, DestinationGuideUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/DestinationGuide\") {}\n\nexport const LookupDestination = Tool.make(\"lookup_destination\", {\n parameters: DestinationQuery,\n success: DestinationFacts,\n failure: DestinationGuideUnavailable,\n failureMode: \"error\",\n dependencies: [DestinationGuide],\n});\n\nexport const DestinationResearcherToolkit = Toolkit.make(LookupDestination);\n\nexport const DestinationResearcherToolkitLayer = DestinationResearcherToolkit.toLayer({\n lookup_destination: (query) => Effect.flatMap(DestinationGuide, (guide) => guide.lookup(query)),\n});\n\nexport class DestinationBrief extends Schema.Class<DestinationBrief>(\"DestinationBrief\")({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationReport extends Schema.Class<DestinationReport>(\"DestinationReport\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport const DestinationResearcher = Agent.make(\"destination-researcher\", {\n input: DestinationBrief,\n output: DestinationReport,\n instructions:\n \"Consult lookup_destination exactly once for the briefed airport, then return only a JSON destination report.\",\n toolkit: DestinationResearcherToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n description: \"Research one candidate destination with the deterministic travel guide.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\n// ---------------------------------------------------------------------------\n// Deterministic guide data and Layer (deterministic-layers.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst decodeAirportCode = Schema.decodeSync(AirportCode);\n\nconst guideFacts = new Map<string, DestinationFacts>([\n [\n \"LHR\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"LHR\"),\n highlights: [\"Barbican brutalism walk\", \"Kew glasshouse survey\"],\n advisory: \"London favors museum mornings and riverside evenings.\",\n }),\n ],\n [\n \"CDG\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"CDG\"),\n highlights: [\"Marais passage crawl\", \"Seine bookstall loop\"],\n advisory: \"Paris rewards early galleries and late cafes.\",\n }),\n ],\n]);\n\n/** Deterministic guide lookup shared by the default and test-local guide Layers. */\nexport const destinationLookup = (\n query: DestinationQuery,\n): Effect.Effect<DestinationFacts, DestinationGuideUnavailable> => {\n const facts = guideFacts.get(query.destination);\n\n return facts === undefined\n ? Effect.fail(\n DestinationGuideUnavailable.make({\n destination: query.destination,\n message: \"No deterministic guide entry exists for this destination.\",\n }),\n )\n : Effect.succeed(facts);\n};\n\nconst requireDestinationFacts = (destination: string): DestinationFacts => {\n const facts = guideFacts.get(destination);\n\n if (facts === undefined) {\n throw new Error(`No deterministic guide entry exists for destination ${destination}`);\n }\n\n return facts;\n};\n\n/** The report the scripted researcher writes after consulting the guide. */\nexport const destinationReportFor = (destination: string): DestinationReport => {\n const facts = requireDestinationFacts(destination);\n\n return DestinationReport.make({\n destination: facts.destination,\n highlights: facts.highlights,\n advisory: facts.advisory,\n });\n};\n\nexport const encodedDestinationReport = (destination: string): string =>\n JSON.stringify(Schema.encodeSync(DestinationReport)(destinationReportFor(destination)));\n\nexport const DestinationGuideLayer = Layer.effect(\n DestinationGuide,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n\n return DestinationGuide.of({ lookup: destinationLookup });\n }),\n);\n\n/** Child-side construction requirements of the delegation handler Layer. */\nexport const DestinationResearchSupportLayer = Layer.mergeAll(\n DestinationResearcherToolkitLayer,\n DestinationGuideLayer,\n);\n\n// ---------------------------------------------------------------------------\n// Delegation Definition: the coordinator sees exactly\n// one Effect AI Tool with explicit input/result projections and finite bounds.\n// ---------------------------------------------------------------------------\n\nexport class DestinationResearchRequest extends Schema.Class<DestinationResearchRequest>(\n \"DestinationResearchRequest\",\n)({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFindings extends Schema.Class<DestinationResearchFindings>(\n \"DestinationResearchFindings\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFailed extends Schema.TaggedError<DestinationResearchFailed>()(\n \"DestinationResearchFailed\",\n {\n childErrorTag: Schema.NonEmptyString,\n },\n) {}\n\n/**\n * Deterministic delegation-admission choreography seam. `prepareInput` awaits\n * this gate before the handler reserves budget or spawns, so tests can order\n * concurrent delegation preflights without sleeps. It also keeps the\n * projection's construction requirements honestly visible in the handler\n * Layer's `R`. The open Layer never waits.\n */\nexport class ResearchDispatchGate extends Context.Service<\n ResearchDispatchGate,\n { readonly awaitDispatch: (destination: string) => Effect.Effect<void> }\n>()(\"@effect-agent/testing/travel-planner/ResearchDispatchGate\") {\n static readonly layerOpen = Layer.succeed(\n this,\n ResearchDispatchGate.of({ awaitDispatch: () => Effect.void }),\n );\n}\n\n/**\n * Finite per-invocation bounds (SUB-009): each child may use two Turns and\n * one Tool Call; the parent Run may establish at most two children with at\n * most two running concurrently.\n */\nexport const destinationResearchPolicy = SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"10 seconds\",\n});\n\nexport const destinationResearchDelegation = Subagent.define(\"delegate_destination_research\", {\n description:\n \"Research one candidate destination with the deterministic travel guide and return a bounded finding.\",\n target: DestinationResearcher,\n parameters: DestinationResearchRequest,\n success: DestinationResearchFindings,\n failure: DestinationResearchFailed,\n prepareInput: (request) =>\n Effect.gen(function* () {\n const gate = yield* ResearchDispatchGate;\n\n yield* gate.awaitDispatch(request.destination);\n\n return DestinationBrief.make({\n destination: request.destination,\n focus: `research:${request.focus}`,\n });\n }),\n // The explicit declassification boundary (SUB-015): only the advisory\n // crosses to the parent; guide highlights stay in the child Thread.\n projectResult: (report) =>\n Effect.succeed(\n DestinationResearchFindings.make({\n destination: report.destination,\n summary: report.advisory,\n }),\n ),\n policy: destinationResearchPolicy,\n});\n\n/** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */\nexport const mapResearchChildFailure = (failure: {\n readonly _tag: string;\n}): DestinationResearchFailed => DestinationResearchFailed.make({ childErrorTag: failure._tag });\n\n/** Runtime wiring: pair the immutable delegation with one explicit child Binding. */\nexport const destinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n Subagent.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n });\n\n// ---------------------------------------------------------------------------\n// Travel Coordinator: the parent Agent that delegates destination research.\n// ---------------------------------------------------------------------------\n\nexport class ResearchMission extends Schema.Class<ResearchMission>(\"ResearchMission\")({\n request: Schema.NonEmptyString,\n candidates: Schema.Array(AirportCode).check(Schema.isMinLength(1)),\n}) {}\n\nexport class DestinationRecommendation extends Schema.Class<DestinationRecommendation>(\n \"DestinationRecommendation\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationShortlist extends Schema.Class<DestinationShortlist>(\n \"DestinationShortlist\",\n)({\n recommendations: Schema.Array(DestinationRecommendation),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\n/** Parent-only transcript markers used to prove child context isolation (SUB-006/015). */\nexport const coordinatorConfidentialMarker = \"coordinator-vault-7q42\";\nexport const missionConfidentialMarker = \"traveler-dossier-19f\";\n\nexport const TravelCoordinatorToolkit = Toolkit.make(destinationResearchDelegation.tool);\n\nexport const TravelCoordinator = Agent.make(\"travel-coordinator\", {\n input: ResearchMission,\n output: DestinationShortlist,\n instructions: [\n \"You are the Effect Agent Travel Planner S1 delegation coordinator.\",\n `Coordinator-only context: ${coordinatorConfidentialMarker}.`,\n \"Call delegate_destination_research once per candidate in one Tool batch.\",\n \"Return only a JSON shortlist built from the delegated findings. This is read-only planning.\",\n ].join(\"\\n\"),\n toolkit: TravelCoordinatorToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Coordinate bounded destination research through one declared attached delegation Tool.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\nexport const researchMission = Schema.decodeSync(ResearchMission)({\n request: `Shortlist one September culture city; keep ${missionConfidentialMarker} inside the coordinator thread.`,\n candidates: [\"LHR\", \"CDG\"],\n});\n\nexport const expectedDestinationShortlist = DestinationShortlist.make({\n recommendations: researchMission.candidates.map((destination) =>\n DestinationRecommendation.make({\n destination,\n summary: requireDestinationFacts(destination).advisory,\n }),\n ),\n nextAction: \"review\",\n});\n\n// ---------------------------------------------------------------------------\n// Scripted turns (scenarios.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\nexport interface DestinationResearchCall {\n readonly id: string;\n readonly destination: string;\n readonly focus: string;\n}\n\n/** One coordinator Turn that declares the given delegation Tool Calls in order. */\nexport const coordinatorResearchTurn = (\n calls: ReadonlyArray<DestinationResearchCall>,\n): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n ...calls.map((call) => ({\n type: \"tool-call\" as const,\n id: call.id,\n name: \"delegate_destination_research\",\n params: { destination: call.destination, focus: call.focus },\n })),\n { type: \"finish\" as const, reason: \"tool-calls\" as const, usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** The coordinator's final structured-output Turn. */\nexport const coordinatorShortlistTurn = (shortlist: DestinationShortlist): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** Static researcher script for single-child tests: one guide lookup, then the report. */\nexport const researcherHappyPathTurns = (\n destination: string,\n): readonly [ScriptedTurnInput, ScriptedTurnInput] => [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(destination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Destination-keyed researcher model for parallel-children tests.\n// ---------------------------------------------------------------------------\n\n/**\n * Deterministic controls for parallel researcher children whose completions\n * are released in a caller-selected order (ReverseCompletionToolkitLayer\n * pattern). This is intentionally a test fixture: it uses no clock or sleep.\n */\nexport interface DestinationResearcherControls {\n /** Await the first model request of the child researching this destination. */\n readonly awaitStarted: (destination: string) => Effect.Effect<void>;\n /** Allow the child researching this destination to produce its final report. */\n readonly release: (destination: string) => Effect.Effect<void>;\n /** JSON-encoded first-Turn child prompts in arrival order (isolation evidence). */\n readonly prompts: Effect.Effect<ReadonlyArray<string>>;\n}\n\ninterface ResearcherGates {\n readonly started: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * Build a deterministic researcher Model whose per-child behavior is keyed by\n * the destination named in the child's own prompt: Turn one records the\n * prompt, signals `started`, and calls the guide Tool; Turn two waits for the\n * caller's `release` before writing the report. Each child Run builds the\n * Model Layer inside its own scope, so one `CatalogLifecycle` acquisition and\n * finalization is observed per child — the same acquire/release counting the\n * catalog Layers use to prove interruption reaches every finalizer.\n */\nexport const makeDestinationResearcherModel = (destinations: ReadonlyArray<string>) =>\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const gates = new Map<string, ResearcherGates>();\n\n for (const destination of destinations) {\n gates.set(destination, {\n started: yield* Deferred.make<void>(),\n release: yield* Deferred.make<void>(),\n });\n }\n\n const gatesFor = (destination: string): Effect.Effect<ResearcherGates> =>\n Effect.suspend(() => {\n const entry = gates.get(destination);\n\n return entry === undefined\n ? Effect.die(new Error(`No researcher gates exist for destination ${destination}`))\n : Effect.succeed(entry);\n });\n\n const controls: DestinationResearcherControls = {\n awaitStarted: (destination) =>\n gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.await(entry.started))),\n release: (destination) =>\n gatesFor(destination).pipe(\n Effect.flatMap((entry) => Deferred.succeed(entry.release, undefined)),\n Effect.asVoid,\n ),\n prompts: Ref.get(prompts),\n };\n\n const model = Model.make(\n \"scripted\",\n \"destination-researcher-scripted\",\n Layer.effect(\n LanguageModel.LanguageModel,\n Effect.gen(function* () {\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n const turn = yield* Ref.make(0);\n\n return yield* LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const promptJson = JSON.stringify(options.prompt.content);\n\n const destination = destinations.find((candidate) =>\n promptJson.includes(candidate),\n );\n\n if (destination === undefined) {\n return yield* Effect.die(\n new Error(\"The researcher prompt names no scripted destination\"),\n );\n }\n const entry = yield* gatesFor(destination);\n const index = yield* Ref.getAndUpdate(turn, (value) => value + 1);\n\n if (index === 0) {\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n yield* Deferred.succeed(entry.started, undefined);\n\n return Stream.fromIterable(researcherLookupParts(destination));\n }\n yield* Deferred.await(entry.release);\n\n return Stream.fromIterable(researcherReportParts(destination));\n }),\n ),\n });\n }),\n ),\n );\n\n return { controls, model };\n });\n","import { Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"effect-agent/agent-registration\";\nimport { type RuntimeBinding } from \"effect-agent/agent-runtime\";\nimport { type DurableSubmitOptions } from \"effect-agent/durable-agent-runtime\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport { DefinitionDigests, DeploymentId, Digest, ProducerId } from \"effect-agent/records\";\nimport * as Subagent from \"effect-agent/subagent\";\nimport { delegationAllocationFromPolicy } from \"effect-agent/subagent\";\nimport { SubagentReservationsMemoryLive } from \"effect-agent/subagent-reservations\";\nimport { Principal, type IdempotencyKey } from \"effect-agent/submission-ledger\";\nimport { LanguageModel, Model, type Response, type Toolkit } from \"effect/unstable/ai\";\n\nimport { DeterministicIdGeneratorLayer } from \"./deterministic-layers.ts\";\nimport type {\n DestinationBrief,\n DestinationReport,\n DestinationResearcherToolkit,\n} from \"./subagents.ts\";\nimport {\n DestinationFacts,\n DestinationGuide,\n DestinationRecommendation,\n DestinationResearcher,\n DestinationResearcherToolkitLayer,\n destinationLookup,\n destinationReportFor,\n destinationResearchDelegation,\n destinationResearchPolicy,\n DestinationShortlist,\n encodedDestinationReport,\n mapResearchChildFailure,\n ResearchDispatchGate,\n TravelCoordinator,\n} from \"./subagents.ts\";\n\n/** Registered coordinator and researcher bindings for durable delegation tests. */\nexport const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-s2-deployment\",\n);\n\nexport const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-s2-producer\",\n);\n\nexport const s2TravelPlannerPrincipal = Schema.decodeSync(Principal)(\"travel-planner-s2-principal\");\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic parent (coordinator) definition digests for this fixture version. */\nexport const s2CoordinatorDigests = DefinitionDigests.make({\n agent: digestOf(\"a\"),\n model: digestOf(\"b\"),\n tools: digestOf(\"c\"),\n});\n\n/**\n * The exact child Binding digest strings the application declares on\n * `SubagentRuntimeOptions.durable.targetDigests` AND the host registers with\n * the host's binding array for the researcher Binding. The coordinator\n * stores and verifies them byte-for-byte (SUB-023); a host registration under\n * different strings is a `ChildCompatibilityFailure`, never a substitution.\n */\nexport const s2ResearcherDigestStrings = {\n agent: \"d\".repeat(64),\n model: \"e\".repeat(64),\n tools: \"f\".repeat(64),\n} as const;\n\nexport const s2ResearcherDigests = DefinitionDigests.make({\n agent: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.agent),\n model: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.model),\n tools: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.tools),\n});\n\n/** Durable admission options for one coordinator Submission on one mission lane. */\nexport const s2TravelPlannerSubmitOptions = (\n threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\n principal: s2TravelPlannerPrincipal,\n idempotencyKey,\n definitions: s2CoordinatorDigests,\n});\n\n/** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */\nexport const s2CoordinatorSubmitAgent = {\n definition: { id: TravelCoordinator.id, input: TravelCoordinator.input },\n} as const;\n\n/**\n * The per-invocation reservation the durable handler computes from the S1\n * delegation policy (`delegationAllocationFromPolicy`): the conservation\n * evidence in the S2 tests checks the ledger reservation rows and the\n * canonical `SubagentJoined.finalAccounting` against exactly this value.\n */\nexport const durableResearchAllocation = delegationAllocationFromPolicy(destinationResearchPolicy);\n\n/** The one scripted delegation Tool Call id of the durable coordinator Run. */\nexport const durableResearchCallId = \"research-lhr-1\";\n\n/** The child's own scripted guide-lookup Tool Call id. */\nexport const durableChildLookupCallId = (destination: string): string => `lookup-${destination}`;\n\n/** The projected finding the parent joins (only the advisory crosses, SUB-015). */\nexport const durableResearchFinding = (destination: string) => ({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n});\n\n/** The coordinator's expected final shortlist for one researched destination. */\nexport const durableResearchShortlist = (destination: string): DestinationShortlist =>\n DestinationShortlist.make({\n recommendations: [\n DestinationRecommendation.make({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n }),\n ],\n nextAction: \"review\",\n });\n\n/**\n * The deterministic guide facts in encoded (wire) form: the \"supplier truth\"\n * an authorized operator records through `resolveUnknown` when a child guide\n * lookup stopped at an Unknown Outcome (DUR-017 — the framework never guesses\n * or replays it).\n */\nexport const encodedDestinationFacts = (destination: string): unknown => {\n const report = destinationReportFor(destination);\n\n return Schema.encodeSync(DestinationFacts)(\n DestinationFacts.make({\n destination: report.destination,\n highlights: report.highlights,\n advisory: report.advisory,\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Invocation-counting scripted models (the P5 SupplierBookingDesk counter\n// pattern): the call counter and captured prompts live OUTSIDE the Model\n// Layer, so they survive Layer rebuilds across Attempts and across separate\n// runtime handles over the same SQLite file — \"the child was never\n// re-executed\" is asserted, not assumed.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\n/** One scripted model whose behavior is keyed by the global invocation index. */\nexport const makeInvocationCountingModel = (\n name: string,\n script: (call: number) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Effect.gen(function* () {\n const calls = yield* Ref.make(0);\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n\n const model = Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const call = yield* Ref.getAndUpdate(calls, (value) => value + 1);\n\n yield* Ref.update(prompts, (previous) => [\n ...previous,\n JSON.stringify(request.prompt.content),\n ]);\n\n return Stream.fromIterable(script(call));\n }),\n ),\n }),\n ),\n );\n\n return { model, calls: Ref.get(calls), prompts: Ref.get(prompts) };\n });\n\nconst delegationTurnParts = (\n toolCallId: string,\n destination: string,\n focus: string,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: toolCallId,\n name: \"delegate_destination_research\",\n params: { destination, focus },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst shortlistParts = (\n shortlist: DestinationShortlist,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: durableChildLookupCallId(destination),\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n// ---------------------------------------------------------------------------\n// Durable delegation wiring (S2): the SAME immutable S1 Delegation Definition\n// paired with one explicit child Binding, now carrying the construction-fixed\n// durable declaration. Under a durable coordinator the handler establishes an\n// accepted-work child instead of spawning an in-process fiber; without the\n// declaration a durable-mode invocation fails closed (WP5 contract).\n// ---------------------------------------------------------------------------\n\n/** Runtime wiring for the durable slice: the S1 delegation plus the S2 digest declaration. */\nexport const durableDestinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n Subagent.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n durable: { targetDigests: s2ResearcherDigestStrings },\n });\n\n/** Optional overrides for one durable research harness. */\nexport interface DurableResearchHarnessOptions {\n /** Researched destination; defaults to \"LHR\". */\n readonly destination?: string | undefined;\n /** Delegation focus; defaults to \"museums\". */\n readonly focus?: string | undefined;\n /**\n * Digests the HOST registers the child Binding under; defaults to the exact\n * declared `s2ResearcherDigests`. Register different digests to force the\n * fail-closed `ChildCompatibilityFailure` path (SUB-023/SUB-032).\n */\n readonly childRegistrationDigests?: DefinitionDigests | undefined;\n}\n\n/** One durable coordinator/researcher pair with observable invocation counters. */\nexport interface DurableResearchHarness {\n /** Host registrations for `NodeDurableAgentRuntimeOptions.bindings` (parent + child). */\n readonly bindings: ReadonlyArray<ResolvedBinding>;\n /** Total coordinator model invocations across every Attempt and runtime handle. */\n readonly parentModelCalls: Effect.Effect<number>;\n /** JSON-encoded coordinator prompts in request order. */\n readonly parentPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Total researcher model invocations across every Attempt and runtime handle. */\n readonly childModelCalls: Effect.Effect<number>;\n /** JSON-encoded researcher prompts in request order (context-isolation evidence). */\n readonly childPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Deterministic guide-lookup handler executions (ordinary child Tool side effects). */\n readonly guideInvocations: Effect.Effect<number>;\n}\n\n/**\n * Build the S2 Travel Planner harness: an invocation-counting scripted\n * coordinator (Turn 1 declares the one delegation call, Turn 2 writes the\n * shortlist), an invocation-counting scripted researcher (Turn 1 consults the\n * guide, Turn 2 writes the report), and both worker Bindings captured with\n * their requirement Contexts via `DurableWorkerBinding.make` under the exact\n * fixture digests. The returned `bindings` are plain values: they can be\n * registered with several `NodeDurableAgentRuntime` stacks over the same SQLite\n * file while the counters keep counting across all of them.\n */\nexport const makeDurableResearchHarness = (options?: DurableResearchHarnessOptions) =>\n Effect.gen(function* () {\n const destination = options?.destination ?? \"LHR\";\n const focus = options?.focus ?? \"museums\";\n\n const guideInvocations = yield* Ref.make(0);\n\n const guideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Ref.update(guideInvocations, (count) => count + 1).pipe(\n Effect.andThen(destinationLookup(query)),\n ),\n }),\n );\n\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(guideLayer),\n );\n\n const childModel = yield* makeInvocationCountingModel(\"destination-researcher-s2\", (call) =>\n call === 0 ? researcherLookupParts(destination) : researcherReportParts(destination),\n );\n\n const childBinding = Agent.withModel(DestinationResearcher, childModel.model);\n\n const parentModel = yield* makeInvocationCountingModel(\"travel-coordinator-s2\", (call) =>\n call === 0\n ? delegationTurnParts(durableResearchCallId, destination, focus)\n : shortlistParts(durableResearchShortlist(destination)),\n );\n\n const parentBinding = Agent.withModel(TravelCoordinator, parentModel.model);\n\n const delegationLayer = durableDestinationResearchHandlersLayer(childBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n );\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n s2CoordinatorDigests,\n ).pipe(Effect.provide(delegationLayer));\n\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n options?.childRegistrationDigests ?? s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n const harness: DurableResearchHarness = {\n bindings: [parentResolved, childResolved],\n parentModelCalls: parentModel.calls,\n parentPrompts: parentModel.prompts,\n childModelCalls: childModel.calls,\n childPrompts: childModel.prompts,\n guideInvocations: Ref.get(guideInvocations),\n };\n\n return harness;\n });\n","import { Duration, Effect, Layer, Schema, Stream } from \"effect\";\nimport * as Agent from \"effect-agent/agent\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"effect-agent/agent-registration\";\nimport { type Receipt } from \"effect-agent/durable-agent-runtime\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"effect-agent/records\";\nimport { SubagentReservationsMemoryLive } from \"effect-agent/subagent-reservations\";\nimport { type ToolReconciler } from \"effect-agent/tool-reconciler\";\nimport { LanguageModel, Model, type Response } from \"effect/unstable/ai\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport {\n DeterministicIdGeneratorLayer,\n SupplierBookingDesk,\n supplierBookingRefFor,\n} from \"./deterministic-layers.ts\";\nimport {\n TravelPlannerDurableEvidenceError,\n TravelPlannerPhase4,\n normalizeDurableTravelPlannerEvidence,\n phase4TravelPlannerDefinitionDigests,\n phase4TravelPlannerWorkerLayer,\n} from \"./phase4.ts\";\nimport {\n TravelPlannerPhase5,\n TravelSupplierReconcilerLayer,\n bookFlightIdempotencyKey,\n phase5TravelPlannerDefinitionDigests,\n phase5TravelPlannerWorkerLayer,\n} from \"./phase5.ts\";\nimport { expectedTravelPlan } from \"./scenarios.ts\";\nimport {\n durableDestinationResearchHandlersLayer,\n durableResearchCallId,\n durableResearchShortlist,\n s2CoordinatorDigests,\n s2ResearcherDigests,\n} from \"./subagents-durable.ts\";\nimport {\n DestinationGuide,\n DestinationResearcher,\n DestinationResearcherToolkitLayer,\n DestinationShortlist,\n ResearchDispatchGate,\n ResearchMission,\n TravelCoordinator,\n destinationLookup,\n encodedDestinationReport,\n} from \"./subagents.ts\";\n\n/** Platform-neutral bindings and canonical evidence shared by Node and Cloudflare tests. */\nexport const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p6-deployment\",\n);\n\n/** Producer prefix of the DC host; each Object mints `{prefix}:{threadId}`. */\nexport const phase6TravelPlannerProducerPrefix = \"travel-planner-p6-producer\";\n\n/** The full producer identity one DC Thread Object mints for itself. */\nexport const phase6TravelPlannerProducerId = (threadId: string): ProducerId =>\n Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${threadId}`);\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/**\n * Registration digests of the GATED planner Binding: the same `TravelPlannerPhase4` definition\n * bound to a model whose first response waits on a test gate, addressable separately so the\n * admission-limits rows can hold a lane busy deterministically without touching the ordinary\n * planner registration.\n */\nexport const phase6GatedPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digestOf(\"9\"),\n model: digestOf(\"8\"),\n tools: digestOf(\"7\"),\n});\n\n// ---------------------------------------------------------------------------\n// Cross-platform evidence normal form (plan §1.8, D-P6-6)\n// ---------------------------------------------------------------------------\n\n/** The run-specific identities the cross-platform normal form scrubs. */\nexport interface CrossPlatformEvidenceIdentity {\n /** The Thread lane the evidence came from. */\n readonly threadId: string;\n /** The host's deployment identity (`DeploymentId` on every record envelope). */\n readonly deploymentId: string;\n /** The full producer identity of the run (DN: configured; DC: `{prefix}:{threadId}`). */\n readonly producerId: string;\n}\n\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/** The base normal form's element shape, re-decoded so sequences can be renumbered. */\nconst ComparableEnvelope = Schema.Struct({\n batchId: Schema.String,\n sequence: Schema.Number,\n record: Schema.Json,\n});\n\nconst decodeComparableEnvelopes = Schema.decodeUnknownEffect(Schema.Array(ComparableEnvelope));\n\n/**\n * The CROSS-PLATFORM extension of `normalizeDurableTravelPlannerEvidence` (D-P6-6): after the\n * base normalization replaces the two ledger-minted identities (which also normalizes the\n * DC-format routable `{uuidv7}:{threadId}` Submission identities and everything derived\n * from them), this form additionally scrubs everything that legitimately differs between a DN\n * process and a DC Durable Object over the same scenario:\n *\n * - `RepairAnnotated` audit records are dropped BEFORE normalization and the canonical\n * sequence is renumbered to the surviving order: repairs are DUR-013 evidence of recovery\n * itself, legally present in a recovered run and legally absent from an uninterrupted\n * control (on DC even a CLEAN run carries one, because every pass reconciles before it\n * claims, so the ready lane's input is applied through the recovery path). Canonical ORDER\n * is the durability §5 claim; sequence contiguity is a platform artifact of who appended;\n * - the Thread identity (DC lanes mint unique names per test run);\n * - the deployment and producer identities (host configuration, not canonical semantics);\n * - `createdAt` commit timestamps (wall clock);\n * - 64-hex digests (they hash RAW content that legally embeds run-specific identity, so they\n * can never be byte-equal across runs; chain integrity is asserted separately by the\n * adapters and the convergence helpers).\n *\n * Two runs whose cross-platform normalized evidence is byte-equal took canonically equivalent\n * histories — the exact sense in which durability §5 permits storage differences while\n * requiring the same observable ordering. Both the DN and DC suites assert equality against\n * the one committed `phase6TravelPlannerGoldenEvidence`, so DN ≡ DC transitively.\n */\nexport const normalizeCrossPlatformTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase6.normalizeCrossPlatformTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n identity: CrossPlatformEvidenceIdentity,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const canonical = records.filter(\n (envelope) => envelope.record.payload._tag !== \"RepairAnnotated\",\n );\n\n const base = yield* normalizeDurableTravelPlannerEvidence(canonical, receipt);\n\n const scrubbed: unknown = JSON.parse(\n JSON.stringify(base)\n .replaceAll(identity.producerId, \"{producerId}\")\n .replaceAll(identity.deploymentId, \"{deploymentId}\")\n .replaceAll(identity.threadId, \"{threadId}\")\n .replaceAll(/\\d{4}-\\d{2}-\\d{2}T[0-9:.]+Z/g, \"{timestamp}\")\n .replaceAll(/\"[0-9a-f]{64}\"/g, '\"{digest}\"'),\n );\n\n const comparable = yield* decodeComparableEnvelopes(scrubbed).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence lost the comparable shape: ${error.message}`,\n }),\n ),\n );\n\n const renumbered = comparable.map((entry, index) => ({\n batchId: entry.batchId,\n sequence: index + 1,\n record: entry.record,\n }));\n\n return yield* decodeComparableJson(renumbered).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n\n// ---------------------------------------------------------------------------\n// Prompt-aware scripted models. A DC Attempt may resume on a FRESH Object\n// incarnation whose Layers (and any in-memory turn counter) were rebuilt, so\n// every phase-6 model derives its response purely from the committed history\n// in its prompt — the way a real model would — instead of from call order.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\nconst promptAwareModel = (\n name: string,\n decide: (promptJson: string) => Stream.Stream<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(Effect.sync(() => decide(JSON.stringify(options.prompt)))),\n }),\n ),\n );\n\n/** The P1/P4 happy-path Tool Call identities (scenarios.ts, byte-stable since P1). */\nexport const phase6FlightCallId = \"flight-call-1\";\nexport const phase6LodgingCallId = \"lodging-call-1\";\nexport const phase6ActivityCallId = \"activity-call-1\";\n\n/** Turn 1 of the planner: the SAME three search declarations as `phase1HappyPathTurns`. */\nconst plannerSearchTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6FlightCallId,\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6LodgingCallId,\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6ActivityCallId,\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\n/** Turn 2 of the planner: the SAME itinerary text as `phase1HappyPathTurns`. */\nconst plannerPlanTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst plannerDecide = (promptJson: string): Stream.Stream<Response.StreamPartEncoded> =>\n promptJson.includes(phase6FlightCallId)\n ? Stream.fromIterable(plannerPlanTurnParts)\n : Stream.fromIterable(plannerSearchTurnParts);\n\n/**\n * The P4 planner script (`phase1HappyPathTurns`) as a prompt-aware model: once the search\n * batch is committed history, every later request gets the plan — identical parts, so the DC\n * canonical evidence is byte-equivalent to the DN ScriptedModel run after normalization.\n */\nexport const phase6PlannerModel = promptAwareModel(\"travel-planner-phase-4\", plannerDecide);\n\n// ---------------------------------------------------------------------------\n// Deterministic test gate for the admission-limits rows. Module state is\n// intentionally NOT durable: it plays the external world's role (a slow\n// upstream model), never Thread state.\n// ---------------------------------------------------------------------------\n\nconst releasedPlannerGates = new Set<string>();\n\n/** Release the gated planner model for one `[gate:...]` marker. */\nexport const releasePhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.add(marker);\n};\n\n/** Re-close one gate marker (fresh suites reuse markers safely). */\nexport const resetPhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.delete(marker);\n};\n\nconst awaitPlannerGate = (marker: string): Effect.Effect<void> =>\n Effect.gen(function* () {\n while (!releasedPlannerGates.has(marker)) {\n yield* Effect.sleep(Duration.millis(10));\n }\n });\n\nconst gateMarkerFromPrompt = (promptJson: string): string =>\n /\\[gate:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-gate\";\n\n/** A trip whose request text carries the gate marker the gated model waits on. */\nexport const phase6GatedTrip = (marker: string): TripRequest =>\n Schema.decodeSync(TripRequest)({\n request: `Plan a review-only London trip, but wait for the concierge. [gate:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\n/**\n * The SAME planner behavior with a hanging first response: the model waits on the released\n * gate before answering, keeping its lane durably busy so queue-depth admission limits can be\n * exercised deterministically.\n */\nexport const phase6GatedPlannerModel = Model.make(\n \"scripted\",\n \"travel-planner-phase-4-gated\",\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.sync(() => {\n const promptJson = JSON.stringify(options.prompt);\n\n return promptJson.includes(phase6FlightCallId)\n ? plannerDecide(promptJson)\n : Stream.fromEffectDrain(awaitPlannerGate(gateMarkerFromPrompt(promptJson))).pipe(\n Stream.concat(plannerDecide(promptJson)),\n );\n }),\n ),\n }),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// P5 booking slice: the SAME phase-5 booking agent and supplier desk. The desk\n// is a module-level singleton because it IS the external supplier: like a real\n// supplier's ledger, its bookings and call counters survive `ctx.abort()` and\n// incarnation loss, which is exactly what the never-fabricate and\n// executed-once assertions measure.\n// ---------------------------------------------------------------------------\n\nconst sharedSupplierDesk = Effect.runSync(\n Effect.flatMap(SupplierBookingDesk, Effect.succeed).pipe(\n Effect.provide(SupplierBookingDesk.layer),\n ),\n);\n\n/** The shared external supplier desk instance (module-level external truth). */\nexport const phase6SupplierDesk = sharedSupplierDesk;\n\n/** Layer handing the shared desk to Bindings, reconcilers, and assertions. */\nexport const phase6SupplierDeskLayer: Layer.Layer<SupplierBookingDesk> = Layer.succeed(\n SupplierBookingDesk,\n sharedSupplierDesk,\n);\n\n/**\n * The REAL P5 supplier reconciliation policy over the shared desk, closed to no requirements\n * so a Thread Object can install it directly: `book_flight` recovers only from supplier\n * truth (absence stays fail-closed `Uncertain` → durable Unknown Outcome), keyed Steps are\n * provably re-enterable.\n */\nexport const phase6SupplierReconcilerLayer: Layer.Layer<ToolReconciler> =\n TravelSupplierReconcilerLayer.pipe(Layer.provide(phase6SupplierDeskLayer));\n\nconst bookingMarkerFromPrompt = (promptJson: string): string =>\n /\\[case:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-case\";\n\n/** The deterministic booking Tool Call identity for one `[case:...]` marker. */\nexport const phase6BookingToolCallId = (marker: string): string => `book-${marker}`;\n\n/** The bookingRef the supplier desk mints for one marker's approved booking. */\nexport const phase6BookingRef = (marker: string): string =>\n supplierBookingRefFor(bookFlightIdempotencyKey(phase6BookingToolCallId(marker)));\n\n/** A trip whose request text carries the per-lane booking case marker. */\nexport const phase6BookingTrip = (marker: string): TripRequest =>\n Schema.decodeSync(TripRequest)({\n request: `Book the approved London flight for the traveler. [case:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\nconst bookingCallParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: phase6BookingToolCallId(marker),\n name: \"book_flight\",\n params: {\n quoteId: \"quote-sfo-lhr-001\",\n travelerRef: `traveler-${marker}`,\n departOn: \"2026-09-14\",\n },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst bookingReportParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"booking-report\" },\n {\n type: \"text-delta\",\n id: \"booking-report\",\n delta: JSON.stringify({\n summary: \"trip booked\",\n bookingRefs: [phase6BookingRef(marker)],\n }),\n },\n { type: \"text-end\", id: \"booking-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * The P5 booking script as a prompt-aware model: request 1 declares the approval-gated\n * `book_flight` call (identity derived from the lane's `[case:...]` marker so supplier\n * idempotency keys never collide across lanes); once that call is committed history, the model\n * writes the booking report.\n */\nexport const phase6BookingModel = promptAwareModel(\"travel-planner-phase-5\", (promptJson) => {\n const marker = bookingMarkerFromPrompt(promptJson);\n\n return promptJson.includes(phase6BookingToolCallId(marker))\n ? Stream.fromIterable(bookingReportParts(marker))\n : Stream.fromIterable(bookingCallParts(marker));\n});\n\n// ---------------------------------------------------------------------------\n// S2 delegation slice: the SAME coordinator → destination-researcher pair.\n// The guide invocation counter is module state for the same reason as the\n// desk: it is the child's external side-effect record, and \"the completed\n// child never re-executes\" is asserted against it across evictions.\n// ---------------------------------------------------------------------------\n\nlet guideInvocations = 0;\n\n/** Deterministic guide-lookup handler executions across every incarnation. */\nexport const phase6GuideInvocationCount = (): number => guideInvocations;\n\nconst countingGuideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Effect.suspend(() => {\n guideInvocations += 1;\n\n return destinationLookup(query);\n }),\n }),\n);\n\n/** The one-candidate research mission of the DC delegation slice. */\nexport const phase6ResearchMission = Schema.decodeSync(ResearchMission)({\n request: \"Shortlist one September culture city for the DC delegation slice.\",\n candidates: [\"LHR\"],\n});\n\nexport const phase6ResearchDestination = \"LHR\";\n\n/** The child's scripted guide-lookup Tool Call identity. */\nexport const phase6ChildLookupCallId = `lookup-${phase6ResearchDestination}`;\n\nconst coordinatorDelegationParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: durableResearchCallId,\n name: \"delegate_destination_research\",\n params: { destination: phase6ResearchDestination, focus: \"museums\" },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst coordinatorShortlistParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(\n Schema.encodeSync(DestinationShortlist)(durableResearchShortlist(phase6ResearchDestination)),\n ),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6ChildLookupCallId,\n name: \"lookup_destination\",\n params: { destination: phase6ResearchDestination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(phase6ResearchDestination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/** Prompt-aware S2 coordinator: delegation call first, shortlist once it is history. */\nexport const phase6CoordinatorModel = promptAwareModel(\"travel-coordinator-p6\", (promptJson) =>\n promptJson.includes(durableResearchCallId)\n ? Stream.fromIterable(coordinatorShortlistParts)\n : Stream.fromIterable(coordinatorDelegationParts),\n);\n\nlet researcherGateReleased = false;\n\n/** Allow the researcher's FIRST model response to proceed (sticky across incarnations). */\nexport const releasePhase6ResearcherGate = (): void => {\n researcherGateReleased = true;\n};\n\n/** Re-close the researcher gate (each delegation scenario starts gated). */\nexport const resetPhase6ResearcherGate = (): void => {\n researcherGateReleased = false;\n};\n\nconst awaitResearcherGate: Effect.Effect<void> = Effect.gen(function* () {\n while (!researcherGateReleased) {\n yield* Effect.sleep(Duration.millis(10));\n }\n});\n\n/**\n * Prompt-aware S2 researcher: guide lookup first, report once it is history. The FIRST\n * response waits on the researcher gate — a stand-in for real model latency. The child's own\n * Object may legally start its Attempt the moment its routed admission commits, while the\n * parent is still appending the lineage record into the child's log; a child whose first\n * batch commits during that window races the parent's append on one tail. Real models answer\n * in seconds, so establishment always wins that race in production; the gate reproduces that\n * timing deterministically instead of relying on scheduler luck.\n */\nexport const phase6ResearcherModel = promptAwareModel(\"destination-researcher-p6\", (promptJson) =>\n promptJson.includes(phase6ChildLookupCallId)\n ? Stream.fromIterable(researcherReportParts)\n : Stream.fromEffectDrain(awaitResearcherGate).pipe(\n Stream.concat(Stream.fromIterable(researcherLookupParts)),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// Worker Binding registrations for the DC Thread Object\n// ---------------------------------------------------------------------------\n\n/**\n * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts:\n * the P4 planner and its gated twin, the P5 booking agent over the\n * shared supplier desk, and the S2 coordinator/researcher pair wired through the durable\n * delegation Layer. A Thread Object registers these via its `bindings` option; the\n * capture runs once per incarnation, and everything stateful the assertions rely on (desk,\n * guide counter, gates) lives at module level so it survives incarnation loss.\n */\nexport const makePhase6TravelPlannerBindings: Effect.Effect<ReadonlyArray<ResolvedBinding>> =\n Effect.gen(function* () {\n const planner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6PlannerModel),\n phase4TravelPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const gatedPlanner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6GatedPlannerModel),\n phase6GatedPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const booking: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase5, phase6BookingModel),\n phase5TravelPlannerDefinitionDigests,\n ).pipe(\n Effect.provide(\n phase5TravelPlannerWorkerLayer.pipe(Layer.provideMerge(phase6SupplierDeskLayer)),\n ),\n );\n\n const researcherBinding = Agent.withModel(DestinationResearcher, phase6ResearcherModel);\n\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(countingGuideLayer),\n );\n\n const coordinator: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelCoordinator, phase6CoordinatorModel),\n s2CoordinatorDigests,\n ).pipe(\n Effect.provide(\n durableDestinationResearchHandlersLayer(researcherBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n ),\n ),\n );\n\n const researcher: ResolvedBinding = yield* DurableWorkerBinding.make(\n researcherBinding,\n s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n return [planner, gatedPlanner, booking, coordinator, researcher];\n });\n\n// ---------------------------------------------------------------------------\n// The committed golden normalized-evidence fixture (D-P6-6)\n// ---------------------------------------------------------------------------\n\n/**\n * The committed cross-platform normalized canonical evidence of ONE uninterrupted Travel\n * Planner planning Submission (the P1/P4 happy path: canonical input, the search Turn, three\n * Tool settlements, the plan Turn, one Settlement). `travel-planner-phase6.test.ts` asserts\n * the DN run equals this value and `travel-planner-dc.test.ts` asserts the DC run equals this\n * value, so the two platforms' canonical outcomes are byte-equivalent transitively — the P6\n * exit gate \"Travel Planner produces equivalent canonical outcomes under DN and DC\".\n *\n * Regenerate ONLY when the Travel Planner scenario itself changes, by printing either suite's\n * normalized value; both suites must then agree on the new golden.\n */\nexport const phase6TravelPlannerGoldenEvidence: Schema.Json = [\n {\n batchId: \"thread-created:{threadId}\",\n sequence: 1,\n record: {\n recordId: \"thread-created:{threadId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ThreadCreated\",\n agentId: \"travel-planner-phase-4\",\n definitions: {\n agent: \"{digest}\",\n model: \"{digest}\",\n tools: \"{digest}\",\n },\n },\n },\n },\n {\n batchId: \"submission-input:{submissionId}\",\n sequence: 2,\n record: {\n recordId: \"input:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"UserInputRecorded\",\n submissionId: \"{submissionId}\",\n kind: \"user\",\n runId: \"run:{submissionId}\",\n input: {\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350000,\n currency: \"USD\",\n },\n },\n },\n },\n {\n batchId: \"run-start:run:{submissionId}\",\n sequence: 3,\n record: {\n recordId: \"run-start:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunStarted\",\n runId: \"run:{submissionId}\",\n policyAccountingVersion: 1,\n maxDurationMillis: 30_000,\n },\n },\n },\n {\n batchId: \"turn-response:run:{submissionId}:1\",\n sequence: 4,\n record: {\n recordId: \"model-response:run:{submissionId}:1\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:1\",\n turn: 1,\n inputTokens: 128,\n outputTokens: 96,\n runScopedPrefixLength: 2,\n modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\n messages: {\n content: [\n {\n options: {},\n role: \"system\",\n content:\n 'You are the Effect Agent Travel Planner P1 interpreter fixture.\\nThe user asked: Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\\nCall search_flights, search_lodging, and search_activities exactly once in one Tool batch.\\nThen return only a JSON object of exactly this shape, no prose:\\n{\"itineraries\": [{\"title\": \"<short itinerary name>\", \"route\": \"<origin-destination>\", \"dates\": \"<date range>\", \"flight\": \"<flight description from the Tool result>\", \"lodging\": \"<lodging description from the Tool result>\", \"activities\": [\"<activity>\", \"...\"], \"estimatedTotalCents\": <positive integer total in cents>, \"currency\": \"USD\", \"quoteId\": \"<quoteId from the flight Tool result>\", \"assumptions\": [\"<assumption>\", \"...\"], \"unresolvedConstraints\": [], \"nextAction\": \"review\"}]}\\nUse the Tool results verbatim; activity results may legitimately be an empty array.\\nThis is read-only planning. Require review before any mutation.',\n },\n {\n options: {},\n role: \"user\",\n content:\n '{\"request\":\"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\"origin\":\"SFO\",\"destination\":\"LHR\",\"departOn\":\"2026-09-14\",\"nights\":4,\"travelers\":2,\"budgetCents\":350000,\"currency\":\"USD\"}',\n },\n {\n options: {},\n role: \"assistant\",\n content: [\n {\n options: {},\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: {\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n ],\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 5,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:flight-call-1\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"flight-call-1\",\n toolName: \"search_flights\",\n result: {\n quoteId: \"quote-sfo-lhr-001\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 6,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:lodging-call-1\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"lodging-call-1\",\n toolName: \"search_lodging\",\n result: {\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 7,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:activity-call-1\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"activity-call-1\",\n toolName: \"search_activities\",\n result: {\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn:run:{submissionId}:2\",\n sequence: 8,\n record: {\n recordId: \"model-response:run:{submissionId}:2\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:2\",\n turn: 2,\n inputTokens: 128,\n outputTokens: 96,\n modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\n messages: {\n content: [\n {\n options: {},\n role: \"assistant\",\n content:\n '{\"itineraries\":[{\"title\":\"Westward light, eastbound overnight\",\"route\":\"San Francisco → London\",\"dates\":\"14–19 September 2026\",\"flight\":\"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\"lodging\":\"Bloomsbury House · refundable studio · 4 nights\",\"activities\":[\"British Museum timed entry\",\"Thames evening walk\"],\"estimatedTotalCents\":284000,\"currency\":\"USD\",\"quoteId\":\"quote-sfo-lhr-001\",\"assumptions\":[\"Two travelers sharing one studio\",\"Quote is read-only availability, not a reservation\"],\"unresolvedConstraints\":[\"Traveler names and accessibility requests are intentionally omitted\"],\"nextAction\":\"review\"}]}',\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"turn:run:{submissionId}:2\",\n sequence: 9,\n record: {\n recordId: \"run-completed:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunCompleted\",\n runId: \"run:{submissionId}\",\n output: {\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n },\n },\n },\n },\n {\n batchId: \"submission-settlement:{submissionId}\",\n sequence: 10,\n record: {\n recordId: \"settlement:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"SubmissionSettled\",\n submissionId: \"{submissionId}\",\n settlementId: \"settlement:{submissionId}\",\n receiptId: \"{receiptId}\",\n outcome: \"completed\",\n runId: \"run:{submissionId}\",\n result: {\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n },\n usageSummary: {\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n unobservedModelCalls: 0,\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n byModel: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\n },\n },\n },\n },\n];\n","/** Explicit opt-in switch for live integration tests. */\nexport const PHASE7_LIVE_GATE_ENV = \"EFFECT_AGENT_LIVE\";\n\n/** The credential required by the Travel Planner live-model tests. */\nexport const PHASE7_LIVE_CREDENTIAL_ENV = \"OPENAI_API_KEY\";\n\n/** Structural shape of an environment without importing Node types. */\nexport interface Phase7LiveGateEnvironment {\n readonly [name: string]: string | undefined;\n}\n\n/** Enable live tests only when both the opt-in flag and credential are present. */\nexport const phase7LiveProfileEnabled = (env: Phase7LiveGateEnvironment): boolean =>\n env[PHASE7_LIVE_GATE_ENV] === \"1\" && (env[PHASE7_LIVE_CREDENTIAL_ENV] ?? \"\") !== \"\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,uBAAb,cAA0C,OAAO,MAC/C,2DACF,CAAC,CAAC;CACA,SAAS;CACT,kBAAkB,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,EAAE,CAAC;AAC5F,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,gBAAb,cAAmC,OAAO,MACxC,oDACF,CAAC,CAAC;CACA,QAAQ,OAAO;CACf,SAAS;CACT,QAAQ,OAAO,QAAQ,MAAM;AAC/B,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA;CACE,SAAS;CACT,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,QAAQ,QAOhD,CAAC,CAAC,2DAA2D,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;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,aAAa;IACb,cAAc;IACd,uBAAuB;IACvB,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,UAAU,EACR,SAAS;KACP;MACE,SAAS,CAAC;MACV,MAAM;MACN,SACE;KACJ;KACA;MACE,SAAS,CAAC;MACV,MAAM;MACN,SACE;KACJ;KACA;MACE,SAAS,CAAC;MACV,MAAM;MACN,SAAS;OACP;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,QAAQ;SACR,aAAa;SACb,UAAU;SACV,WAAW;QACb;QACA,kBAAkB;OACpB;OACA;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,aAAa;SACb,UAAU;SACV,QAAQ;SACR,WAAW;QACb;QACA,kBAAkB;OACpB;OACA;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,aAAa;SACb,UAAU;SACV,QAAQ;SACR,WAAW;QACb;QACA,kBAAkB;OACpB;MACF;KACF;IACF,EACF;IACA,gBAAgB;GAClB;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ;KACN,SAAS;KACT,QAAQ;KACR,gBAAgB;KAChB,UAAU;IACZ;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ;KACN,SAAS;KACT,gBAAgB;KAChB,UAAU;IACZ;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ,EACN,YAAY,CAAC,8BAA8B,qBAAqB,EAClE;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,aAAa;IACb,cAAc;IACd,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,UAAU,EACR,SAAS,CACP;KACE,SAAS,CAAC;KACV,MAAM;KACN,SACE;IACJ,CACF,EACF;IACA,gBAAgB;GAClB;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ,EACN,aAAa,CACX;KACE,OAAO;KACP,OAAO;KACP,OAAO;KACP,QAAQ;KACR,SAAS;KACT,YAAY,CAAC,8BAA8B,qBAAqB;KAChE,qBAAqB;KACrB,UAAU;KACV,SAAS;KACT,aAAa,CACX,oCACA,oDACF;KACA,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