@effect-agent/testing 0.1.0-beta.38 → 0.1.0-beta.40

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 (44) hide show
  1. package/dist/certification.d.mts +102 -0
  2. package/dist/certification.mjs +561 -0
  3. package/dist/certification.mjs.map +1 -0
  4. package/dist/chaos.d.mts +124 -0
  5. package/dist/chaos.mjs +739 -0
  6. package/dist/chaos.mjs.map +1 -0
  7. package/dist/code-executor.d.mts +48 -0
  8. package/dist/code-executor.mjs +565 -0
  9. package/dist/code-executor.mjs.map +1 -0
  10. package/dist/deterministic-layers-CKyYxBhN.mjs +354 -0
  11. package/dist/deterministic-layers-CKyYxBhN.mjs.map +1 -0
  12. package/dist/docs-researcher.d.mts +254 -0
  13. package/dist/docs-researcher.mjs +479 -0
  14. package/dist/docs-researcher.mjs.map +1 -0
  15. package/dist/index.d.mts +2 -2947
  16. package/dist/index.mjs +2 -4913
  17. package/dist/scripted-model-C2y0ztuj.mjs +167 -0
  18. package/dist/scripted-model-C2y0ztuj.mjs.map +1 -0
  19. package/dist/scripted-model-dOa_e0-n.d.mts +677 -0
  20. package/dist/travel-planner.d.mts +1767 -0
  21. package/dist/travel-planner.mjs +2103 -0
  22. package/dist/travel-planner.mjs.map +1 -0
  23. package/package.json +34 -11
  24. package/src/certification.ts +71 -61
  25. package/src/chaos.ts +58 -71
  26. package/src/code-executor.ts +3 -0
  27. package/src/docs-researcher.ts +2 -0
  28. package/src/fixtures/docs-researcher/definition.ts +7 -7
  29. package/src/fixtures/docs-researcher/harness.ts +12 -14
  30. package/src/fixtures/docs-researcher/index.ts +1 -1
  31. package/src/fixtures/travel-planner/definition.ts +1 -1
  32. package/src/fixtures/travel-planner/deterministic-layers.ts +7 -4
  33. package/src/fixtures/travel-planner/phase2.ts +1 -1
  34. package/src/fixtures/travel-planner/phase3.ts +14 -18
  35. package/src/fixtures/travel-planner/phase4.ts +7 -7
  36. package/src/fixtures/travel-planner/phase5.ts +5 -5
  37. package/src/fixtures/travel-planner/phase6.ts +30 -29
  38. package/src/fixtures/travel-planner/subagents-durable.ts +6 -6
  39. package/src/fixtures/travel-planner/subagents.ts +4 -4
  40. package/src/index.ts +1 -10
  41. package/src/travel-planner.ts +2 -0
  42. package/dist/index.mjs.map +0 -1
  43. package/src/code-executor-conformance.d.ts +0 -30
  44. package/src/fixtures/warehouse/index.ts +0 -412
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-executor.mjs","names":[],"sources":["../src/code-executor-conformance.ts","../src/code-executor-substitute.ts"],"sourcesContent":["import {\n CodeExecutionHost,\n CodeExecutionLimits,\n CodeExecutionNamespace,\n CodeExecutionRequest,\n CodeExecutor,\n CodeHostCallFailure,\n CodeHostCallSuccess,\n NetworkAllowlist,\n NetworkDisabled,\n type CodeExecutionError,\n type CodeExecutionResult,\n type CodeHostCall,\n type CodeHostCallResult,\n type SandboxImplementation,\n} from \"@effect-agent/sandbox\";\nimport { Deferred, Duration, Effect, Fiber, Schema } from \"effect\";\n\n/**\n * Shared `CodeExecutor` conformance (TEST-015). Every adapter — the\n * deterministic `unisolated` substitute and each isolated adapter — runs\n * `codeExecutorConformanceCases` verbatim. Enforcement cases that only genuine\n * isolation can prove (ambient network denial, synchronous CPU runaway\n * termination) are NOT here; they belong to isolated adapters only\n * (testing spec §8.1).\n *\n * Cases assume the live `Clock` (the wall-clock case uses a short real\n * deadline) and take one fresh executor pass per case, so a suite may share\n * one executor Layer across cases.\n */\nexport class CodeExecutorConformanceViolation extends Schema.TaggedError<CodeExecutorConformanceViolation>()(\n \"CodeExecutorConformanceViolation\",\n {\n caseName: Schema.String,\n message: Schema.String,\n },\n) {}\n\nexport interface CodeExecutorConformanceCase {\n readonly name: string;\n readonly run: Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor>;\n}\n\nexport interface CodeExecutorConformanceOptions {\n /** The posture the adapter under test must stamp on results and errors. */\n readonly implementation: SandboxImplementation;\n}\n\nconst baseLimits = CodeExecutionLimits.make({\n maxSourceBytes: 64 * 1024,\n maxWallTime: Duration.seconds(10),\n maxLogBytes: 16 * 1024,\n maxResultBytes: 64 * 1024,\n maxHostCalls: 8,\n maxHostCallArgumentBytes: 16 * 1024,\n maxHostCallResultBytes: 32 * 1024,\n});\n\nconst warehouseNamespace = CodeExecutionNamespace.make({\n name: \"warehouse\",\n methods: [\"query\", \"count\"],\n});\n\nconst makeRequest = (\n source: string,\n overrides?: {\n readonly limits?: CodeExecutionLimits;\n readonly namespaces?: ReadonlyArray<CodeExecutionNamespace>;\n readonly network?: CodeExecutionRequest[\"network\"];\n },\n): CodeExecutionRequest =>\n CodeExecutionRequest.make({\n language: \"javascript\",\n source,\n namespaces: overrides?.namespaces ?? [],\n network: overrides?.network ?? NetworkDisabled.make(),\n limits: overrides?.limits ?? baseLimits,\n });\n\nconst unusedHost: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Effect.die(\n new Error(\"this conformance case expected no host call to reach the CodeExecutionHost\"),\n ),\n};\n\nconst respondingHost = (\n respond: (call: CodeHostCall) => CodeHostCallResult,\n): { readonly host: CodeExecutionHost[\"Service\"]; readonly calls: Array<CodeHostCall> } => {\n const calls: Array<CodeHostCall> = [];\n return {\n calls,\n host: {\n call: (call) =>\n Effect.sync(() => {\n calls.push(call);\n return respond(call);\n }),\n },\n };\n};\n\nconst runPass = (\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n): Effect.Effect<CodeExecutionResult, CodeExecutionError, CodeExecutor> =>\n Effect.gen(function* () {\n const executor = yield* CodeExecutor;\n return yield* executor\n .execute(request)\n .pipe(Effect.provideService(CodeExecutionHost, CodeExecutionHost.of(host)));\n }).pipe(Effect.scoped);\n\nconst violation = (caseName: string, message: string) =>\n CodeExecutorConformanceViolation.make({ caseName, message });\n\nconst preview = (value: unknown): string => {\n try {\n return JSON.stringify(value)?.slice(0, 200) ?? String(value).slice(0, 200);\n } catch {\n return String(value).slice(0, 200);\n }\n};\n\nconst expectSuccess = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n check: (result: CodeExecutionResult) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n Effect.flatMap((result) => {\n const complaint = check(result);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nconst expectFailure = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n tag: CodeExecutionError[\"_tag\"],\n check?: (error: CodeExecutionError) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.flip,\n Effect.mapError((result) =>\n violation(caseName, `expected ${tag}, but the pass succeeded with ${preview(result.value)}`),\n ),\n Effect.flatMap((error) => {\n if (error._tag !== tag) {\n return Effect.fail(\n violation(caseName, `expected ${tag}, got ${error._tag}: ${preview(error)}`),\n );\n }\n const complaint = check?.(error);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nexport const codeExecutorConformanceCases = (\n options: CodeExecutorConformanceOptions,\n): ReadonlyArray<CodeExecutorConformanceCase> => {\n const posture = options.implementation;\n return [\n {\n name: \"TEST-015 executes bounded JSON computation and returns the program value\",\n run: expectSuccess(\n \"TEST-015 executes bounded JSON computation and returns the program value\",\n makeRequest(\n \"async () => { const xs = [1, 2, 3].map((n) => n * 2); return { xs, sum: xs.reduce((a, b) => a + b, 0) }; }\",\n ),\n unusedHost,\n (result) =>\n JSON.stringify(result.value) === JSON.stringify({ xs: [2, 4, 6], sum: 12 })\n ? undefined\n : `unexpected program value ${preview(result.value)}`,\n ),\n },\n {\n name: \"CAP-015 reports its isolation posture honestly in results and errors\",\n run: Effect.gen(function* () {\n const caseName = \"CAP-015 reports its isolation posture honestly in results and errors\";\n const result = yield* runPass(makeRequest(\"async () => 1\"), unusedHost).pipe(\n Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}`)),\n );\n if (\n result.implementation.isolation !== posture.isolation ||\n result.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `result posture ${preview(result.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n const error = yield* runPass(makeRequest(\"async () => {\"), unusedHost).pipe(\n Effect.flip,\n Effect.mapError(() => violation(caseName, \"expected the invalid-source pass to fail\")),\n );\n // Every expected execution failure carries the posture; an adapter\n // omitting the field must fail this case, not slip past a probe.\n if (\n error.implementation === undefined ||\n error.implementation.isolation !== posture.isolation ||\n error.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `error posture ${preview(error.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 routes host calls through the CodeExecutionHost in program order\",\n run: Effect.gen(function* () {\n const caseName =\n \"TEST-015 routes host calls through the CodeExecutionHost in program order\";\n const { host, calls } = respondingHost((call) =>\n call.method === \"query\"\n ? CodeHostCallSuccess.make({ value: { rows: [1, 2, 3] } })\n : CodeHostCallSuccess.make({ value: 3 }),\n );\n const result = yield* runPass(\n makeRequest(\n \"async () => { const q = await warehouse.query({ sql: 'select' }); const c = await warehouse.count({ table: 't' }); return { rows: q.rows, count: c }; }\",\n { namespaces: [warehouseNamespace] },\n ),\n host,\n ).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n );\n if (JSON.stringify(result.value) !== JSON.stringify({ rows: [1, 2, 3], count: 3 })) {\n return yield* violation(caseName, `unexpected value ${preview(result.value)}`);\n }\n const observed = calls.map((call) => `${call.namespace}.${call.method}`);\n if (JSON.stringify(observed) !== JSON.stringify([\"warehouse.query\", \"warehouse.count\"])) {\n return yield* violation(caseName, `unexpected host call order ${preview(observed)}`);\n }\n if (result.resourceUse.hostCalls !== 2) {\n return yield* violation(\n caseName,\n `expected 2 accounted host calls, got ${result.resourceUse.hostCalls}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n run: expectSuccess(\n \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n makeRequest(\n \"async () => { try { await warehouse.query({ sql: 'x' }); return 'unreachable'; } catch (envelope) { return { caught: envelope }; } }\",\n { namespaces: [warehouseNamespace] },\n ),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"ToolInputError\", message: \"bad input\" } }),\n ).host,\n (result) =>\n JSON.stringify(result.value) ===\n JSON.stringify({ caught: { _tag: \"ToolInputError\", message: \"bad input\" } })\n ? undefined\n : `the envelope did not round-trip: ${preview(result.value)}`,\n ),\n },\n {\n name: \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n run: expectFailure(\n \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n makeRequest(\"async () => warehouse.query({ sql: 'x' })\", {\n namespaces: [warehouseNamespace],\n }),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"PolicyDenied\", message: \"denied\" } }),\n ).host,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"rejected\" &&\n JSON.stringify(error.thrown) ===\n JSON.stringify({ _tag: \"PolicyDenied\", message: \"denied\" })\n ? undefined\n : `unexpected failure detail ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on syntactically invalid source\",\n run: expectFailure(\n \"TEST-015 fails typed on syntactically invalid source\",\n makeRequest(\"async () => {\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"invalid\"\n ? undefined\n : `expected reason invalid, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the expression is not one async function\",\n run: expectFailure(\n \"TEST-015 fails typed when the expression is not one async function\",\n makeRequest(\"1 + 1\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"not-a-function\"\n ? undefined\n : `expected reason not-a-function, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on source larger than the declared byte limit\",\n run: expectFailure(\n \"TEST-015 fails typed on source larger than the declared byte limit\",\n makeRequest(`async () => \"${\"x\".repeat(2_000)}\"`, {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxSourceBytes: 256 }),\n }),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"oversized\"\n ? undefined\n : `expected reason oversized, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n run: expectFailure(\n \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n makeRequest(\"async () => { await new Promise(() => {}); return 1; }\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxWallTime: Duration.millis(250) }),\n }),\n unusedHost,\n \"CodeExecutionTimeoutError\",\n ),\n },\n {\n name: \"TEST-015 fails typed when console output exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when console output exceeds its byte budget\",\n makeRequest(\n \"async () => { for (let i = 0; i < 64; i += 1) { console.log('x'.repeat(256)); } return 1; }\",\n { limits: CodeExecutionLimits.make({ ...baseLimits, maxLogBytes: 2_048 }) },\n ),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"logs\"\n ? undefined\n : `expected surface logs, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the final result exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when the final result exceeds its byte budget\",\n makeRequest(\"async () => 'y'.repeat(4096)\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxResultBytes: 1_024 }),\n }),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"result\"\n ? undefined\n : `expected surface result, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when host calls exceed the executor cap\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 fails typed when host calls exceed the executor cap\";\n const { host, calls } = respondingHost(() => CodeHostCallSuccess.make({ value: null }));\n yield* expectFailure(\n caseName,\n makeRequest(\n \"async () => { await warehouse.query({}); await warehouse.query({}); await warehouse.query({}); return 1; }\",\n {\n namespaces: [warehouseNamespace],\n limits: CodeExecutionLimits.make({ ...baseLimits, maxHostCalls: 2 }),\n },\n ),\n host,\n \"CodeHostCallLimitError\",\n );\n // The cap is enforced before dispatch: the over-limit call must never\n // have reached the host, or an unauthorized side effect already ran.\n if (calls.length !== 2) {\n return yield* violation(\n caseName,\n `expected exactly 2 dispatched host calls under a cap of 2, observed ${calls.length}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n run: expectFailure(\n \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n {\n // Deliberately violate the compile-time host contract to verify that an adapter\n // independently decodes the runtime protocol boundary.\n call: () => Effect.succeed({ bogus: true } as unknown as CodeHostCallResult),\n },\n \"CodeExecutionProtocolError\",\n ),\n },\n {\n name: \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n run: expectFailure(\n \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n makeRequest(\n \"async () => { console.log('before the failure'); throw new Error('deliberate'); }\",\n ),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"threw\" &&\n error.logs.some((line) => line.includes(\"before the failure\"))\n ? undefined\n : `expected a threw failure carrying the log capture, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the program returns a non-JSON value\",\n run: expectFailure(\n \"TEST-015 fails typed when the program returns a non-JSON value\",\n makeRequest(\"async () => (() => 1)\"),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" && error.reason === \"non-json-result\"\n ? undefined\n : `expected reason non-json-result, got ${preview(error)}`,\n ),\n },\n {\n name: \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n run: expectFailure(\n \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n makeRequest(\"async () => 1\", {\n network: NetworkAllowlist.make({ domains: [\"example.com\"], ports: [443] }),\n }),\n unusedHost,\n \"CodeExecutorUnsupportedError\",\n (error) =>\n error._tag === \"CodeExecutorUnsupportedError\" && error.feature === \"network\"\n ? undefined\n : `expected feature network, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 interruption reaches in-flight host calls and pass teardown\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 interruption reaches in-flight host calls and pass teardown\";\n const started = yield* Deferred.make<void>();\n const witness = { hostCallInterrupted: false };\n const host: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Effect.never),\n Effect.ensuring(\n Effect.sync(() => {\n witness.hostCallInterrupted = true;\n }),\n ),\n ),\n };\n const fiber = yield* runPass(\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n host,\n ).pipe(Effect.forkChild);\n // Guard against a broken adapter that settles the pass without ever\n // reaching the host: the case must report a violation, not hang.\n const winner = yield* Effect.raceFirst(\n Deferred.await(started).pipe(Effect.as(\"started\" as const)),\n Fiber.join(fiber).pipe(Effect.exit, Effect.as(\"exited\" as const)),\n );\n if (winner === \"exited\") {\n return yield* violation(\n caseName,\n \"the pass settled before any host call reached the CodeExecutionHost\",\n );\n }\n yield* Fiber.interrupt(fiber);\n if (!witness.hostCallInterrupted) {\n return yield* violation(\n caseName,\n \"interrupting the pass did not interrupt the in-flight host call\",\n );\n }\n }),\n },\n ];\n};\n","import {\n CodeExecutionHost,\n CodeExecutionProtocolError,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n type CodeExecutorExecute,\n CodeExecutorUnsupportedError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n SandboxImplementation,\n type CodeExecutionLimits,\n type CodeExecutionNamespace,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox\";\nimport { Clock, Duration, Effect, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\n/**\n * The deterministic in-process executor substitute (C1 of ADR-0017). It runs\n * the generated program on the host JavaScript engine with best-effort global\n * shadowing only, so it self-identifies as `unisolated` and is never a\n * security boundary (CAP-010, CAP-015). It exists to prove the public\n * `CodeExecutor` contract and to drive deterministic capability tests.\n */\nexport const inProcessCodeExecutorImplementation = SandboxImplementation.make({\n isolation: \"unisolated\",\n identity: \"in-process-javascript\",\n});\n\n// These two caps mirror the wire schema bounds (`BoundedLogs` is at most\n// 4096 lines of at most 16 KiB each): capture must stay inside what\n// `CodeExecutionResult` can carry. A line over the per-line cap is truncated\n// with an explicit `…` marker; exceeding either the byte budget or the line\n// cap fails the pass typed.\nconst MAX_LOG_LINES = 4_096;\nconst MAX_LOG_LINE_CHARACTERS = 16_000;\nconst MAX_THROWN_CHARACTERS = 4_000;\n\nconst utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength;\n\n/**\n * Ambient globals shadowed inside the harness. Shadowing blocks the obvious\n * identifier paths only; a determined program can still escape, which is\n * exactly why this executor reports `unisolated` and the isolated network and\n * CPU enforcement conformance cases run only against isolated adapters.\n */\nconst shadowedGlobals = [\n \"fetch\",\n \"process\",\n \"require\",\n \"module\",\n \"exports\",\n \"global\",\n \"globalThis\",\n \"XMLHttpRequest\",\n \"WebSocket\",\n \"Deno\",\n \"Bun\",\n] as const;\n\nclass LogLimitSignal {\n constructor(readonly observed: number) {}\n}\n\nclass EvaluationThrew {\n constructor(readonly inner: unknown) {}\n}\n\nclass NotAFunction {\n constructor(readonly actual: string) {}\n}\n\ninterface LogCapture {\n readonly lines: Array<string>;\n bytes: number;\n}\n\n/**\n * Total, defect-free rendering of untrusted values: a hostile Proxy can throw\n * from property access, `toString`, and `Symbol.toPrimitive`, and an expected\n * program failure must never escape the typed channel as a defect while its\n * diagnostics are being serialized.\n */\nconst formatLogValue = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value) ?? String(value);\n } catch {\n try {\n return String(value);\n } catch {\n return \"[unprintable value]\";\n }\n }\n};\n\nconst makeConsole = (capture: LogCapture, limits: CodeExecutionLimits) => {\n const write = (...values: ReadonlyArray<unknown>): void => {\n const joined = values.map(formatLogValue).join(\" \");\n const line =\n joined.length > MAX_LOG_LINE_CHARACTERS\n ? `${joined.slice(0, MAX_LOG_LINE_CHARACTERS - 1)}…`\n : joined;\n const bytes = utf8ByteLength(line);\n if (capture.lines.length >= MAX_LOG_LINES || capture.bytes + bytes > limits.maxLogBytes) {\n throw new LogLimitSignal(capture.bytes + bytes);\n }\n capture.lines.push(line);\n capture.bytes += bytes;\n };\n return { debug: write, error: write, info: write, log: write, warn: write };\n};\n\ninterface PendingHostCall {\n readonly namespace: string;\n readonly method: string;\n readonly argument: unknown;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\nconst buildNamespaceObject = (\n namespace: CodeExecutionNamespace,\n offer: (pending: PendingHostCall) => void,\n): Record<string, unknown> => {\n const methods: Record<string, unknown> = {};\n for (const method of namespace.methods) {\n methods[method] = (argument: unknown) =>\n new Promise((resolve, reject) => {\n offer({ namespace: namespace.name, method, argument, resolve, reject });\n });\n }\n return methods;\n};\n\nconst boundedText = (value: unknown): string => {\n try {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : formatLogValue(value);\n return text.slice(0, MAX_THROWN_CHARACTERS);\n } catch {\n return \"[unserializable thrown value]\";\n }\n};\n\n/** Schema decoding of hostile values may itself throw through trap getters. */\nconst safeDecodeJson = (value: unknown): Option.Option<Schema.Json> => {\n try {\n return Schema.decodeUnknownOption(Schema.Json)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst boundedThrown = (value: unknown): Schema.Json => {\n const decoded = safeDecodeJson(value);\n if (Option.isSome(decoded)) {\n try {\n const encoded = JSON.stringify(decoded.value);\n if (encoded !== undefined && encoded.length <= MAX_THROWN_CHARACTERS) {\n return decoded.value;\n }\n } catch {\n // fall through to the bounded string form\n }\n }\n return boundedText(value);\n};\n\nconst encodedJsonByteLength = (value: Schema.Json): number | undefined => {\n try {\n const encoded = JSON.stringify(value);\n return encoded === undefined ? undefined : utf8ByteLength(encoded);\n } catch {\n return undefined;\n }\n};\n\n/** Host outcomes are protocol input; a hostile value must not defect mid-decode. */\nconst decodeHostOutcome = (value: unknown): Option.Option<CodeHostCallResult> => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst validateRequest = (\n request: CodeExecutionRequest,\n): Effect.Effect<void, CodeExecutorUnsupportedError | CodeSourceError> =>\n Effect.gen(function* () {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"network\",\n message:\n \"The unisolated in-process executor cannot enforce an egress allowlist; only NetworkDisabled is accepted, and even that is shadowed rather than enforced\",\n });\n }\n if (request.limits.cpuMillis !== undefined) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"cpu-limit\",\n message:\n \"The unisolated in-process executor shares the host engine and cannot enforce a CPU limit\",\n });\n }\n const reservedNames = new Set<string>([...shadowedGlobals, \"console\"]);\n const seen = new Set<string>();\n for (const namespace of request.namespaces) {\n if (reservedNames.has(namespace.name) || seen.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding or another namespace`,\n });\n }\n seen.add(namespace.name);\n }\n const sourceBytes = utf8ByteLength(request.source);\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n });\n\nconst serveHostCalls = (\n host: CodeExecutionHost[\"Service\"],\n queue: Queue.Queue<PendingHostCall>,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n counter: { calls: number },\n): Effect.Effect<\n never,\n CodeHostCallLimitError | CodeOutputLimitError | CodeExecutionProtocolError\n> =>\n Effect.gen(function* () {\n while (true) {\n const pending = yield* Queue.take(queue);\n counter.calls += 1;\n if (counter.calls > limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n const argument = safeDecodeJson(pending.argument);\n if (Option.isNone(argument)) {\n pending.reject(new TypeError(\"host call arguments must be JSON values\"));\n continue;\n }\n const argumentBytes = encodedJsonByteLength(argument.value);\n if (argumentBytes === undefined || argumentBytes > limits.maxHostCallArgumentBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-argument\",\n limit: limits.maxHostCallArgumentBytes,\n observed: argumentBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n const rawOutcome = yield* host.call(\n CodeHostCall.make({\n namespace: pending.namespace,\n method: pending.method,\n argument: argument.value,\n }),\n );\n const outcome = decodeHostOutcome(rawOutcome);\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: inProcessCodeExecutorImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n }\n if (outcome.value._tag === \"CodeHostCallFailure\") {\n pending.reject(outcome.value.error);\n continue;\n }\n const resultBytes = encodedJsonByteLength(outcome.value.value);\n if (resultBytes === undefined || resultBytes > limits.maxHostCallResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-result\",\n limit: limits.maxHostCallResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n pending.resolve(outcome.value.value);\n }\n });\n\nconst classifyProgramFailure = (\n thrown: unknown,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n): CodeOutputLimitError | CodeSourceError | CodeProgramFailedError => {\n const inner = thrown instanceof EvaluationThrew ? thrown.inner : thrown;\n if (inner instanceof LogLimitSignal) {\n return CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"logs\",\n limit: limits.maxLogBytes,\n observed: inner.observed,\n logs: [...capture.lines],\n });\n }\n if (inner instanceof NotAFunction) {\n return CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${inner.actual}; it must evaluate to one async function`,\n });\n }\n // An async function converts a body-level `throw` into a rejection, so the\n // split is by value shape: exception-like values read as `threw`, plain\n // rejection values (an uncaught host failure envelope) read as `rejected`.\n const reason = thrown instanceof EvaluationThrew || inner instanceof Error ? \"threw\" : \"rejected\";\n return CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason,\n thrown: boundedThrown(inner),\n message: boundedText(inner),\n logs: [...capture.lines],\n });\n};\n\nconst executeInProcess: CodeExecutorExecute = Effect.fn(\"InProcessCodeExecutor.execute\")(\n function* (request) {\n yield* validateRequest(request);\n const host = yield* CodeExecutionHost;\n const capture: LogCapture = { lines: [], bytes: 0 };\n const counter = { calls: 0 };\n const queue = yield* Queue.unbounded<PendingHostCall>();\n\n const factory = yield* Effect.try({\n try: () =>\n // This substitute intentionally evaluates authored test programs in-process and reports\n // an `unisolated` posture. Real adapters own the security boundary and never use this path.\n // oxlint-disable-next-line typescript/no-implied-eval\n new Function(\n ...shadowedGlobals,\n \"console\",\n ...request.namespaces.map((namespace) => namespace.name),\n `\"use strict\";\\nreturn (\\n${request.source}\\n);`,\n ),\n catch: (cause) =>\n CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"invalid\",\n message: boundedText(cause),\n }),\n });\n\n const harnessConsole = makeConsole(capture, request.limits);\n // Admission is enforced at call creation, not only at the single-consumer\n // dequeue: a burst of unawaited calls can enqueue at most one entry past\n // the cap (the entry the server fails the pass on); everything beyond is\n // rejected synchronously, so the queue stays bounded against hostile\n // programs.\n let issuedHostCalls = 0;\n const namespaceObjects = request.namespaces.map((namespace) =>\n buildNamespaceObject(namespace, (pending) => {\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls + 1) {\n pending.reject(new Error(`host-call limit of ${request.limits.maxHostCalls} exceeded`));\n return;\n }\n Queue.offerUnsafe(queue, pending);\n }),\n );\n\n const server = yield* serveHostCalls(host, queue, request.limits, capture, counter).pipe(\n Effect.forkScoped,\n );\n\n const program = Effect.tryPromise({\n try: async () => {\n let candidate: unknown;\n try {\n candidate = factory(\n ...shadowedGlobals.map(() => undefined),\n harnessConsole,\n ...namespaceObjects,\n );\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n if (typeof candidate !== \"function\") {\n throw new EvaluationThrew(new NotAFunction(typeof candidate));\n }\n let outcome: unknown;\n try {\n outcome = candidate();\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n return await Promise.resolve(outcome);\n },\n catch: (thrown) => classifyProgramFailure(thrown, request.limits, capture),\n });\n\n const startedAt = yield* Clock.currentTimeMillis;\n // The wall-clock deadline interrupts only at asynchronous suspension\n // points: a synchronous runaway shares the host thread and cannot be\n // stopped in-process — exactly why the platform CPU enforcement cases\n // belong to isolated adapters only (testing spec §8.1). The server fiber\n // is interrupted when the pass settles so no host call outlives the\n // program that issued it.\n const returned = yield* Effect.raceFirst(program, Fiber.join(server)).pipe(\n Effect.timeoutOrElse({\n duration: request.limits.maxWallTime,\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: inProcessCodeExecutorImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [...capture.lines],\n }),\n }),\n Effect.ensuring(Fiber.interrupt(server)),\n );\n const finishedAt = yield* Clock.currentTimeMillis;\n\n // An unawaited burst can outrun the server: the program may return before\n // the over-limit entry is dequeued, so the admission counter is the\n // authority — a pass that ISSUED more calls than the cap fails even when\n // its promise settled first.\n if (issuedHostCalls > request.limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: request.limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n\n const value = yield* Schema.decodeUnknownEffect(Schema.Json)(returned).pipe(\n Effect.mapError(() =>\n CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: [...capture.lines],\n }),\n ),\n );\n const resultBytes = encodedJsonByteLength(value);\n if (resultBytes === undefined || resultBytes > request.limits.maxResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n\n return CodeExecutionResult.make({\n implementation: inProcessCodeExecutorImplementation,\n value,\n logs: [...capture.lines],\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.millis(Math.max(0, finishedAt - startedAt)),\n hostCalls: counter.calls,\n logBytes: capture.bytes,\n resultBytes,\n }),\n });\n },\n);\n\n/**\n * Layer providing the unisolated in-process `CodeExecutor` substitute. The\n * per-pass `CodeExecutionHost` stays in the caller's requirement channel, the\n * same as every real adapter.\n */\nexport const inProcessCodeExecutorLayer: Layer.Layer<CodeExecutor> = Layer.succeed(CodeExecutor)(\n CodeExecutor.of({ execute: executeInProcess }),\n);\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,IAAa,mCAAb,cAAsD,OAAO,YAA8C,CAAC,CAC1G,oCACA;CACE,UAAU,OAAO;CACjB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;AAYH,MAAM,aAAa,oBA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C,KACrE,OAAO,eACL,uBAAuB,KAAK;EAC1B,gBAAgB;EAChB,QAAQ;EACR,QAAQ;EACR,SAAS;EACT,MAAM,CAAC,GAAG,QAAQ,KAAK;CACzB,CAAC,CACH,CACF;CACA,MAAM,cAAc,sBAAsB,KAAK;CAC/C,IAAI,gBAAgB,KAAA,KAAa,cAAc,QAAQ,OAAO,gBAC5D,OAAO,OAAO,qBAAqB,KAAK;EACtC,gBAAgB;EAChB,SAAS;EACT,OAAO,QAAQ,OAAO;EACtB,UAAU,eAAe;EACzB,MAAM,CAAC,GAAG,QAAQ,KAAK;CACzB,CAAC;CAGH,OAAO,oBAAoB,KAAK;EAC9B,gBAAgB;EAChB;EACA,MAAM,CAAC,GAAG,QAAQ,KAAK;EACvB,aAAa,yBAAyB,KAAK;GACzC,UAAU,SAAS,OAAO,KAAK,IAAI,GAAG,aAAa,SAAS,CAAC;GAC7D,WAAW,QAAQ;GACnB,UAAU,QAAQ;GAClB;EACF,CAAC;CACH,CAAC;AACH,CACF;;;;;;AAOA,MAAa,6BAAwD,MAAM,QAAQ,YAAY,CAAC,CAC9F,aAAa,GAAG,EAAE,SAAS,iBAAiB,CAAC,CAC/C"}
@@ -0,0 +1,354 @@
1
+ import { Context, Deferred, Effect, Layer, Option, Ref, Schema } from "effect";
2
+ import { Tool, Toolkit } from "effect/unstable/ai";
3
+ import { Agent, AgentPolicy, IdGenerator, RunId, ThreadId, TurnId } from "@effect-agent/core";
4
+ import { RunContextPreparationPassthrough, ThreadHistory } from "@effect-agent/engine";
5
+ //#region src/fixtures/travel-planner/definition.ts
6
+ const AirportCode = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/AirportCode"));
7
+ const QuoteId = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/QuoteId"));
8
+ var TripRequest = class extends Schema.Class("TripRequest")({
9
+ request: Schema.NonEmptyString,
10
+ origin: AirportCode,
11
+ destination: AirportCode,
12
+ departOn: Schema.String,
13
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
14
+ travelers: Schema.Int.check(Schema.isGreaterThan(0)),
15
+ budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),
16
+ currency: Schema.Literal("USD")
17
+ }) {};
18
+ var FlightQuery = class extends Schema.Class("FlightQuery")({
19
+ origin: AirportCode,
20
+ destination: AirportCode,
21
+ departOn: Schema.String,
22
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
23
+ }) {};
24
+ var LodgingQuery = class extends Schema.Class("LodgingQuery")({
25
+ destination: AirportCode,
26
+ departOn: Schema.String,
27
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
28
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
29
+ }) {};
30
+ var ActivityQuery = class extends Schema.Class("ActivityQuery")({
31
+ destination: AirportCode,
32
+ departOn: Schema.String,
33
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
34
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
35
+ }) {};
36
+ var FlightOption = class extends Schema.Class("FlightOption")({
37
+ quoteId: QuoteId,
38
+ flight: Schema.String,
39
+ estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
40
+ currency: Schema.Literal("USD")
41
+ }) {};
42
+ var LodgingOption = class extends Schema.Class("LodgingOption")({
43
+ lodging: Schema.String,
44
+ estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
45
+ currency: Schema.Literal("USD")
46
+ }) {};
47
+ /** A successful empty activity search is distinct from supplier unavailability. */
48
+ var ActivitySearchResult = class extends Schema.Class("ActivitySearchResult")({ activities: Schema.Array(Schema.String) }) {};
49
+ var Itinerary = class extends Schema.Class("Itinerary")({
50
+ title: Schema.String,
51
+ route: Schema.String,
52
+ dates: Schema.String,
53
+ flight: Schema.String,
54
+ lodging: Schema.String,
55
+ activities: Schema.Array(Schema.String),
56
+ estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),
57
+ currency: Schema.Literal("USD"),
58
+ quoteId: QuoteId,
59
+ assumptions: Schema.Array(Schema.String),
60
+ unresolvedConstraints: Schema.Array(Schema.String),
61
+ nextAction: Schema.Literal("review")
62
+ }) {};
63
+ var TravelPlan = class extends Schema.Class("TravelPlan")({ itineraries: Schema.Array(Itinerary) }) {};
64
+ const unavailableFields = {
65
+ query: Schema.String,
66
+ message: Schema.String
67
+ };
68
+ var FlightUnavailable = class extends Schema.TaggedError()("FlightUnavailable", unavailableFields) {};
69
+ var LodgingUnavailable = class extends Schema.TaggedError()("LodgingUnavailable", unavailableFields) {};
70
+ var ActivityUnavailable = class extends Schema.TaggedError()("ActivityUnavailable", unavailableFields) {};
71
+ var GuidanceFailure = class extends Schema.TaggedError()("GuidanceFailure", { message: Schema.String }) {};
72
+ var FlightCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/FlightCatalog") {};
73
+ var LodgingCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/LodgingCatalog") {};
74
+ var ActivityCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/ActivityCatalog") {};
75
+ var TravelGuidance = class extends Context.Service()("@effect-agent/testing/travel-planner/TravelGuidance") {};
76
+ const SearchFlights = Tool.make("search_flights", {
77
+ parameters: FlightQuery,
78
+ success: FlightOption,
79
+ failure: FlightUnavailable,
80
+ failureMode: "error",
81
+ dependencies: [FlightCatalog]
82
+ });
83
+ const SearchLodging = Tool.make("search_lodging", {
84
+ parameters: LodgingQuery,
85
+ success: LodgingOption,
86
+ failure: LodgingUnavailable,
87
+ failureMode: "error",
88
+ dependencies: [LodgingCatalog]
89
+ });
90
+ const SearchActivities = Tool.make("search_activities", {
91
+ parameters: ActivityQuery,
92
+ success: ActivitySearchResult,
93
+ failure: ActivityUnavailable,
94
+ failureMode: "error",
95
+ dependencies: [ActivityCatalog]
96
+ });
97
+ const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);
98
+ const TravelPlannerToolkitLayer = TravelPlannerToolkit.toLayer({
99
+ search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),
100
+ search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),
101
+ search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query))
102
+ });
103
+ const TravelPlanner = Agent.make("travel-planner", {
104
+ input: TripRequest,
105
+ output: TravelPlan,
106
+ instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
107
+ toolkit: TravelPlannerToolkit,
108
+ policy: AgentPolicy.make({
109
+ maxTurns: 2,
110
+ maxToolCalls: 3,
111
+ maxDuration: "30 seconds",
112
+ toolConcurrency: 3
113
+ }),
114
+ description: "Build one review-only itinerary from bounded parallel deterministic searches.",
115
+ metadata: {
116
+ deploymentClass: "E",
117
+ phase: "P1"
118
+ }
119
+ });
120
+ //#endregion
121
+ //#region src/fixtures/travel-planner/deterministic-layers.ts
122
+ var CatalogLifecycleCounts = class extends Schema.Class("CatalogLifecycleCounts")({
123
+ acquired: Schema.Natural,
124
+ finalized: Schema.Natural
125
+ }) {};
126
+ var CatalogLifecycle = class CatalogLifecycle extends Context.Service()("@effect-agent/testing/travel-planner/CatalogLifecycle") {
127
+ static layerNoDeps = Layer.effect(this, Effect.gen(function* () {
128
+ const acquired = yield* Ref.make(0);
129
+ const finalized = yield* Ref.make(0);
130
+ return CatalogLifecycle.of({
131
+ markAcquired: Ref.update(acquired, (n) => n + 1),
132
+ markFinalized: Ref.update(finalized, (n) => n + 1),
133
+ counts: Effect.all({
134
+ acquired: Ref.get(acquired),
135
+ finalized: Ref.get(finalized)
136
+ }).pipe(Effect.map((counts) => CatalogLifecycleCounts.make(counts)))
137
+ });
138
+ }));
139
+ };
140
+ const flight = FlightOption.make({
141
+ quoteId: Schema.decodeSync(QuoteId)("quote-sfo-lhr-001"),
142
+ flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
143
+ estimatedCents: 18e4,
144
+ currency: "USD"
145
+ });
146
+ const lodging = LodgingOption.make({
147
+ lodging: "Bloomsbury House · refundable studio · 4 nights",
148
+ estimatedCents: 104e3,
149
+ currency: "USD"
150
+ });
151
+ const activities = ActivitySearchResult.make({ activities: ["British Museum timed entry", "Thames evening walk"] });
152
+ const ReverseCompletionToolkitLayer = Effect.gen(function* () {
153
+ const flightStarted = yield* Deferred.make();
154
+ const lodgingStarted = yield* Deferred.make();
155
+ const activityStarted = yield* Deferred.make();
156
+ const releaseFlight = yield* Deferred.make();
157
+ const releaseLodging = yield* Deferred.make();
158
+ const releaseActivity = yield* Deferred.make();
159
+ const awaitRelease = (started, release, value) => Deferred.succeed(started, void 0).pipe(Effect.andThen(Deferred.await(release)), Effect.as(value));
160
+ return {
161
+ controls: {
162
+ flightStarted: Deferred.await(flightStarted),
163
+ lodgingStarted: Deferred.await(lodgingStarted),
164
+ activityStarted: Deferred.await(activityStarted),
165
+ releaseFlight: Deferred.succeed(releaseFlight, void 0).pipe(Effect.asVoid),
166
+ releaseLodging: Deferred.succeed(releaseLodging, void 0).pipe(Effect.asVoid),
167
+ releaseActivity: Deferred.succeed(releaseActivity, void 0).pipe(Effect.asVoid)
168
+ },
169
+ layer: TravelPlannerToolkit.toLayer({
170
+ search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),
171
+ search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),
172
+ search_activities: () => awaitRelease(activityStarted, releaseActivity, activities)
173
+ })
174
+ };
175
+ });
176
+ const FlightCatalogLayer = Layer.effect(FlightCatalog, Effect.gen(function* () {
177
+ const lifecycle = yield* CatalogLifecycle;
178
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
179
+ return FlightCatalog.of({ search: (query) => query.origin === query.destination ? Effect.fail(FlightUnavailable.make({
180
+ query: `${query.origin}-${query.destination}`,
181
+ message: "Origin and destination must differ."
182
+ })) : Effect.succeed(flight) });
183
+ }));
184
+ const LodgingCatalogLayer = Layer.effect(LodgingCatalog, Effect.gen(function* () {
185
+ const lifecycle = yield* CatalogLifecycle;
186
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
187
+ return LodgingCatalog.of({ search: (query) => query.nights < 1 ? Effect.fail(LodgingUnavailable.make({
188
+ query: query.destination,
189
+ message: "At least one night is required."
190
+ })) : Effect.succeed(lodging) });
191
+ }));
192
+ const ActivityCatalogLayer = Layer.effect(ActivityCatalog, Effect.gen(function* () {
193
+ const lifecycle = yield* CatalogLifecycle;
194
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
195
+ return ActivityCatalog.of({ search: (query) => query.destination === "" ? Effect.fail(ActivityUnavailable.make({
196
+ query: query.destination,
197
+ message: "Destination is required."
198
+ })) : Effect.succeed(activities) });
199
+ }));
200
+ /** Stable supplier-side booking identity, minted deterministically from the idempotency key. */
201
+ const BookingRef = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/BookingRef"));
202
+ /** The supplier desk operations the P5 booking Tools and Steps invoke. */
203
+ const SupplierOperation = Schema.Literals([
204
+ "book-flight",
205
+ "cancel-booking",
206
+ "reserve-flight",
207
+ "reserve-lodging",
208
+ "issue-confirmation"
209
+ ]);
210
+ /**
211
+ * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a
212
+ * call with the same key returns this exact record without creating a second booking — which is
213
+ * precisely the honesty model of DUR-010: the framework never makes an external call
214
+ * exactly-once; the supplier's idempotency key does.
215
+ */
216
+ var SupplierBookingRecord = class extends Schema.Class("@effect-agent/testing/travel-planner/SupplierBookingRecord")({
217
+ bookingRef: BookingRef,
218
+ idempotencyKey: Schema.NonEmptyString,
219
+ operation: SupplierOperation,
220
+ detail: Schema.NonEmptyString,
221
+ status: Schema.Literals(["confirmed", "cancelled"])
222
+ }) {};
223
+ var SupplierUnavailable = class extends Schema.TaggedError()("SupplierUnavailable", { message: Schema.String }) {};
224
+ /** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */
225
+ const cancelBookingIdempotencyKey = (bookingRef) => `cancel-booking:${bookingRef}`;
226
+ /** The deterministic bookingRef the desk mints for one idempotency key. */
227
+ const supplierBookingRefFor = (idempotencyKey) => Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);
228
+ /**
229
+ * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call
230
+ * counters and injectable crash windows.
231
+ *
232
+ * - `book`/`cancel` always count the call (at-least-once execution stays observable), then
233
+ * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and
234
+ * Steps rely on.
235
+ * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its
236
+ * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point
237
+ * models "the external effect happened but no outcome was recorded" without any wall clock.
238
+ * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate
239
+ * assertions.
240
+ */
241
+ var SupplierBookingDesk = class SupplierBookingDesk extends Context.Service()("@effect-agent/testing/travel-planner/SupplierBookingDesk") {
242
+ static layer = Layer.effect(this, Effect.gen(function* () {
243
+ const state = yield* Ref.make({
244
+ bookings: /* @__PURE__ */ new Map(),
245
+ counts: /* @__PURE__ */ new Map(),
246
+ holds: /* @__PURE__ */ new Map()
247
+ });
248
+ const enterHold = (hold) => Option.isSome(hold) ? Deferred.succeed(hold.value.held, void 0).pipe(Effect.andThen(Deferred.await(hold.value.release))) : Effect.void;
249
+ const book = (request) => Ref.modify(state, (current) => {
250
+ const counts = new Map(current.counts).set(request.idempotencyKey, (current.counts.get(request.idempotencyKey) ?? 0) + 1);
251
+ const existing = current.bookings.get(request.idempotencyKey);
252
+ const record = existing ?? SupplierBookingRecord.make({
253
+ bookingRef: supplierBookingRefFor(request.idempotencyKey),
254
+ idempotencyKey: request.idempotencyKey,
255
+ operation: request.operation,
256
+ detail: request.detail,
257
+ status: "confirmed"
258
+ });
259
+ const bookings = existing === void 0 ? new Map(current.bookings).set(request.idempotencyKey, record) : current.bookings;
260
+ const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));
261
+ const holds = Option.isSome(hold) ? (() => {
262
+ const next = new Map(current.holds);
263
+ next.delete(request.idempotencyKey);
264
+ return next;
265
+ })() : current.holds;
266
+ return [{
267
+ record,
268
+ hold
269
+ }, {
270
+ bookings,
271
+ counts,
272
+ holds
273
+ }];
274
+ }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));
275
+ const cancel = (bookingRef) => Ref.modify(state, (current) => {
276
+ const key = cancelBookingIdempotencyKey(bookingRef);
277
+ const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);
278
+ const existingEntry = [...current.bookings.entries()].find(([, record]) => record.bookingRef === bookingRef);
279
+ if (existingEntry === void 0) return [{
280
+ record: Option.none(),
281
+ hold: Option.none()
282
+ }, {
283
+ ...current,
284
+ counts
285
+ }];
286
+ const [storeKey, existing] = existingEntry;
287
+ const cancelled = existing.status === "cancelled" ? existing : SupplierBookingRecord.make({
288
+ ...existing,
289
+ status: "cancelled"
290
+ });
291
+ const bookings = new Map(current.bookings).set(storeKey, cancelled);
292
+ const hold = Option.fromNullishOr(current.holds.get(key));
293
+ const holds = Option.isSome(hold) ? (() => {
294
+ const next = new Map(current.holds);
295
+ next.delete(key);
296
+ return next;
297
+ })() : current.holds;
298
+ return [{
299
+ record: Option.some(cancelled),
300
+ hold
301
+ }, {
302
+ bookings,
303
+ counts,
304
+ holds
305
+ }];
306
+ }).pipe(Effect.flatMap(({ hold, record }) => Option.isNone(record) ? Effect.fail(SupplierUnavailable.make({ message: `The supplier desk has no booking under ${bookingRef}.` })) : enterHold(hold).pipe(Effect.as(record.value))));
307
+ return SupplierBookingDesk.of({
308
+ book,
309
+ cancel,
310
+ lookup: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey)))),
311
+ bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),
312
+ callCount: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),
313
+ holdAfterWrite: (idempotencyKey) => Effect.gen(function* () {
314
+ const held = yield* Deferred.make();
315
+ const release = yield* Deferred.make();
316
+ yield* Ref.update(state, (current) => ({
317
+ ...current,
318
+ holds: new Map(current.holds).set(idempotencyKey, {
319
+ held,
320
+ release
321
+ })
322
+ }));
323
+ return {
324
+ held: Deferred.await(held),
325
+ release: Deferred.succeed(release, void 0).pipe(Effect.asVoid)
326
+ };
327
+ })
328
+ });
329
+ }));
330
+ };
331
+ const TravelGuidanceLayer = Layer.succeed(TravelGuidance, TravelGuidance.of({ instructions: (input) => Effect.succeed([
332
+ "You are the Effect Agent Travel Planner P1 interpreter fixture.",
333
+ `The user asked: ${input.request}`,
334
+ "Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.",
335
+ "Then return only a JSON object of exactly this shape, no prose:",
336
+ "{\"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\"}]}",
337
+ "Use the Tool results verbatim; activity results may legitimately be an empty array.",
338
+ "This is read-only planning. Require review before any mutation."
339
+ ].join("\n")) }));
340
+ const DeterministicIdGeneratorLayer = Layer.effect(IdGenerator, Effect.gen(function* () {
341
+ const thread = yield* Ref.make(0);
342
+ const run = yield* Ref.make(0);
343
+ const turn = yield* Ref.make(0);
344
+ return IdGenerator.of({
345
+ nextThreadId: Ref.updateAndGet(thread, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(ThreadId)(`thread-${n}`))),
346
+ nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`))),
347
+ nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)))
348
+ });
349
+ }));
350
+ const TravelPlannerRuntimeLayer = Layer.mergeAll(RunContextPreparationPassthrough, ThreadHistory.layerTransient, TravelPlannerToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer, TravelGuidanceLayer, DeterministicIdGeneratorLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
351
+ //#endregion
352
+ export { LodgingQuery as A, TravelPlannerToolkitLayer as B, FlightOption as C, Itinerary as D, GuidanceFailure as E, SearchLodging as F, TravelGuidance as I, TravelPlan as L, QuoteId as M, SearchActivities as N, LodgingCatalog as O, SearchFlights as P, TravelPlanner as R, FlightCatalog as S, FlightUnavailable as T, TripRequest as V, ActivityCatalog as _, DeterministicIdGeneratorLayer as a, ActivityUnavailable as b, ReverseCompletionToolkitLayer as c, SupplierOperation as d, SupplierUnavailable as f, supplierBookingRefFor as g, cancelBookingIdempotencyKey as h, CatalogLifecycleCounts as i, LodgingUnavailable as j, LodgingOption as k, SupplierBookingDesk as l, TravelPlannerRuntimeLayer as m, BookingRef as n, FlightCatalogLayer as o, TravelGuidanceLayer as p, CatalogLifecycle as r, LodgingCatalogLayer as s, ActivityCatalogLayer as t, SupplierBookingRecord as u, ActivityQuery as v, FlightQuery as w, AirportCode as x, ActivitySearchResult as y, TravelPlannerToolkit as z };
353
+
354
+ //# sourceMappingURL=deterministic-layers-CKyYxBhN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deterministic-layers-CKyYxBhN.mjs","names":[],"sources":["../src/fixtures/travel-planner/definition.ts","../src/fixtures/travel-planner/deterministic-layers.ts"],"sourcesContent":["import { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nexport const AirportCode = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/AirportCode\"),\n);\nexport type AirportCode = typeof AirportCode.Type;\n\nexport const QuoteId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/QuoteId\"),\n);\nexport type QuoteId = typeof QuoteId.Type;\n\nexport class TripRequest extends Schema.Class<TripRequest>(\"TripRequest\")({\n request: Schema.NonEmptyString,\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class FlightQuery extends Schema.Class<FlightQuery>(\"FlightQuery\")({\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class LodgingQuery extends Schema.Class<LodgingQuery>(\"LodgingQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class ActivityQuery extends Schema.Class<ActivityQuery>(\"ActivityQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class FlightOption extends Schema.Class<FlightOption>(\"FlightOption\")({\n quoteId: QuoteId,\n flight: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class LodgingOption extends Schema.Class<LodgingOption>(\"LodgingOption\")({\n lodging: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\n/** A successful empty activity search is distinct from supplier unavailability. */\nexport class ActivitySearchResult extends Schema.Class<ActivitySearchResult>(\n \"ActivitySearchResult\",\n)({\n activities: Schema.Array(Schema.String),\n}) {}\n\nexport class Itinerary extends Schema.Class<Itinerary>(\"Itinerary\")({\n title: Schema.String,\n route: Schema.String,\n dates: Schema.String,\n flight: Schema.String,\n lodging: Schema.String,\n activities: Schema.Array(Schema.String),\n estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n quoteId: QuoteId,\n assumptions: Schema.Array(Schema.String),\n unresolvedConstraints: Schema.Array(Schema.String),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\nexport class TravelPlan extends Schema.Class<TravelPlan>(\"TravelPlan\")({\n itineraries: Schema.Array(Itinerary),\n}) {}\n\nconst unavailableFields = { query: Schema.String, message: Schema.String };\nexport class FlightUnavailable extends Schema.TaggedError<FlightUnavailable>()(\n \"FlightUnavailable\",\n unavailableFields,\n) {}\nexport class LodgingUnavailable extends Schema.TaggedError<LodgingUnavailable>()(\n \"LodgingUnavailable\",\n unavailableFields,\n) {}\nexport class ActivityUnavailable extends Schema.TaggedError<ActivityUnavailable>()(\n \"ActivityUnavailable\",\n unavailableFields,\n) {}\nexport class GuidanceFailure extends Schema.TaggedError<GuidanceFailure>()(\"GuidanceFailure\", {\n message: Schema.String,\n}) {}\n\nexport class FlightCatalog extends Context.Service<\n FlightCatalog,\n { readonly search: (query: FlightQuery) => Effect.Effect<FlightOption, FlightUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/FlightCatalog\") {}\nexport class LodgingCatalog extends Context.Service<\n LodgingCatalog,\n { readonly search: (query: LodgingQuery) => Effect.Effect<LodgingOption, LodgingUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/LodgingCatalog\") {}\nexport class ActivityCatalog extends Context.Service<\n ActivityCatalog,\n {\n readonly search: (\n query: ActivityQuery,\n ) => Effect.Effect<ActivitySearchResult, ActivityUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ActivityCatalog\") {}\nexport class TravelGuidance extends Context.Service<\n TravelGuidance,\n { readonly instructions: (input: TripRequest) => Effect.Effect<string, GuidanceFailure> }\n>()(\"@effect-agent/testing/travel-planner/TravelGuidance\") {}\n\nexport const SearchFlights = Tool.make(\"search_flights\", {\n parameters: FlightQuery,\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n});\nexport const SearchLodging = Tool.make(\"search_lodging\", {\n parameters: LodgingQuery,\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n});\nexport const SearchActivities = Tool.make(\"search_activities\", {\n parameters: ActivityQuery,\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n});\n\nexport const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);\nexport const TravelPlannerToolkitLayer = TravelPlannerToolkit.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});\n\nexport const TravelPlanner = Agent.make(\"travel-planner\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description: \"Build one review-only itinerary from bounded parallel deterministic searches.\",\n metadata: { deploymentClass: \"E\", phase: \"P1\" },\n});\n","import { ThreadId, IdGenerator, RunId, TurnId } from \"@effect-agent/core\";\nimport { ThreadHistory, RunContextPreparationPassthrough } from \"@effect-agent/engine\";\nimport { Context, Deferred, Effect, Layer, Option, Ref, Schema } from \"effect\";\n\nimport {\n ActivityCatalog,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingUnavailable,\n QuoteId,\n TravelGuidance,\n TravelPlannerToolkit,\n TravelPlannerToolkitLayer,\n} from \"./definition.ts\";\n\nexport class CatalogLifecycleCounts extends Schema.Class<CatalogLifecycleCounts>(\n \"CatalogLifecycleCounts\",\n)({\n acquired: Schema.Natural,\n finalized: Schema.Natural,\n}) {}\nexport class CatalogLifecycle extends Context.Service<\n CatalogLifecycle,\n {\n readonly markAcquired: Effect.Effect<void>;\n readonly markFinalized: Effect.Effect<void>;\n readonly counts: Effect.Effect<CatalogLifecycleCounts>;\n }\n>()(\"@effect-agent/testing/travel-planner/CatalogLifecycle\") {\n static readonly layerNoDeps = Layer.effect(\n this,\n Effect.gen(function* () {\n const acquired = yield* Ref.make(0);\n const finalized = yield* Ref.make(0);\n return CatalogLifecycle.of({\n markAcquired: Ref.update(acquired, (n) => n + 1),\n markFinalized: Ref.update(finalized, (n) => n + 1),\n counts: Effect.all({ acquired: Ref.get(acquired), finalized: Ref.get(finalized) }).pipe(\n Effect.map((counts) => CatalogLifecycleCounts.make(counts)),\n ),\n });\n }),\n );\n}\n\nconst flight = FlightOption.make({\n quoteId: Schema.decodeSync(QuoteId)(\"quote-sfo-lhr-001\"),\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180_000,\n currency: \"USD\",\n});\nconst lodging = LodgingOption.make({\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104_000,\n currency: \"USD\",\n});\nconst activities = ActivitySearchResult.make({\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n});\n\n/**\n * Deterministic controls for a Tool batch whose completions are released in a\n * caller-selected order. This is intentionally a test fixture: it uses no\n * clock or sleep and lets engine scheduler tests prove parallel starts and\n * declaration-order prompt materialization.\n */\nexport interface TravelPlannerCompletionControls {\n readonly flightStarted: Effect.Effect<void>;\n readonly lodgingStarted: Effect.Effect<void>;\n readonly activityStarted: Effect.Effect<void>;\n readonly releaseFlight: Effect.Effect<void>;\n readonly releaseLodging: Effect.Effect<void>;\n readonly releaseActivity: Effect.Effect<void>;\n}\n\nexport const ReverseCompletionToolkitLayer = Effect.gen(function* () {\n const flightStarted = yield* Deferred.make<void>();\n const lodgingStarted = yield* Deferred.make<void>();\n const activityStarted = yield* Deferred.make<void>();\n const releaseFlight = yield* Deferred.make<void>();\n const releaseLodging = yield* Deferred.make<void>();\n const releaseActivity = yield* Deferred.make<void>();\n const awaitRelease = <A>(\n started: Deferred.Deferred<void>,\n release: Deferred.Deferred<void>,\n value: A,\n ) =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Deferred.await(release)),\n Effect.as(value),\n );\n return {\n controls: {\n flightStarted: Deferred.await(flightStarted),\n lodgingStarted: Deferred.await(lodgingStarted),\n activityStarted: Deferred.await(activityStarted),\n releaseFlight: Deferred.succeed(releaseFlight, undefined).pipe(Effect.asVoid),\n releaseLodging: Deferred.succeed(releaseLodging, undefined).pipe(Effect.asVoid),\n releaseActivity: Deferred.succeed(releaseActivity, undefined).pipe(Effect.asVoid),\n },\n layer: TravelPlannerToolkit.toLayer({\n search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),\n search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),\n search_activities: () => awaitRelease(activityStarted, releaseActivity, activities),\n }),\n };\n});\n\nexport const FlightCatalogLayer = Layer.effect(\n FlightCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return FlightCatalog.of({\n search: (query) =>\n query.origin === query.destination\n ? Effect.fail(\n FlightUnavailable.make({\n query: `${query.origin}-${query.destination}`,\n message: \"Origin and destination must differ.\",\n }),\n )\n : Effect.succeed(flight),\n });\n }),\n);\nexport const LodgingCatalogLayer = Layer.effect(\n LodgingCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return LodgingCatalog.of({\n search: (query) =>\n query.nights < 1\n ? Effect.fail(\n LodgingUnavailable.make({\n query: query.destination,\n message: \"At least one night is required.\",\n }),\n )\n : Effect.succeed(lodging),\n });\n }),\n);\nexport const ActivityCatalogLayer = Layer.effect(\n ActivityCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return ActivityCatalog.of({\n search: (query) =>\n query.destination === \"\"\n ? Effect.fail(\n ActivityUnavailable.make({\n query: query.destination,\n message: \"Destination is required.\",\n }),\n )\n : Effect.succeed(activities),\n });\n }),\n);\n/** Stable supplier-side booking identity, minted deterministically from the idempotency key. */\nexport const BookingRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/BookingRef\"),\n);\nexport type BookingRef = typeof BookingRef.Type;\n\n/** The supplier desk operations the P5 booking Tools and Steps invoke. */\nexport const SupplierOperation = Schema.Literals([\n \"book-flight\",\n \"cancel-booking\",\n \"reserve-flight\",\n \"reserve-lodging\",\n \"issue-confirmation\",\n]);\nexport type SupplierOperation = typeof SupplierOperation.Type;\n\n/**\n * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a\n * call with the same key returns this exact record without creating a second booking — which is\n * precisely the honesty model of DUR-010: the framework never makes an external call\n * exactly-once; the supplier's idempotency key does.\n */\nexport class SupplierBookingRecord extends Schema.Class<SupplierBookingRecord>(\n \"@effect-agent/testing/travel-planner/SupplierBookingRecord\",\n)({\n bookingRef: BookingRef,\n idempotencyKey: Schema.NonEmptyString,\n operation: SupplierOperation,\n detail: Schema.NonEmptyString,\n status: Schema.Literals([\"confirmed\", \"cancelled\"]),\n}) {}\n\nexport class SupplierUnavailable extends Schema.TaggedError<SupplierUnavailable>()(\n \"SupplierUnavailable\",\n { message: Schema.String },\n) {}\n\nexport interface SupplierBookRequest {\n readonly operation: SupplierOperation;\n readonly idempotencyKey: string;\n readonly detail: string;\n}\n\n/** Controls returned by an armed crash window (`holdAfterWrite`). */\nexport interface SupplierHoldControls {\n /** Resolves once the armed call has performed its supplier write and is blocked. */\n readonly held: Effect.Effect<void>;\n /** Releases the blocked call (tests that interrupt the Attempt never call this). */\n readonly release: Effect.Effect<void>;\n}\n\n/** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */\nexport const cancelBookingIdempotencyKey = (bookingRef: string): string =>\n `cancel-booking:${bookingRef}`;\n\n/** The deterministic bookingRef the desk mints for one idempotency key. */\nexport const supplierBookingRefFor = (idempotencyKey: string): BookingRef =>\n Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);\n\ninterface SupplierHoldWindow {\n readonly held: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\ninterface SupplierDeskState {\n readonly bookings: ReadonlyMap<string, SupplierBookingRecord>;\n readonly counts: ReadonlyMap<string, number>;\n readonly holds: ReadonlyMap<string, SupplierHoldWindow>;\n}\n\n/**\n * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call\n * counters and injectable crash windows.\n *\n * - `book`/`cancel` always count the call (at-least-once execution stays observable), then\n * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and\n * Steps rely on.\n * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its\n * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point\n * models \"the external effect happened but no outcome was recorded\" without any wall clock.\n * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate\n * assertions.\n */\nexport class SupplierBookingDesk extends Context.Service<\n SupplierBookingDesk,\n {\n readonly book: (\n request: SupplierBookRequest,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly cancel: (\n bookingRef: BookingRef,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly lookup: (\n idempotencyKey: string,\n ) => Effect.Effect<Option.Option<SupplierBookingRecord>>;\n readonly bookings: Effect.Effect<ReadonlyArray<SupplierBookingRecord>>;\n readonly callCount: (idempotencyKey: string) => Effect.Effect<number>;\n readonly holdAfterWrite: (idempotencyKey: string) => Effect.Effect<SupplierHoldControls>;\n }\n>()(\"@effect-agent/testing/travel-planner/SupplierBookingDesk\") {\n static readonly layer: Layer.Layer<SupplierBookingDesk> = Layer.effect(\n this,\n Effect.gen(function* () {\n const state = yield* Ref.make<SupplierDeskState>({\n bookings: new Map(),\n counts: new Map(),\n holds: new Map(),\n });\n\n const enterHold = (hold: Option.Option<SupplierHoldWindow>) =>\n Option.isSome(hold)\n ? Deferred.succeed(hold.value.held, undefined).pipe(\n Effect.andThen(Deferred.await(hold.value.release)),\n )\n : Effect.void;\n\n const book = (request: SupplierBookRequest) =>\n Ref.modify(state, (current) => {\n const counts = new Map(current.counts).set(\n request.idempotencyKey,\n (current.counts.get(request.idempotencyKey) ?? 0) + 1,\n );\n const existing = current.bookings.get(request.idempotencyKey);\n const record =\n existing ??\n SupplierBookingRecord.make({\n bookingRef: supplierBookingRefFor(request.idempotencyKey),\n idempotencyKey: request.idempotencyKey,\n operation: request.operation,\n detail: request.detail,\n status: \"confirmed\",\n });\n const bookings =\n existing === undefined\n ? new Map(current.bookings).set(request.idempotencyKey, record)\n : current.bookings;\n const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(request.idempotencyKey);\n return next;\n })()\n : current.holds;\n return [\n { record, hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));\n\n const cancel = (bookingRef: BookingRef) =>\n Ref.modify(state, (current) => {\n const key = cancelBookingIdempotencyKey(bookingRef);\n const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);\n const existingEntry = [...current.bookings.entries()].find(\n ([, record]) => record.bookingRef === bookingRef,\n );\n if (existingEntry === undefined) {\n return [\n { record: Option.none<SupplierBookingRecord>(), hold: Option.none() },\n { ...current, counts },\n ] as const;\n }\n const [storeKey, existing] = existingEntry;\n const cancelled =\n existing.status === \"cancelled\"\n ? existing\n : SupplierBookingRecord.make({ ...existing, status: \"cancelled\" });\n const bookings = new Map(current.bookings).set(storeKey, cancelled);\n const hold = Option.fromNullishOr(current.holds.get(key));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(key);\n return next;\n })()\n : current.holds;\n return [\n { record: Option.some(cancelled), hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(\n Effect.flatMap(({ hold, record }) =>\n Option.isNone(record)\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `The supplier desk has no booking under ${bookingRef}.`,\n }),\n )\n : enterHold(hold).pipe(Effect.as(record.value)),\n ),\n );\n\n return SupplierBookingDesk.of({\n book,\n cancel,\n lookup: (idempotencyKey) =>\n Ref.get(state).pipe(\n Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey))),\n ),\n bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),\n callCount: (idempotencyKey) =>\n Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),\n holdAfterWrite: (idempotencyKey) =>\n Effect.gen(function* () {\n const held = yield* Deferred.make<void>();\n const release = yield* Deferred.make<void>();\n yield* Ref.update(state, (current) => ({\n ...current,\n holds: new Map(current.holds).set(idempotencyKey, { held, release }),\n }));\n return {\n held: Deferred.await(held),\n release: Deferred.succeed(release, undefined).pipe(Effect.asVoid),\n };\n }),\n });\n }),\n );\n}\n\nexport const TravelGuidanceLayer = Layer.succeed(\n TravelGuidance,\n TravelGuidance.of({\n instructions: (input) =>\n Effect.succeed(\n [\n \"You are the Effect Agent Travel Planner P1 interpreter fixture.\",\n `The user asked: ${input.request}`,\n \"Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.\",\n \"Then 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\"}]}',\n \"Use the Tool results verbatim; activity results may legitimately be an empty array.\",\n \"This is read-only planning. Require review before any mutation.\",\n ].join(\"\\n\"),\n ),\n }),\n);\nexport const DeterministicIdGeneratorLayer = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const thread = yield* Ref.make(0);\n const run = yield* Ref.make(0);\n const turn = yield* Ref.make(0);\n return IdGenerator.of({\n nextThreadId: Ref.updateAndGet(thread, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(ThreadId)(`thread-${n}`)),\n ),\n nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`)),\n ),\n nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)),\n ),\n });\n }),\n);\nexport const TravelPlannerRuntimeLayer = Layer.mergeAll(\n RunContextPreparationPassthrough,\n ThreadHistory.layerTransient,\n TravelPlannerToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n DeterministicIdGeneratorLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n"],"mappings":";;;;;AAIA,MAAa,cAAc,OAAO,eAAe,KAC/C,OAAO,MAAM,kDAAkD,CACjE;AAGA,MAAa,UAAU,OAAO,eAAe,KAC3C,OAAO,MAAM,8CAA8C,CAC7D;AAGA,IAAa,cAAb,cAAiC,OAAO,MAAmB,aAAa,CAAC,CAAC;CACxE,SAAS,OAAO;CAChB,QAAQ;CACR,aAAa;CACb,UA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