@effect-agent/testing 0.1.0-beta.6 → 0.1.0-beta.61

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 (54) hide show
  1. package/dist/Certification.d.mts +105 -0
  2. package/dist/Certification.mjs +590 -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 +364 -0
  12. package/dist/CodeExecutorSubstitute.mjs.map +1 -0
  13. package/dist/DocsResearcher.d.mts +270 -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 +1665 -0
  21. package/dist/TravelPlanner.mjs +1968 -0
  22. package/dist/TravelPlanner.mjs.map +1 -0
  23. package/dist/deterministic-layers-Eka0fMZq.mjs +358 -0
  24. package/dist/deterministic-layers-Eka0fMZq.mjs.map +1 -0
  25. package/dist/index.d.mts +2 -3378
  26. package/dist/index.mjs +2 -4766
  27. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  28. package/package.json +1 -48
  29. package/src/{certification.ts → Certification.ts} +251 -115
  30. package/src/{chaos.ts → Chaos.ts} +246 -122
  31. package/src/{code-executor-conformance.ts → CodeExecutorConformance.ts} +29 -6
  32. package/src/{code-executor-substitute.ts → CodeExecutorSubstitute.ts} +104 -42
  33. package/src/{fixtures/docs-researcher/index.ts → DocsResearcher.ts} +68 -5
  34. package/src/{scripted-model.ts → ScriptedModel.ts} +22 -25
  35. package/src/TravelPlanner.ts +232 -0
  36. package/src/fixtures/docs-researcher/definition.ts +19 -10
  37. package/src/fixtures/docs-researcher/harness.ts +41 -30
  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 +18 -37
  43. package/src/fixtures/travel-planner/phase4.ts +23 -36
  44. package/src/fixtures/travel-planner/phase5.ts +38 -41
  45. package/src/fixtures/travel-planner/phase6.ts +192 -84
  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 +33 -57
  49. package/src/fixtures/travel-planner/subagents.ts +35 -13
  50. package/src/index.ts +1 -11
  51. package/dist/index.mjs.map +0 -1
  52. package/src/code-executor-conformance.d.ts +0 -30
  53. package/src/fixtures/travel-planner/index.ts +0 -11
  54. package/src/fixtures/warehouse/index.ts +0 -412
package/dist/index.mjs CHANGED
@@ -1,4766 +1,2 @@
1
- import { McpConnectionRequest, McpConnector, McpServerIdentity, McpToolkitMismatch, Redactor, Subagent, SubagentPolicy, SubagentReservationsMemoryLive, SubagentRuntime, connectMcp, delegationAllocationFromPolicy } from "@effect-agent/capabilities";
2
- import { Agent, AgentId, AgentPolicy, ConversationId, IdGenerator, RunId, SubmissionId, ToolCallId, TurnId } from "@effect-agent/core";
3
- import { DurableStep, DurableStepError, ToolExecutionClass } from "@effect-agent/engine";
4
- import { AbortCommand, AgentBindingResolver, ApprovalDecisionCommand, BatchId, CanonicalBatch, CanonicalRecordEnvelope, CertificationReport, CertificationSweepResult, CertificationTierThreeReport, CertifiedAdapterIdentity, ConversationCheckpoint, ConversationExportRequest, ConversationProjection, ConversationStore, DEFAULT_OWNERSHIP_LEASE_DURATION, DefinitionDigests, DeploymentId, Digest, DurableAgentRuntime, DurableRuntimeConfig, DurableRuntimeFailpoint, DurableRuntimeFailpointError, DurableRuntimeFailpointLocation, DurableRuntimeFailpointTestControl, DurableWorkerBinding, IdempotencyKey, LoadCheckpointRequest, ObligationThresholds, PersistedJson, Principal, ProducerId, ReconciliationCompleted, ReconciliationSafeToRetry, ReconciliationUncertain, RecordEnvelope, RecordId, ResolutionAbortSubmission, ResolutionCompletedWithResult, ResolutionNeverHappened, ResolutionSafeToRetry, SubmissionLedger, SubmissionLookupById, ToolReconciler, ToolReconcilerError, UnknownResolutionCommand, WakeScheduler, certifyPorts, childConversationIdFor, verifyConversationInvariants } from "@effect-agent/session";
5
- import { Cause, Clock, Context, DateTime, Deferred, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Ref, Schema, Stream } from "effect";
6
- import { FastCheck, TestClock } from "effect/testing";
7
- import { AiError, LanguageModel, Model, Response, Tool, Toolkit } from "effect/unstable/ai";
8
- import { CodeExecutionHost, CodeExecutionLimits, CodeExecutionNamespace, CodeExecutionProtocolError, CodeExecutionRequest, CodeExecutionResourceUse, CodeExecutionResult, CodeExecutionTimeoutError, CodeExecutor, CodeExecutorUnsupportedError, CodeHostCall, CodeHostCallFailure, CodeHostCallLimitError, CodeHostCallResult, CodeHostCallSuccess, CodeOutputLimitError, CodeProgramFailedError, CodeSourceError, NetworkAllowlist, NetworkDisabled, SandboxImplementation } from "@effect-agent/sandbox";
9
- import * as McpSchema from "effect/unstable/ai/McpSchema";
10
- //#region src/certification.ts
11
- /** The six Tier-2 scenario shapes in sweep order. */
12
- const CERTIFICATION_SCENARIOS = [
13
- "plain",
14
- "uncertain-tool",
15
- "durable-steps",
16
- "approval",
17
- "join",
18
- "delegation"
19
- ];
20
- /**
21
- * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
22
- * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do
23
- * not take. They are pinned in-process by the P5/S2 suites
24
- * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
25
- * intent failpoint", `durable-runtime.test.ts` abort rows,
26
- * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
27
- * matrices. Runner tests assert the observed never-fired set equals EXACTLY this list, so a
28
- * protocol change that silently stops exercising a location fails the certification.
29
- */
30
- const TIER2_UNREACHED_LOCATIONS = [
31
- "abort:after-intent",
32
- "resolve:after-intent",
33
- "subagent:after-child-abort-intent"
34
- ];
35
- /** Locations of `tier2` rows whose armed fault never fired in ANY scenario, sorted. */
36
- const tier2NeverFiredLocations = (tier2) => {
37
- const fired = /* @__PURE__ */ new Set();
38
- for (const row of tier2) if (row.failpointFired) fired.add(row.location);
39
- return DurableRuntimeFailpointLocation.literals.filter((location) => !fired.has(location)).sort();
40
- };
41
- const SHA_A = Schema.decodeSync(Digest)("a".repeat(64));
42
- const DIGESTS = DefinitionDigests.make({
43
- agent: SHA_A,
44
- model: SHA_A,
45
- tools: SHA_A
46
- });
47
- const CHILD_DIGEST_STRINGS = {
48
- agent: "b".repeat(64),
49
- model: "c".repeat(64),
50
- tools: "d".repeat(64)
51
- };
52
- const CHILD_DIGESTS = DefinitionDigests.make({
53
- agent: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.agent),
54
- model: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.model),
55
- tools: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.tools)
56
- });
57
- const PRINCIPAL = Schema.decodeSync(Principal)("principal-certification");
58
- const decodeConversationId$1 = Schema.decodeSync(ConversationId);
59
- const decodeIdempotencyKey$1 = Schema.decodeSync(IdempotencyKey);
60
- const decodeToolCallId$1 = Schema.decodeSync(ToolCallId);
61
- const usage$2 = {
62
- inputTokens: {},
63
- outputTokens: {}
64
- };
65
- const finalParts$1 = (text) => [
66
- {
67
- type: "text-start",
68
- id: "answer"
69
- },
70
- {
71
- type: "text-delta",
72
- id: "answer",
73
- delta: text
74
- },
75
- {
76
- type: "text-end",
77
- id: "answer"
78
- },
79
- {
80
- type: "finish",
81
- reason: "stop",
82
- usage: usage$2
83
- }
84
- ];
85
- const toolCallPart$1 = (id, name, params) => ({
86
- type: "tool-call",
87
- id,
88
- name,
89
- params,
90
- providerExecuted: false
91
- });
92
- const toolTurn$1 = (...calls) => [...calls, {
93
- type: "finish",
94
- reason: "tool-calls",
95
- usage: usage$2
96
- }];
97
- /**
98
- * Stateless scripted model that decides by PROMPT SHAPE instead of call count: while the
99
- * prompt carries no committed tool result the model declares `toolParts` (when given),
100
- * otherwise it answers with the final text. Deciding on the canonical prompt keeps every cell
101
- * deterministic regardless of where the injected fault fell — a re-invoked Turn re-declares
102
- * the same batch and a resumed batch flows into the final answer, so every scenario always
103
- * exercises its tool path and always converges.
104
- */
105
- const promptShapeModel = (name, finalText, toolParts) => Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
106
- generateText: () => Effect.succeed([]),
107
- streamText: (request) => {
108
- const hasToolResult = request.prompt.content.some((message) => message.role === "tool");
109
- const parts = toolParts === void 0 || hasToolResult ? finalParts$1(finalText) : toolParts;
110
- return Stream.fromIterable(parts);
111
- }
112
- })));
113
- const policy$1 = AgentPolicy.make({
114
- maxTurns: 4,
115
- maxToolCalls: 4,
116
- maxDuration: "30 seconds",
117
- toolConcurrency: 2
118
- });
119
- const QuestionInput = Schema.Struct({ question: Schema.String });
120
- const AnswerOutput = Schema.Struct({ answer: Schema.String });
121
- /** plain / join: no tools — the pure Turn/submission/join seams. */
122
- const plainDefinition$1 = Agent.define("certify-plain", {
123
- input: QuestionInput,
124
- output: AnswerOutput,
125
- instructions: "Answer as JSON.",
126
- toolkit: Toolkit.empty,
127
- policy: policy$1
128
- });
129
- /** uncertain-tool: unannotated → fail-closed `uncertain`, enters the prepared/settled protocol. */
130
- const Book = Tool.make("book", {
131
- parameters: Schema.Struct({ ref: Schema.String }),
132
- success: Schema.Struct({ confirmation: Schema.String })
133
- });
134
- const bookToolkit = Toolkit.make(Book);
135
- const uncertainDefinition = Agent.define("certify-uncertain", {
136
- input: QuestionInput,
137
- output: AnswerOutput,
138
- instructions: "Book it.",
139
- toolkit: bookToolkit,
140
- policy: policy$1
141
- });
142
- /** durable-steps: declaring `DurableStep` as a dependency is what makes the Tool durable. */
143
- const Itinerary$2 = Tool.make("itinerary", {
144
- parameters: Schema.Struct({ ref: Schema.String }),
145
- success: Schema.Struct({ state: Schema.String }),
146
- failure: DurableStepError,
147
- dependencies: [DurableStep]
148
- });
149
- const itineraryToolkit = Toolkit.make(Itinerary$2);
150
- const stepsDefinition = Agent.define("certify-steps", {
151
- input: QuestionInput,
152
- output: AnswerOutput,
153
- instructions: "Reserve the itinerary.",
154
- toolkit: itineraryToolkit,
155
- policy: policy$1
156
- });
157
- /** approval: fail-closed — no `DurableApprovalResolver` Layer, so undecided approvals suspend. */
158
- const BookApproval$1 = Tool.make("book", {
159
- parameters: Schema.Struct({ ref: Schema.String }),
160
- success: Schema.Struct({ confirmation: Schema.String }),
161
- needsApproval: true
162
- });
163
- const approvalToolkit = Toolkit.make(BookApproval$1);
164
- const approvalDefinition$1 = Agent.define("certify-approval", {
165
- input: QuestionInput,
166
- output: AnswerOutput,
167
- instructions: "Book after approval.",
168
- toolkit: approvalToolkit,
169
- policy: policy$1
170
- });
171
- /** delegation: durable attached child plus an ordinary uncertain sibling in ONE batch. */
172
- const childDefinition$1 = Agent.define("certify-child", {
173
- input: QuestionInput,
174
- output: AnswerOutput,
175
- instructions: "Answer as JSON.",
176
- toolkit: Toolkit.empty,
177
- policy: AgentPolicy.make({
178
- maxTurns: 2,
179
- maxToolCalls: 1,
180
- maxDuration: "30 seconds",
181
- toolConcurrency: 1
182
- })
183
- });
184
- var CertifyDelegationFailed = class extends Schema.TaggedError()("CertifyDelegationFailed", { childErrorTag: Schema.String }) {};
185
- const researchDelegation = Subagent.define("delegate_research", {
186
- description: "Research one bounded question and return findings.",
187
- target: childDefinition$1,
188
- parameters: Schema.Struct({ topic: Schema.String }),
189
- success: Schema.Struct({ summary: Schema.String }),
190
- failure: CertifyDelegationFailed,
191
- prepareInput: ({ topic }) => Effect.succeed({ question: `research:${topic}` }),
192
- projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),
193
- policy: SubagentPolicy.make({
194
- maxChildren: 2,
195
- maxConcurrency: 2,
196
- maxTurns: 4,
197
- maxToolCalls: 4,
198
- maxDuration: "10 seconds"
199
- })
200
- });
201
- const Lookup = Tool.make("lookup", {
202
- parameters: Schema.Struct({ key: Schema.String }),
203
- success: Schema.Struct({ value: Schema.String })
204
- });
205
- const coordinatorDefinition$1 = Agent.define("certify-coordinator", {
206
- input: Schema.Struct({ mission: Schema.String }),
207
- output: Schema.Struct({ report: Schema.String }),
208
- instructions: "Delegate and look up, then answer as JSON.",
209
- toolkit: Toolkit.make(researchDelegation.tool, Lookup),
210
- policy: AgentPolicy.make({
211
- maxTurns: 4,
212
- maxToolCalls: 3,
213
- maxDuration: "30 seconds",
214
- toolConcurrency: 2
215
- })
216
- });
217
- const mapChildFailure = (failure) => CertifyDelegationFailed.make({ childErrorTag: failure._tag });
218
- const DELEGATE_CALL = decodeToolCallId$1("delegate-1");
219
- /** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */
220
- const identifiers = Layer.effect(IdGenerator, Effect.gen(function* () {
221
- const counter = yield* Ref.make(0);
222
- const next = (decode, prefix) => Ref.getAndUpdate(counter, (value) => value + 1).pipe(Effect.map((value) => decode(`${prefix}-${value}`)));
223
- return {
224
- nextConversationId: next(decodeConversationId$1, "certify-fixture-conversation"),
225
- nextRunId: next(Schema.decodeSync(RunId), "certify-fixture-run"),
226
- nextTurnId: next(Schema.decodeSync(TurnId), "certify-fixture-turn")
227
- };
228
- }));
229
- const delegationSupport$1 = Layer.mergeAll(SubagentReservationsMemoryLive, identifiers);
230
- const submitOptionsFor = (slug, conversationId) => ({
231
- conversationId,
232
- principal: PRINCIPAL,
233
- idempotencyKey: decodeIdempotencyKey$1(`certify-key-${slug}`),
234
- definitions: DIGESTS
235
- });
236
- /** One single-agent cell: one lane, one Submission, one registered exact-digest binding. */
237
- const makeSingleAgentCell = (definition, resolved, slug) => {
238
- const conversationId = decodeConversationId$1(`certify-${slug}`);
239
- const submit = Effect.gen(function* () {
240
- return [yield* (yield* DurableAgentRuntime).submit({ definition: {
241
- id: definition.id,
242
- input: definition.input
243
- } }, { question: `certify ${slug}` }, submitOptionsFor(slug, conversationId))];
244
- });
245
- return {
246
- resolver: AgentBindingResolver.fromBindings([resolved]),
247
- submit,
248
- lanes: () => [conversationId]
249
- };
250
- };
251
- const makeCell = Effect.fn("Certification.makeCell")(function* (scenario, slug) {
252
- switch (scenario) {
253
- case "plain": {
254
- const binding = Agent.withModel(plainDefinition$1, promptShapeModel("certify-plain", "{\"answer\":\"done\"}"));
255
- const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
256
- return makeSingleAgentCell(plainDefinition$1, resolved, slug);
257
- }
258
- case "uncertain-tool": {
259
- const binding = Agent.withModel(uncertainDefinition, promptShapeModel("certify-uncertain", "{\"answer\":\"booked\"}", toolTurn$1(toolCallPart$1("book-1", "book", { ref: `r-${slug}` }))));
260
- const toolLayer = bookToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
261
- const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
262
- return makeSingleAgentCell(uncertainDefinition, resolved, slug);
263
- }
264
- case "durable-steps": {
265
- const binding = Agent.withModel(stepsDefinition, promptShapeModel("certify-steps", "{\"answer\":\"reserved\"}", toolTurn$1(toolCallPart$1("itinerary-1", "itinerary", { ref: `trip-${slug}` }))));
266
- const toolLayer = itineraryToolkit.toLayer({ itinerary: ({ ref }) => Effect.gen(function* () {
267
- const step = yield* DurableStep;
268
- return { state: `${yield* step.do("reserve-flight", Schema.String, Effect.succeed(`flight-${ref}`))}+${yield* step.do("reserve-lodging", Schema.String, Effect.succeed(`lodging-${ref}`))}` };
269
- }) });
270
- const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
271
- return makeSingleAgentCell(stepsDefinition, resolved, slug);
272
- }
273
- case "approval": {
274
- const binding = Agent.withModel(approvalDefinition$1, promptShapeModel("certify-approval", "{\"answer\":\"approved\"}", toolTurn$1(toolCallPart$1("book-1", "book", { ref: `r-${slug}` }))));
275
- const toolLayer = approvalToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
276
- const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
277
- return makeSingleAgentCell(approvalDefinition$1, resolved, slug);
278
- }
279
- case "join": {
280
- const binding = Agent.withModel(plainDefinition$1, promptShapeModel("certify-join", "{\"answer\":\"host answer\"}"));
281
- const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
282
- const conversationId = decodeConversationId$1(`certify-${slug}`);
283
- const submitOne = (key, question) => Effect.gen(function* () {
284
- return yield* (yield* DurableAgentRuntime).submit({ definition: {
285
- id: plainDefinition$1.id,
286
- input: plainDefinition$1.input
287
- } }, { question }, {
288
- conversationId,
289
- principal: PRINCIPAL,
290
- idempotencyKey: decodeIdempotencyKey$1(key),
291
- definitions: DIGESTS
292
- });
293
- });
294
- return {
295
- resolver: AgentBindingResolver.fromBindings([resolved]),
296
- submit: Effect.gen(function* () {
297
- return [yield* submitOne(`certify-key-${slug}-host`, "host question"), yield* submitOne(`certify-key-${slug}-queued`, "queued question")];
298
- }),
299
- lanes: () => [conversationId]
300
- };
301
- }
302
- case "delegation": {
303
- const childBinding = Agent.withModel(childDefinition$1, promptShapeModel("certify-child", "{\"answer\":\"child-answer\"}"));
304
- const parentBinding = Agent.withModel(coordinatorDefinition$1, promptShapeModel("certify-parent", "{\"report\":\"done\"}", toolTurn$1(toolCallPart$1("delegate-1", "delegate_research", { topic: "paris" }), toolCallPart$1("lookup-1", "lookup", { key: "hotels" }))));
305
- const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {
306
- mapChildFailure,
307
- durable: { targetDigests: CHILD_DIGEST_STRINGS }
308
- }).pipe(Layer.provide(delegationSupport$1));
309
- const lookupLayer = Toolkit.make(Lookup).toLayer({ lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }) });
310
- const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)));
311
- const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);
312
- const conversationId = decodeConversationId$1(`certify-${slug}`);
313
- return {
314
- resolver: AgentBindingResolver.fromBindings([parentResolved, childResolved]),
315
- submit: Effect.gen(function* () {
316
- return [yield* (yield* DurableAgentRuntime).submit({ definition: {
317
- id: coordinatorDefinition$1.id,
318
- input: coordinatorDefinition$1.input
319
- } }, { mission: "plan" }, submitOptionsFor(slug, conversationId))];
320
- }),
321
- lanes: (receipts) => {
322
- const parent = receipts.at(0);
323
- return parent === void 0 ? [conversationId] : [conversationId, childConversationIdFor(parent.submissionId, DELEGATE_CALL)];
324
- }
325
- };
326
- }
327
- }
328
- });
329
- /** Maximum recovery/drive/unblock rounds before a cell is reported non-convergent. */
330
- const MAX_REDRIVE_ROUNDS = 8;
331
- /**
332
- * Verify one lane after convergence: canonical export + every lane Submission the ledger or
333
- * the log names (the same collection rule as the admin `verify` member), fed to the shared
334
- * invariant checker in convergence mode WITH the captured per-batch producer directory, so
335
- * the digest chain is fully recomputed instead of skipped.
336
- */
337
- const verifyLane = Effect.fn("Certification.verifyLane")(function* (lane, batchProducers) {
338
- const store = yield* ConversationStore;
339
- const ledger = yield* SubmissionLedger;
340
- const exported = yield* store.export(ConversationExportRequest.make({ conversationId: lane }));
341
- const rows = /* @__PURE__ */ new Map();
342
- const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
343
- for (const submission of nonterminal) if (submission.conversationId === lane) rows.set(submission.submissionId, submission);
344
- const named = /* @__PURE__ */ new Set();
345
- for (const envelope of exported.records) {
346
- const payload = envelope.record.payload;
347
- if (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled" || payload._tag === "AbortRequested") named.add(payload.submissionId);
348
- }
349
- for (const submissionId of named) {
350
- if (rows.has(submissionId)) continue;
351
- const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId }));
352
- if (Option.isSome(found) && found.value.conversationId === lane) rows.set(submissionId, found.value);
353
- }
354
- const checkpoint = yield* store.loadCheckpoint(LoadCheckpointRequest.make({ conversationId: lane }));
355
- return yield* verifyConversationInvariants({
356
- export: exported,
357
- submissions: [...rows.values()],
358
- batchProducers,
359
- checkpoint: Option.getOrUndefined(checkpoint),
360
- requireAllSettled: true
361
- });
362
- });
363
- const failureTagOf = (cause) => {
364
- const failure = Cause.findErrorOption(cause);
365
- if (Option.isSome(failure)) {
366
- const error = failure.value;
367
- if (typeof error === "object" && error !== null && "_tag" in error) return String(error._tag);
368
- return String(error).slice(0, 256);
369
- }
370
- return "defect";
371
- };
372
- /** One Tier-2 sweep cell: arm `location` one-shot, drive `scenario`, converge, verify. */
373
- const runSweepCell = Effect.fn("Certification.runSweepCell")(function* (scenario, location, batchProducers, leaseAdvance) {
374
- const runtime = yield* DurableAgentRuntime;
375
- const ledger = yield* SubmissionLedger;
376
- const control = yield* DurableRuntimeFailpointTestControl;
377
- const slug = `${scenario}-${location.replaceAll(":", "-")}`;
378
- const failed = (detail, fired) => CertificationSweepResult.make({
379
- scenario,
380
- location,
381
- failpointFired: fired,
382
- status: "failed",
383
- digestChainVerified: false,
384
- detail: detail.slice(0, 4096)
385
- });
386
- const cell = yield* makeCell(scenario, slug);
387
- const fired = yield* Ref.make(false);
388
- yield* control.setHandler((hit) => hit !== location ? Effect.void : Ref.getAndSet(fired, true).pipe(Effect.flatMap((already) => already ? Effect.void : Effect.fail(DurableRuntimeFailpointError.make({ location: hit })))));
389
- let receipts;
390
- const firstSubmit = yield* Effect.exit(cell.submit);
391
- if (Exit.isSuccess(firstSubmit)) receipts = firstSubmit.value;
392
- else {
393
- const secondSubmit = yield* Effect.exit(cell.submit);
394
- if (Exit.isFailure(secondSubmit)) {
395
- yield* control.clear;
396
- return failed(`submission replay did not recover: ${failureTagOf(secondSubmit.cause)}`, yield* Ref.get(fired));
397
- }
398
- receipts = secondSubmit.value;
399
- }
400
- const lanes = cell.lanes(receipts);
401
- const driveLane = (lane) => runtime.processConversationResolved(lane).pipe(Effect.provideService(AgentBindingResolver, cell.resolver));
402
- const allSettled = Effect.gen(function* () {
403
- for (const receipt of receipts) {
404
- const snapshot = yield* ledger.lookup(SubmissionLookupById.make({ submissionId: receipt.submissionId }));
405
- if (Option.isNone(snapshot) || snapshot.value.state !== "settled") return false;
406
- }
407
- return true;
408
- });
409
- let converged = false;
410
- for (let round = 0; round < MAX_REDRIVE_ROUNDS && !converged; round++) {
411
- yield* TestClock.adjust(leaseAdvance);
412
- yield* Effect.exit(runtime.runRecovery);
413
- for (const lane of lanes) yield* Effect.exit(driveLane(lane));
414
- for (const lane of lanes) {
415
- const explains = yield* Effect.exit(runtime.explainConversation(lane));
416
- if (Exit.isFailure(explains)) continue;
417
- for (const explanation of explains.value) {
418
- for (const unknown of explanation.evidence.unknownCalls) {
419
- if (unknown.resolved) continue;
420
- yield* Effect.exit(runtime.resolveUnknown(UnknownResolutionCommand.make({
421
- submissionId: explanation.submission.submissionId,
422
- toolCallId: unknown.toolCallId,
423
- author: "certification-runner",
424
- reason: `re-drive after injected fault at ${location}`,
425
- resolution: ResolutionSafeToRetry.make()
426
- })));
427
- }
428
- for (const pending of explanation.evidence.approvalsPending) {
429
- if (explanation.evidence.approvalDecisions.some((decision) => decision.toolCallId === pending.toolCallId)) continue;
430
- yield* Effect.exit(runtime.resolveApproval(ApprovalDecisionCommand.make({
431
- submissionId: explanation.submission.submissionId,
432
- toolCallId: pending.toolCallId,
433
- decision: "approved",
434
- resolver: "certification-runner",
435
- reason: `re-drive after injected fault at ${location}`
436
- })));
437
- }
438
- }
439
- }
440
- const settled = yield* Effect.exit(allSettled);
441
- converged = Exit.isSuccess(settled) && settled.value;
442
- }
443
- yield* control.clear;
444
- const wasFired = yield* Ref.get(fired);
445
- if (!converged) return failed(`did not converge within ${MAX_REDRIVE_ROUNDS} re-drive rounds`, wasFired);
446
- let digestChainVerified = true;
447
- const failedChecks = [];
448
- for (const lane of lanes) {
449
- const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));
450
- if (Exit.isFailure(verdict)) return failed(`lane ${lane} could not be verified: ${failureTagOf(verdict.cause)}`, wasFired);
451
- for (const check of verdict.value.checks) {
452
- if (check.status === "failed") failedChecks.push(`${lane}:${check.name}${check.detail === void 0 ? "" : ` (${check.detail})`}`);
453
- if (check.name === "digest-chain" && check.status !== "passed") digestChainVerified = false;
454
- }
455
- }
456
- if (failedChecks.length > 0 || !digestChainVerified) return failed(failedChecks.length > 0 ? `invariant checks failed: ${failedChecks.join("; ")}` : "the digest chain was not fully recomputed", wasFired);
457
- return CertificationSweepResult.make({
458
- scenario,
459
- location,
460
- failpointFired: wasFired,
461
- status: wasFired ? "converged" : "not-triggered",
462
- digestChainVerified
463
- });
464
- });
465
- /**
466
- * Resolve the Tier-3 record honestly (plan §1): a non-durable reference adapter has no real
467
- * loss to exercise (`not-applicable`); a supplied lever runs NOW (`exercised`); committed
468
- * real-loss citations are recorded (`recorded-evidence`); otherwise the certificate says
469
- * `not-exercised` — a scoped statement, never a silent claim.
470
- */
471
- const resolveTierThree = Effect.fn("Certification.resolveTierThree")(function* (durability, options) {
472
- if (durability === "non-durable") return CertificationTierThreeReport.make({
473
- status: "not-applicable",
474
- evidence: [],
475
- cases: [],
476
- detail: "the adapter declares non-durable state (reference/conformance adapter); there is no real loss to exercise"
477
- });
478
- if (options.crashLever !== void 0) {
479
- const cases = yield* options.crashLever;
480
- return CertificationTierThreeReport.make({
481
- status: "exercised",
482
- evidence: options.tierThreeEvidence ?? [],
483
- cases
484
- });
485
- }
486
- if (options.tierThreeEvidence !== void 0 && options.tierThreeEvidence.length > 0) return CertificationTierThreeReport.make({
487
- status: "recorded-evidence",
488
- evidence: options.tierThreeEvidence,
489
- cases: []
490
- });
491
- return CertificationTierThreeReport.make({
492
- status: "not-exercised",
493
- evidence: [],
494
- cases: [],
495
- detail: "no crash lever was supplied and no committed real-loss evidence was cited; Tier 3 is NOT discharged for this adapter"
496
- });
497
- });
498
- const nowUtc = Effect.map(Clock.currentTimeMillis, (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis)));
499
- /**
500
- * Certify one durable adapter pair (plan §1, §8 WP2). Runs Tier 2 FIRST over pristine
501
- * storage (each cell converges to all-settled before the next starts, so the recovery scan
502
- * never sees foreign leftovers), then Tier 1's port contract cases (whose lanes deliberately
503
- * end in every nonterminal shape), then records Tier 3. Requires `Crypto.Crypto` and a
504
- * TestClock-backed environment; the candidate Layers are built exactly once.
505
- */
506
- const certifyDurableAdapters = (options) => {
507
- const batchProducers = /* @__PURE__ */ new Map();
508
- const capturingStore = Layer.effect(ConversationStore)(Effect.gen(function* () {
509
- const inner = yield* ConversationStore;
510
- return ConversationStore.of({
511
- ...inner,
512
- append: (request) => Effect.sync(() => {
513
- batchProducers.set(request.batch.batchId, request.batch.producerId);
514
- }).pipe(Effect.andThen(inner.append(request)))
515
- });
516
- })).pipe(Layer.provide(options.conversationStore));
517
- const support = Layer.mergeAll(options.submissionLedger, capturingStore, options.wakeScheduler ?? WakeScheduler.layerNoop, DurableRuntimeFailpoint.layerTest, ToolReconciler.uncertain, DurableRuntimeConfig.layer({
518
- deploymentId: Schema.decodeSync(DeploymentId)("deployment-certification"),
519
- producerId: Schema.decodeSync(ProducerId)("producer-certification"),
520
- settlementPollInterval: Duration.millis(50),
521
- leaseRenewalInterval: Duration.seconds(5),
522
- abortPollInterval: Duration.millis(50)
523
- }));
524
- const environment = DurableAgentRuntime.layer.pipe(Layer.provideMerge(support));
525
- const leaseAdvance = Duration.millis(Duration.toMillis(options.ownershipLeaseDuration ?? DEFAULT_OWNERSHIP_LEASE_DURATION) + 1e3);
526
- return Effect.gen(function* () {
527
- const ledger = yield* SubmissionLedger;
528
- const tier2 = [];
529
- for (const scenario of CERTIFICATION_SCENARIOS) for (const location of DurableRuntimeFailpointLocation.literals) tier2.push(yield* runSweepCell(scenario, location, batchProducers, leaseAdvance));
530
- const tier1 = yield* certifyPorts();
531
- const capabilities = yield* ledger.capabilities;
532
- const tier3 = yield* resolveTierThree(capabilities.durability, options);
533
- const generatedAt = yield* nowUtc;
534
- const ok = tier1.every((result) => result.status === "passed") && tier2.every((result) => result.status !== "failed") && tier3.cases.every((result) => result.status === "passed");
535
- return CertificationReport.make({
536
- format: "effect-agent/certification@1",
537
- adapter: CertifiedAdapterIdentity.make({
538
- name: options.adapter.name,
539
- ...options.adapter.version === void 0 ? {} : { version: options.adapter.version },
540
- durability: capabilities.durability
541
- }),
542
- generatedAt,
543
- tier1,
544
- tier2,
545
- tier3,
546
- ok
547
- });
548
- }).pipe(Effect.provide(environment));
549
- };
550
- //#endregion
551
- //#region src/chaos.ts
552
- /**
553
- * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over
554
- * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a
555
- * deterministic runner that drives the durable coordinator over whatever adapter pair the test
556
- * provides. Every plan ends in the SAME claims the crash matrices make:
557
- *
558
- * 1. `verifyConversationInvariants` in convergence mode over every touched Conversation (the
559
- * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);
560
- * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);
561
- * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no
562
- * canonical Tool success exists that the external store did not actually produce).
563
- *
564
- * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed
565
- * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing
566
- * plan's own seed in the failure output, so any red run is replayable byte-for-byte.
567
- */
568
- /** The six durable scenario flavors a chaos lane can exercise (plan §5). */
569
- const ChaosScenarioKind = Schema.Literals([
570
- "plain",
571
- "uncertain-tool",
572
- "durable-steps",
573
- "approval",
574
- "join",
575
- "delegation"
576
- ]);
577
- const LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));
578
- /** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */
579
- var ChaosSubmissionSpec = class extends Schema.Class("@effect-agent/testing/ChaosSubmissionSpec")({
580
- lane: LaneIndex,
581
- /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */
582
- kind: ChaosScenarioKind
583
- }) {};
584
- /** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */
585
- const ChaosResolutionKind = Schema.Literals([
586
- "never-happened",
587
- "completed-from-supplier",
588
- "abort-submission"
589
- ]);
590
- const ChaosApprovalDecision = Schema.Literals(["approved", "denied"]);
591
- const BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));
592
- /**
593
- * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays
594
- * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are
595
- * adapter-owned location names the adapter test validates (the memory runner has none).
596
- */
597
- var ChaosPlan = class extends Schema.Class("@effect-agent/testing/ChaosPlan")({
598
- /** Identifies this plan in failure output; derived from the root seed plus the plan index. */
599
- seed: Schema.Int,
600
- /** Lane count; submissions address lanes `0..lanes-1`. */
601
- lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),
602
- submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),
603
- /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */
604
- failpointArms: Schema.Array(DurableRuntimeFailpointLocation),
605
- /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */
606
- adapterArms: Schema.Array(BoundedAdapterArm),
607
- /** Flattened submission indices to abort mid-plan (modulo the submission count). */
608
- abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
609
- /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */
610
- resolutionInjections: Schema.Array(ChaosResolutionKind),
611
- /** Approval decisions for suspended approval lanes, indexed deterministically per call. */
612
- approvalDecisions: Schema.Array(ChaosApprovalDecision)
613
- }) {};
614
- /** Per-lane verification result inside a plan report. */
615
- var ChaosLaneReport = class extends Schema.Class("@effect-agent/testing/ChaosLaneReport")({
616
- conversationId: ConversationId,
617
- kind: ChaosScenarioKind,
618
- submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
619
- /** Verdict of `verifyConversationInvariants` in convergence mode. */
620
- verified: Schema.Boolean
621
- }) {};
622
- /** The Schema-first outcome of one executed chaos plan. */
623
- var ChaosPlanReport = class extends Schema.Class("@effect-agent/testing/ChaosPlanReport")({
624
- seed: Schema.Int,
625
- rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
626
- lanes: Schema.Array(ChaosLaneReport),
627
- /** `scanObligations` entries after convergence — MUST be zero. */
628
- openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
629
- }) {};
630
- /** Typed convergence/verification failure of one chaos plan (never a bare defect). */
631
- var ChaosConvergenceFailure = class extends Schema.TaggedError()("ChaosConvergenceFailure", {
632
- seed: Schema.Int,
633
- message: Schema.String.check(Schema.isMaxLength(16384))
634
- }) {};
635
- /** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */
636
- const DEFAULT_CHAOS_SEED = 20260813;
637
- /** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */
638
- const chaosSeedFromEnv = (env) => {
639
- const raw = env["CHAOS_SEED"];
640
- if (raw === void 0 || raw === "") return DEFAULT_CHAOS_SEED;
641
- const parsed = Number.parseInt(raw, 10);
642
- return Number.isSafeInteger(parsed) ? parsed : DEFAULT_CHAOS_SEED;
643
- };
644
- const laneArbitrary = FastCheck.constantFrom("plain", "uncertain-tool", "durable-steps", "approval", "join", "delegation").chain((kind) => kind === "join" ? FastCheck.integer({
645
- min: 2,
646
- max: 3
647
- }).map((depth) => ({
648
- kind,
649
- depth
650
- })) : kind === "plain" ? FastCheck.integer({
651
- min: 1,
652
- max: 2
653
- }).map((depth) => ({
654
- kind,
655
- depth
656
- })) : FastCheck.constant({
657
- kind,
658
- depth: 1
659
- }));
660
- const planShapeArbitrary = (adapterArms) => FastCheck.record({
661
- lanes: FastCheck.array(laneArbitrary, {
662
- minLength: 1,
663
- maxLength: 3
664
- }),
665
- failpointArms: FastCheck.uniqueArray(FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals), { maxLength: 3 }),
666
- adapterArms: adapterArms.length === 0 ? FastCheck.constant([]) : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),
667
- abortInjections: FastCheck.uniqueArray(FastCheck.integer({
668
- min: 0,
669
- max: 15
670
- }), { maxLength: 2 }),
671
- resolutionInjections: FastCheck.array(FastCheck.constantFrom("never-happened", "completed-from-supplier", "abort-submission"), { maxLength: 4 }),
672
- approvalDecisions: FastCheck.array(FastCheck.constantFrom("approved", "denied"), { maxLength: 2 })
673
- }).map((shape) => {
674
- const [first, ...rest] = shape.lanes.flatMap((lane, index) => Array.from({ length: lane.depth }, () => ChaosSubmissionSpec.make({
675
- lane: index,
676
- kind: lane.kind
677
- })));
678
- if (first === void 0) throw new Error("chaos generator produced an empty plan");
679
- return {
680
- lanes: shape.lanes.length,
681
- submissions: [first, ...rest],
682
- failpointArms: shape.failpointArms,
683
- adapterArms: shape.adapterArms,
684
- abortInjections: shape.abortInjections,
685
- resolutionInjections: shape.resolutionInjections,
686
- approvalDecisions: shape.approvalDecisions
687
- };
688
- });
689
- /**
690
- * Derive `count` chaos plans deterministically from one root seed. The same
691
- * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line
692
- * `CHAOS_SEED=<seed>` replays the exact schedule.
693
- */
694
- const generateChaosPlans = (options) => {
695
- return FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {
696
- seed: options.seed,
697
- numRuns: options.count
698
- }).map((shape, index) => ChaosPlan.make({
699
- ...shape,
700
- seed: Math.imul(options.seed, 31) + index | 0
701
- }));
702
- };
703
- /** Deterministic PRNG for the runner's small ordering choices (lane drive order). */
704
- const mulberry32 = (seed) => {
705
- let state = seed | 0;
706
- return () => {
707
- state = state + 1831565813 | 0;
708
- let t = Math.imul(state ^ state >>> 15, 1 | state);
709
- t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
710
- return ((t ^ t >>> 14) >>> 0) / 4294967296;
711
- };
712
- };
713
- const usage$1 = {
714
- inputTokens: {},
715
- outputTokens: {}
716
- };
717
- const finalParts = (text) => [
718
- {
719
- type: "text-start",
720
- id: "answer"
721
- },
722
- {
723
- type: "text-delta",
724
- id: "answer",
725
- delta: text
726
- },
727
- {
728
- type: "text-end",
729
- id: "answer"
730
- },
731
- {
732
- type: "finish",
733
- reason: "stop",
734
- usage: usage$1
735
- }
736
- ];
737
- const toolTurn = (...calls) => [...calls, {
738
- type: "finish",
739
- reason: "tool-calls",
740
- usage: usage$1
741
- }];
742
- const toolCallPart = (id, name, params) => ({
743
- type: "tool-call",
744
- id,
745
- name,
746
- params,
747
- providerExecuted: false
748
- });
749
- /**
750
- * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays
751
- * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter
752
- * to drift when chaos re-enters a Turn.
753
- */
754
- const promptScriptedModel = (label, script) => Model.make("scripted", label, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
755
- generateText: () => Effect.succeed([]),
756
- streamText: (request) => Stream.fromIterable(script(request.prompt))
757
- })));
758
- const lastRole = (prompt) => prompt.content.at(-1)?.role;
759
- const policy = AgentPolicy.make({
760
- maxTurns: 3,
761
- maxToolCalls: 4,
762
- maxDuration: "30 seconds",
763
- toolConcurrency: 2
764
- });
765
- const PlainInput = Schema.Struct({ question: Schema.String });
766
- const PlainOutput = Schema.Struct({ answer: Schema.String });
767
- const plainDefinition = Agent.define("chaos-plain", {
768
- input: PlainInput,
769
- output: PlainOutput,
770
- instructions: "Answer as JSON.",
771
- toolkit: Toolkit.empty,
772
- policy
773
- });
774
- /** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */
775
- const BookUncertain = Tool.make("book", {
776
- parameters: Schema.Struct({ ref: Schema.String }),
777
- success: Schema.Struct({ confirmation: Schema.String })
778
- });
779
- const bookTools = Toolkit.make(BookUncertain);
780
- const bookDefinition = Agent.define("chaos-book", {
781
- input: PlainInput,
782
- output: PlainOutput,
783
- instructions: "Book it.",
784
- toolkit: bookTools,
785
- policy
786
- });
787
- const BookApproval = Tool.make("book", {
788
- parameters: Schema.Struct({ ref: Schema.String }),
789
- success: Schema.Struct({ confirmation: Schema.String }),
790
- needsApproval: true
791
- });
792
- const approvalTools = Toolkit.make(BookApproval);
793
- const approvalDefinition = Agent.define("chaos-approval", {
794
- input: PlainInput,
795
- output: PlainOutput,
796
- instructions: "Book after approval.",
797
- toolkit: approvalTools,
798
- policy
799
- });
800
- const Itinerary$1 = Tool.make("itinerary", {
801
- parameters: Schema.Struct({ ref: Schema.String }),
802
- success: Schema.Struct({ state: Schema.String }),
803
- failure: DurableStepError,
804
- dependencies: [DurableStep]
805
- }).annotate(ToolExecutionClass, "uncertain");
806
- const itineraryTools = Toolkit.make(Itinerary$1);
807
- const itineraryDefinition = Agent.define("chaos-itinerary", {
808
- input: PlainInput,
809
- output: PlainOutput,
810
- instructions: "Reserve the itinerary.",
811
- toolkit: itineraryTools,
812
- policy
813
- });
814
- const childDefinition = Agent.define("chaos-child", {
815
- input: PlainInput,
816
- output: PlainOutput,
817
- instructions: "Answer as JSON.",
818
- toolkit: Toolkit.empty,
819
- policy: AgentPolicy.make({
820
- maxTurns: 2,
821
- maxToolCalls: 1,
822
- maxDuration: "30 seconds",
823
- toolConcurrency: 1
824
- })
825
- });
826
- var ChaosDelegationFailed = class extends Schema.TaggedError()("ChaosDelegationFailed", { childErrorTag: Schema.String }) {};
827
- const chaosDelegation = Subagent.define("delegate_chaos", {
828
- description: "Delegate one bounded chaos question.",
829
- target: childDefinition,
830
- parameters: Schema.Struct({ topic: Schema.String }),
831
- success: Schema.Struct({ summary: Schema.String }),
832
- failure: ChaosDelegationFailed,
833
- prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),
834
- projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),
835
- policy: SubagentPolicy.make({
836
- maxChildren: 2,
837
- maxConcurrency: 2,
838
- maxTurns: 4,
839
- maxToolCalls: 4,
840
- maxDuration: "30 seconds"
841
- })
842
- });
843
- const coordinatorDefinition = Agent.define("chaos-coordinator", {
844
- input: Schema.Struct({ mission: Schema.String }),
845
- output: Schema.Struct({ report: Schema.String }),
846
- instructions: "Delegate, then report as JSON.",
847
- toolkit: Toolkit.make(chaosDelegation.tool),
848
- policy
849
- });
850
- const DELEGATE_CALL_ID = "chaos-delegate-1";
851
- const HEX = "0123456789abcdef";
852
- const decodeDigest = Schema.decodeSync(Digest);
853
- const laneDigests = (lane) => {
854
- const digest = decodeDigest(HEX[lane % 8].repeat(64));
855
- return DefinitionDigests.make({
856
- agent: digest,
857
- model: digest,
858
- tools: digest
859
- });
860
- };
861
- const childDigestStrings = (lane) => {
862
- const char = HEX[8 + lane % 8];
863
- return {
864
- agent: char.repeat(64),
865
- model: char.repeat(64),
866
- tools: char.repeat(64)
867
- };
868
- };
869
- const childLaneDigests = (lane) => {
870
- const strings = childDigestStrings(lane);
871
- return DefinitionDigests.make({
872
- agent: decodeDigest(strings.agent),
873
- model: decodeDigest(strings.model),
874
- tools: decodeDigest(strings.tools)
875
- });
876
- };
877
- const CHAOS_PRINCIPAL = Schema.decodeSync(Principal)("principal-chaos");
878
- const decodeConversationId = Schema.decodeSync(ConversationId);
879
- const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);
880
- const decodeToolCallId = Schema.decodeSync(ToolCallId);
881
- const decodeRunId = Schema.decodeSync(RunId);
882
- const decodeTurnId = Schema.decodeSync(TurnId);
883
- /** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */
884
- const chaosIdentifiers = Layer.effect(IdGenerator, Effect.gen(function* () {
885
- const counter = yield* Ref.make(0);
886
- const next = (decode, prefix) => Ref.getAndUpdate(counter, (value) => value + 1).pipe(Effect.map((value) => decode(`${prefix}-${value}`)));
887
- return {
888
- nextConversationId: next(decodeConversationId, "chaos-fixture-conversation"),
889
- nextRunId: next(decodeRunId, "chaos-fixture-run"),
890
- nextTurnId: next(decodeTurnId, "chaos-fixture-turn")
891
- };
892
- }));
893
- const delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);
894
- const makeChaosDesk = Effect.gen(function* () {
895
- const produced = yield* Ref.make(/* @__PURE__ */ new Set());
896
- return {
897
- produced: Ref.get(produced),
898
- record: (value) => Ref.update(produced, (current) => new Set(current).add(value))
899
- };
900
- });
901
- const bookConfirmation = (ref) => `confirmed-${ref}`;
902
- const flightValue = (ref) => `flight-${ref}`;
903
- const lodgingValue = (ref) => `lodging-${ref}`;
904
- /** Success → Some; typed failure → None (chaos tolerates it); defect → rethrown loudly. */
905
- const tolerateTyped = (effect) => effect.pipe(Effect.exit, Effect.flatMap((exit) => {
906
- if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));
907
- if (Option.isSome(Cause.findErrorOption(exit.cause))) return Effect.succeed(Option.none());
908
- return Effect.die(/* @__PURE__ */ new Error(`chaos step died: ${Cause.pretty(exit.cause)}`));
909
- }));
910
- const scriptFor = (kind, ref) => {
911
- switch (kind) {
912
- case "plain":
913
- case "join": return () => finalParts("{\"answer\":\"chaos\"}");
914
- case "uncertain-tool":
915
- case "approval": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"answer\":\"booked\"}") : toolTurn(toolCallPart(`book-${ref}`, "book", { ref }));
916
- case "durable-steps": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"answer\":\"reserved\"}") : toolTurn(toolCallPart(`itinerary-${ref}`, "itinerary", { ref }));
917
- case "delegation": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"report\":\"done\"}") : toolTurn(toolCallPart(DELEGATE_CALL_ID, "delegate_chaos", { topic: ref }));
918
- }
919
- };
920
- const makeLaneFixture = Effect.fn("Chaos.makeLaneFixture")(function* (plan, laneIndex, kind, submissionIndexes, desk) {
921
- const runtime = yield* DurableAgentRuntime;
922
- const conversationId = decodeConversationId(`chaos-${plan.seed}-lane-${laneIndex}`);
923
- const ref = `ref-l${laneIndex}`;
924
- const script = scriptFor(kind, ref);
925
- const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);
926
- const digests = laneDigests(laneIndex);
927
- const submitOptionsFor = (flatIndex) => ({
928
- conversationId,
929
- principal: CHAOS_PRINCIPAL,
930
- idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),
931
- definitions: digests
932
- });
933
- const bookToolLayerFor = (tools) => tools.toLayer({ book: ({ ref: called }) => desk.record(bookConfirmation(called)).pipe(Effect.as({ confirmation: bookConfirmation(called) })) });
934
- const plainLaneFixture = (deskInPlay, drive, submitOne) => ({
935
- index: laneIndex,
936
- kind,
937
- conversationId,
938
- ref,
939
- deskInPlay,
940
- submissionIndexes,
941
- submitOne,
942
- drives: () => [drive],
943
- childConversationOf: () => void 0
944
- });
945
- switch (kind) {
946
- case "plain":
947
- case "join": {
948
- const agent = Agent.withModel(plainDefinition, model);
949
- return plainLaneFixture(false, runtime.processConversation(agent, conversationId), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
950
- }
951
- case "uncertain-tool": {
952
- const agent = Agent.withModel(bookDefinition, model);
953
- return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(bookToolLayerFor(bookTools))), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
954
- }
955
- case "approval": {
956
- const agent = Agent.withModel(approvalDefinition, model);
957
- return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(bookToolLayerFor(approvalTools))), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
958
- }
959
- case "durable-steps": {
960
- const agent = Agent.withModel(itineraryDefinition, model);
961
- const toolLayer = itineraryTools.toLayer({ itinerary: ({ ref: called }) => Effect.gen(function* () {
962
- const step = yield* DurableStep;
963
- return { state: `${yield* step.do("reserve-flight", Schema.String, desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))))}+${yield* step.do("reserve-lodging", Schema.String, desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))))}` };
964
- }) });
965
- return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(toolLayer)), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
966
- }
967
- case "delegation": {
968
- const parentBinding = Agent.withModel(coordinatorDefinition, model);
969
- const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () => finalParts("{\"answer\":\"child\"}"));
970
- const childBinding = Agent.withModel(childDefinition, childModel);
971
- const delegationLayer = SubagentRuntime.layer(chaosDelegation, childBinding, {
972
- mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),
973
- durable: { targetDigests: childDigestStrings(laneIndex) }
974
- }).pipe(Layer.provide(delegationSupport));
975
- const parentResolved = yield* DurableWorkerBinding.make(parentBinding, digests).pipe(Effect.provide(delegationLayer));
976
- const childResolved = yield* DurableWorkerBinding.make(childBinding, childLaneDigests(laneIndex));
977
- const resolver = AgentBindingResolver.fromBindings([parentResolved, childResolved]);
978
- const driveResolved = (conversation) => runtime.processConversationResolved(conversation).pipe(Effect.provideService(AgentBindingResolver, resolver));
979
- return {
980
- index: laneIndex,
981
- kind,
982
- conversationId,
983
- ref,
984
- deskInPlay: false,
985
- submissionIndexes,
986
- submitOne: (flatIndex) => runtime.submit({ definition: {
987
- id: coordinatorDefinition.id,
988
- input: coordinatorDefinition.input
989
- } }, { mission: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),
990
- drives: (firstReceipt) => {
991
- const drives = [driveResolved(conversationId)];
992
- if (firstReceipt !== void 0) drives.push(driveResolved(childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID))));
993
- return drives;
994
- },
995
- childConversationOf: (firstReceipt) => childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID))
996
- };
997
- }
998
- }
999
- });
1000
- /** Stable per-call index into an injection list (identical across resolution passes). */
1001
- const injectionIndex = (submissionFlatIndex, callId, length) => {
1002
- let hash = submissionFlatIndex + 1;
1003
- for (const char of callId) hash = Math.imul(hash, 31) + char.charCodeAt(0) | 0;
1004
- return (hash % length + length) % length;
1005
- };
1006
- const resolutionFor = (kind, toolName, ref, produced) => {
1007
- switch (kind) {
1008
- case "abort-submission": return ResolutionAbortSubmission.make();
1009
- case "completed-from-supplier":
1010
- if (toolName === "book" && produced.has(bookConfirmation(ref))) return ResolutionCompletedWithResult.make({
1011
- result: { confirmation: bookConfirmation(ref) },
1012
- isFailure: false
1013
- });
1014
- if (toolName === "itinerary" && produced.has(flightValue(ref)) && produced.has(lodgingValue(ref))) return ResolutionCompletedWithResult.make({
1015
- result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },
1016
- isFailure: false
1017
- });
1018
- return ResolutionNeverHappened.make();
1019
- case "never-happened": return ResolutionNeverHappened.make();
1020
- }
1021
- };
1022
- /** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */
1023
- const resolutionPass = Effect.fn("Chaos.resolutionPass")(function* (plan, states, desk) {
1024
- const runtime = yield* DurableAgentRuntime;
1025
- const ledger = yield* SubmissionLedger;
1026
- const produced = yield* desk.produced;
1027
- const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1028
- if (Option.isNone(nonterminal)) return;
1029
- const byId = /* @__PURE__ */ new Map();
1030
- for (const state of states) if (state.receipt !== void 0) byId.set(state.receipt.submissionId, state);
1031
- for (const row of nonterminal.value) {
1032
- if (row.state !== "unknown" && row.state !== "suspended") continue;
1033
- const state = byId.get(row.submissionId);
1034
- const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));
1035
- if (Option.isNone(explanation)) continue;
1036
- const flatIndex = state?.flatIndex ?? 0;
1037
- const ref = state?.lane.ref ?? "ref-child";
1038
- if (row.state === "unknown") for (const call of explanation.value.evidence.unknownCalls) {
1039
- if (call.resolved) continue;
1040
- const kind = plan.resolutionInjections.length === 0 ? "never-happened" : plan.resolutionInjections[injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length)];
1041
- yield* tolerateTyped(runtime.resolveUnknown(UnknownResolutionCommand.make({
1042
- submissionId: row.submissionId,
1043
- toolCallId: call.toolCallId,
1044
- author: "chaos-runner",
1045
- reason: `chaos plan ${plan.seed} resolution (${kind})`,
1046
- resolution: resolutionFor(kind, call.toolName, ref, produced)
1047
- })));
1048
- }
1049
- else for (const pending of explanation.value.evidence.approvalsPending) {
1050
- const decision = plan.approvalDecisions.length === 0 ? "approved" : plan.approvalDecisions[injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length)];
1051
- yield* tolerateTyped(runtime.resolveApproval(ApprovalDecisionCommand.make({
1052
- submissionId: row.submissionId,
1053
- toolCallId: pending.toolCallId,
1054
- decision,
1055
- resolver: "chaos-runner",
1056
- reason: `chaos plan ${plan.seed} approval (${decision})`
1057
- })));
1058
- }
1059
- }
1060
- });
1061
- const submissionIdsNamedBy = (records) => {
1062
- const named = /* @__PURE__ */ new Set();
1063
- for (const envelope of records) {
1064
- const payload = envelope.record.payload;
1065
- if (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled" || payload._tag === "AbortRequested") named.add(payload.submissionId);
1066
- }
1067
- return named;
1068
- };
1069
- /**
1070
- * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a
1071
- * desk-backed lane must be a value the desk actually produced.
1072
- */
1073
- const BookResult = Schema.Struct({ confirmation: Schema.String });
1074
- const ItineraryResult = Schema.Struct({ state: Schema.String });
1075
- const decodeBookResult = Schema.decodeUnknownOption(BookResult);
1076
- const decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);
1077
- const decodeStepOutput = Schema.decodeUnknownOption(Schema.String);
1078
- const assertNoFabrication = (plan, records, produced) => {
1079
- const fabricated = [];
1080
- const requireProduced = (value, label) => {
1081
- if (!produced.has(value)) fabricated.push(`${label} "${value}"`);
1082
- };
1083
- for (const envelope of records) {
1084
- const payload = envelope.record.payload;
1085
- if (payload._tag === "ToolCallSettled" && !payload.isFailure) {
1086
- if (payload.toolName === "book") {
1087
- const result = decodeBookResult(payload.result);
1088
- if (Option.isSome(result)) requireProduced(result.value.confirmation, "book result");
1089
- }
1090
- if (payload.toolName === "itinerary") {
1091
- const result = decodeItineraryResult(payload.result);
1092
- if (Option.isSome(result)) for (const part of result.value.state.split("+")) requireProduced(part, "itinerary step result");
1093
- }
1094
- }
1095
- if (payload._tag === "ToolStepSettled") {
1096
- const output = decodeStepOutput(payload.output);
1097
- if (Option.isSome(output)) requireProduced(output.value, "step output");
1098
- }
1099
- }
1100
- return fabricated.length === 0 ? Effect.void : Effect.fail(ChaosConvergenceFailure.make({
1101
- seed: plan.seed,
1102
- message: `fabricated Tool results absent from the desk: ${fabricated.join(", ")}`
1103
- }));
1104
- };
1105
- /**
1106
- * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the
1107
- * shared invariant claims. Deterministic: same plan + same adapters → same schedule.
1108
- */
1109
- const runChaosPlan = Effect.fn("Chaos.runChaosPlan")(function* (plan, options) {
1110
- const runtime = yield* DurableAgentRuntime;
1111
- const ledger = yield* SubmissionLedger;
1112
- const store = yield* ConversationStore;
1113
- const config = yield* DurableRuntimeConfig;
1114
- const failpoints = yield* DurableRuntimeFailpointTestControl;
1115
- const random = mulberry32(plan.seed);
1116
- const desk = yield* makeChaosDesk;
1117
- const laneKinds = /* @__PURE__ */ new Map();
1118
- const laneSubmissions = /* @__PURE__ */ new Map();
1119
- plan.submissions.forEach((spec, flatIndex) => {
1120
- const lane = spec.lane % plan.lanes;
1121
- if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);
1122
- const list = laneSubmissions.get(lane) ?? [];
1123
- list.push(flatIndex);
1124
- laneSubmissions.set(lane, list);
1125
- });
1126
- const lanes = [];
1127
- for (const [lane, kind] of laneKinds) lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));
1128
- const states = plan.submissions.map((spec, flatIndex) => ({
1129
- flatIndex,
1130
- lane: lanes.find((fixture) => fixture.index === spec.lane % plan.lanes),
1131
- receipt: void 0
1132
- }));
1133
- const appliedAborts = /* @__PURE__ */ new Set();
1134
- const armQueue = [...plan.failpointArms.map((location) => ({
1135
- family: "coordinator",
1136
- location
1137
- })), ...plan.adapterArms.map((location) => ({
1138
- family: "adapter",
1139
- location
1140
- }))];
1141
- const allSettled = Effect.gen(function* () {
1142
- if (states.some((state) => state.receipt === void 0)) return false;
1143
- const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1144
- return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;
1145
- });
1146
- const maxRounds = armQueue.length + states.length * 2 + 12;
1147
- let rounds = 0;
1148
- let converged = false;
1149
- for (let round = 0; round < maxRounds; round++) {
1150
- rounds = round + 1;
1151
- const arm = armQueue[round];
1152
- if (arm?.family === "coordinator") {
1153
- const location = arm.location;
1154
- yield* failpoints.setHandler((hit) => hit === location ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit })) : Effect.void);
1155
- } else if (arm?.family === "adapter" && options?.adapterFailpoints !== void 0) yield* options.adapterFailpoints.arm(arm.location);
1156
- for (const state of states) {
1157
- if (state.receipt !== void 0) continue;
1158
- const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));
1159
- if (Option.isSome(receipt)) state.receipt = receipt.value;
1160
- }
1161
- const order = [...lanes].sort(() => random() - .5);
1162
- for (const lane of order) {
1163
- const firstFlat = lane.submissionIndexes[0];
1164
- const firstReceipt = firstFlat === void 0 ? void 0 : states[firstFlat]?.receipt;
1165
- for (const drive of lane.drives(firstReceipt)) yield* tolerateTyped(drive);
1166
- }
1167
- if (round >= 1) for (const rawIndex of plan.abortInjections) {
1168
- const index = rawIndex % states.length;
1169
- if (appliedAborts.has(index)) continue;
1170
- const receipt = states[index]?.receipt;
1171
- if (receipt === void 0) continue;
1172
- appliedAborts.add(index);
1173
- yield* tolerateTyped(runtime.abort(AbortCommand.make({
1174
- submissionId: receipt.submissionId,
1175
- author: "chaos-runner",
1176
- reason: `chaos plan ${plan.seed} abort injection`
1177
- })));
1178
- }
1179
- yield* resolutionPass(plan, states, desk);
1180
- yield* failpoints.clear;
1181
- if (options?.adapterFailpoints !== void 0) yield* options.adapterFailpoints.clear;
1182
- yield* tolerateTyped(runtime.runRecovery);
1183
- yield* resolutionPass(plan, states, desk);
1184
- if (yield* allSettled) {
1185
- converged = true;
1186
- break;
1187
- }
1188
- if (options?.betweenRounds !== void 0) yield* options.betweenRounds;
1189
- }
1190
- if (!converged) {
1191
- const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1192
- const detail = Option.isSome(nonterminal) ? Array.from(nonterminal.value).map((row) => `${row.submissionId}(${row.state})`).join(", ") : "ledger scan failed";
1193
- return yield* ChaosConvergenceFailure.make({
1194
- seed: plan.seed,
1195
- message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === void 0).length}`
1196
- });
1197
- }
1198
- const produced = yield* desk.produced;
1199
- const laneReports = [];
1200
- const verifyConversation = Effect.fn("Chaos.verifyConversation")(function* (conversationId, kind, deskInPlay) {
1201
- const exported = yield* store.export(ConversationExportRequest.make({ conversationId })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1202
- seed: plan.seed,
1203
- message: `export of ${conversationId} failed: ${String(error)}`
1204
- })));
1205
- const rows = [];
1206
- for (const submissionId of submissionIdsNamedBy(exported.records)) {
1207
- const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1208
- seed: plan.seed,
1209
- message: `lookup of ${submissionId} failed: ${String(error)}`
1210
- })));
1211
- if (Option.isSome(found)) rows.push(found.value);
1212
- }
1213
- const report = yield* verifyConversationInvariants({
1214
- export: exported,
1215
- submissions: rows,
1216
- batchProducers: new Map(exported.records.map((envelope) => [envelope.batchId, config.producerId])),
1217
- requireAllSettled: true
1218
- });
1219
- if (!report.ok) {
1220
- const failed = report.checks.filter((check) => check.status === "failed").map((check) => `${check.name}: ${check.detail ?? "failed"}`).join("; ");
1221
- return yield* ChaosConvergenceFailure.make({
1222
- seed: plan.seed,
1223
- message: `invariants failed for ${conversationId} (${kind}): ${failed}`
1224
- });
1225
- }
1226
- if (deskInPlay) yield* assertNoFabrication(plan, exported.records, produced);
1227
- laneReports.push(ChaosLaneReport.make({
1228
- conversationId,
1229
- kind,
1230
- submissionCount: rows.length,
1231
- verified: report.ok
1232
- }));
1233
- });
1234
- for (const lane of lanes) {
1235
- yield* verifyConversation(lane.conversationId, lane.kind, lane.deskInPlay);
1236
- for (const flatIndex of lane.submissionIndexes) {
1237
- const receipt = states[flatIndex]?.receipt;
1238
- if (receipt === void 0) continue;
1239
- const child = lane.childConversationOf(receipt);
1240
- if (child === void 0) continue;
1241
- const childExport = yield* Effect.exit(store.export(ConversationExportRequest.make({ conversationId: child })));
1242
- if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) yield* verifyConversation(child, "plain", false);
1243
- }
1244
- }
1245
- const obligations = yield* runtime.scanObligations(ObligationThresholds.make({
1246
- agingSeconds: 0,
1247
- overdueSeconds: 0
1248
- })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1249
- seed: plan.seed,
1250
- message: `scanObligations failed: ${String(error)}`
1251
- })));
1252
- if (obligations.entries.length > 0) return yield* ChaosConvergenceFailure.make({
1253
- seed: plan.seed,
1254
- message: `open obligations after convergence: ${obligations.entries.map((entry) => `${entry.submissionId}(${entry.blockedOn})`).join(", ")}`
1255
- });
1256
- return ChaosPlanReport.make({
1257
- seed: plan.seed,
1258
- rounds,
1259
- lanes: laneReports,
1260
- openObligations: obligations.entries.length
1261
- });
1262
- });
1263
- //#endregion
1264
- //#region src/code-executor-conformance.ts
1265
- /**
1266
- * Shared `CodeExecutor` conformance (TEST-015). Every adapter — the
1267
- * deterministic `unisolated` substitute and each isolated adapter — runs
1268
- * `codeExecutorConformanceCases` verbatim. Enforcement cases that only genuine
1269
- * isolation can prove (ambient network denial, synchronous CPU runaway
1270
- * termination) are NOT here; they belong to isolated adapters only
1271
- * (testing spec §8.1).
1272
- *
1273
- * Cases assume the live `Clock` (the wall-clock case uses a short real
1274
- * deadline) and take one fresh executor pass per case, so a suite may share
1275
- * one executor Layer across cases.
1276
- */
1277
- var CodeExecutorConformanceViolation = class extends Schema.TaggedError()("CodeExecutorConformanceViolation", {
1278
- caseName: Schema.String,
1279
- message: Schema.String
1280
- }) {};
1281
- const baseLimits = CodeExecutionLimits.make({
1282
- maxSourceBytes: 64 * 1024,
1283
- maxWallTime: Duration.seconds(10),
1284
- maxLogBytes: 16 * 1024,
1285
- maxResultBytes: 64 * 1024,
1286
- maxHostCalls: 8,
1287
- maxHostCallArgumentBytes: 16 * 1024,
1288
- maxHostCallResultBytes: 32 * 1024
1289
- });
1290
- const warehouseNamespace = CodeExecutionNamespace.make({
1291
- name: "warehouse",
1292
- methods: ["query", "count"]
1293
- });
1294
- const makeRequest = (source, overrides) => CodeExecutionRequest.make({
1295
- language: "javascript",
1296
- source,
1297
- namespaces: overrides?.namespaces ?? [],
1298
- network: overrides?.network ?? NetworkDisabled.make(),
1299
- limits: overrides?.limits ?? baseLimits
1300
- });
1301
- const unusedHost = { call: () => Effect.die(/* @__PURE__ */ new Error("this conformance case expected no host call to reach the CodeExecutionHost")) };
1302
- const respondingHost = (respond) => {
1303
- const calls = [];
1304
- return {
1305
- calls,
1306
- host: { call: (call) => Effect.sync(() => {
1307
- calls.push(call);
1308
- return respond(call);
1309
- }) }
1310
- };
1311
- };
1312
- const runPass = (request, host) => Effect.gen(function* () {
1313
- return yield* (yield* CodeExecutor).execute(request).pipe(Effect.provideService(CodeExecutionHost, CodeExecutionHost.of(host)));
1314
- }).pipe(Effect.scoped);
1315
- const violation = (caseName, message) => CodeExecutorConformanceViolation.make({
1316
- caseName,
1317
- message
1318
- });
1319
- const preview = (value) => {
1320
- try {
1321
- return JSON.stringify(value)?.slice(0, 200) ?? String(value).slice(0, 200);
1322
- } catch {
1323
- return String(value).slice(0, 200);
1324
- }
1325
- };
1326
- const expectSuccess = (caseName, request, host, check) => runPass(request, host).pipe(Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`)), Effect.flatMap((result) => {
1327
- const complaint = check(result);
1328
- return complaint === void 0 ? Effect.void : Effect.fail(violation(caseName, complaint));
1329
- }));
1330
- const expectFailure = (caseName, request, host, tag, check) => runPass(request, host).pipe(Effect.flip, Effect.mapError((result) => violation(caseName, `expected ${tag}, but the pass succeeded with ${preview(result.value)}`)), Effect.flatMap((error) => {
1331
- if (error._tag !== tag) return Effect.fail(violation(caseName, `expected ${tag}, got ${error._tag}: ${preview(error)}`));
1332
- const complaint = check?.(error);
1333
- return complaint === void 0 ? Effect.void : Effect.fail(violation(caseName, complaint));
1334
- }));
1335
- const codeExecutorConformanceCases = (options) => {
1336
- const posture = options.implementation;
1337
- return [
1338
- {
1339
- name: "TEST-015 executes bounded JSON computation and returns the program value",
1340
- run: expectSuccess("TEST-015 executes bounded JSON computation and returns the program value", makeRequest("async () => { const xs = [1, 2, 3].map((n) => n * 2); return { xs, sum: xs.reduce((a, b) => a + b, 0) }; }"), unusedHost, (result) => JSON.stringify(result.value) === JSON.stringify({
1341
- xs: [
1342
- 2,
1343
- 4,
1344
- 6
1345
- ],
1346
- sum: 12
1347
- }) ? void 0 : `unexpected program value ${preview(result.value)}`)
1348
- },
1349
- {
1350
- name: "CAP-015 reports its isolation posture honestly in results and errors",
1351
- run: Effect.gen(function* () {
1352
- const caseName = "CAP-015 reports its isolation posture honestly in results and errors";
1353
- const result = yield* runPass(makeRequest("async () => 1"), unusedHost).pipe(Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}`)));
1354
- if (result.implementation.isolation !== posture.isolation || result.implementation.identity !== posture.identity) return yield* violation(caseName, `result posture ${preview(result.implementation)} does not match the declared ${preview(posture)}`);
1355
- const error = yield* runPass(makeRequest("async () => {"), unusedHost).pipe(Effect.flip, Effect.mapError(() => violation(caseName, "expected the invalid-source pass to fail")));
1356
- if (error.implementation === void 0 || error.implementation.isolation !== posture.isolation || error.implementation.identity !== posture.identity) return yield* violation(caseName, `error posture ${preview(error.implementation)} does not match the declared ${preview(posture)}`);
1357
- })
1358
- },
1359
- {
1360
- name: "TEST-015 routes host calls through the CodeExecutionHost in program order",
1361
- run: Effect.gen(function* () {
1362
- const caseName = "TEST-015 routes host calls through the CodeExecutionHost in program order";
1363
- const { host, calls } = respondingHost((call) => call.method === "query" ? CodeHostCallSuccess.make({ value: { rows: [
1364
- 1,
1365
- 2,
1366
- 3
1367
- ] } }) : CodeHostCallSuccess.make({ value: 3 }));
1368
- const result = yield* runPass(makeRequest("async () => { const q = await warehouse.query({ sql: 'select' }); const c = await warehouse.count({ table: 't' }); return { rows: q.rows, count: c }; }", { namespaces: [warehouseNamespace] }), host).pipe(Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`)));
1369
- if (JSON.stringify(result.value) !== JSON.stringify({
1370
- rows: [
1371
- 1,
1372
- 2,
1373
- 3
1374
- ],
1375
- count: 3
1376
- })) return yield* violation(caseName, `unexpected value ${preview(result.value)}`);
1377
- const observed = calls.map((call) => `${call.namespace}.${call.method}`);
1378
- if (JSON.stringify(observed) !== JSON.stringify(["warehouse.query", "warehouse.count"])) return yield* violation(caseName, `unexpected host call order ${preview(observed)}`);
1379
- if (result.resourceUse.hostCalls !== 2) return yield* violation(caseName, `expected 2 accounted host calls, got ${result.resourceUse.hostCalls}`);
1380
- })
1381
- },
1382
- {
1383
- name: "TEST-015 a caught failed host call lets the program branch on the envelope",
1384
- run: expectSuccess("TEST-015 a caught failed host call lets the program branch on the envelope", makeRequest("async () => { try { await warehouse.query({ sql: 'x' }); return 'unreachable'; } catch (envelope) { return { caught: envelope }; } }", { namespaces: [warehouseNamespace] }), respondingHost(() => CodeHostCallFailure.make({ error: {
1385
- _tag: "ToolInputError",
1386
- message: "bad input"
1387
- } })).host, (result) => JSON.stringify(result.value) === JSON.stringify({ caught: {
1388
- _tag: "ToolInputError",
1389
- message: "bad input"
1390
- } }) ? void 0 : `the envelope did not round-trip: ${preview(result.value)}`)
1391
- },
1392
- {
1393
- name: "TEST-015 an uncaught failed host call fails the program with the envelope",
1394
- run: expectFailure("TEST-015 an uncaught failed host call fails the program with the envelope", makeRequest("async () => warehouse.query({ sql: 'x' })", { namespaces: [warehouseNamespace] }), respondingHost(() => CodeHostCallFailure.make({ error: {
1395
- _tag: "PolicyDenied",
1396
- message: "denied"
1397
- } })).host, "CodeProgramFailedError", (error) => error._tag === "CodeProgramFailedError" && error.reason === "rejected" && JSON.stringify(error.thrown) === JSON.stringify({
1398
- _tag: "PolicyDenied",
1399
- message: "denied"
1400
- }) ? void 0 : `unexpected failure detail ${preview(error)}`)
1401
- },
1402
- {
1403
- name: "TEST-015 fails typed on syntactically invalid source",
1404
- run: expectFailure("TEST-015 fails typed on syntactically invalid source", makeRequest("async () => {"), unusedHost, "CodeSourceError", (error) => error._tag === "CodeSourceError" && error.reason === "invalid" ? void 0 : `expected reason invalid, got ${preview(error)}`)
1405
- },
1406
- {
1407
- name: "TEST-015 fails typed when the expression is not one async function",
1408
- run: expectFailure("TEST-015 fails typed when the expression is not one async function", makeRequest("1 + 1"), unusedHost, "CodeSourceError", (error) => error._tag === "CodeSourceError" && error.reason === "not-a-function" ? void 0 : `expected reason not-a-function, got ${preview(error)}`)
1409
- },
1410
- {
1411
- name: "TEST-015 fails typed on source larger than the declared byte limit",
1412
- run: expectFailure("TEST-015 fails typed on source larger than the declared byte limit", makeRequest(`async () => "${"x".repeat(2e3)}"`, { limits: CodeExecutionLimits.make({
1413
- ...baseLimits,
1414
- maxSourceBytes: 256
1415
- }) }), unusedHost, "CodeSourceError", (error) => error._tag === "CodeSourceError" && error.reason === "oversized" ? void 0 : `expected reason oversized, got ${preview(error)}`)
1416
- },
1417
- {
1418
- name: "TEST-015 terminates a never-settling program at the wall-clock deadline",
1419
- run: expectFailure("TEST-015 terminates a never-settling program at the wall-clock deadline", makeRequest("async () => { await new Promise(() => {}); return 1; }", { limits: CodeExecutionLimits.make({
1420
- ...baseLimits,
1421
- maxWallTime: Duration.millis(250)
1422
- }) }), unusedHost, "CodeExecutionTimeoutError")
1423
- },
1424
- {
1425
- name: "TEST-015 fails typed when console output exceeds its byte budget",
1426
- run: expectFailure("TEST-015 fails typed when console output exceeds its byte budget", makeRequest("async () => { for (let i = 0; i < 64; i += 1) { console.log('x'.repeat(256)); } return 1; }", { limits: CodeExecutionLimits.make({
1427
- ...baseLimits,
1428
- maxLogBytes: 2048
1429
- }) }), unusedHost, "CodeOutputLimitError", (error) => error._tag === "CodeOutputLimitError" && error.surface === "logs" ? void 0 : `expected surface logs, got ${preview(error)}`)
1430
- },
1431
- {
1432
- name: "TEST-015 fails typed when the final result exceeds its byte budget",
1433
- run: expectFailure("TEST-015 fails typed when the final result exceeds its byte budget", makeRequest("async () => 'y'.repeat(4096)", { limits: CodeExecutionLimits.make({
1434
- ...baseLimits,
1435
- maxResultBytes: 1024
1436
- }) }), unusedHost, "CodeOutputLimitError", (error) => error._tag === "CodeOutputLimitError" && error.surface === "result" ? void 0 : `expected surface result, got ${preview(error)}`)
1437
- },
1438
- {
1439
- name: "TEST-015 fails typed when host calls exceed the executor cap",
1440
- run: Effect.gen(function* () {
1441
- const caseName = "TEST-015 fails typed when host calls exceed the executor cap";
1442
- const { host, calls } = respondingHost(() => CodeHostCallSuccess.make({ value: null }));
1443
- yield* expectFailure(caseName, makeRequest("async () => { await warehouse.query({}); await warehouse.query({}); await warehouse.query({}); return 1; }", {
1444
- namespaces: [warehouseNamespace],
1445
- limits: CodeExecutionLimits.make({
1446
- ...baseLimits,
1447
- maxHostCalls: 2
1448
- })
1449
- }), host, "CodeHostCallLimitError");
1450
- if (calls.length !== 2) return yield* violation(caseName, `expected exactly 2 dispatched host calls under a cap of 2, observed ${calls.length}`);
1451
- })
1452
- },
1453
- {
1454
- name: "TEST-015 fails typed on a host outcome outside the protocol schema",
1455
- run: expectFailure("TEST-015 fails typed on a host outcome outside the protocol schema", makeRequest("async () => warehouse.query({})", { namespaces: [warehouseNamespace] }), { call: () => Effect.succeed({ bogus: true }) }, "CodeExecutionProtocolError")
1456
- },
1457
- {
1458
- name: "TEST-015 surfaces an uncaught program throw with its bounded log capture",
1459
- run: expectFailure("TEST-015 surfaces an uncaught program throw with its bounded log capture", makeRequest("async () => { console.log('before the failure'); throw new Error('deliberate'); }"), unusedHost, "CodeProgramFailedError", (error) => error._tag === "CodeProgramFailedError" && error.reason === "threw" && error.logs.some((line) => line.includes("before the failure")) ? void 0 : `expected a threw failure carrying the log capture, got ${preview(error)}`)
1460
- },
1461
- {
1462
- name: "TEST-015 fails typed when the program returns a non-JSON value",
1463
- run: expectFailure("TEST-015 fails typed when the program returns a non-JSON value", makeRequest("async () => (() => 1)"), unusedHost, "CodeProgramFailedError", (error) => error._tag === "CodeProgramFailedError" && error.reason === "non-json-result" ? void 0 : `expected reason non-json-result, got ${preview(error)}`)
1464
- },
1465
- {
1466
- name: "CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error",
1467
- run: expectFailure("CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error", makeRequest("async () => 1", { network: NetworkAllowlist.make({
1468
- domains: ["example.com"],
1469
- ports: [443]
1470
- }) }), unusedHost, "CodeExecutorUnsupportedError", (error) => error._tag === "CodeExecutorUnsupportedError" && error.feature === "network" ? void 0 : `expected feature network, got ${preview(error)}`)
1471
- },
1472
- {
1473
- name: "TEST-015 interruption reaches in-flight host calls and pass teardown",
1474
- run: Effect.gen(function* () {
1475
- const caseName = "TEST-015 interruption reaches in-flight host calls and pass teardown";
1476
- const started = yield* Deferred.make();
1477
- const witness = { hostCallInterrupted: false };
1478
- const fiber = yield* runPass(makeRequest("async () => warehouse.query({})", { namespaces: [warehouseNamespace] }), { call: () => Deferred.succeed(started, void 0).pipe(Effect.andThen(Effect.never), Effect.ensuring(Effect.sync(() => {
1479
- witness.hostCallInterrupted = true;
1480
- }))) }).pipe(Effect.forkChild);
1481
- if ((yield* Effect.raceFirst(Deferred.await(started).pipe(Effect.as("started")), Fiber.join(fiber).pipe(Effect.exit, Effect.as("exited")))) === "exited") return yield* violation(caseName, "the pass settled before any host call reached the CodeExecutionHost");
1482
- yield* Fiber.interrupt(fiber);
1483
- if (!witness.hostCallInterrupted) return yield* violation(caseName, "interrupting the pass did not interrupt the in-flight host call");
1484
- })
1485
- }
1486
- ];
1487
- };
1488
- //#endregion
1489
- //#region src/code-executor-substitute.ts
1490
- /**
1491
- * The deterministic in-process executor substitute (C1 of ADR-0017). It runs
1492
- * the generated program on the host JavaScript engine with best-effort global
1493
- * shadowing only, so it self-identifies as `unisolated` and is never a
1494
- * security boundary (CAP-010, CAP-015). It exists to prove the public
1495
- * `CodeExecutor` contract and to drive deterministic capability tests.
1496
- */
1497
- const inProcessCodeExecutorImplementation = SandboxImplementation.make({
1498
- isolation: "unisolated",
1499
- identity: "in-process-javascript"
1500
- });
1501
- const MAX_LOG_LINES = 4096;
1502
- const MAX_LOG_LINE_CHARACTERS = 16e3;
1503
- const MAX_THROWN_CHARACTERS = 4e3;
1504
- const utf8ByteLength = (value) => new TextEncoder().encode(value).byteLength;
1505
- /**
1506
- * Ambient globals shadowed inside the harness. Shadowing blocks the obvious
1507
- * identifier paths only; a determined program can still escape, which is
1508
- * exactly why this executor reports `unisolated` and the isolated network and
1509
- * CPU enforcement conformance cases run only against isolated adapters.
1510
- */
1511
- const shadowedGlobals = [
1512
- "fetch",
1513
- "process",
1514
- "require",
1515
- "module",
1516
- "exports",
1517
- "global",
1518
- "globalThis",
1519
- "XMLHttpRequest",
1520
- "WebSocket",
1521
- "Deno",
1522
- "Bun"
1523
- ];
1524
- var LogLimitSignal = class {
1525
- observed;
1526
- constructor(observed) {
1527
- this.observed = observed;
1528
- }
1529
- };
1530
- var EvaluationThrew = class {
1531
- inner;
1532
- constructor(inner) {
1533
- this.inner = inner;
1534
- }
1535
- };
1536
- var NotAFunction = class {
1537
- actual;
1538
- constructor(actual) {
1539
- this.actual = actual;
1540
- }
1541
- };
1542
- /**
1543
- * Total, defect-free rendering of untrusted values: a hostile Proxy can throw
1544
- * from property access, `toString`, and `Symbol.toPrimitive`, and an expected
1545
- * program failure must never escape the typed channel as a defect while its
1546
- * diagnostics are being serialized.
1547
- */
1548
- const formatLogValue = (value) => {
1549
- try {
1550
- if (typeof value === "string") return value;
1551
- return JSON.stringify(value) ?? String(value);
1552
- } catch {
1553
- try {
1554
- return String(value);
1555
- } catch {
1556
- return "[unprintable value]";
1557
- }
1558
- }
1559
- };
1560
- const makeConsole = (capture, limits) => {
1561
- const write = (...values) => {
1562
- const joined = values.map(formatLogValue).join(" ");
1563
- const line = joined.length > MAX_LOG_LINE_CHARACTERS ? `${joined.slice(0, MAX_LOG_LINE_CHARACTERS - 1)}…` : joined;
1564
- const bytes = utf8ByteLength(line);
1565
- if (capture.lines.length >= MAX_LOG_LINES || capture.bytes + bytes > limits.maxLogBytes) throw new LogLimitSignal(capture.bytes + bytes);
1566
- capture.lines.push(line);
1567
- capture.bytes += bytes;
1568
- };
1569
- return {
1570
- debug: write,
1571
- error: write,
1572
- info: write,
1573
- log: write,
1574
- warn: write
1575
- };
1576
- };
1577
- const buildNamespaceObject = (namespace, offer) => {
1578
- const methods = {};
1579
- for (const method of namespace.methods) methods[method] = (argument) => new Promise((resolve, reject) => {
1580
- offer({
1581
- namespace: namespace.name,
1582
- method,
1583
- argument,
1584
- resolve,
1585
- reject
1586
- });
1587
- });
1588
- return methods;
1589
- };
1590
- const boundedText = (value) => {
1591
- try {
1592
- return (value instanceof Error ? `${value.name}: ${value.message}` : formatLogValue(value)).slice(0, MAX_THROWN_CHARACTERS);
1593
- } catch {
1594
- return "[unserializable thrown value]";
1595
- }
1596
- };
1597
- /** Schema decoding of hostile values may itself throw through trap getters. */
1598
- const safeDecodeJson = (value) => {
1599
- try {
1600
- return Schema.decodeUnknownOption(Schema.Json)(value);
1601
- } catch {
1602
- return Option.none();
1603
- }
1604
- };
1605
- const boundedThrown = (value) => {
1606
- const decoded = safeDecodeJson(value);
1607
- if (Option.isSome(decoded)) try {
1608
- const encoded = JSON.stringify(decoded.value);
1609
- if (encoded !== void 0 && encoded.length <= MAX_THROWN_CHARACTERS) return decoded.value;
1610
- } catch {}
1611
- return boundedText(value);
1612
- };
1613
- const encodedJsonByteLength = (value) => {
1614
- try {
1615
- const encoded = JSON.stringify(value);
1616
- return encoded === void 0 ? void 0 : utf8ByteLength(encoded);
1617
- } catch {
1618
- return;
1619
- }
1620
- };
1621
- /** Host outcomes are protocol input; a hostile value must not defect mid-decode. */
1622
- const decodeHostOutcome = (value) => {
1623
- try {
1624
- return Schema.decodeUnknownOption(CodeHostCallResult)(value);
1625
- } catch {
1626
- return Option.none();
1627
- }
1628
- };
1629
- const validateRequest = (request) => Effect.gen(function* () {
1630
- if (request.network._tag !== "NetworkDisabled") return yield* CodeExecutorUnsupportedError.make({
1631
- implementation: inProcessCodeExecutorImplementation,
1632
- feature: "network",
1633
- message: "The unisolated in-process executor cannot enforce an egress allowlist; only NetworkDisabled is accepted, and even that is shadowed rather than enforced"
1634
- });
1635
- if (request.limits.cpuMillis !== void 0) return yield* CodeExecutorUnsupportedError.make({
1636
- implementation: inProcessCodeExecutorImplementation,
1637
- feature: "cpu-limit",
1638
- message: "The unisolated in-process executor shares the host engine and cannot enforce a CPU limit"
1639
- });
1640
- const reservedNames = /* @__PURE__ */ new Set([...shadowedGlobals, "console"]);
1641
- const seen = /* @__PURE__ */ new Set();
1642
- for (const namespace of request.namespaces) {
1643
- if (reservedNames.has(namespace.name) || seen.has(namespace.name)) return yield* CodeExecutorUnsupportedError.make({
1644
- implementation: inProcessCodeExecutorImplementation,
1645
- feature: "namespaces",
1646
- message: `Namespace ${namespace.name} collides with a harness binding or another namespace`
1647
- });
1648
- seen.add(namespace.name);
1649
- }
1650
- const sourceBytes = utf8ByteLength(request.source);
1651
- if (sourceBytes > request.limits.maxSourceBytes) return yield* CodeSourceError.make({
1652
- implementation: inProcessCodeExecutorImplementation,
1653
- reason: "oversized",
1654
- message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`
1655
- });
1656
- });
1657
- const serveHostCalls = (host, queue, limits, capture, counter) => Effect.gen(function* () {
1658
- while (true) {
1659
- const pending = yield* Queue.take(queue);
1660
- counter.calls += 1;
1661
- if (counter.calls > limits.maxHostCalls) return yield* CodeHostCallLimitError.make({
1662
- implementation: inProcessCodeExecutorImplementation,
1663
- limit: limits.maxHostCalls,
1664
- logs: [...capture.lines]
1665
- });
1666
- const argument = safeDecodeJson(pending.argument);
1667
- if (Option.isNone(argument)) {
1668
- pending.reject(/* @__PURE__ */ new TypeError("host call arguments must be JSON values"));
1669
- continue;
1670
- }
1671
- const argumentBytes = encodedJsonByteLength(argument.value);
1672
- if (argumentBytes === void 0 || argumentBytes > limits.maxHostCallArgumentBytes) return yield* CodeOutputLimitError.make({
1673
- implementation: inProcessCodeExecutorImplementation,
1674
- surface: "host-call-argument",
1675
- limit: limits.maxHostCallArgumentBytes,
1676
- observed: argumentBytes ?? 0,
1677
- logs: [...capture.lines]
1678
- });
1679
- const rawOutcome = yield* host.call(CodeHostCall.make({
1680
- namespace: pending.namespace,
1681
- method: pending.method,
1682
- argument: argument.value
1683
- }));
1684
- const outcome = decodeHostOutcome(rawOutcome);
1685
- if (Option.isNone(outcome)) return yield* CodeExecutionProtocolError.make({
1686
- implementation: inProcessCodeExecutorImplementation,
1687
- message: "The execution host returned a value outside the CodeHostCallResult schema"
1688
- });
1689
- if (outcome.value._tag === "CodeHostCallFailure") {
1690
- pending.reject(outcome.value.error);
1691
- continue;
1692
- }
1693
- const resultBytes = encodedJsonByteLength(outcome.value.value);
1694
- if (resultBytes === void 0 || resultBytes > limits.maxHostCallResultBytes) return yield* CodeOutputLimitError.make({
1695
- implementation: inProcessCodeExecutorImplementation,
1696
- surface: "host-call-result",
1697
- limit: limits.maxHostCallResultBytes,
1698
- observed: resultBytes ?? 0,
1699
- logs: [...capture.lines]
1700
- });
1701
- pending.resolve(outcome.value.value);
1702
- }
1703
- });
1704
- const classifyProgramFailure = (thrown, limits, capture) => {
1705
- const inner = thrown instanceof EvaluationThrew ? thrown.inner : thrown;
1706
- if (inner instanceof LogLimitSignal) return CodeOutputLimitError.make({
1707
- implementation: inProcessCodeExecutorImplementation,
1708
- surface: "logs",
1709
- limit: limits.maxLogBytes,
1710
- observed: inner.observed,
1711
- logs: [...capture.lines]
1712
- });
1713
- if (inner instanceof NotAFunction) return CodeSourceError.make({
1714
- implementation: inProcessCodeExecutorImplementation,
1715
- reason: "not-a-function",
1716
- message: `The source expression evaluated to ${inner.actual}; it must evaluate to one async function`
1717
- });
1718
- const reason = thrown instanceof EvaluationThrew || inner instanceof Error ? "threw" : "rejected";
1719
- return CodeProgramFailedError.make({
1720
- implementation: inProcessCodeExecutorImplementation,
1721
- reason,
1722
- thrown: boundedThrown(inner),
1723
- message: boundedText(inner),
1724
- logs: [...capture.lines]
1725
- });
1726
- };
1727
- const executeInProcess = Effect.fn("InProcessCodeExecutor.execute")(function* (request) {
1728
- yield* validateRequest(request);
1729
- const host = yield* CodeExecutionHost;
1730
- const capture = {
1731
- lines: [],
1732
- bytes: 0
1733
- };
1734
- const counter = { calls: 0 };
1735
- const queue = yield* Queue.unbounded();
1736
- const factory = yield* Effect.try({
1737
- try: () => new Function(...shadowedGlobals, "console", ...request.namespaces.map((namespace) => namespace.name), `"use strict";\nreturn (\n${request.source}\n);`),
1738
- catch: (cause) => CodeSourceError.make({
1739
- implementation: inProcessCodeExecutorImplementation,
1740
- reason: "invalid",
1741
- message: boundedText(cause)
1742
- })
1743
- });
1744
- const harnessConsole = makeConsole(capture, request.limits);
1745
- let issuedHostCalls = 0;
1746
- const namespaceObjects = request.namespaces.map((namespace) => buildNamespaceObject(namespace, (pending) => {
1747
- issuedHostCalls += 1;
1748
- if (issuedHostCalls > request.limits.maxHostCalls + 1) {
1749
- pending.reject(/* @__PURE__ */ new Error(`host-call limit of ${request.limits.maxHostCalls} exceeded`));
1750
- return;
1751
- }
1752
- Queue.offerUnsafe(queue, pending);
1753
- }));
1754
- const server = yield* serveHostCalls(host, queue, request.limits, capture, counter).pipe(Effect.forkScoped);
1755
- const program = Effect.tryPromise({
1756
- try: async () => {
1757
- let candidate;
1758
- try {
1759
- candidate = factory(...shadowedGlobals.map(() => void 0), harnessConsole, ...namespaceObjects);
1760
- } catch (cause) {
1761
- throw new EvaluationThrew(cause);
1762
- }
1763
- if (typeof candidate !== "function") throw new EvaluationThrew(new NotAFunction(typeof candidate));
1764
- let outcome;
1765
- try {
1766
- outcome = candidate();
1767
- } catch (cause) {
1768
- throw new EvaluationThrew(cause);
1769
- }
1770
- return await Promise.resolve(outcome);
1771
- },
1772
- catch: (thrown) => classifyProgramFailure(thrown, request.limits, capture)
1773
- });
1774
- const startedAt = yield* Clock.currentTimeMillis;
1775
- const returned = yield* Effect.raceFirst(program, Fiber.join(server)).pipe(Effect.timeoutOrElse({
1776
- duration: request.limits.maxWallTime,
1777
- orElse: () => CodeExecutionTimeoutError.make({
1778
- implementation: inProcessCodeExecutorImplementation,
1779
- kind: "wall-clock",
1780
- maxWallTime: request.limits.maxWallTime,
1781
- logs: [...capture.lines]
1782
- })
1783
- }), Effect.ensuring(Fiber.interrupt(server)));
1784
- const finishedAt = yield* Clock.currentTimeMillis;
1785
- if (issuedHostCalls > request.limits.maxHostCalls) return yield* CodeHostCallLimitError.make({
1786
- implementation: inProcessCodeExecutorImplementation,
1787
- limit: request.limits.maxHostCalls,
1788
- logs: [...capture.lines]
1789
- });
1790
- const value = yield* Schema.decodeUnknownEffect(Schema.Json)(returned).pipe(Effect.mapError(() => CodeProgramFailedError.make({
1791
- implementation: inProcessCodeExecutorImplementation,
1792
- reason: "non-json-result",
1793
- thrown: null,
1794
- message: "The program must return a JSON value",
1795
- logs: [...capture.lines]
1796
- })));
1797
- const resultBytes = encodedJsonByteLength(value);
1798
- if (resultBytes === void 0 || resultBytes > request.limits.maxResultBytes) return yield* CodeOutputLimitError.make({
1799
- implementation: inProcessCodeExecutorImplementation,
1800
- surface: "result",
1801
- limit: request.limits.maxResultBytes,
1802
- observed: resultBytes ?? 0,
1803
- logs: [...capture.lines]
1804
- });
1805
- return CodeExecutionResult.make({
1806
- implementation: inProcessCodeExecutorImplementation,
1807
- value,
1808
- logs: [...capture.lines],
1809
- resourceUse: CodeExecutionResourceUse.make({
1810
- wallTime: Duration.millis(Math.max(0, finishedAt - startedAt)),
1811
- hostCalls: counter.calls,
1812
- logBytes: capture.bytes,
1813
- resultBytes
1814
- })
1815
- });
1816
- });
1817
- /**
1818
- * Layer providing the unisolated in-process `CodeExecutor` substitute. The
1819
- * per-pass `CodeExecutionHost` stays in the caller's requirement channel, the
1820
- * same as every real adapter.
1821
- */
1822
- const inProcessCodeExecutorLayer = Layer.succeed(CodeExecutor)(CodeExecutor.of({ execute: executeInProcess }));
1823
- //#endregion
1824
- //#region src/fixtures/docs-researcher/definition.ts
1825
- const ResearchDocumentId = Schema.NonEmptyString.check(Schema.isMaxLength(64)).pipe(Schema.brand("@effect-agent/testing/docs-researcher/ResearchDocumentId"));
1826
- const BoundedTitle = Schema.NonEmptyString.check(Schema.isMaxLength(120));
1827
- const BoundedBody = Schema.NonEmptyString.check(Schema.isMaxLength(16 * 1024));
1828
- /** Bounded summary text: the ONLY child-derived text that may cross to the parent. */
1829
- const BoundedSummary = Schema.NonEmptyString.check(Schema.isMaxLength(240));
1830
- var DocumentQuery = class extends Schema.Class("DocumentQuery")({ documentId: ResearchDocumentId }) {};
1831
- /** One bounded research document as the MCP content server exposes it. */
1832
- var ResearchDocument = class extends Schema.Class("ResearchDocument")({
1833
- documentId: ResearchDocumentId,
1834
- title: BoundedTitle,
1835
- body: BoundedBody
1836
- }) {};
1837
- var DocumentUnavailable = class extends Schema.TaggedError()("DocumentUnavailable", {
1838
- documentId: ResearchDocumentId,
1839
- message: Schema.String
1840
- }) {};
1841
- /** The content store behind the scripted MCP server. */
1842
- var DocumentLibrary = class extends Context.Service()("@effect-agent/testing/docs-researcher/DocumentLibrary") {};
1843
- /**
1844
- * The one content tool the doc-summarizer child uses. Its authored JSON
1845
- * schema is what MCP discovery must serve byte-for-byte: the scripted MCP
1846
- * fixture derives its discovery entry from `Tool.getJsonSchema(FetchDocument)`
1847
- * and `validateMcpDiscovery` re-derives and digests both sides (CAP-009).
1848
- */
1849
- const FetchDocument = Tool.make("fetch_document", {
1850
- description: "Fetch one bounded research document by its identifier.",
1851
- parameters: DocumentQuery,
1852
- success: ResearchDocument,
1853
- failure: DocumentUnavailable,
1854
- failureMode: "error",
1855
- dependencies: [DocumentLibrary]
1856
- });
1857
- const DocContentToolkit = Toolkit.make(FetchDocument);
1858
- const docContentToolkitLayer = DocContentToolkit.toLayer({ fetch_document: (query) => Effect.flatMap(DocumentLibrary, (library) => library.fetch(query)) });
1859
- /** Never allowed outside a child Conversation or an unredacted fixture value. */
1860
- const docsDocumentBodySecret = "docs-vault-secret-771";
1861
- const decodeDocumentId = Schema.decodeSync(ResearchDocumentId);
1862
- const corpusEntries = new Map([{
1863
- documentId: "durability-notes",
1864
- title: "Durability protocol notes",
1865
- bodyPhrase: "amber-ledger-passage",
1866
- summary: "Settlement results are recorded exactly once while external side effects stay at-least-once."
1867
- }, {
1868
- documentId: "subagent-notes",
1869
- title: "Subagent join notes",
1870
- bodyPhrase: "cobalt-join-corridor",
1871
- summary: "A parent joins only the verified settlement of its own established child."
1872
- }].map((entry) => [entry.documentId, {
1873
- document: ResearchDocument.make({
1874
- documentId: decodeDocumentId(entry.documentId),
1875
- title: entry.title,
1876
- body: `${entry.bodyPhrase}: internal working notes. ${docsDocumentBodySecret}. ${entry.summary} Raw notes stay inside the child Conversation.`
1877
- }),
1878
- bodyPhrase: entry.bodyPhrase,
1879
- summary: entry.summary
1880
- }]));
1881
- /** The corpus document ids in canonical fixture order. */
1882
- const researchCorpusDocumentIds = [decodeDocumentId("durability-notes"), decodeDocumentId("subagent-notes")];
1883
- const requireCorpusEntry = (documentId) => {
1884
- const entry = corpusEntries.get(documentId);
1885
- if (entry === void 0) throw new Error(`No deterministic corpus entry exists for document ${documentId}`);
1886
- return entry;
1887
- };
1888
- /** Deterministic library lookup shared by the scripted MCP content handlers. */
1889
- const researchDocumentLookup = (query) => {
1890
- const entry = corpusEntries.get(query.documentId);
1891
- return entry === void 0 ? Effect.fail(DocumentUnavailable.make({
1892
- documentId: query.documentId,
1893
- message: "No deterministic corpus entry exists for this document."
1894
- })) : Effect.succeed(entry.document);
1895
- };
1896
- /** The full fixture document (body includes the secret marker — child-side only). */
1897
- const researchDocumentFor = (documentId) => requireCorpusEntry(documentId).document;
1898
- /** The distinctive body phrase used by context-isolation assertions. */
1899
- const documentBodyPhrase = (documentId) => requireCorpusEntry(documentId).bodyPhrase;
1900
- var SummaryBrief = class extends Schema.Class("SummaryBrief")({
1901
- documentId: ResearchDocumentId,
1902
- focus: Schema.NonEmptyString
1903
- }) {};
1904
- var DocumentSummary = class extends Schema.Class("DocumentSummary")({
1905
- documentId: ResearchDocumentId,
1906
- summary: BoundedSummary
1907
- }) {};
1908
- /** The summary the scripted child writes after fetching the document. */
1909
- const documentSummaryFor = (documentId) => DocumentSummary.make({
1910
- documentId: requireCorpusEntry(documentId).document.documentId,
1911
- summary: requireCorpusEntry(documentId).summary
1912
- });
1913
- const encodedDocumentSummary = (documentId) => JSON.stringify(Schema.encodeSync(DocumentSummary)(documentSummaryFor(documentId)));
1914
- const DocSummarizer = Agent.define("doc-summarizer", {
1915
- input: SummaryBrief,
1916
- output: DocumentSummary,
1917
- instructions: "Fetch the briefed document with fetch_document exactly once, then return only a JSON document summary. Never copy raw notes or secrets into the summary.",
1918
- toolkit: DocContentToolkit,
1919
- policy: AgentPolicy.make({
1920
- maxTurns: 2,
1921
- maxToolCalls: 1,
1922
- maxDuration: "30 seconds",
1923
- toolConcurrency: 1
1924
- }),
1925
- description: "Summarize one bounded research document fetched through MCP content tools.",
1926
- metadata: {
1927
- deploymentClass: "DN",
1928
- phase: "P7"
1929
- }
1930
- });
1931
- var SummaryRequest = class extends Schema.Class("SummaryRequest")({ documentId: ResearchDocumentId }) {};
1932
- var SummaryFinding = class extends Schema.Class("SummaryFinding")({
1933
- documentId: ResearchDocumentId,
1934
- summary: BoundedSummary
1935
- }) {};
1936
- var DocumentSummaryFailed = class extends Schema.TaggedError()("DocumentSummaryFailed", { childErrorTag: Schema.NonEmptyString }) {};
1937
- /** Finite per-invocation bounds (SUB-009): one fetch per child, two children per Run. */
1938
- const documentSummaryPolicy = SubagentPolicy.make({
1939
- maxChildren: 2,
1940
- maxConcurrency: 2,
1941
- maxTurns: 2,
1942
- maxToolCalls: 1,
1943
- maxDuration: "10 seconds"
1944
- });
1945
- const delegateDocumentSummary = Subagent.define("delegate_document_summary", {
1946
- description: "Summarize one research document through the doc-summarizer child and return a bounded finding.",
1947
- target: DocSummarizer,
1948
- parameters: SummaryRequest,
1949
- success: SummaryFinding,
1950
- failure: DocumentSummaryFailed,
1951
- prepareInput: (request) => Effect.succeed(SummaryBrief.make({
1952
- documentId: request.documentId,
1953
- focus: "summarize:durability-claims"
1954
- })),
1955
- projectResult: (summary) => Effect.succeed(SummaryFinding.make({
1956
- documentId: summary.documentId,
1957
- summary: summary.summary
1958
- })),
1959
- policy: documentSummaryPolicy
1960
- });
1961
- /** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */
1962
- const mapSummaryChildFailure = (failure) => DocumentSummaryFailed.make({ childErrorTag: failure._tag });
1963
- /** The exact digest strings the durable declaration AND host registration must share (SUB-023). */
1964
- const docsSummarizerDigestStrings = {
1965
- agent: "50".repeat(32),
1966
- model: "51".repeat(32),
1967
- tools: "52".repeat(32)
1968
- };
1969
- /** Runtime wiring: the immutable delegation plus one explicit child Binding (S2 declaration). */
1970
- const docsSummaryHandlersLayer = (childBinding) => SubagentRuntime.layer(delegateDocumentSummary, childBinding, {
1971
- mapChildFailure: mapSummaryChildFailure,
1972
- durable: { targetDigests: docsSummarizerDigestStrings }
1973
- });
1974
- var ResearchRequest = class extends Schema.Class("ResearchRequest")({
1975
- question: Schema.NonEmptyString,
1976
- documentIds: Schema.Array(ResearchDocumentId).check(Schema.isMinLength(1))
1977
- }) {};
1978
- var ResearchDigest = class extends Schema.Class("ResearchDigest")({
1979
- findings: Schema.Array(SummaryFinding),
1980
- nextAction: Schema.Literal("review")
1981
- }) {};
1982
- /** Parent-only transcript markers proving child context isolation (SUB-006/SUB-015). */
1983
- const docsCoordinatorConfidentialMarker = "docs-coordinator-vault-19x";
1984
- const docsMissionConfidentialMarker = "docs-mission-dossier-42f";
1985
- const DocsResearcherToolkit = Toolkit.make(delegateDocumentSummary.tool);
1986
- const DocsResearcher = Agent.define("docs-researcher", {
1987
- input: ResearchRequest,
1988
- output: ResearchDigest,
1989
- instructions: [
1990
- "You are the Effect Agent P7 docs-researcher coordinator.",
1991
- `Coordinator-only context: ${docsCoordinatorConfidentialMarker}.`,
1992
- "Call delegate_document_summary once per requested document in one Tool batch.",
1993
- "Return only a JSON digest built from the delegated findings. This is read-only research."
1994
- ].join("\n"),
1995
- toolkit: DocsResearcherToolkit,
1996
- policy: AgentPolicy.make({
1997
- maxTurns: 2,
1998
- maxToolCalls: 2,
1999
- maxDuration: "30 seconds",
2000
- toolConcurrency: 2
2001
- }),
2002
- description: "Coordinate per-document summarization through one declared delegation Tool.",
2003
- metadata: {
2004
- deploymentClass: "DN",
2005
- phase: "P7"
2006
- }
2007
- });
2008
- /** The default two-document research mission. */
2009
- const researchMissionRequest = ResearchRequest.make({
2010
- question: `Summarize the durability and subagent notes; keep ${docsMissionConfidentialMarker} inside the coordinator conversation.`,
2011
- documentIds: researchCorpusDocumentIds
2012
- });
2013
- /** The coordinator's expected final digest for the given documents. */
2014
- const expectedResearchDigest = (documentIds = researchCorpusDocumentIds) => ResearchDigest.make({
2015
- findings: documentIds.map((documentId) => {
2016
- const summary = documentSummaryFor(documentId);
2017
- return SummaryFinding.make({
2018
- documentId: summary.documentId,
2019
- summary: summary.summary
2020
- });
2021
- }),
2022
- nextAction: "review"
2023
- });
2024
- //#endregion
2025
- //#region src/fixtures/travel-planner/definition.ts
2026
- const AirportCode = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/AirportCode"));
2027
- const QuoteId = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/QuoteId"));
2028
- var TripRequest = class extends Schema.Class("TripRequest")({
2029
- request: Schema.NonEmptyString,
2030
- origin: AirportCode,
2031
- destination: AirportCode,
2032
- departOn: Schema.String,
2033
- nights: Schema.Int.check(Schema.isGreaterThan(0)),
2034
- travelers: Schema.Int.check(Schema.isGreaterThan(0)),
2035
- budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),
2036
- currency: Schema.Literal("USD")
2037
- }) {};
2038
- var FlightQuery = class extends Schema.Class("FlightQuery")({
2039
- origin: AirportCode,
2040
- destination: AirportCode,
2041
- departOn: Schema.String,
2042
- travelers: Schema.Int.check(Schema.isGreaterThan(0))
2043
- }) {};
2044
- var LodgingQuery = class extends Schema.Class("LodgingQuery")({
2045
- destination: AirportCode,
2046
- departOn: Schema.String,
2047
- nights: Schema.Int.check(Schema.isGreaterThan(0)),
2048
- travelers: Schema.Int.check(Schema.isGreaterThan(0))
2049
- }) {};
2050
- var ActivityQuery = class extends Schema.Class("ActivityQuery")({
2051
- destination: AirportCode,
2052
- departOn: Schema.String,
2053
- nights: Schema.Int.check(Schema.isGreaterThan(0)),
2054
- travelers: Schema.Int.check(Schema.isGreaterThan(0))
2055
- }) {};
2056
- var FlightOption = class extends Schema.Class("FlightOption")({
2057
- quoteId: QuoteId,
2058
- flight: Schema.String,
2059
- estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
2060
- currency: Schema.Literal("USD")
2061
- }) {};
2062
- var LodgingOption = class extends Schema.Class("LodgingOption")({
2063
- lodging: Schema.String,
2064
- estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
2065
- currency: Schema.Literal("USD")
2066
- }) {};
2067
- /** A successful empty activity search is distinct from supplier unavailability. */
2068
- var ActivitySearchResult = class extends Schema.Class("ActivitySearchResult")({ activities: Schema.Array(Schema.String) }) {};
2069
- var Itinerary = class extends Schema.Class("Itinerary")({
2070
- title: Schema.String,
2071
- route: Schema.String,
2072
- dates: Schema.String,
2073
- flight: Schema.String,
2074
- lodging: Schema.String,
2075
- activities: Schema.Array(Schema.String),
2076
- estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),
2077
- currency: Schema.Literal("USD"),
2078
- quoteId: QuoteId,
2079
- assumptions: Schema.Array(Schema.String),
2080
- unresolvedConstraints: Schema.Array(Schema.String),
2081
- nextAction: Schema.Literal("review")
2082
- }) {};
2083
- var TravelPlan = class extends Schema.Class("TravelPlan")({ itineraries: Schema.Array(Itinerary) }) {};
2084
- const unavailableFields = {
2085
- query: Schema.String,
2086
- message: Schema.String
2087
- };
2088
- var FlightUnavailable = class extends Schema.TaggedError()("FlightUnavailable", unavailableFields) {};
2089
- var LodgingUnavailable = class extends Schema.TaggedError()("LodgingUnavailable", unavailableFields) {};
2090
- var ActivityUnavailable = class extends Schema.TaggedError()("ActivityUnavailable", unavailableFields) {};
2091
- var GuidanceFailure = class extends Schema.TaggedError()("GuidanceFailure", { message: Schema.String }) {};
2092
- var FlightCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/FlightCatalog") {};
2093
- var LodgingCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/LodgingCatalog") {};
2094
- var ActivityCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/ActivityCatalog") {};
2095
- var TravelGuidance = class extends Context.Service()("@effect-agent/testing/travel-planner/TravelGuidance") {};
2096
- const SearchFlights = Tool.make("search_flights", {
2097
- parameters: FlightQuery,
2098
- success: FlightOption,
2099
- failure: FlightUnavailable,
2100
- failureMode: "error",
2101
- dependencies: [FlightCatalog]
2102
- });
2103
- const SearchLodging = Tool.make("search_lodging", {
2104
- parameters: LodgingQuery,
2105
- success: LodgingOption,
2106
- failure: LodgingUnavailable,
2107
- failureMode: "error",
2108
- dependencies: [LodgingCatalog]
2109
- });
2110
- const SearchActivities = Tool.make("search_activities", {
2111
- parameters: ActivityQuery,
2112
- success: ActivitySearchResult,
2113
- failure: ActivityUnavailable,
2114
- failureMode: "error",
2115
- dependencies: [ActivityCatalog]
2116
- });
2117
- const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);
2118
- const TravelPlannerToolkitLayer = TravelPlannerToolkit.toLayer({
2119
- search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),
2120
- search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),
2121
- search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query))
2122
- });
2123
- const TravelPlanner = Agent.define("travel-planner", {
2124
- input: TripRequest,
2125
- output: TravelPlan,
2126
- instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
2127
- toolkit: TravelPlannerToolkit,
2128
- policy: AgentPolicy.make({
2129
- maxTurns: 2,
2130
- maxToolCalls: 3,
2131
- maxDuration: "30 seconds",
2132
- toolConcurrency: 3
2133
- }),
2134
- description: "Build one review-only itinerary from bounded parallel deterministic searches.",
2135
- metadata: {
2136
- deploymentClass: "E",
2137
- phase: "P1"
2138
- }
2139
- });
2140
- //#endregion
2141
- //#region src/fixtures/travel-planner/deterministic-layers.ts
2142
- var CatalogLifecycleCounts = class extends Schema.Class("CatalogLifecycleCounts")({
2143
- acquired: Schema.Natural,
2144
- finalized: Schema.Natural
2145
- }) {};
2146
- var CatalogLifecycle = class CatalogLifecycle extends Context.Service()("@effect-agent/testing/travel-planner/CatalogLifecycle") {
2147
- static layerNoDeps = Layer.effect(this, Effect.gen(function* () {
2148
- const acquired = yield* Ref.make(0);
2149
- const finalized = yield* Ref.make(0);
2150
- return CatalogLifecycle.of({
2151
- markAcquired: Ref.update(acquired, (n) => n + 1),
2152
- markFinalized: Ref.update(finalized, (n) => n + 1),
2153
- counts: Effect.all({
2154
- acquired: Ref.get(acquired),
2155
- finalized: Ref.get(finalized)
2156
- }).pipe(Effect.map((counts) => CatalogLifecycleCounts.make(counts)))
2157
- });
2158
- }));
2159
- };
2160
- const flight = FlightOption.make({
2161
- quoteId: Schema.decodeSync(QuoteId)("quote-sfo-lhr-001"),
2162
- flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
2163
- estimatedCents: 18e4,
2164
- currency: "USD"
2165
- });
2166
- const lodging = LodgingOption.make({
2167
- lodging: "Bloomsbury House · refundable studio · 4 nights",
2168
- estimatedCents: 104e3,
2169
- currency: "USD"
2170
- });
2171
- const activities = ActivitySearchResult.make({ activities: ["British Museum timed entry", "Thames evening walk"] });
2172
- const ReverseCompletionToolkitLayer = Effect.gen(function* () {
2173
- const flightStarted = yield* Deferred.make();
2174
- const lodgingStarted = yield* Deferred.make();
2175
- const activityStarted = yield* Deferred.make();
2176
- const releaseFlight = yield* Deferred.make();
2177
- const releaseLodging = yield* Deferred.make();
2178
- const releaseActivity = yield* Deferred.make();
2179
- const awaitRelease = (started, release, value) => Deferred.succeed(started, void 0).pipe(Effect.andThen(Deferred.await(release)), Effect.as(value));
2180
- return {
2181
- controls: {
2182
- flightStarted: Deferred.await(flightStarted),
2183
- lodgingStarted: Deferred.await(lodgingStarted),
2184
- activityStarted: Deferred.await(activityStarted),
2185
- releaseFlight: Deferred.succeed(releaseFlight, void 0).pipe(Effect.asVoid),
2186
- releaseLodging: Deferred.succeed(releaseLodging, void 0).pipe(Effect.asVoid),
2187
- releaseActivity: Deferred.succeed(releaseActivity, void 0).pipe(Effect.asVoid)
2188
- },
2189
- layer: TravelPlannerToolkit.toLayer({
2190
- search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),
2191
- search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),
2192
- search_activities: () => awaitRelease(activityStarted, releaseActivity, activities)
2193
- })
2194
- };
2195
- });
2196
- const FlightCatalogLayer = Layer.effect(FlightCatalog, Effect.gen(function* () {
2197
- const lifecycle = yield* CatalogLifecycle;
2198
- yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
2199
- return FlightCatalog.of({ search: (query) => query.origin === query.destination ? Effect.fail(FlightUnavailable.make({
2200
- query: `${query.origin}-${query.destination}`,
2201
- message: "Origin and destination must differ."
2202
- })) : Effect.succeed(flight) });
2203
- }));
2204
- const LodgingCatalogLayer = Layer.effect(LodgingCatalog, Effect.gen(function* () {
2205
- const lifecycle = yield* CatalogLifecycle;
2206
- yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
2207
- return LodgingCatalog.of({ search: (query) => query.nights < 1 ? Effect.fail(LodgingUnavailable.make({
2208
- query: query.destination,
2209
- message: "At least one night is required."
2210
- })) : Effect.succeed(lodging) });
2211
- }));
2212
- const ActivityCatalogLayer = Layer.effect(ActivityCatalog, Effect.gen(function* () {
2213
- const lifecycle = yield* CatalogLifecycle;
2214
- yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
2215
- return ActivityCatalog.of({ search: (query) => query.destination === "" ? Effect.fail(ActivityUnavailable.make({
2216
- query: query.destination,
2217
- message: "Destination is required."
2218
- })) : Effect.succeed(activities) });
2219
- }));
2220
- /** Stable supplier-side booking identity, minted deterministically from the idempotency key. */
2221
- const BookingRef = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/BookingRef"));
2222
- /** The supplier desk operations the P5 booking Tools and Steps invoke. */
2223
- const SupplierOperation = Schema.Literals([
2224
- "book-flight",
2225
- "cancel-booking",
2226
- "reserve-flight",
2227
- "reserve-lodging",
2228
- "issue-confirmation"
2229
- ]);
2230
- /**
2231
- * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a
2232
- * call with the same key returns this exact record without creating a second booking — which is
2233
- * precisely the honesty model of DUR-010: the framework never makes an external call
2234
- * exactly-once; the supplier's idempotency key does.
2235
- */
2236
- var SupplierBookingRecord = class extends Schema.Class("@effect-agent/testing/travel-planner/SupplierBookingRecord")({
2237
- bookingRef: BookingRef,
2238
- idempotencyKey: Schema.NonEmptyString,
2239
- operation: SupplierOperation,
2240
- detail: Schema.NonEmptyString,
2241
- status: Schema.Literals(["confirmed", "cancelled"])
2242
- }) {};
2243
- var SupplierUnavailable = class extends Schema.TaggedError()("SupplierUnavailable", { message: Schema.String }) {};
2244
- /** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */
2245
- const cancelBookingIdempotencyKey = (bookingRef) => `cancel-booking:${bookingRef}`;
2246
- /** The deterministic bookingRef the desk mints for one idempotency key. */
2247
- const supplierBookingRefFor = (idempotencyKey) => Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);
2248
- /**
2249
- * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call
2250
- * counters and injectable crash windows.
2251
- *
2252
- * - `book`/`cancel` always count the call (at-least-once execution stays observable), then
2253
- * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and
2254
- * Steps rely on.
2255
- * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its
2256
- * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point
2257
- * models "the external effect happened but no outcome was recorded" without any wall clock.
2258
- * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate
2259
- * assertions.
2260
- */
2261
- var SupplierBookingDesk = class SupplierBookingDesk extends Context.Service()("@effect-agent/testing/travel-planner/SupplierBookingDesk") {
2262
- static layer = Layer.effect(this, Effect.gen(function* () {
2263
- const state = yield* Ref.make({
2264
- bookings: /* @__PURE__ */ new Map(),
2265
- counts: /* @__PURE__ */ new Map(),
2266
- holds: /* @__PURE__ */ new Map()
2267
- });
2268
- const enterHold = (hold) => Option.isSome(hold) ? Deferred.succeed(hold.value.held, void 0).pipe(Effect.andThen(Deferred.await(hold.value.release))) : Effect.void;
2269
- const book = (request) => Ref.modify(state, (current) => {
2270
- const counts = new Map(current.counts).set(request.idempotencyKey, (current.counts.get(request.idempotencyKey) ?? 0) + 1);
2271
- const existing = current.bookings.get(request.idempotencyKey);
2272
- const record = existing ?? SupplierBookingRecord.make({
2273
- bookingRef: supplierBookingRefFor(request.idempotencyKey),
2274
- idempotencyKey: request.idempotencyKey,
2275
- operation: request.operation,
2276
- detail: request.detail,
2277
- status: "confirmed"
2278
- });
2279
- const bookings = existing === void 0 ? new Map(current.bookings).set(request.idempotencyKey, record) : current.bookings;
2280
- const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));
2281
- const holds = Option.isSome(hold) ? (() => {
2282
- const next = new Map(current.holds);
2283
- next.delete(request.idempotencyKey);
2284
- return next;
2285
- })() : current.holds;
2286
- return [{
2287
- record,
2288
- hold
2289
- }, {
2290
- bookings,
2291
- counts,
2292
- holds
2293
- }];
2294
- }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));
2295
- const cancel = (bookingRef) => Ref.modify(state, (current) => {
2296
- const key = cancelBookingIdempotencyKey(bookingRef);
2297
- const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);
2298
- const existingEntry = [...current.bookings.entries()].find(([, record]) => record.bookingRef === bookingRef);
2299
- if (existingEntry === void 0) return [{
2300
- record: Option.none(),
2301
- hold: Option.none()
2302
- }, {
2303
- ...current,
2304
- counts
2305
- }];
2306
- const [storeKey, existing] = existingEntry;
2307
- const cancelled = existing.status === "cancelled" ? existing : SupplierBookingRecord.make({
2308
- ...existing,
2309
- status: "cancelled"
2310
- });
2311
- const bookings = new Map(current.bookings).set(storeKey, cancelled);
2312
- const hold = Option.fromNullishOr(current.holds.get(key));
2313
- const holds = Option.isSome(hold) ? (() => {
2314
- const next = new Map(current.holds);
2315
- next.delete(key);
2316
- return next;
2317
- })() : current.holds;
2318
- return [{
2319
- record: Option.some(cancelled),
2320
- hold
2321
- }, {
2322
- bookings,
2323
- counts,
2324
- holds
2325
- }];
2326
- }).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))));
2327
- return SupplierBookingDesk.of({
2328
- book,
2329
- cancel,
2330
- lookup: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey)))),
2331
- bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),
2332
- callCount: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),
2333
- holdAfterWrite: (idempotencyKey) => Effect.gen(function* () {
2334
- const held = yield* Deferred.make();
2335
- const release = yield* Deferred.make();
2336
- yield* Ref.update(state, (current) => ({
2337
- ...current,
2338
- holds: new Map(current.holds).set(idempotencyKey, {
2339
- held,
2340
- release
2341
- })
2342
- }));
2343
- return {
2344
- held: Deferred.await(held),
2345
- release: Deferred.succeed(release, void 0).pipe(Effect.asVoid)
2346
- };
2347
- })
2348
- });
2349
- }));
2350
- };
2351
- const TravelGuidanceLayer = Layer.succeed(TravelGuidance, TravelGuidance.of({ instructions: (input) => Effect.succeed([
2352
- "You are the Effect Agent Travel Planner P1 interpreter fixture.",
2353
- `The user asked: ${input.request}`,
2354
- "Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.",
2355
- "Then return only a JSON object of exactly this shape, no prose:",
2356
- "{\"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\"}]}",
2357
- "Use the Tool results verbatim; activity results may legitimately be an empty array.",
2358
- "This is read-only planning. Require review before any mutation."
2359
- ].join("\n")) }));
2360
- const DeterministicIdGeneratorLayer = Layer.effect(IdGenerator, Effect.gen(function* () {
2361
- const conversation = yield* Ref.make(0);
2362
- const run = yield* Ref.make(0);
2363
- const turn = yield* Ref.make(0);
2364
- return IdGenerator.of({
2365
- nextConversationId: Ref.updateAndGet(conversation, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(ConversationId)(`conversation-${n}`))),
2366
- nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`))),
2367
- nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)))
2368
- });
2369
- }));
2370
- const TravelPlannerRuntimeLayer = Layer.mergeAll(TravelPlannerToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer, TravelGuidanceLayer, DeterministicIdGeneratorLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
2371
- //#endregion
2372
- //#region src/fixtures/docs-researcher/mcp.ts
2373
- /** Framework-side hard bounds one docs-researcher assembly requests. */
2374
- const docsMcpRequest = McpConnectionRequest.make({
2375
- serverId: "docs-content-mcp",
2376
- maxToolCount: 4,
2377
- maxToolDescriptionBytes: 256,
2378
- maxDiscoveryBytes: 16384,
2379
- connectTimeoutMillis: 1e3
2380
- });
2381
- const docsMcpIdentity = McpServerIdentity.make({
2382
- serverId: docsMcpRequest.serverId,
2383
- implementation: McpSchema.Implementation.make({
2384
- name: "docs-researcher-content-fixture",
2385
- version: "1.0.0"
2386
- })
2387
- });
2388
- const discoveredFetchDocument = McpSchema.Tool.make({
2389
- name: FetchDocument.name,
2390
- description: "Fetch one bounded research document by its identifier.",
2391
- inputSchema: Tool.getJsonSchema(FetchDocument)
2392
- });
2393
- const scriptedConnector = (tools) => Layer.succeed(McpConnector)({ connect: () => Effect.acquireRelease(Effect.succeed({
2394
- identity: docsMcpIdentity,
2395
- capabilities: McpSchema.ServerCapabilities.make({}),
2396
- tools,
2397
- toolkit: DocContentToolkit
2398
- }), () => Effect.void) });
2399
- /** The well-behaved scripted content server. */
2400
- const docsMcpConnectorLayer = scriptedConnector([discoveredFetchDocument]);
2401
- /** Serves a tool description exceeding `maxToolDescriptionBytes` (SEC-013 bound). */
2402
- const docsMcpOversizedConnectorLayer = scriptedConnector([McpSchema.Tool.make({
2403
- name: discoveredFetchDocument.name,
2404
- description: "x".repeat(1024),
2405
- inputSchema: discoveredFetchDocument.inputSchema
2406
- })]);
2407
- /** Serves a discovery schema that disagrees with the authored toolkit (drift fails closed). */
2408
- const docsMcpMismatchedConnectorLayer = scriptedConnector([McpSchema.Tool.make({
2409
- name: discoveredFetchDocument.name,
2410
- description: discoveredFetchDocument.description,
2411
- inputSchema: {
2412
- type: "object",
2413
- properties: { url: { type: "string" } }
2414
- }
2415
- })]);
2416
- const isJsonEqual = (left, right) => JSON.stringify(left) === JSON.stringify(right);
2417
- /**
2418
- * Bind DISCOVERY to AUTHORING: `validateMcpDiscovery` (inside `connectMcp`)
2419
- * already proved the served discovery matches the connection's own Toolkit;
2420
- * this check additionally proves that Toolkit is the exact toolkit the
2421
- * doc-summarizer was AUTHORED against — same tool names, same derived JSON
2422
- * schemas — so a connector cannot substitute a look-alike toolkit. The
2423
- * docs-researcher harness runs it before any worker Binding registration and
2424
- * fails closed on any drift.
2425
- */
2426
- const assertDiscoveryMatchesAuthoredToolkit = Effect.fn("DocsResearcher.assertDiscoveryMatchesAuthoredToolkit")(function* (connection) {
2427
- const authored = Object.values(DocContentToolkit.tools).map((tool) => ({
2428
- name: tool.name,
2429
- inputSchema: Tool.getJsonSchema(tool)
2430
- })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
2431
- const discovered = Object.values(connection.toolkit.tools).map((tool) => ({
2432
- name: tool.name,
2433
- inputSchema: Tool.getJsonSchema(tool)
2434
- })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
2435
- if (!(authored.length === discovered.length && authored.every((tool, index) => tool.name === discovered[index]?.name && isJsonEqual(tool.inputSchema, discovered[index]?.inputSchema)))) return yield* McpToolkitMismatch.make({
2436
- serverId: connection.discovery.identity.serverId,
2437
- message: "The MCP-discovered toolkit does not match the doc-summarizer's authored content toolkit"
2438
- });
2439
- });
2440
- /** Round-trip guard for encoded discovery values persisted as fixture evidence. */
2441
- const DocsMcpDiscoveryEvidence = Schema.Struct({
2442
- serverId: Schema.NonEmptyString,
2443
- toolCount: Schema.Natural,
2444
- encodedBytes: Schema.Natural,
2445
- toolkitSchemaDigest: Schema.String
2446
- });
2447
- //#endregion
2448
- //#region src/fixtures/docs-researcher/harness.ts
2449
- const docsResearcherDeploymentId = Schema.decodeSync(DeploymentId)("docs-researcher-p7-deployment");
2450
- const docsResearcherProducerId = Schema.decodeSync(ProducerId)("docs-researcher-p7-producer");
2451
- const docsResearcherPrincipal = Schema.decodeSync(Principal)("docs-researcher-p7-principal");
2452
- const digestOf$2 = (pair) => Schema.decodeSync(Digest)(pair.repeat(32));
2453
- /** Redacted, deterministic coordinator definition digests for this fixture version. */
2454
- const docsCoordinatorDigests = DefinitionDigests.make({
2455
- agent: digestOf$2("40"),
2456
- model: digestOf$2("41"),
2457
- tools: digestOf$2("42")
2458
- });
2459
- /** The child registration digests — byte-equal to `docsSummarizerDigestStrings` (SUB-023). */
2460
- const docsSummarizerDigests = DefinitionDigests.make({
2461
- agent: digestOf$2("50"),
2462
- model: digestOf$2("51"),
2463
- tools: digestOf$2("52")
2464
- });
2465
- /** Durable admission options for one docs-researcher Submission on one mission lane. */
2466
- const docsResearcherSubmitOptions = (conversationId, idempotencyKey) => ({
2467
- conversationId,
2468
- principal: docsResearcherPrincipal,
2469
- idempotencyKey,
2470
- definitions: docsCoordinatorDigests
2471
- });
2472
- /** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */
2473
- const docsResearcherSubmitAgent = { definition: {
2474
- id: DocsResearcher.id,
2475
- input: DocsResearcher.input
2476
- } };
2477
- /** The deterministic delegation Tool Call identity for one document. */
2478
- const summarizeCallId = (documentId) => `summarize-${documentId}`;
2479
- /** The child's own scripted fetch Tool Call identity for one document. */
2480
- const fetchCallId = (documentId) => `fetch-${documentId}`;
2481
- const scriptedUsage$3 = {
2482
- inputTokens: { total: 96 },
2483
- outputTokens: { total: 64 }
2484
- };
2485
- const summaryDelegationParts = (documentIds) => [...documentIds.map((documentId) => ({
2486
- type: "tool-call",
2487
- id: summarizeCallId(documentId),
2488
- name: "delegate_document_summary",
2489
- params: { documentId },
2490
- providerExecuted: false
2491
- })), {
2492
- type: "finish",
2493
- reason: "tool-calls",
2494
- usage: scriptedUsage$3
2495
- }];
2496
- const digestParts = (documentIds) => [
2497
- {
2498
- type: "text-start",
2499
- id: "digest"
2500
- },
2501
- {
2502
- type: "text-delta",
2503
- id: "digest",
2504
- delta: JSON.stringify(Schema.encodeSync(ResearchDigest)(expectedResearchDigest(documentIds)))
2505
- },
2506
- {
2507
- type: "text-end",
2508
- id: "digest"
2509
- },
2510
- {
2511
- type: "finish",
2512
- reason: "stop",
2513
- usage: scriptedUsage$3
2514
- }
2515
- ];
2516
- const fetchParts = (documentId) => [{
2517
- type: "tool-call",
2518
- id: fetchCallId(documentId),
2519
- name: "fetch_document",
2520
- params: { documentId },
2521
- providerExecuted: false
2522
- }, {
2523
- type: "finish",
2524
- reason: "tool-calls",
2525
- usage: scriptedUsage$3
2526
- }];
2527
- const summaryParts = (documentId) => [
2528
- {
2529
- type: "text-start",
2530
- id: "document-summary"
2531
- },
2532
- {
2533
- type: "text-delta",
2534
- id: "document-summary",
2535
- delta: encodedDocumentSummary(documentId)
2536
- },
2537
- {
2538
- type: "text-end",
2539
- id: "document-summary"
2540
- },
2541
- {
2542
- type: "finish",
2543
- reason: "stop",
2544
- usage: scriptedUsage$3
2545
- }
2546
- ];
2547
- /**
2548
- * One prompt-aware scripted model with externally observable counters. A DN
2549
- * Attempt may resume on a fresh Layer build, so responses derive from the
2550
- * committed history in the prompt — never from an in-Layer turn counter.
2551
- */
2552
- const makeCountingModel = (name, decide) => Effect.gen(function* () {
2553
- const calls = yield* Ref.make(0);
2554
- const prompts = yield* Ref.make([]);
2555
- return {
2556
- model: Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
2557
- generateText: () => Effect.succeed([]),
2558
- streamText: (request) => Stream.unwrap(Effect.gen(function* () {
2559
- yield* Ref.update(calls, (value) => value + 1);
2560
- const promptJson = JSON.stringify(request.prompt);
2561
- yield* Ref.update(prompts, (previous) => [...previous, promptJson]);
2562
- return Stream.fromIterable(yield* decide(promptJson));
2563
- }))
2564
- }))),
2565
- calls: Ref.get(calls),
2566
- prompts: Ref.get(prompts)
2567
- };
2568
- });
2569
- /**
2570
- * Build the docs-researcher harness. Order matters and is the point: the
2571
- * child's content toolkit is only registered as a worker Binding AFTER the
2572
- * MCP connector's bounded discovery validated the authored toolkit
2573
- * byte-for-byte (`connectMcp` + `assertDiscoveryMatchesAuthoredToolkit`), so
2574
- * "the tools the summarizer runs are the tools discovery served" is enforced
2575
- * at assembly, not assumed. Content-tool execution then flows through the
2576
- * counting `DocumentLibrary` — the scripted MCP server's content store.
2577
- */
2578
- const makeDocsResearcherHarness = (options) => Effect.gen(function* () {
2579
- const documentIds = options?.documentIds ?? researchCorpusDocumentIds;
2580
- const discovery = yield* Effect.scoped(Effect.gen(function* () {
2581
- const connection = yield* connectMcp(docsMcpRequest);
2582
- yield* assertDiscoveryMatchesAuthoredToolkit(connection);
2583
- return connection.discovery;
2584
- })).pipe(Effect.provide(docsMcpConnectorLayer));
2585
- const fetchCounts = yield* Ref.make(/* @__PURE__ */ new Map());
2586
- const libraryLayer = Layer.succeed(DocumentLibrary, DocumentLibrary.of({ fetch: (query) => Ref.update(fetchCounts, (current) => new Map(current).set(query.documentId, (current.get(query.documentId) ?? 0) + 1)).pipe(Effect.andThen(researchDocumentLookup(query))) }));
2587
- const childToolkitLayer = docContentToolkitLayer.pipe(Layer.provideMerge(libraryLayer));
2588
- const childModel = yield* makeCountingModel("doc-summarizer-p7", (promptJson) => Effect.suspend(() => {
2589
- const documentId = documentIds.find((candidate) => promptJson.includes(candidate));
2590
- if (documentId === void 0) return Effect.die(/* @__PURE__ */ new Error("The summarizer prompt names no corpus document"));
2591
- return Effect.succeed(promptJson.includes(fetchCallId(documentId)) ? summaryParts(documentId) : fetchParts(documentId));
2592
- }));
2593
- const childBinding = Agent.withModel(DocSummarizer, childModel.model);
2594
- const firstCallId = summarizeCallId(documentIds[0] ?? "durability-notes");
2595
- const parentModel = yield* makeCountingModel("docs-researcher-p7", (promptJson) => Effect.succeed(promptJson.includes(firstCallId) ? digestParts(documentIds) : summaryDelegationParts(documentIds)));
2596
- const parentBinding = Agent.withModel(DocsResearcher, parentModel.model);
2597
- const delegationLayer = docsSummaryHandlersLayer(childBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer)));
2598
- return {
2599
- bindings: [yield* DurableWorkerBinding.make(parentBinding, docsCoordinatorDigests).pipe(Effect.provide(delegationLayer)), yield* DurableWorkerBinding.make(childBinding, docsSummarizerDigests).pipe(Effect.provide(childToolkitLayer))],
2600
- discovery,
2601
- parentModelCalls: parentModel.calls,
2602
- parentPrompts: parentModel.prompts,
2603
- childModelCalls: childModel.calls,
2604
- childPrompts: childModel.prompts,
2605
- fetchInvocations: (documentId) => Ref.get(fetchCounts).pipe(Effect.map((current) => current.get(documentId) ?? 0))
2606
- };
2607
- });
2608
- const encodeResearchDocument = Schema.encodeEffect(ResearchDocument);
2609
- /**
2610
- * The audit-surface preview of one fetched document: the raw document —
2611
- * secret marker and all — passes through the configured structural `Redactor`
2612
- * before anything may quote it outside the child Conversation (SEC-008,
2613
- * CAP-013). Tests assert the preview keeps shape but no scalar content.
2614
- */
2615
- const redactedDocumentPreview = Effect.fn("DocsResearcher.redactedDocumentPreview")(function* (documentId) {
2616
- const redactor = yield* Redactor;
2617
- const encoded = yield* encodeResearchDocument(researchDocumentFor(documentId)).pipe(Effect.orDie);
2618
- return yield* redactor.redact(encoded);
2619
- });
2620
- //#endregion
2621
- //#region src/fixtures/travel-planner/phase2.ts
2622
- var ItineraryHoldRequest = class extends Schema.Class("@effect-agent/testing/travel-planner/ItineraryHoldRequest")({
2623
- quoteId: QuoteId,
2624
- expiresInMinutes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(60))
2625
- }) {};
2626
- var ItineraryHold = class extends Schema.Class("@effect-agent/testing/travel-planner/ItineraryHold")({
2627
- holdId: Schema.NonEmptyString,
2628
- quoteId: QuoteId,
2629
- status: Schema.Literal("held")
2630
- }) {};
2631
- var ItineraryHoldUnavailable = class extends Schema.TaggedError()("ItineraryHoldUnavailable", {
2632
- quoteId: QuoteId,
2633
- message: Schema.String
2634
- }) {};
2635
- var ItineraryHoldGateway = class extends Context.Service()("@effect-agent/testing/travel-planner/ItineraryHoldGateway") {};
2636
- /**
2637
- * The first mutating Travel Planner Tool. Effect AI marks it as approval-gated
2638
- * so the engine must settle approval before acquiring a handler permit.
2639
- */
2640
- const HoldItinerary = Tool.make("hold_itinerary", {
2641
- parameters: ItineraryHoldRequest,
2642
- success: ItineraryHold,
2643
- failure: ItineraryHoldUnavailable,
2644
- failureMode: "error",
2645
- dependencies: [ItineraryHoldGateway],
2646
- needsApproval: true
2647
- });
2648
- const TravelPlannerPhase2Toolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities, HoldItinerary);
2649
- const TravelPlannerPhase2ToolkitLayer = TravelPlannerPhase2Toolkit.toLayer({
2650
- search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),
2651
- search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),
2652
- search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),
2653
- hold_itinerary: (request) => Effect.flatMap(ItineraryHoldGateway, (gateway) => gateway.hold(request))
2654
- });
2655
- const TravelPlannerPhase2 = Agent.define("travel-planner-phase-2", {
2656
- input: TripRequest,
2657
- output: TravelPlan,
2658
- instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
2659
- toolkit: TravelPlannerPhase2Toolkit,
2660
- policy: AgentPolicy.make({
2661
- maxTurns: 3,
2662
- maxToolCalls: 4,
2663
- maxDuration: "30 seconds",
2664
- toolConcurrency: 3,
2665
- tokenBudget: 2048
2666
- }),
2667
- description: "Build a review-only itinerary and require approval before creating a temporary hold.",
2668
- metadata: {
2669
- deploymentClass: "E",
2670
- phase: "P2"
2671
- }
2672
- });
2673
- //#endregion
2674
- //#region src/fixtures/travel-planner/scenarios.ts
2675
- const usage = {
2676
- inputTokens: { total: 128 },
2677
- outputTokens: { total: 96 }
2678
- };
2679
- const phase1Trip = Schema.decodeSync(TripRequest)({
2680
- request: "Plan a review-only London trip using the deterministic flight, lodging, and activity searches.",
2681
- origin: "SFO",
2682
- destination: "LHR",
2683
- departOn: "2026-09-14",
2684
- nights: 4,
2685
- travelers: 2,
2686
- budgetCents: 35e4,
2687
- currency: "USD"
2688
- });
2689
- /** Backward-compatible fixture alias while consumers transition to the P1 name. */
2690
- const phase0Trip = phase1Trip;
2691
- const expectedTravelPlan = Schema.decodeSync(TravelPlan)({ itineraries: [{
2692
- title: "Westward light, eastbound overnight",
2693
- route: "San Francisco → London",
2694
- dates: "14–19 September 2026",
2695
- flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
2696
- lodging: "Bloomsbury House · refundable studio · 4 nights",
2697
- activities: ["British Museum timed entry", "Thames evening walk"],
2698
- estimatedTotalCents: 284e3,
2699
- currency: "USD",
2700
- quoteId: "quote-sfo-lhr-001",
2701
- assumptions: ["Two travelers sharing one studio", "Quote is read-only availability, not a reservation"],
2702
- unresolvedConstraints: ["Traveler names and accessibility requests are intentionally omitted"],
2703
- nextAction: "review"
2704
- }] });
2705
- const phase1HappyPathTurns = [{
2706
- _tag: "Stream",
2707
- parts: [
2708
- {
2709
- type: "tool-call",
2710
- id: "flight-call-1",
2711
- name: "search_flights",
2712
- params: {
2713
- origin: "SFO",
2714
- destination: "LHR",
2715
- departOn: "2026-09-14",
2716
- travelers: 2
2717
- }
2718
- },
2719
- {
2720
- type: "tool-call",
2721
- id: "lodging-call-1",
2722
- name: "search_lodging",
2723
- params: {
2724
- destination: "LHR",
2725
- departOn: "2026-09-14",
2726
- nights: 4,
2727
- travelers: 2
2728
- }
2729
- },
2730
- {
2731
- type: "tool-call",
2732
- id: "activity-call-1",
2733
- name: "search_activities",
2734
- params: {
2735
- destination: "LHR",
2736
- departOn: "2026-09-14",
2737
- nights: 4,
2738
- travelers: 2
2739
- }
2740
- },
2741
- {
2742
- type: "finish",
2743
- reason: "tool-calls",
2744
- usage
2745
- }
2746
- ],
2747
- termination: { _tag: "Complete" }
2748
- }, {
2749
- _tag: "Stream",
2750
- parts: [
2751
- {
2752
- type: "text-start",
2753
- id: "itinerary-json"
2754
- },
2755
- {
2756
- type: "text-delta",
2757
- id: "itinerary-json",
2758
- delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan))
2759
- },
2760
- {
2761
- type: "text-end",
2762
- id: "itinerary-json"
2763
- },
2764
- {
2765
- type: "finish",
2766
- reason: "stop",
2767
- usage
2768
- }
2769
- ],
2770
- termination: { _tag: "Complete" }
2771
- }];
2772
- const phase0HappyPathTurns = phase1HappyPathTurns;
2773
- //#endregion
2774
- //#region src/fixtures/travel-planner/phase3.ts
2775
- /**
2776
- * The Phase 3 profile persists Conversation history but deliberately does not
2777
- * claim durable admission or recovery of accepted work.
2778
- */
2779
- var TravelPlannerPersistenceProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerPersistenceProfile")({
2780
- deploymentClass: Schema.Literal("P"),
2781
- durableAcceptedWork: Schema.Literal(false),
2782
- canonicalSchemaVersion: Schema.Literal(1)
2783
- }) {};
2784
- const phase3TravelPlannerProfile = TravelPlannerPersistenceProfile.make({
2785
- deploymentClass: "P",
2786
- durableAcceptedWork: false,
2787
- canonicalSchemaVersion: 1
2788
- });
2789
- const phase3TravelPlannerConversationId = Schema.decodeSync(ConversationId)("travel-planner-p3-conversation");
2790
- const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p3-producer");
2791
- const phase3TravelPlannerRunId = Schema.decodeSync(RunId)("travel-planner-p3-run");
2792
- const deploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p3-scripted");
2793
- const agentId = Schema.decodeSync(AgentId)("travel-planner");
2794
- const submissionId = Schema.decodeSync(SubmissionId)("travel-planner-p3-submission");
2795
- const digest$2 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
2796
- /** Redacted, deterministic definition identities for the current fixture version. */
2797
- const phase3TravelPlannerDefinitionDigests = DefinitionDigests.make({
2798
- agent: digest$2("a"),
2799
- model: digest$2("b"),
2800
- tools: digest$2("c")
2801
- });
2802
- const tripInput = Schema.encodeSync(TripRequest)(phase1Trip);
2803
- const travelPlanOutput = Schema.encodeSync(TravelPlan)(expectedTravelPlan);
2804
- const record = (recordId, createdAt, payload) => Schema.decodeUnknownSync(RecordEnvelope)({
2805
- recordId: Schema.decodeSync(RecordId)(recordId),
2806
- family: "conversation",
2807
- schemaVersion: 1,
2808
- createdAt,
2809
- deploymentId,
2810
- payload
2811
- });
2812
- /**
2813
- * The first atomic append establishes the Conversation and records its input.
2814
- * Its encoded value is the redacted current-version persistence fixture.
2815
- */
2816
- const phase3TravelPlannerInitialBatch = CanonicalBatch.make({
2817
- batchId: Schema.decodeSync(BatchId)("travel-planner-p3-initial"),
2818
- producerId: phase3TravelPlannerProducerId,
2819
- records: [record("travel-planner-p3-created", "2026-09-01T00:00:00.000Z", {
2820
- _tag: "ConversationCreated",
2821
- agentId,
2822
- definitions: phase3TravelPlannerDefinitionDigests
2823
- }), record("travel-planner-p3-input", "2026-09-01T00:00:01.000Z", {
2824
- _tag: "UserInputRecorded",
2825
- submissionId,
2826
- kind: "user",
2827
- runId: phase3TravelPlannerRunId,
2828
- input: tripInput
2829
- })]
2830
- });
2831
- /** The second append records the Schema-decoded itinerary and terminal Run result. */
2832
- const phase3TravelPlannerCompletionBatch = CanonicalBatch.make({
2833
- batchId: Schema.decodeSync(BatchId)("travel-planner-p3-completion"),
2834
- producerId: phase3TravelPlannerProducerId,
2835
- records: [record("travel-planner-p3-model", "2026-09-01T00:00:02.000Z", {
2836
- _tag: "ModelCompleted",
2837
- runId: phase3TravelPlannerRunId,
2838
- output: travelPlanOutput
2839
- }), record("travel-planner-p3-completed", "2026-09-01T00:00:03.000Z", {
2840
- _tag: "RunCompleted",
2841
- runId: phase3TravelPlannerRunId,
2842
- output: travelPlanOutput
2843
- })]
2844
- });
2845
- const phase3TravelPlannerBatches = [phase3TravelPlannerInitialBatch, phase3TravelPlannerCompletionBatch];
2846
- /** Portable current-version fixture; it contains no passenger identity or credentials. */
2847
- const phase3TravelPlannerEncodedFixture = Schema.encodeSync(Schema.Array(CanonicalBatch))(phase3TravelPlannerBatches);
2848
- var TravelPlannerProjectionError = class extends Schema.TaggedError()("TravelPlannerProjectionError", { message: Schema.String }) {};
2849
- /** Decode the itinerary projection rebuilt from canonical model-completion records. */
2850
- const travelPlanFromProjection = (projection) => {
2851
- const output = projection.modelOutputs.at(-1);
2852
- if (output === void 0) return Effect.fail(TravelPlannerProjectionError.make({ message: "The canonical projection has no completed Travel Planner model output." }));
2853
- return Schema.decodeUnknownEffect(TravelPlan)(output).pipe(Effect.mapError((error) => TravelPlannerProjectionError.make({ message: error.message })));
2854
- };
2855
- /** Build a disposable checkpoint bound to a validated canonical prefix. */
2856
- const makePhase3TravelPlannerCheckpoint = (projection) => Schema.decodeSync(ConversationCheckpoint)({
2857
- schemaVersion: 1,
2858
- conversationId: projection.conversationId,
2859
- throughSequence: projection.throughSequence,
2860
- tailDigest: projection.tailDigest,
2861
- engineVersion: "phase-3-test-runtime",
2862
- agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,
2863
- modelDigest: phase3TravelPlannerDefinitionDigests.model,
2864
- toolDigest: phase3TravelPlannerDefinitionDigests.tools,
2865
- state: Schema.encodeSync(ConversationProjection)(projection),
2866
- createdAt: "2026-09-01T00:00:04.000Z"
2867
- });
2868
- //#endregion
2869
- //#region src/scripted-model.ts
2870
- const ScriptedPartMetadata = Schema.Record(Schema.String, Schema.NullOr(Schema.Json));
2871
- const ScriptedPartBase = { metadata: Schema.optionalKey(ScriptedPartMetadata) };
2872
- const ScriptedToolCallPart = Schema.Struct({
2873
- ...ScriptedPartBase,
2874
- type: Schema.Literal("tool-call"),
2875
- id: Schema.String,
2876
- name: Schema.String,
2877
- params: Schema.Unknown,
2878
- providerExecuted: Schema.optionalKey(Schema.Boolean)
2879
- });
2880
- const ScriptedToolResultPart = Schema.Struct({
2881
- ...ScriptedPartBase,
2882
- type: Schema.Literal("tool-result"),
2883
- id: Schema.String,
2884
- name: Schema.String,
2885
- result: Schema.Unknown,
2886
- isFailure: Schema.Boolean,
2887
- providerExecuted: Schema.optionalKey(Schema.Boolean),
2888
- preliminary: Schema.optionalKey(Schema.Boolean)
2889
- });
2890
- /**
2891
- * Schema for encoded, non-streaming Effect AI response parts.
2892
- *
2893
- * Generic Tool payloads remain explicitly unknown here. `LanguageModel.make`
2894
- * performs the toolkit-specific decode when the scripted response is consumed.
2895
- */
2896
- const ScriptedGeneratePart = Schema.Union([
2897
- Schema.toEncoded(Response.TextPart),
2898
- Schema.toEncoded(Response.ReasoningPart),
2899
- Schema.toEncoded(Response.ReasoningDeltaPart),
2900
- Schema.toEncoded(Response.ReasoningEndPart),
2901
- ScriptedToolCallPart,
2902
- ScriptedToolResultPart,
2903
- Schema.toEncoded(Response.ToolApprovalRequestPart),
2904
- Schema.toEncoded(Response.FilePart),
2905
- Schema.toEncoded(Response.DocumentSourcePart),
2906
- Schema.toEncoded(Response.UrlSourcePart),
2907
- Schema.toEncoded(Response.ResponseMetadataPart),
2908
- Schema.toEncoded(Response.FinishPart)
2909
- ]).annotate({ identifier: "ScriptedGeneratePart" });
2910
- /**
2911
- * Schema for encoded Effect AI streaming response parts.
2912
- */
2913
- const ScriptedStreamPart = Schema.Union([
2914
- Schema.toEncoded(Response.TextStartPart),
2915
- Schema.toEncoded(Response.TextDeltaPart),
2916
- Schema.toEncoded(Response.TextEndPart),
2917
- Schema.toEncoded(Response.ReasoningStartPart),
2918
- Schema.toEncoded(Response.ReasoningDeltaPart),
2919
- Schema.toEncoded(Response.ReasoningEndPart),
2920
- Schema.toEncoded(Response.ToolParamsStartPart),
2921
- Schema.toEncoded(Response.ToolParamsDeltaPart),
2922
- Schema.toEncoded(Response.ToolParamsEndPart),
2923
- ScriptedToolCallPart,
2924
- ScriptedToolResultPart,
2925
- Schema.toEncoded(Response.ToolApprovalRequestPart),
2926
- Schema.toEncoded(Response.FilePart),
2927
- Schema.toEncoded(Response.DocumentSourcePart),
2928
- Schema.toEncoded(Response.UrlSourcePart),
2929
- Schema.toEncoded(Response.ResponseMetadataPart),
2930
- Schema.toEncoded(Response.FinishPart),
2931
- Schema.toEncoded(Response.ErrorPart)
2932
- ]).annotate({ identifier: "ScriptedStreamPart" });
2933
- /** Controls whether a scripted stream completes, fails, or waits for interruption. */
2934
- const ScriptedStreamTermination = Schema.Union([
2935
- Schema.TaggedStruct("Complete", {}),
2936
- Schema.TaggedStruct("Fail", { description: Schema.String }),
2937
- Schema.TaggedStruct("Hang", {})
2938
- ]);
2939
- /** One non-streaming invocation and the encoded response parts it returns. */
2940
- const ScriptedGenerateTurn = Schema.TaggedStruct("Generate", { parts: Schema.Array(ScriptedGeneratePart) });
2941
- /** One streaming invocation with its encoded parts and terminal behavior. */
2942
- const ScriptedStreamTurn = Schema.TaggedStruct("Stream", {
2943
- parts: Schema.Array(ScriptedStreamPart),
2944
- termination: ScriptedStreamTermination
2945
- });
2946
- /**
2947
- * Serializable grammar for one finite scripted provider invocation.
2948
- */
2949
- const ScriptedTurn = Schema.Union([ScriptedGenerateTurn, ScriptedStreamTurn]);
2950
- const scriptedError = (method, description) => AiError.AiError.make({
2951
- module: "@effect-agent/testing/ScriptedModel",
2952
- method,
2953
- reason: AiError.UnknownError.make({ description })
2954
- });
2955
- const runAssertion = Effect.fn("ScriptedModel.runAssertion")((assertion, request) => {
2956
- if (assertion === void 0) return Effect.void;
2957
- return Effect.suspend(() => {
2958
- const result = assertion(request);
2959
- return Effect.isEffect(result) ? result : Effect.void;
2960
- });
2961
- });
2962
- const takeTurn = Effect.fn("ScriptedModel.takeTurn")((state, kind, options) => Ref.modify(state, (current) => {
2963
- const turn = current.remaining[0];
2964
- if (turn === void 0) return [void 0, {
2965
- ...current,
2966
- requests: [...current.requests, {
2967
- kind,
2968
- options
2969
- }]
2970
- }];
2971
- return [turn, {
2972
- remaining: current.remaining.slice(1),
2973
- requests: [...current.requests, {
2974
- kind,
2975
- options
2976
- }]
2977
- }];
2978
- }).pipe(Effect.flatMap((turn) => turn === void 0 ? Effect.fail(scriptedError(kind, `Script exhausted before the ${kind} request`)) : Effect.succeed(turn))));
2979
- const requireGenerateTurn = (turn) => turn._tag === "Generate" ? Effect.succeed(turn) : Effect.fail(scriptedError("generate", `Expected a Generate turn but found ${turn._tag}`));
2980
- const requireStreamTurn = (turn) => turn._tag === "Stream" ? Effect.succeed(turn) : Effect.fail(scriptedError("stream", `Expected a Stream turn but found ${turn._tag}`));
2981
- const streamForTurn = (turn) => {
2982
- let stream = Stream.fromIterable(turn.parts);
2983
- switch (turn.termination._tag) {
2984
- case "Complete": break;
2985
- case "Fail":
2986
- stream = stream.pipe(Stream.concat(Stream.fail(scriptedError("stream", turn.termination.description))));
2987
- break;
2988
- case "Hang":
2989
- stream = stream.pipe(Stream.concat(Stream.never));
2990
- break;
2991
- }
2992
- if (turn.onStreamStart !== void 0) stream = Stream.fromEffectDrain(turn.onStreamStart).pipe(Stream.concat(stream));
2993
- if (turn.onStreamFinalize !== void 0) stream = stream.pipe(Stream.ensuring(turn.onStreamFinalize));
2994
- return stream;
2995
- };
2996
- /** Inspection service for a deterministic LanguageModel backed by finite scripted turns. */
2997
- var ScriptedModel = class ScriptedModel extends Context.Service()("@effect-agent/testing/ScriptedModel") {
2998
- /**
2999
- * Provides the native Effect AI `LanguageModel` and this inspection service.
3000
- * Supplying the extra inspection service does not add it to model-call
3001
- * requirements. Each model invocation consumes one turn before assertion and
3002
- * turn-kind validation.
3003
- */
3004
- static layer(turns) {
3005
- return Layer.effectContext(Effect.gen(function* () {
3006
- const state = yield* Ref.make({
3007
- remaining: [...turns],
3008
- requests: []
3009
- });
3010
- const languageModel = yield* LanguageModel.make({
3011
- generateText: (options) => Effect.gen(function* () {
3012
- const turn = yield* takeTurn(state, "generate", options);
3013
- yield* runAssertion(turn.assertRequest, options);
3014
- return [...(yield* requireGenerateTurn(turn)).parts];
3015
- }),
3016
- streamText: (options) => Stream.unwrap(Effect.gen(function* () {
3017
- const turn = yield* takeTurn(state, "stream", options);
3018
- yield* runAssertion(turn.assertRequest, options);
3019
- const streamTurn = yield* requireStreamTurn(turn);
3020
- return streamForTurn(streamTurn);
3021
- }))
3022
- });
3023
- const inspection = ScriptedModel.of({
3024
- requests: Ref.get(state).pipe(Effect.map((current) => current.requests)),
3025
- remaining: Ref.get(state).pipe(Effect.map((current) => current.remaining.length)),
3026
- assertExhausted: Ref.get(state).pipe(Effect.flatMap((current) => current.remaining.length === 0 ? Effect.void : Effect.fail(scriptedError("assertExhausted", `${current.remaining.length} scripted turn(s) remain`))))
3027
- });
3028
- return Context.make(LanguageModel.LanguageModel, languageModel).pipe(Context.add(ScriptedModel, inspection));
3029
- }));
3030
- }
3031
- };
3032
- //#endregion
3033
- //#region src/fixtures/travel-planner/phase4.ts
3034
- /**
3035
- * The Phase 4 profile claims durable accepted work on the Node/SQLite runtime (deployment class
3036
- * DN): once `submit` returns a Receipt, the Submission settles exactly once even across process
3037
- * loss. The claim is limited to safe-to-repeat toolkits (D6): supplier booking is explicitly NOT
3038
- * claimed safely replayable — replay-safe external mutation is P5 (Durable Tools) scope.
3039
- */
3040
- var TravelPlannerDurabilityProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerDurabilityProfile")({
3041
- deploymentClass: Schema.Literal("DN"),
3042
- durableAcceptedWork: Schema.Literal(true),
3043
- canonicalSchemaVersion: Schema.Literal(1),
3044
- /** Supplier booking replay safety is P5 (Durable Tools) scope; DN does not claim it. */
3045
- supplierBookingReplaySafe: Schema.Literal(false)
3046
- }) {};
3047
- const phase4TravelPlannerProfile = TravelPlannerDurabilityProfile.make({
3048
- deploymentClass: "DN",
3049
- durableAcceptedWork: true,
3050
- canonicalSchemaVersion: 1,
3051
- supplierBookingReplaySafe: false
3052
- });
3053
- const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p4-deployment");
3054
- const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p4-producer");
3055
- const phase4TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-p4-principal");
3056
- const digest$1 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
3057
- /** Redacted, deterministic definition identities for the current fixture version. */
3058
- const phase4TravelPlannerDefinitionDigests = DefinitionDigests.make({
3059
- agent: digest$1("d"),
3060
- model: digest$1("e"),
3061
- tools: digest$1("f")
3062
- });
3063
- /** Durable admission options for one Travel Planner Submission on one trip lane. */
3064
- const phase4TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
3065
- conversationId,
3066
- principal: phase4TravelPlannerPrincipal,
3067
- idempotencyKey,
3068
- definitions: phase4TravelPlannerDefinitionDigests
3069
- });
3070
- /**
3071
- * The P4 read-only search Tools, calling the same deterministic catalogs as the P1 toolkit.
3072
- *
3073
- * The plain-Struct parameter shape is a historical remnant of the P4 carry-in workaround: since
3074
- * the P5 engine fix, official history carries Schema-ENCODED Tool-call parameters, so class-typed
3075
- * parameter codecs persist canonically too — the Structs simply need no change here. The
3076
- * `ToolExecutionClass` `readonly` annotation is the deliberate P5 migration (plan §4.3): these
3077
- * Tools perform no external mutation, so a crash between start and settlement is a free re-run
3078
- * and they never enter the prepared/settled uncertainty protocol — keeping the P4 canonical
3079
- * history byte-stable (an unannotated Tool fails closed to `uncertain`).
3080
- */
3081
- const DurableSearchFlights = Tool.make("search_flights", {
3082
- parameters: Schema.Struct(FlightQuery.fields),
3083
- success: FlightOption,
3084
- failure: FlightUnavailable,
3085
- failureMode: "error",
3086
- dependencies: [FlightCatalog]
3087
- }).annotate(ToolExecutionClass, "readonly");
3088
- const DurableSearchLodging = Tool.make("search_lodging", {
3089
- parameters: Schema.Struct(LodgingQuery.fields),
3090
- success: LodgingOption,
3091
- failure: LodgingUnavailable,
3092
- failureMode: "error",
3093
- dependencies: [LodgingCatalog]
3094
- }).annotate(ToolExecutionClass, "readonly");
3095
- const DurableSearchActivities = Tool.make("search_activities", {
3096
- parameters: Schema.Struct(ActivityQuery.fields),
3097
- success: ActivitySearchResult,
3098
- failure: ActivityUnavailable,
3099
- failureMode: "error",
3100
- dependencies: [ActivityCatalog]
3101
- }).annotate(ToolExecutionClass, "readonly");
3102
- const TravelPlannerPhase4Toolkit = Toolkit.make(DurableSearchFlights, DurableSearchLodging, DurableSearchActivities);
3103
- const TravelPlannerPhase4ToolkitLayer = TravelPlannerPhase4Toolkit.toLayer({
3104
- search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),
3105
- search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),
3106
- search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query)))
3107
- });
3108
- /**
3109
- * The cumulative Travel Planner, Phase 4: the P1 planning behavior on the durable Node/SQLite
3110
- * runtime. The searches are read-only and safe to repeat across Attempts (D6); supplier booking
3111
- * is deliberately absent because DN does NOT claim replay-safe external mutation (P5 scope).
3112
- */
3113
- const TravelPlannerPhase4 = Agent.define("travel-planner-phase-4", {
3114
- input: TripRequest,
3115
- output: TravelPlan,
3116
- instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
3117
- toolkit: TravelPlannerPhase4Toolkit,
3118
- policy: AgentPolicy.make({
3119
- maxTurns: 2,
3120
- maxToolCalls: 3,
3121
- maxDuration: "30 seconds",
3122
- toolConcurrency: 3
3123
- }),
3124
- description: "Durably plan one review-only itinerary from safe-to-repeat deterministic searches; supplier booking is not claimed safely replayable.",
3125
- metadata: {
3126
- deploymentClass: "DN",
3127
- phase: "P4"
3128
- }
3129
- });
3130
- /**
3131
- * The P4 Agent Binding: the durable Travel Planner definition bound to a finite scripted model.
3132
- * The scripted Layer is rebuilt per Run, so every Run of one Binding replays the same
3133
- * deterministic script.
3134
- */
3135
- const makePhase4TravelPlannerAgent = (turns = phase1HappyPathTurns) => Agent.withModel(TravelPlannerPhase4, Model.make("scripted", "travel-planner-phase-4", ScriptedModel.layer(turns)));
3136
- /**
3137
- * Everything a durable worker needs beyond the runtime stack, reusing the deterministic P1
3138
- * travel-service Layers. The durable coordinator supplies its own deterministic `IdGenerator`,
3139
- * so this Layer deliberately provides none.
3140
- */
3141
- const phase4TravelPlannerWorkerLayer = Layer.mergeAll(TravelPlannerPhase4ToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer, TravelGuidanceLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
3142
- var TravelPlannerDurableEvidenceError = class extends Schema.TaggedError()("TravelPlannerDurableEvidenceError", { message: Schema.String }) {};
3143
- /**
3144
- * Decode the completed itinerary from the canonical `SubmissionSettled` record. Canonical history
3145
- * is the outcome authority (DUR-015): the settled result — not any ledger cache — must decode
3146
- * through the trip output schema.
3147
- */
3148
- const travelPlanFromDurableSettlement = Effect.fn("TravelPlannerPhase4.travelPlanFromDurableSettlement")(function* (records) {
3149
- const settled = records.flatMap((envelope) => envelope.record.payload._tag === "SubmissionSettled" ? [envelope.record.payload] : []).at(0);
3150
- if (settled === void 0) return yield* TravelPlannerDurableEvidenceError.make({ message: "The canonical Conversation Log has no SubmissionSettled record." });
3151
- if (settled.outcome !== "completed" || settled.result === void 0) return yield* TravelPlannerDurableEvidenceError.make({ message: `The Submission settled ${settled.outcome} without a completed itinerary result.` });
3152
- return yield* Schema.decodeUnknownEffect(TravelPlan)(settled.result).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `The settled result does not decode through the TravelPlan schema: ${error.message}` })));
3153
- });
3154
- const encodeEvidence = Schema.encodeEffect(Schema.Array(CanonicalRecordEnvelope));
3155
- const decodeComparableJson$1 = Schema.decodeUnknownEffect(Schema.Json);
3156
- /**
3157
- * Project canonical evidence into a Submission-identity-independent comparable form: batch
3158
- * identity, canonical sequence, and the full encoded record, with the ledger-minted
3159
- * `submissionId`/`receiptId` (and every identity derived from them: run, turn, batch, record,
3160
- * and settlement ids) replaced by stable placeholders. Two Conversations whose normalized
3161
- * evidence is equal took byte-equivalent canonical histories, so restart-equivalence can compare
3162
- * a recovered run against an uninterrupted control run on a separate database.
3163
- */
3164
- const normalizeDurableTravelPlannerEvidence = Effect.fn("TravelPlannerPhase4.normalizeDurableTravelPlannerEvidence")(function* (records, receipt) {
3165
- const comparable = (yield* encodeEvidence(records).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Canonical evidence failed to encode: ${error.message}` })))).map((envelope) => ({
3166
- batchId: envelope.batchId,
3167
- sequence: envelope.sequence,
3168
- record: envelope.record
3169
- }));
3170
- const substituted = JSON.parse(JSON.stringify(comparable).replaceAll(receipt.submissionId, "{submissionId}").replaceAll(receipt.receiptId, "{receiptId}"));
3171
- return yield* decodeComparableJson$1(substituted).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Normalized evidence is not comparable JSON: ${error.message}` })));
3172
- });
3173
- //#endregion
3174
- //#region src/fixtures/travel-planner/phase5.ts
3175
- /**
3176
- * The Phase 5 profile extends the P4 `DN` claim to consequential supplier mutation: booking
3177
- * Tools enter the prepared/settled uncertainty protocol, unresolved external effects stop at
3178
- * Unknown Outcomes instead of replaying, Durable Steps replay recorded results, and queued
3179
- * traveler input joins the active Run. Exactly-once EXTERNAL execution is still — deliberately —
3180
- * not claimed (DUR-003): the supplier's own idempotency keys are what dedupe repeats.
3181
- */
3182
- var TravelPlannerBookingProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerBookingProfile")({
3183
- deploymentClass: Schema.Literal("DN"),
3184
- durableAcceptedWork: Schema.Literal(true),
3185
- canonicalSchemaVersion: Schema.Literal(1),
3186
- /** P5: supplier mutations get prepared/settled records, Unknown Outcomes, and reconciliation. */
3187
- supplierBookingUncertaintyProtocol: Schema.Literal(true),
3188
- /** P5: Durable Steps are exactly-once-RECORDED; their side effects stay at-least-once. */
3189
- durableStepsRecorded: Schema.Literal(true),
3190
- /** Never claimed at any phase (DUR-003). */
3191
- exactlyOnceExternalEffects: Schema.Literal(false)
3192
- }) {};
3193
- const phase5TravelPlannerProfile = TravelPlannerBookingProfile.make({
3194
- deploymentClass: "DN",
3195
- durableAcceptedWork: true,
3196
- canonicalSchemaVersion: 1,
3197
- supplierBookingUncertaintyProtocol: true,
3198
- durableStepsRecorded: true,
3199
- exactlyOnceExternalEffects: false
3200
- });
3201
- const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p5-deployment");
3202
- const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p5-producer");
3203
- const phase5TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-p5-principal");
3204
- const digest = (character) => Schema.decodeSync(Digest)(character.repeat(64));
3205
- /** Redacted, deterministic definition identities for the current fixture version. */
3206
- const phase5TravelPlannerDefinitionDigests = DefinitionDigests.make({
3207
- agent: digest("1"),
3208
- model: digest("2"),
3209
- tools: digest("3")
3210
- });
3211
- /** Durable admission options for one Travel Planner Submission on one trip lane. */
3212
- const phase5TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
3213
- conversationId,
3214
- principal: phase5TravelPlannerPrincipal,
3215
- idempotencyKey,
3216
- definitions: phase5TravelPlannerDefinitionDigests
3217
- });
3218
- const TravelerRef = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/TravelerRef"));
3219
- /**
3220
- * Class-shaped booking parameters with branded fields: since the P5 engine fix, official history
3221
- * carries Schema-ENCODED Tool-call parameters, so class-typed parameter codecs persist
3222
- * canonically end-to-end (the P4 Struct workaround is gone for new Tools).
3223
- */
3224
- var FlightBookingRequest = class extends Schema.Class("FlightBookingRequest")({
3225
- quoteId: QuoteId,
3226
- travelerRef: TravelerRef,
3227
- departOn: Schema.String
3228
- }) {};
3229
- var SupplierBookingConfirmation = class extends Schema.Class("SupplierBookingConfirmation")({
3230
- bookingRef: BookingRef,
3231
- status: Schema.Literal("confirmed"),
3232
- detail: Schema.String
3233
- }) {};
3234
- var CancelBookingRequest = class extends Schema.Class("CancelBookingRequest")({
3235
- bookingRef: BookingRef,
3236
- travelerRef: TravelerRef
3237
- }) {};
3238
- var CancellationConfirmation = class extends Schema.Class("CancellationConfirmation")({
3239
- bookingRef: BookingRef,
3240
- status: Schema.Literal("cancelled")
3241
- }) {};
3242
- var ItineraryBookingRequest = class extends Schema.Class("ItineraryBookingRequest")({
3243
- quoteId: QuoteId,
3244
- destination: AirportCode,
3245
- nights: Schema.Int.check(Schema.isGreaterThan(0)),
3246
- travelerRef: TravelerRef
3247
- }) {};
3248
- var ItineraryConfirmation = class extends Schema.Class("ItineraryConfirmation")({
3249
- flightBookingRef: BookingRef,
3250
- lodgingBookingRef: BookingRef,
3251
- confirmationCode: Schema.String
3252
- }) {};
3253
- /** The P5 Run output: a booked (or explicitly not-booked) trip report. */
3254
- var TravelBookingReport = class extends Schema.Class("TravelBookingReport")({
3255
- summary: Schema.String,
3256
- bookingRefs: Schema.Array(BookingRef)
3257
- }) {};
3258
- /**
3259
- * Supplier idempotency-key derivations. The handler owns key derivation (the `idempotent` and
3260
- * `uncertain` execution classes carry no key), and the reconciler MUST use the same derivations
3261
- * to query external truth — both sides are exported so they cannot drift.
3262
- */
3263
- const bookFlightIdempotencyKey = (toolCallId) => `book-flight:${toolCallId}`;
3264
- const itineraryStepIdempotencyKey = (toolCallId, stepName) => `${toolCallId}:${stepName}`;
3265
- /**
3266
- * Approval-gated supplier booking, explicitly `uncertain`: a crash after the call may have
3267
- * mutated supplier state without a recorded outcome, so recovery must reconcile or stop at an
3268
- * Unknown Outcome — never replay automatically (DUR-009, ADR-0004).
3269
- */
3270
- const BookFlight = Tool.make("book_flight", {
3271
- parameters: FlightBookingRequest,
3272
- success: SupplierBookingConfirmation,
3273
- failure: SupplierUnavailable,
3274
- failureMode: "error",
3275
- needsApproval: true,
3276
- dependencies: [SupplierBookingDesk]
3277
- }).annotate(ToolExecutionClass, "uncertain");
3278
- /**
3279
- * Approval-gated cancellation, annotated `idempotent`: the DECLARED external contract is that
3280
- * cancellation is idempotent by `bookingRef` (the supplier desk enforces it), so recovery may
3281
- * re-execute a prepared-but-unsettled cancel without reconciliation proof. Repeats stay
3282
- * observable in the supplier call counters — the annotation never claims exactly-once execution.
3283
- */
3284
- const CancelBooking = Tool.make("cancel_booking", {
3285
- parameters: CancelBookingRequest,
3286
- success: CancellationConfirmation,
3287
- failure: SupplierUnavailable,
3288
- failureMode: "error",
3289
- needsApproval: true,
3290
- dependencies: [SupplierBookingDesk]
3291
- }).annotate(ToolExecutionClass, "idempotent");
3292
- /**
3293
- * The Durable Tool: declaring `DurableStep` in `dependencies` is what makes it durable
3294
- * (CONTEXT.md). Its handler divides supplier mutation into three named Steps — `reserve-flight`,
3295
- * `reserve-lodging`, `issue-confirmation` — each deriving its supplier idempotency key from
3296
- * `(toolCallId, stepName)`, so re-entry after interruption replays recorded Step results and the
3297
- * supplier dedupes any honestly-repeated call. The Tool itself carries no execution-class
3298
- * annotation: it stays fail-closed `uncertain`, and `TravelSupplierReconcilerLayer` proves
3299
- * re-entry safe from the keyed-Step construction instead.
3300
- */
3301
- const BookItinerary = Tool.make("book_itinerary", {
3302
- parameters: ItineraryBookingRequest,
3303
- success: ItineraryConfirmation,
3304
- failure: Schema.Union([SupplierUnavailable, DurableStepError]),
3305
- failureMode: "error",
3306
- dependencies: [DurableStep, SupplierBookingDesk]
3307
- });
3308
- const TravelPlannerPhase5Toolkit = Toolkit.make(DurableSearchFlights, DurableSearchLodging, DurableSearchActivities, BookFlight, CancelBooking, BookItinerary);
3309
- const requireToolCallId = (toolName, toolCallId) => toolCallId === void 0 ? Effect.fail(SupplierUnavailable.make({ message: `${toolName} needs its stable Tool Call ID to derive the supplier idempotency key.` })) : Effect.succeed(toolCallId);
3310
- const TravelPlannerPhase5ToolkitLayer = TravelPlannerPhase5Toolkit.toLayer({
3311
- search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),
3312
- search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),
3313
- search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),
3314
- book_flight: (request, context) => Effect.gen(function* () {
3315
- const desk = yield* SupplierBookingDesk;
3316
- const toolCallId = yield* requireToolCallId("book_flight", context.toolCallId);
3317
- const record = yield* desk.book({
3318
- operation: "book-flight",
3319
- idempotencyKey: bookFlightIdempotencyKey(toolCallId),
3320
- detail: `flight ${request.quoteId} for ${request.travelerRef} on ${request.departOn}`
3321
- });
3322
- return SupplierBookingConfirmation.make({
3323
- bookingRef: record.bookingRef,
3324
- status: "confirmed",
3325
- detail: record.detail
3326
- });
3327
- }),
3328
- cancel_booking: (request) => Effect.gen(function* () {
3329
- const record = yield* (yield* SupplierBookingDesk).cancel(request.bookingRef);
3330
- return CancellationConfirmation.make({
3331
- bookingRef: record.bookingRef,
3332
- status: "cancelled"
3333
- });
3334
- }),
3335
- book_itinerary: (request, context) => Effect.gen(function* () {
3336
- const desk = yield* SupplierBookingDesk;
3337
- const step = yield* DurableStep;
3338
- const toolCallId = yield* requireToolCallId("book_itinerary", context.toolCallId);
3339
- const bookStep = (stepName, detail) => step.do(stepName, SupplierBookingRecord, desk.book({
3340
- operation: stepName,
3341
- idempotencyKey: itineraryStepIdempotencyKey(toolCallId, stepName),
3342
- detail
3343
- }));
3344
- const flight = yield* bookStep("reserve-flight", `flight ${request.quoteId} for ${request.travelerRef}`);
3345
- const lodging = yield* bookStep("reserve-lodging", `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`);
3346
- const confirmation = yield* bookStep("issue-confirmation", `itinerary confirmation for ${request.travelerRef}`);
3347
- return ItineraryConfirmation.make({
3348
- flightBookingRef: flight.bookingRef,
3349
- lodgingBookingRef: lodging.bookingRef,
3350
- confirmationCode: confirmation.bookingRef
3351
- });
3352
- })
3353
- });
3354
- const decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);
3355
- const encodeConfirmation = Schema.encodeEffect(SupplierBookingConfirmation);
3356
- /**
3357
- * The application reconciliation policy (durability §10): a claim about EXTERNAL truth, queried
3358
- * from the supplier desk by the same idempotency-key derivations the handlers use.
3359
- *
3360
- * - `book_flight`: a confirmed booking under `book-flight:{toolCallId}` is recovered supplier
3361
- * truth — `CompletedWithResult` settles it canonically without executing anything. Absence is
3362
- * NOT proof the call never started (a real supplier write could be in flight), so the desk
3363
- * answer stays fail-closed `Uncertain`.
3364
- * - `book_itinerary`: every external mutation inside is a named Step whose supplier idempotency
3365
- * key derives from `(toolCallId, stepName)`, so re-entry is provably safe by construction —
3366
- * `SafeToRetry`. Committed Steps replay from their records; repeated calls dedupe at the desk.
3367
- * - `cancel_booking`: declared `idempotent`, so the coordinator re-executes without consulting
3368
- * this policy; if ever asked, the bookingRef contract makes `SafeToRetry` honest.
3369
- * - anything else: fail-closed `Uncertain` (AGENTS rule 11).
3370
- */
3371
- const TravelSupplierReconcilerLayer = Layer.effect(ToolReconciler, Effect.gen(function* () {
3372
- const desk = yield* SupplierBookingDesk;
3373
- return ToolReconciler.of({ reconcile: (evidence) => Effect.gen(function* () {
3374
- switch (evidence.toolName) {
3375
- case "book_flight": {
3376
- const key = bookFlightIdempotencyKey(evidence.toolCallId);
3377
- const booking = yield* desk.lookup(key);
3378
- if (Option.isSome(booking) && booking.value.status === "confirmed") {
3379
- const confirmation = yield* encodeConfirmation(SupplierBookingConfirmation.make({
3380
- bookingRef: booking.value.bookingRef,
3381
- status: "confirmed",
3382
- detail: booking.value.detail
3383
- })).pipe(Effect.flatMap(decodePersistedJson));
3384
- return ReconciliationCompleted.make({
3385
- result: confirmation,
3386
- isFailure: false
3387
- });
3388
- }
3389
- return ReconciliationUncertain.make({ reason: `The supplier desk shows no confirmed booking under ${key}; a write may still be in flight.` });
3390
- }
3391
- case "book_itinerary": return ReconciliationSafeToRetry.make();
3392
- case "cancel_booking": return ReconciliationSafeToRetry.make();
3393
- default: return ReconciliationUncertain.make({ reason: `No supplier reconciliation exists for ${evidence.toolName}.` });
3394
- }
3395
- }).pipe(Effect.mapError((error) => ToolReconcilerError.make({
3396
- toolCallId: evidence.toolCallId,
3397
- message: `Supplier reconciliation failed: ${error.message}`
3398
- }))) });
3399
- }));
3400
- /**
3401
- * The cumulative Travel Planner, Phase 5: the durable planner now performs consequential
3402
- * supplier mutation under the full uncertainty protocol — approval-gated uncertain booking,
3403
- * idempotent-by-contract cancellation, and one Durable Tool whose Steps carry supplier
3404
- * idempotency keys.
3405
- */
3406
- const TravelPlannerPhase5 = Agent.define("travel-planner-phase-5", {
3407
- input: TripRequest,
3408
- output: TravelBookingReport,
3409
- instructions: [
3410
- "You are the Effect Agent Travel Planner P5 booking fixture.",
3411
- "Search with the read-only tools, then book with book_flight, book_itinerary, or",
3412
- "cancel_booking exactly as scripted. Every consequential mutation is approval-gated",
3413
- "or Step-structured. Return only a JSON object with summary and bookingRefs."
3414
- ].join(" "),
3415
- toolkit: TravelPlannerPhase5Toolkit,
3416
- policy: AgentPolicy.make({
3417
- maxTurns: 4,
3418
- maxToolCalls: 6,
3419
- maxDuration: "30 seconds",
3420
- toolConcurrency: 2
3421
- }),
3422
- description: "Durably book one itinerary with prepared/settled supplier records, Unknown Outcomes, named Steps, and joined traveler input.",
3423
- metadata: {
3424
- deploymentClass: "DN",
3425
- phase: "P5"
3426
- }
3427
- });
3428
- var TravelPlannerBookingEvidenceError = class extends Schema.TaggedError()("TravelPlannerBookingEvidenceError", { message: Schema.String }) {};
3429
- const bookingResultRefs = (result) => {
3430
- if (typeof result !== "object" || result === null) return [];
3431
- const refs = [];
3432
- for (const [field, value] of Object.entries(result)) if (typeof value === "string" && (field === "bookingRef" || field === "flightBookingRef" || field === "lodgingBookingRef" || field === "confirmationCode")) refs.push(value);
3433
- return refs;
3434
- };
3435
- const bookingToolNames = /* @__PURE__ */ new Set([
3436
- "book_flight",
3437
- "cancel_booking",
3438
- "book_itinerary"
3439
- ]);
3440
- /**
3441
- * Never-fabricate assertion (ROADMAP P5 exit gate): every successfully settled booking result in
3442
- * canonical history must reference a booking that actually exists in the supplier store. A
3443
- * `ToolCallSettled` whose bookingRef the supplier cannot produce would be a fabricated result —
3444
- * the exact lie the uncertainty protocol exists to prevent.
3445
- */
3446
- const assertSettledBookingsExistAtSupplier = Effect.fn("TravelPlannerPhase5.assertSettledBookingsExistAtSupplier")(function* (records) {
3447
- const bookings = yield* (yield* SupplierBookingDesk).bookings;
3448
- const knownRefs = new Set(bookings.map((booking) => booking.bookingRef));
3449
- for (const envelope of records) {
3450
- const payload = envelope.record.payload;
3451
- if (payload._tag !== "ToolCallSettled" || payload.isFailure || !bookingToolNames.has(payload.toolName)) continue;
3452
- for (const ref of bookingResultRefs(payload.result)) if (!knownRefs.has(ref)) return yield* TravelPlannerBookingEvidenceError.make({ message: `Canonical record ${envelope.record.recordId} settled bookingRef ${ref}, which the supplier store cannot produce — a fabricated result.` });
3453
- }
3454
- });
3455
- /**
3456
- * Everything a durable P5 worker needs beyond the runtime stack and the supplier desk: the
3457
- * booking toolkit plus the deterministic P1 travel-service Layers. `SupplierBookingDesk` is
3458
- * deliberately NOT provided here — tests own the desk's lifetime so its counters, bookings, and
3459
- * crash windows survive Tool-Layer rebuilds across Attempts.
3460
- */
3461
- const phase5TravelPlannerWorkerLayer = Layer.mergeAll(TravelPlannerPhase5ToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
3462
- //#endregion
3463
- //#region src/fixtures/travel-planner/subagents.ts
3464
- var DestinationQuery = class extends Schema.Class("DestinationQuery")({ destination: AirportCode }) {};
3465
- var DestinationFacts = class extends Schema.Class("DestinationFacts")({
3466
- destination: AirportCode,
3467
- highlights: Schema.Array(Schema.String),
3468
- advisory: Schema.NonEmptyString
3469
- }) {};
3470
- var DestinationGuideUnavailable = class extends Schema.TaggedError()("DestinationGuideUnavailable", {
3471
- destination: AirportCode,
3472
- message: Schema.String
3473
- }) {};
3474
- var DestinationGuide = class extends Context.Service()("@effect-agent/testing/travel-planner/DestinationGuide") {};
3475
- const LookupDestination = Tool.make("lookup_destination", {
3476
- parameters: DestinationQuery,
3477
- success: DestinationFacts,
3478
- failure: DestinationGuideUnavailable,
3479
- failureMode: "error",
3480
- dependencies: [DestinationGuide]
3481
- });
3482
- const DestinationResearcherToolkit = Toolkit.make(LookupDestination);
3483
- const DestinationResearcherToolkitLayer = DestinationResearcherToolkit.toLayer({ lookup_destination: (query) => Effect.flatMap(DestinationGuide, (guide) => guide.lookup(query)) });
3484
- var DestinationBrief = class extends Schema.Class("DestinationBrief")({
3485
- destination: AirportCode,
3486
- focus: Schema.NonEmptyString
3487
- }) {};
3488
- var DestinationReport = class extends Schema.Class("DestinationReport")({
3489
- destination: AirportCode,
3490
- highlights: Schema.Array(Schema.String),
3491
- advisory: Schema.NonEmptyString
3492
- }) {};
3493
- const DestinationResearcher = Agent.define("destination-researcher", {
3494
- input: DestinationBrief,
3495
- output: DestinationReport,
3496
- instructions: "Consult lookup_destination exactly once for the briefed airport, then return only a JSON destination report.",
3497
- toolkit: DestinationResearcherToolkit,
3498
- policy: AgentPolicy.make({
3499
- maxTurns: 2,
3500
- maxToolCalls: 1,
3501
- maxDuration: "30 seconds",
3502
- toolConcurrency: 1
3503
- }),
3504
- description: "Research one candidate destination with the deterministic travel guide.",
3505
- metadata: {
3506
- deploymentClass: "E",
3507
- phase: "S1"
3508
- }
3509
- });
3510
- const decodeAirportCode = Schema.decodeSync(AirportCode);
3511
- const guideFacts = /* @__PURE__ */ new Map([["LHR", DestinationFacts.make({
3512
- destination: decodeAirportCode("LHR"),
3513
- highlights: ["Barbican brutalism walk", "Kew glasshouse survey"],
3514
- advisory: "London favors museum mornings and riverside evenings."
3515
- })], ["CDG", DestinationFacts.make({
3516
- destination: decodeAirportCode("CDG"),
3517
- highlights: ["Marais passage crawl", "Seine bookstall loop"],
3518
- advisory: "Paris rewards early galleries and late cafes."
3519
- })]]);
3520
- /** Deterministic guide lookup shared by the default and test-local guide Layers. */
3521
- const destinationLookup = (query) => {
3522
- const facts = guideFacts.get(query.destination);
3523
- return facts === void 0 ? Effect.fail(DestinationGuideUnavailable.make({
3524
- destination: query.destination,
3525
- message: "No deterministic guide entry exists for this destination."
3526
- })) : Effect.succeed(facts);
3527
- };
3528
- const requireDestinationFacts = (destination) => {
3529
- const facts = guideFacts.get(destination);
3530
- if (facts === void 0) throw new Error(`No deterministic guide entry exists for destination ${destination}`);
3531
- return facts;
3532
- };
3533
- /** The report the scripted researcher writes after consulting the guide. */
3534
- const destinationReportFor = (destination) => {
3535
- const facts = requireDestinationFacts(destination);
3536
- return DestinationReport.make({
3537
- destination: facts.destination,
3538
- highlights: facts.highlights,
3539
- advisory: facts.advisory
3540
- });
3541
- };
3542
- const encodedDestinationReport = (destination) => JSON.stringify(Schema.encodeSync(DestinationReport)(destinationReportFor(destination)));
3543
- const DestinationGuideLayer = Layer.effect(DestinationGuide, Effect.gen(function* () {
3544
- const lifecycle = yield* CatalogLifecycle;
3545
- yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
3546
- return DestinationGuide.of({ lookup: destinationLookup });
3547
- }));
3548
- /** Child-side construction requirements of the delegation handler Layer. */
3549
- const DestinationResearchSupportLayer = Layer.mergeAll(DestinationResearcherToolkitLayer, DestinationGuideLayer);
3550
- var DestinationResearchRequest = class extends Schema.Class("DestinationResearchRequest")({
3551
- destination: AirportCode,
3552
- focus: Schema.NonEmptyString
3553
- }) {};
3554
- var DestinationResearchFindings = class extends Schema.Class("DestinationResearchFindings")({
3555
- destination: AirportCode,
3556
- summary: Schema.NonEmptyString
3557
- }) {};
3558
- var DestinationResearchFailed = class extends Schema.TaggedError()("DestinationResearchFailed", { childErrorTag: Schema.NonEmptyString }) {};
3559
- /**
3560
- * Deterministic delegation-admission choreography seam. `prepareInput` awaits
3561
- * this gate before the handler reserves budget or spawns, so tests can order
3562
- * concurrent delegation preflights without sleeps. It also keeps the
3563
- * projection's construction requirements honestly visible in the handler
3564
- * Layer's `R` (spec/subagents.md §4.1). The open Layer never waits.
3565
- */
3566
- var ResearchDispatchGate = class ResearchDispatchGate extends Context.Service()("@effect-agent/testing/travel-planner/ResearchDispatchGate") {
3567
- static layerOpen = Layer.succeed(this, ResearchDispatchGate.of({ awaitDispatch: () => Effect.void }));
3568
- };
3569
- /**
3570
- * Finite per-invocation bounds (SUB-009): each child may use two Turns and
3571
- * one Tool Call; the parent Run may establish at most two children with at
3572
- * most two running concurrently.
3573
- */
3574
- const destinationResearchPolicy = SubagentPolicy.make({
3575
- maxChildren: 2,
3576
- maxConcurrency: 2,
3577
- maxTurns: 2,
3578
- maxToolCalls: 1,
3579
- maxDuration: "10 seconds"
3580
- });
3581
- const destinationResearchDelegation = Subagent.define("delegate_destination_research", {
3582
- description: "Research one candidate destination with the deterministic travel guide and return a bounded finding.",
3583
- target: DestinationResearcher,
3584
- parameters: DestinationResearchRequest,
3585
- success: DestinationResearchFindings,
3586
- failure: DestinationResearchFailed,
3587
- prepareInput: (request) => Effect.gen(function* () {
3588
- yield* (yield* ResearchDispatchGate).awaitDispatch(request.destination);
3589
- return DestinationBrief.make({
3590
- destination: request.destination,
3591
- focus: `research:${request.focus}`
3592
- });
3593
- }),
3594
- projectResult: (report) => Effect.succeed(DestinationResearchFindings.make({
3595
- destination: report.destination,
3596
- summary: report.advisory
3597
- })),
3598
- policy: destinationResearchPolicy
3599
- });
3600
- /** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */
3601
- const mapResearchChildFailure = (failure) => DestinationResearchFailed.make({ childErrorTag: failure._tag });
3602
- /** Runtime wiring: pair the immutable delegation with one explicit child Binding. */
3603
- const destinationResearchHandlersLayer = (childBinding) => SubagentRuntime.layer(destinationResearchDelegation, childBinding, { mapChildFailure: mapResearchChildFailure });
3604
- var ResearchMission = class extends Schema.Class("ResearchMission")({
3605
- request: Schema.NonEmptyString,
3606
- candidates: Schema.Array(AirportCode).check(Schema.isMinLength(1))
3607
- }) {};
3608
- var DestinationRecommendation = class extends Schema.Class("DestinationRecommendation")({
3609
- destination: AirportCode,
3610
- summary: Schema.NonEmptyString
3611
- }) {};
3612
- var DestinationShortlist = class extends Schema.Class("DestinationShortlist")({
3613
- recommendations: Schema.Array(DestinationRecommendation),
3614
- nextAction: Schema.Literal("review")
3615
- }) {};
3616
- /** Parent-only transcript markers used to prove child context isolation (SUB-006/015). */
3617
- const coordinatorConfidentialMarker = "coordinator-vault-7q42";
3618
- const missionConfidentialMarker = "traveler-dossier-19f";
3619
- const TravelCoordinatorToolkit = Toolkit.make(destinationResearchDelegation.tool);
3620
- const TravelCoordinator = Agent.define("travel-coordinator", {
3621
- input: ResearchMission,
3622
- output: DestinationShortlist,
3623
- instructions: [
3624
- "You are the Effect Agent Travel Planner S1 delegation coordinator.",
3625
- `Coordinator-only context: ${coordinatorConfidentialMarker}.`,
3626
- "Call delegate_destination_research once per candidate in one Tool batch.",
3627
- "Return only a JSON shortlist built from the delegated findings. This is read-only planning."
3628
- ].join("\n"),
3629
- toolkit: TravelCoordinatorToolkit,
3630
- policy: AgentPolicy.make({
3631
- maxTurns: 2,
3632
- maxToolCalls: 3,
3633
- maxDuration: "30 seconds",
3634
- toolConcurrency: 3
3635
- }),
3636
- description: "Coordinate bounded destination research through one declared attached delegation Tool.",
3637
- metadata: {
3638
- deploymentClass: "E",
3639
- phase: "S1"
3640
- }
3641
- });
3642
- const researchMission = Schema.decodeSync(ResearchMission)({
3643
- request: `Shortlist one September culture city; keep ${missionConfidentialMarker} inside the coordinator conversation.`,
3644
- candidates: ["LHR", "CDG"]
3645
- });
3646
- const expectedDestinationShortlist = DestinationShortlist.make({
3647
- recommendations: researchMission.candidates.map((destination) => DestinationRecommendation.make({
3648
- destination,
3649
- summary: requireDestinationFacts(destination).advisory
3650
- })),
3651
- nextAction: "review"
3652
- });
3653
- const scriptedUsage$2 = {
3654
- inputTokens: { total: 96 },
3655
- outputTokens: { total: 64 }
3656
- };
3657
- /** One coordinator Turn that declares the given delegation Tool Calls in order. */
3658
- const coordinatorResearchTurn = (calls) => ({
3659
- _tag: "Stream",
3660
- parts: [...calls.map((call) => ({
3661
- type: "tool-call",
3662
- id: call.id,
3663
- name: "delegate_destination_research",
3664
- params: {
3665
- destination: call.destination,
3666
- focus: call.focus
3667
- }
3668
- })), {
3669
- type: "finish",
3670
- reason: "tool-calls",
3671
- usage: scriptedUsage$2
3672
- }],
3673
- termination: { _tag: "Complete" }
3674
- });
3675
- /** The coordinator's final structured-output Turn. */
3676
- const coordinatorShortlistTurn = (shortlist) => ({
3677
- _tag: "Stream",
3678
- parts: [
3679
- {
3680
- type: "text-start",
3681
- id: "shortlist"
3682
- },
3683
- {
3684
- type: "text-delta",
3685
- id: "shortlist",
3686
- delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist))
3687
- },
3688
- {
3689
- type: "text-end",
3690
- id: "shortlist"
3691
- },
3692
- {
3693
- type: "finish",
3694
- reason: "stop",
3695
- usage: scriptedUsage$2
3696
- }
3697
- ],
3698
- termination: { _tag: "Complete" }
3699
- });
3700
- /** Static researcher script for single-child tests: one guide lookup, then the report. */
3701
- const researcherHappyPathTurns = (destination) => [{
3702
- _tag: "Stream",
3703
- parts: [{
3704
- type: "tool-call",
3705
- id: `lookup-${destination}`,
3706
- name: "lookup_destination",
3707
- params: { destination }
3708
- }, {
3709
- type: "finish",
3710
- reason: "tool-calls",
3711
- usage: scriptedUsage$2
3712
- }],
3713
- termination: { _tag: "Complete" }
3714
- }, {
3715
- _tag: "Stream",
3716
- parts: [
3717
- {
3718
- type: "text-start",
3719
- id: "destination-report"
3720
- },
3721
- {
3722
- type: "text-delta",
3723
- id: "destination-report",
3724
- delta: encodedDestinationReport(destination)
3725
- },
3726
- {
3727
- type: "text-end",
3728
- id: "destination-report"
3729
- },
3730
- {
3731
- type: "finish",
3732
- reason: "stop",
3733
- usage: scriptedUsage$2
3734
- }
3735
- ],
3736
- termination: { _tag: "Complete" }
3737
- }];
3738
- const researcherLookupParts$2 = (destination) => [{
3739
- type: "tool-call",
3740
- id: `lookup-${destination}`,
3741
- name: "lookup_destination",
3742
- params: { destination },
3743
- providerExecuted: false
3744
- }, {
3745
- type: "finish",
3746
- reason: "tool-calls",
3747
- usage: scriptedUsage$2
3748
- }];
3749
- const researcherReportParts$2 = (destination) => [
3750
- {
3751
- type: "text-start",
3752
- id: "destination-report"
3753
- },
3754
- {
3755
- type: "text-delta",
3756
- id: "destination-report",
3757
- delta: encodedDestinationReport(destination)
3758
- },
3759
- {
3760
- type: "text-end",
3761
- id: "destination-report"
3762
- },
3763
- {
3764
- type: "finish",
3765
- reason: "stop",
3766
- usage: scriptedUsage$2
3767
- }
3768
- ];
3769
- /**
3770
- * Build a deterministic researcher Model whose per-child behavior is keyed by
3771
- * the destination named in the child's own prompt: Turn one records the
3772
- * prompt, signals `started`, and calls the guide Tool; Turn two waits for the
3773
- * caller's `release` before writing the report. Each child Run builds the
3774
- * Model Layer inside its own scope, so one `CatalogLifecycle` acquisition and
3775
- * finalization is observed per child — the same acquire/release counting the
3776
- * catalog Layers use to prove interruption reaches every finalizer.
3777
- */
3778
- const makeDestinationResearcherModel = (destinations) => Effect.gen(function* () {
3779
- const lifecycle = yield* CatalogLifecycle;
3780
- const prompts = yield* Ref.make([]);
3781
- const gates = /* @__PURE__ */ new Map();
3782
- for (const destination of destinations) gates.set(destination, {
3783
- started: yield* Deferred.make(),
3784
- release: yield* Deferred.make()
3785
- });
3786
- const gatesFor = (destination) => Effect.suspend(() => {
3787
- const entry = gates.get(destination);
3788
- return entry === void 0 ? Effect.die(/* @__PURE__ */ new Error(`No researcher gates exist for destination ${destination}`)) : Effect.succeed(entry);
3789
- });
3790
- return {
3791
- controls: {
3792
- awaitStarted: (destination) => gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.await(entry.started))),
3793
- release: (destination) => gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.succeed(entry.release, void 0)), Effect.asVoid),
3794
- prompts: Ref.get(prompts)
3795
- },
3796
- model: Model.make("scripted", "destination-researcher-scripted", Layer.effect(LanguageModel.LanguageModel, Effect.gen(function* () {
3797
- yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
3798
- const turn = yield* Ref.make(0);
3799
- return yield* LanguageModel.make({
3800
- generateText: () => Effect.succeed([]),
3801
- streamText: (options) => Stream.unwrap(Effect.gen(function* () {
3802
- const promptJson = JSON.stringify(options.prompt.content);
3803
- const destination = destinations.find((candidate) => promptJson.includes(candidate));
3804
- if (destination === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("The researcher prompt names no scripted destination"));
3805
- const entry = yield* gatesFor(destination);
3806
- if ((yield* Ref.getAndUpdate(turn, (value) => value + 1)) === 0) {
3807
- yield* Ref.update(prompts, (previous) => [...previous, promptJson]);
3808
- yield* Deferred.succeed(entry.started, void 0);
3809
- return Stream.fromIterable(researcherLookupParts$2(destination));
3810
- }
3811
- yield* Deferred.await(entry.release);
3812
- return Stream.fromIterable(researcherReportParts$2(destination));
3813
- }))
3814
- });
3815
- })))
3816
- };
3817
- });
3818
- //#endregion
3819
- //#region src/fixtures/travel-planner/subagents-durable.ts
3820
- var TravelPlannerSubagentDurabilityProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerSubagentDurabilityProfile")({
3821
- deploymentClass: Schema.Literal("DN"),
3822
- durableAttachedSubagents: Schema.Literal(true),
3823
- canonicalSchemaVersion: Schema.Literal(1),
3824
- /** Establishment/join replay converges on one child Receipt, Conversation, and join batch. */
3825
- subagentReplaySafe: Schema.Literal(true),
3826
- /** Never claimed (rule 8): child ordinary Tools stop at Unknown Outcomes, they do not replay. */
3827
- childExternalEffectsExactlyOnce: Schema.Literal(false),
3828
- /** The same conformance suite under DO eviction/alarms is P6 scope (spec §17 `DC`). */
3829
- cloudflareEquivalence: Schema.Literal(false)
3830
- }) {};
3831
- const s2TravelPlannerProfile = TravelPlannerSubagentDurabilityProfile.make({
3832
- deploymentClass: "DN",
3833
- durableAttachedSubagents: true,
3834
- canonicalSchemaVersion: 1,
3835
- subagentReplaySafe: true,
3836
- childExternalEffectsExactlyOnce: false,
3837
- cloudflareEquivalence: false
3838
- });
3839
- const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-s2-deployment");
3840
- const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-s2-producer");
3841
- const s2TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-s2-principal");
3842
- const digestOf$1 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
3843
- /** Redacted, deterministic parent (coordinator) definition digests for this fixture version. */
3844
- const s2CoordinatorDigests = DefinitionDigests.make({
3845
- agent: digestOf$1("a"),
3846
- model: digestOf$1("b"),
3847
- tools: digestOf$1("c")
3848
- });
3849
- /**
3850
- * The exact child Binding digest strings the application declares on
3851
- * `SubagentRuntimeOptions.durable.targetDigests` AND the host registers with
3852
- * the `AgentBindingResolver` for the researcher Binding. The coordinator
3853
- * stores and verifies them byte-for-byte (SUB-023); a host registration under
3854
- * different strings is a `ChildCompatibilityFailure`, never a substitution.
3855
- */
3856
- const s2ResearcherDigestStrings = {
3857
- agent: "d".repeat(64),
3858
- model: "e".repeat(64),
3859
- tools: "f".repeat(64)
3860
- };
3861
- const s2ResearcherDigests = DefinitionDigests.make({
3862
- agent: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.agent),
3863
- model: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.model),
3864
- tools: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.tools)
3865
- });
3866
- /** Durable admission options for one coordinator Submission on one mission lane. */
3867
- const s2TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
3868
- conversationId,
3869
- principal: s2TravelPlannerPrincipal,
3870
- idempotencyKey,
3871
- definitions: s2CoordinatorDigests
3872
- });
3873
- /** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */
3874
- const s2CoordinatorSubmitAgent = { definition: {
3875
- id: TravelCoordinator.id,
3876
- input: TravelCoordinator.input
3877
- } };
3878
- /**
3879
- * The per-invocation reservation the durable handler computes from the S1
3880
- * delegation policy (`delegationAllocationFromPolicy`): the conservation
3881
- * evidence in the S2 tests checks the ledger reservation rows and the
3882
- * canonical `SubagentJoined.finalAccounting` against exactly this value.
3883
- */
3884
- const durableResearchAllocation = delegationAllocationFromPolicy(destinationResearchPolicy);
3885
- /** The one scripted delegation Tool Call id of the durable coordinator Run. */
3886
- const durableResearchCallId = "research-lhr-1";
3887
- /** The child's own scripted guide-lookup Tool Call id. */
3888
- const durableChildLookupCallId = (destination) => `lookup-${destination}`;
3889
- /** The projected finding the parent joins (only the advisory crosses, SUB-015). */
3890
- const durableResearchFinding = (destination) => ({
3891
- destination: destinationReportFor(destination).destination,
3892
- summary: destinationReportFor(destination).advisory
3893
- });
3894
- /** The coordinator's expected final shortlist for one researched destination. */
3895
- const durableResearchShortlist = (destination) => DestinationShortlist.make({
3896
- recommendations: [DestinationRecommendation.make({
3897
- destination: destinationReportFor(destination).destination,
3898
- summary: destinationReportFor(destination).advisory
3899
- })],
3900
- nextAction: "review"
3901
- });
3902
- /**
3903
- * The deterministic guide facts in encoded (wire) form: the "supplier truth"
3904
- * an authorized operator records through `resolveUnknown` when a child guide
3905
- * lookup stopped at an Unknown Outcome (DUR-017 — the framework never guesses
3906
- * or replays it).
3907
- */
3908
- const encodedDestinationFacts = (destination) => {
3909
- const report = destinationReportFor(destination);
3910
- return Schema.encodeSync(DestinationFacts)(DestinationFacts.make({
3911
- destination: report.destination,
3912
- highlights: report.highlights,
3913
- advisory: report.advisory
3914
- }));
3915
- };
3916
- const scriptedUsage$1 = {
3917
- inputTokens: { total: 96 },
3918
- outputTokens: { total: 64 }
3919
- };
3920
- /** One scripted model whose behavior is keyed by the global invocation index. */
3921
- const makeInvocationCountingModel = (name, script) => Effect.gen(function* () {
3922
- const calls = yield* Ref.make(0);
3923
- const prompts = yield* Ref.make([]);
3924
- return {
3925
- model: Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
3926
- generateText: () => Effect.succeed([]),
3927
- streamText: (request) => Stream.unwrap(Effect.gen(function* () {
3928
- const call = yield* Ref.getAndUpdate(calls, (value) => value + 1);
3929
- yield* Ref.update(prompts, (previous) => [...previous, JSON.stringify(request.prompt.content)]);
3930
- return Stream.fromIterable(script(call));
3931
- }))
3932
- }))),
3933
- calls: Ref.get(calls),
3934
- prompts: Ref.get(prompts)
3935
- };
3936
- });
3937
- const delegationTurnParts = (toolCallId, destination, focus) => [{
3938
- type: "tool-call",
3939
- id: toolCallId,
3940
- name: "delegate_destination_research",
3941
- params: {
3942
- destination,
3943
- focus
3944
- },
3945
- providerExecuted: false
3946
- }, {
3947
- type: "finish",
3948
- reason: "tool-calls",
3949
- usage: scriptedUsage$1
3950
- }];
3951
- const shortlistParts = (shortlist) => [
3952
- {
3953
- type: "text-start",
3954
- id: "shortlist"
3955
- },
3956
- {
3957
- type: "text-delta",
3958
- id: "shortlist",
3959
- delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist))
3960
- },
3961
- {
3962
- type: "text-end",
3963
- id: "shortlist"
3964
- },
3965
- {
3966
- type: "finish",
3967
- reason: "stop",
3968
- usage: scriptedUsage$1
3969
- }
3970
- ];
3971
- const researcherLookupParts$1 = (destination) => [{
3972
- type: "tool-call",
3973
- id: durableChildLookupCallId(destination),
3974
- name: "lookup_destination",
3975
- params: { destination },
3976
- providerExecuted: false
3977
- }, {
3978
- type: "finish",
3979
- reason: "tool-calls",
3980
- usage: scriptedUsage$1
3981
- }];
3982
- const researcherReportParts$1 = (destination) => [
3983
- {
3984
- type: "text-start",
3985
- id: "destination-report"
3986
- },
3987
- {
3988
- type: "text-delta",
3989
- id: "destination-report",
3990
- delta: encodedDestinationReport(destination)
3991
- },
3992
- {
3993
- type: "text-end",
3994
- id: "destination-report"
3995
- },
3996
- {
3997
- type: "finish",
3998
- reason: "stop",
3999
- usage: scriptedUsage$1
4000
- }
4001
- ];
4002
- /** Runtime wiring for the durable slice: the S1 delegation plus the S2 digest declaration. */
4003
- const durableDestinationResearchHandlersLayer = (childBinding) => SubagentRuntime.layer(destinationResearchDelegation, childBinding, {
4004
- mapChildFailure: mapResearchChildFailure,
4005
- durable: { targetDigests: s2ResearcherDigestStrings }
4006
- });
4007
- /**
4008
- * Build the S2 Travel Planner harness: an invocation-counting scripted
4009
- * coordinator (Turn 1 declares the one delegation call, Turn 2 writes the
4010
- * shortlist), an invocation-counting scripted researcher (Turn 1 consults the
4011
- * guide, Turn 2 writes the report), and both worker Bindings captured with
4012
- * their requirement Contexts via `DurableWorkerBinding.make` under the exact
4013
- * fixture digests. The returned `bindings` are plain values: they can be
4014
- * registered with several `NodeDurableRuntime` stacks over the same SQLite
4015
- * file while the counters keep counting across all of them.
4016
- */
4017
- const makeDurableResearchHarness = (options) => Effect.gen(function* () {
4018
- const destination = options?.destination ?? "LHR";
4019
- const focus = options?.focus ?? "museums";
4020
- const guideInvocations = yield* Ref.make(0);
4021
- const guideLayer = Layer.succeed(DestinationGuide, DestinationGuide.of({ lookup: (query) => Ref.update(guideInvocations, (count) => count + 1).pipe(Effect.andThen(destinationLookup(query))) }));
4022
- const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(Layer.provideMerge(guideLayer));
4023
- const childModel = yield* makeInvocationCountingModel("destination-researcher-s2", (call) => call === 0 ? researcherLookupParts$1(destination) : researcherReportParts$1(destination));
4024
- const childBinding = Agent.withModel(DestinationResearcher, childModel.model);
4025
- const parentModel = yield* makeInvocationCountingModel("travel-coordinator-s2", (call) => call === 0 ? delegationTurnParts(durableResearchCallId, destination, focus) : shortlistParts(durableResearchShortlist(destination)));
4026
- const parentBinding = Agent.withModel(TravelCoordinator, parentModel.model);
4027
- const delegationLayer = durableDestinationResearchHandlersLayer(childBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer, ResearchDispatchGate.layerOpen)));
4028
- return {
4029
- bindings: [yield* DurableWorkerBinding.make(parentBinding, s2CoordinatorDigests).pipe(Effect.provide(delegationLayer)), yield* DurableWorkerBinding.make(childBinding, options?.childRegistrationDigests ?? s2ResearcherDigests).pipe(Effect.provide(childToolkitLayer))],
4030
- parentModelCalls: parentModel.calls,
4031
- parentPrompts: parentModel.prompts,
4032
- childModelCalls: childModel.calls,
4033
- childPrompts: childModel.prompts,
4034
- guideInvocations: Ref.get(guideInvocations)
4035
- };
4036
- });
4037
- //#endregion
4038
- //#region src/fixtures/travel-planner/phase6.ts
4039
- /**
4040
- * The Phase 6 profile: the P4/P5/S2 Travel Planner claims re-earned on the Cloudflare Durable
4041
- * Object runtime (deployment class `DC`), where eviction and alarm redelivery replace process
4042
- * kill and restart as the exercised recovery path. `cloudflareEquivalence` is the claim the S2
4043
- * fixture explicitly deferred to P6 (`TravelPlannerSubagentDurabilityProfile` pins it `false`
4044
- * for `DN`): it flips to `true` here ONLY because the phase-6 suites assert byte-equal
4045
- * cross-platform normalized canonical evidence against one committed golden. Exactly-once
4046
- * EXTERNAL effects remain — deliberately — unclaimed on every platform (DUR-003).
4047
- */
4048
- var TravelPlannerCloudflareProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerCloudflareProfile")({
4049
- deploymentClass: Schema.Literal("DC"),
4050
- durableAcceptedWork: Schema.Literal(true),
4051
- canonicalSchemaVersion: Schema.Literal(1),
4052
- /** P5 semantics under DC recovery: prepared/settled records, Unknown Outcomes, approvals. */
4053
- supplierBookingUncertaintyProtocol: Schema.Literal(true),
4054
- /** S2 semantics under DC recovery: cross-Object establishment/join, completed child never re-runs. */
4055
- durableAttachedSubagents: Schema.Literal(true),
4056
- /** DN and DC produce byte-equal cross-platform normalized canonical evidence (one golden). */
4057
- cloudflareEquivalence: Schema.Literal(true),
4058
- /** Never claimed at any phase on any platform (DUR-003). */
4059
- exactlyOnceExternalEffects: Schema.Literal(false)
4060
- }) {};
4061
- const phase6TravelPlannerProfile = TravelPlannerCloudflareProfile.make({
4062
- deploymentClass: "DC",
4063
- durableAcceptedWork: true,
4064
- canonicalSchemaVersion: 1,
4065
- supplierBookingUncertaintyProtocol: true,
4066
- durableAttachedSubagents: true,
4067
- cloudflareEquivalence: true,
4068
- exactlyOnceExternalEffects: false
4069
- });
4070
- const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p6-deployment");
4071
- /** Producer prefix of the DC host; each Object mints `{prefix}:{conversationId}`. */
4072
- const phase6TravelPlannerProducerPrefix = "travel-planner-p6-producer";
4073
- /** The full producer identity one DC Conversation Object mints for itself. */
4074
- const phase6TravelPlannerProducerId = (conversationId) => Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${conversationId}`);
4075
- const digestOf = (character) => Schema.decodeSync(Digest)(character.repeat(64));
4076
- /**
4077
- * Registration digests of the GATED planner Binding: the same `TravelPlannerPhase4` definition
4078
- * bound to a model whose first response waits on a test gate, addressable separately so the
4079
- * admission-limits rows can hold a lane busy deterministically without touching the ordinary
4080
- * planner registration.
4081
- */
4082
- const phase6GatedPlannerDefinitionDigests = DefinitionDigests.make({
4083
- agent: digestOf("9"),
4084
- model: digestOf("8"),
4085
- tools: digestOf("7")
4086
- });
4087
- const decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);
4088
- /** The base normal form's element shape, re-decoded so sequences can be renumbered. */
4089
- const ComparableEnvelope = Schema.Struct({
4090
- batchId: Schema.String,
4091
- sequence: Schema.Number,
4092
- record: Schema.Json
4093
- });
4094
- const decodeComparableEnvelopes = Schema.decodeUnknownEffect(Schema.Array(ComparableEnvelope));
4095
- /**
4096
- * The CROSS-PLATFORM extension of `normalizeDurableTravelPlannerEvidence` (D-P6-6): after the
4097
- * base normalization replaces the two ledger-minted identities (which also normalizes the
4098
- * DC-format routable `{uuidv7}:{conversationId}` Submission identities and everything derived
4099
- * from them), this form additionally scrubs everything that legitimately differs between a DN
4100
- * process and a DC Durable Object over the same scenario:
4101
- *
4102
- * - `RepairAnnotated` audit records are dropped BEFORE normalization and the canonical
4103
- * sequence is renumbered to the surviving order: repairs are DUR-013 evidence of recovery
4104
- * itself, legally present in a recovered run and legally absent from an uninterrupted
4105
- * control (on DC even a CLEAN run carries one, because every pass reconciles before it
4106
- * claims, so the ready lane's input is applied through the recovery path). Canonical ORDER
4107
- * is the durability §5 claim; sequence contiguity is a platform artifact of who appended;
4108
- * - the Conversation identity (DC lanes mint unique names per test run);
4109
- * - the deployment and producer identities (host configuration, not canonical semantics);
4110
- * - `createdAt` commit timestamps (wall clock);
4111
- * - 64-hex digests (they hash RAW content that legally embeds run-specific identity, so they
4112
- * can never be byte-equal across runs; chain integrity is asserted separately by the
4113
- * adapters and the convergence helpers).
4114
- *
4115
- * Two runs whose cross-platform normalized evidence is byte-equal took canonically equivalent
4116
- * histories — the exact sense in which durability §5 permits storage differences while
4117
- * requiring the same observable ordering. Both the DN and DC suites assert equality against
4118
- * the one committed `phase6TravelPlannerGoldenEvidence`, so DN ≡ DC transitively.
4119
- */
4120
- const normalizeCrossPlatformTravelPlannerEvidence = Effect.fn("TravelPlannerPhase6.normalizeCrossPlatformTravelPlannerEvidence")(function* (records, receipt, identity) {
4121
- const base = yield* normalizeDurableTravelPlannerEvidence(records.filter((envelope) => envelope.record.payload._tag !== "RepairAnnotated"), receipt);
4122
- const scrubbed = JSON.parse(JSON.stringify(base).replaceAll(identity.producerId, "{producerId}").replaceAll(identity.deploymentId, "{deploymentId}").replaceAll(identity.conversationId, "{conversationId}").replaceAll(/\d{4}-\d{2}-\d{2}T[0-9:.]+Z/g, "{timestamp}").replaceAll(/"[0-9a-f]{64}"/g, "\"{digest}\""));
4123
- const renumbered = (yield* decodeComparableEnvelopes(scrubbed).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Cross-platform normalized evidence lost the comparable shape: ${error.message}` })))).map((entry, index) => ({
4124
- batchId: entry.batchId,
4125
- sequence: index + 1,
4126
- record: entry.record
4127
- }));
4128
- return yield* decodeComparableJson(renumbered).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Cross-platform normalized evidence is not comparable JSON: ${error.message}` })));
4129
- });
4130
- const scriptedUsage = {
4131
- inputTokens: { total: 128 },
4132
- outputTokens: { total: 96 }
4133
- };
4134
- const promptAwareModel = (name, decide) => Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
4135
- generateText: () => Effect.succeed([]),
4136
- streamText: (options) => Stream.unwrap(Effect.sync(() => decide(JSON.stringify(options.prompt))))
4137
- })));
4138
- /** The P1/P4 happy-path Tool Call identities (scenarios.ts, byte-stable since P1). */
4139
- const phase6FlightCallId = "flight-call-1";
4140
- const phase6LodgingCallId = "lodging-call-1";
4141
- const phase6ActivityCallId = "activity-call-1";
4142
- /** Turn 1 of the planner: the SAME three search declarations as `phase1HappyPathTurns`. */
4143
- const plannerSearchTurnParts = [
4144
- {
4145
- type: "tool-call",
4146
- id: phase6FlightCallId,
4147
- name: "search_flights",
4148
- params: {
4149
- origin: "SFO",
4150
- destination: "LHR",
4151
- departOn: "2026-09-14",
4152
- travelers: 2
4153
- }
4154
- },
4155
- {
4156
- type: "tool-call",
4157
- id: phase6LodgingCallId,
4158
- name: "search_lodging",
4159
- params: {
4160
- destination: "LHR",
4161
- departOn: "2026-09-14",
4162
- nights: 4,
4163
- travelers: 2
4164
- }
4165
- },
4166
- {
4167
- type: "tool-call",
4168
- id: phase6ActivityCallId,
4169
- name: "search_activities",
4170
- params: {
4171
- destination: "LHR",
4172
- departOn: "2026-09-14",
4173
- nights: 4,
4174
- travelers: 2
4175
- }
4176
- },
4177
- {
4178
- type: "finish",
4179
- reason: "tool-calls",
4180
- usage: scriptedUsage
4181
- }
4182
- ];
4183
- /** Turn 2 of the planner: the SAME itinerary text as `phase1HappyPathTurns`. */
4184
- const plannerPlanTurnParts = [
4185
- {
4186
- type: "text-start",
4187
- id: "itinerary-json"
4188
- },
4189
- {
4190
- type: "text-delta",
4191
- id: "itinerary-json",
4192
- delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan))
4193
- },
4194
- {
4195
- type: "text-end",
4196
- id: "itinerary-json"
4197
- },
4198
- {
4199
- type: "finish",
4200
- reason: "stop",
4201
- usage: scriptedUsage
4202
- }
4203
- ];
4204
- const plannerDecide = (promptJson) => promptJson.includes("flight-call-1") ? Stream.fromIterable(plannerPlanTurnParts) : Stream.fromIterable(plannerSearchTurnParts);
4205
- /**
4206
- * The P4 planner script (`phase1HappyPathTurns`) as a prompt-aware model: once the search
4207
- * batch is committed history, every later request gets the plan — identical parts, so the DC
4208
- * canonical evidence is byte-equivalent to the DN ScriptedModel run after normalization.
4209
- */
4210
- const phase6PlannerModel = promptAwareModel("travel-planner-phase-4", plannerDecide);
4211
- const releasedPlannerGates = /* @__PURE__ */ new Set();
4212
- /** Release the gated planner model for one `[gate:...]` marker. */
4213
- const releasePhase6PlannerGate = (marker) => {
4214
- releasedPlannerGates.add(marker);
4215
- };
4216
- /** Re-close one gate marker (fresh suites reuse markers safely). */
4217
- const resetPhase6PlannerGate = (marker) => {
4218
- releasedPlannerGates.delete(marker);
4219
- };
4220
- const awaitPlannerGate = (marker) => Effect.gen(function* () {
4221
- while (!releasedPlannerGates.has(marker)) yield* Effect.sleep(Duration.millis(10));
4222
- });
4223
- const gateMarkerFromPrompt = (promptJson) => /\[gate:([^\]]+)\]/.exec(promptJson)?.[1] ?? "unknown-gate";
4224
- /** A trip whose request text carries the gate marker the gated model waits on. */
4225
- const phase6GatedTrip = (marker) => Schema.decodeUnknownSync(TripRequest)({
4226
- request: `Plan a review-only London trip, but wait for the concierge. [gate:${marker}]`,
4227
- origin: "SFO",
4228
- destination: "LHR",
4229
- departOn: "2026-09-14",
4230
- nights: 4,
4231
- travelers: 2,
4232
- budgetCents: 35e4,
4233
- currency: "USD"
4234
- });
4235
- /**
4236
- * The SAME planner behavior with a hanging first response: the model waits on the released
4237
- * gate before answering, keeping its lane durably busy so queue-depth admission limits can be
4238
- * exercised deterministically.
4239
- */
4240
- const phase6GatedPlannerModel = Model.make("scripted", "travel-planner-phase-4-gated", Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
4241
- generateText: () => Effect.succeed([]),
4242
- streamText: (options) => Stream.unwrap(Effect.sync(() => {
4243
- const promptJson = JSON.stringify(options.prompt);
4244
- return promptJson.includes("flight-call-1") ? plannerDecide(promptJson) : Stream.fromEffectDrain(awaitPlannerGate(gateMarkerFromPrompt(promptJson))).pipe(Stream.concat(plannerDecide(promptJson)));
4245
- }))
4246
- })));
4247
- const sharedSupplierDesk = Effect.runSync(Effect.flatMap(SupplierBookingDesk, Effect.succeed).pipe(Effect.provide(SupplierBookingDesk.layer)));
4248
- /** The shared external supplier desk instance (module-level external truth). */
4249
- const phase6SupplierDesk = sharedSupplierDesk;
4250
- /** Layer handing the shared desk to Bindings, reconcilers, and assertions. */
4251
- const phase6SupplierDeskLayer = Layer.succeed(SupplierBookingDesk, sharedSupplierDesk);
4252
- /**
4253
- * The REAL P5 supplier reconciliation policy over the shared desk, closed to no requirements
4254
- * so a Conversation Object can install it directly: `book_flight` recovers only from supplier
4255
- * truth (absence stays fail-closed `Uncertain` → durable Unknown Outcome), keyed Steps are
4256
- * provably re-enterable.
4257
- */
4258
- const phase6SupplierReconcilerLayer = TravelSupplierReconcilerLayer.pipe(Layer.provide(phase6SupplierDeskLayer));
4259
- const bookingMarkerFromPrompt = (promptJson) => /\[case:([^\]]+)\]/.exec(promptJson)?.[1] ?? "unknown-case";
4260
- /** The deterministic booking Tool Call identity for one `[case:...]` marker. */
4261
- const phase6BookingToolCallId = (marker) => `book-${marker}`;
4262
- /** The bookingRef the supplier desk mints for one marker's approved booking. */
4263
- const phase6BookingRef = (marker) => supplierBookingRefFor(bookFlightIdempotencyKey(phase6BookingToolCallId(marker)));
4264
- /** A trip whose request text carries the per-lane booking case marker. */
4265
- const phase6BookingTrip = (marker) => Schema.decodeUnknownSync(TripRequest)({
4266
- request: `Book the approved London flight for the traveler. [case:${marker}]`,
4267
- origin: "SFO",
4268
- destination: "LHR",
4269
- departOn: "2026-09-14",
4270
- nights: 4,
4271
- travelers: 2,
4272
- budgetCents: 35e4,
4273
- currency: "USD"
4274
- });
4275
- const bookingCallParts = (marker) => [{
4276
- type: "tool-call",
4277
- id: phase6BookingToolCallId(marker),
4278
- name: "book_flight",
4279
- params: {
4280
- quoteId: "quote-sfo-lhr-001",
4281
- travelerRef: `traveler-${marker}`,
4282
- departOn: "2026-09-14"
4283
- },
4284
- providerExecuted: false
4285
- }, {
4286
- type: "finish",
4287
- reason: "tool-calls",
4288
- usage: scriptedUsage
4289
- }];
4290
- const bookingReportParts = (marker) => [
4291
- {
4292
- type: "text-start",
4293
- id: "booking-report"
4294
- },
4295
- {
4296
- type: "text-delta",
4297
- id: "booking-report",
4298
- delta: JSON.stringify({
4299
- summary: "trip booked",
4300
- bookingRefs: [phase6BookingRef(marker)]
4301
- })
4302
- },
4303
- {
4304
- type: "text-end",
4305
- id: "booking-report"
4306
- },
4307
- {
4308
- type: "finish",
4309
- reason: "stop",
4310
- usage: scriptedUsage
4311
- }
4312
- ];
4313
- /**
4314
- * The P5 booking script as a prompt-aware model: request 1 declares the approval-gated
4315
- * `book_flight` call (identity derived from the lane's `[case:...]` marker so supplier
4316
- * idempotency keys never collide across lanes); once that call is committed history, the model
4317
- * writes the booking report.
4318
- */
4319
- const phase6BookingModel = promptAwareModel("travel-planner-phase-5", (promptJson) => {
4320
- const marker = bookingMarkerFromPrompt(promptJson);
4321
- return promptJson.includes(phase6BookingToolCallId(marker)) ? Stream.fromIterable(bookingReportParts(marker)) : Stream.fromIterable(bookingCallParts(marker));
4322
- });
4323
- let guideInvocations = 0;
4324
- /** Deterministic guide-lookup handler executions across every incarnation. */
4325
- const phase6GuideInvocationCount = () => guideInvocations;
4326
- const countingGuideLayer = Layer.succeed(DestinationGuide, DestinationGuide.of({ lookup: (query) => Effect.suspend(() => {
4327
- guideInvocations += 1;
4328
- return destinationLookup(query);
4329
- }) }));
4330
- /** The one-candidate research mission of the DC delegation slice. */
4331
- const phase6ResearchMission = Schema.decodeUnknownSync(ResearchMission)({
4332
- request: "Shortlist one September culture city for the DC delegation slice.",
4333
- candidates: ["LHR"]
4334
- });
4335
- const phase6ResearchDestination = "LHR";
4336
- /** The child's scripted guide-lookup Tool Call identity. */
4337
- const phase6ChildLookupCallId = `lookup-LHR`;
4338
- const coordinatorDelegationParts = [{
4339
- type: "tool-call",
4340
- id: durableResearchCallId,
4341
- name: "delegate_destination_research",
4342
- params: {
4343
- destination: "LHR",
4344
- focus: "museums"
4345
- },
4346
- providerExecuted: false
4347
- }, {
4348
- type: "finish",
4349
- reason: "tool-calls",
4350
- usage: scriptedUsage
4351
- }];
4352
- const coordinatorShortlistParts = [
4353
- {
4354
- type: "text-start",
4355
- id: "shortlist"
4356
- },
4357
- {
4358
- type: "text-delta",
4359
- id: "shortlist",
4360
- delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(durableResearchShortlist("LHR")))
4361
- },
4362
- {
4363
- type: "text-end",
4364
- id: "shortlist"
4365
- },
4366
- {
4367
- type: "finish",
4368
- reason: "stop",
4369
- usage: scriptedUsage
4370
- }
4371
- ];
4372
- const researcherLookupParts = [{
4373
- type: "tool-call",
4374
- id: phase6ChildLookupCallId,
4375
- name: "lookup_destination",
4376
- params: { destination: "LHR" },
4377
- providerExecuted: false
4378
- }, {
4379
- type: "finish",
4380
- reason: "tool-calls",
4381
- usage: scriptedUsage
4382
- }];
4383
- const researcherReportParts = [
4384
- {
4385
- type: "text-start",
4386
- id: "destination-report"
4387
- },
4388
- {
4389
- type: "text-delta",
4390
- id: "destination-report",
4391
- delta: encodedDestinationReport("LHR")
4392
- },
4393
- {
4394
- type: "text-end",
4395
- id: "destination-report"
4396
- },
4397
- {
4398
- type: "finish",
4399
- reason: "stop",
4400
- usage: scriptedUsage
4401
- }
4402
- ];
4403
- /** Prompt-aware S2 coordinator: delegation call first, shortlist once it is history. */
4404
- const phase6CoordinatorModel = promptAwareModel("travel-coordinator-p6", (promptJson) => promptJson.includes("research-lhr-1") ? Stream.fromIterable(coordinatorShortlistParts) : Stream.fromIterable(coordinatorDelegationParts));
4405
- let researcherGateReleased = false;
4406
- /** Allow the researcher's FIRST model response to proceed (sticky across incarnations). */
4407
- const releasePhase6ResearcherGate = () => {
4408
- researcherGateReleased = true;
4409
- };
4410
- /** Re-close the researcher gate (each delegation scenario starts gated). */
4411
- const resetPhase6ResearcherGate = () => {
4412
- researcherGateReleased = false;
4413
- };
4414
- const awaitResearcherGate = Effect.gen(function* () {
4415
- while (!researcherGateReleased) yield* Effect.sleep(Duration.millis(10));
4416
- });
4417
- /**
4418
- * Prompt-aware S2 researcher: guide lookup first, report once it is history. The FIRST
4419
- * response waits on the researcher gate — a stand-in for real model latency. The child's own
4420
- * Object may legally start its Attempt the moment its routed admission commits, while the
4421
- * parent is still appending the lineage record into the child's log; a child whose first
4422
- * batch commits during that window races the parent's append on one tail. Real models answer
4423
- * in seconds, so establishment always wins that race in production; the gate reproduces that
4424
- * timing deterministically instead of relying on scheduler luck.
4425
- */
4426
- const phase6ResearcherModel = promptAwareModel("destination-researcher-p6", (promptJson) => promptJson.includes(phase6ChildLookupCallId) ? Stream.fromIterable(researcherReportParts) : Stream.fromEffectDrain(awaitResearcherGate).pipe(Stream.concat(Stream.fromIterable(researcherLookupParts))));
4427
- /**
4428
- * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts
4429
- * (spec/subagents.md §11): the P4 planner and its gated twin, the P5 booking agent over the
4430
- * shared supplier desk, and the S2 coordinator/researcher pair wired through the durable
4431
- * delegation Layer. A Conversation Object registers these via its `bindings` option; the
4432
- * capture runs once per incarnation, and everything stateful the assertions rely on (desk,
4433
- * guide counter, gates) lives at module level so it survives incarnation loss.
4434
- */
4435
- const makePhase6TravelPlannerBindings = Effect.gen(function* () {
4436
- const planner = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase4, phase6PlannerModel), phase4TravelPlannerDefinitionDigests).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));
4437
- const gatedPlanner = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase4, phase6GatedPlannerModel), phase6GatedPlannerDefinitionDigests).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));
4438
- const booking = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase5, phase6BookingModel), phase5TravelPlannerDefinitionDigests).pipe(Effect.provide(phase5TravelPlannerWorkerLayer.pipe(Layer.provideMerge(phase6SupplierDeskLayer))));
4439
- const researcherBinding = Agent.withModel(DestinationResearcher, phase6ResearcherModel);
4440
- const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(Layer.provideMerge(countingGuideLayer));
4441
- return [
4442
- planner,
4443
- gatedPlanner,
4444
- booking,
4445
- yield* DurableWorkerBinding.make(Agent.withModel(TravelCoordinator, phase6CoordinatorModel), s2CoordinatorDigests).pipe(Effect.provide(durableDestinationResearchHandlersLayer(researcherBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer, ResearchDispatchGate.layerOpen))))),
4446
- yield* DurableWorkerBinding.make(researcherBinding, s2ResearcherDigests).pipe(Effect.provide(childToolkitLayer))
4447
- ];
4448
- });
4449
- /**
4450
- * The committed cross-platform normalized canonical evidence of ONE uninterrupted Travel
4451
- * Planner planning Submission (the P1/P4 happy path: canonical input, the search Turn, three
4452
- * Tool settlements, the plan Turn, one Settlement). `travel-planner-phase6.test.ts` asserts
4453
- * the DN run equals this value and `travel-planner-dc.test.ts` asserts the DC run equals this
4454
- * value, so the two platforms' canonical outcomes are byte-equivalent transitively — the P6
4455
- * exit gate "Travel Planner produces equivalent canonical outcomes under DN and DC".
4456
- *
4457
- * Regenerate ONLY when the Travel Planner scenario itself changes, by printing either suite's
4458
- * normalized value; both suites must then agree on the new golden.
4459
- */
4460
- const phase6TravelPlannerGoldenEvidence = [
4461
- {
4462
- batchId: "conversation-created:{conversationId}",
4463
- sequence: 1,
4464
- record: {
4465
- recordId: "conversation-created:{conversationId}",
4466
- family: "conversation",
4467
- schemaVersion: 1,
4468
- createdAt: "{timestamp}",
4469
- deploymentId: "{deploymentId}",
4470
- payload: {
4471
- _tag: "ConversationCreated",
4472
- agentId: "travel-planner-phase-4",
4473
- definitions: {
4474
- agent: "{digest}",
4475
- model: "{digest}",
4476
- tools: "{digest}"
4477
- }
4478
- }
4479
- }
4480
- },
4481
- {
4482
- batchId: "submission-input:{submissionId}",
4483
- sequence: 2,
4484
- record: {
4485
- recordId: "input:{submissionId}",
4486
- family: "conversation",
4487
- schemaVersion: 1,
4488
- createdAt: "{timestamp}",
4489
- deploymentId: "{deploymentId}",
4490
- payload: {
4491
- _tag: "UserInputRecorded",
4492
- submissionId: "{submissionId}",
4493
- kind: "user",
4494
- runId: "run:{submissionId}",
4495
- input: {
4496
- request: "Plan a review-only London trip using the deterministic flight, lodging, and activity searches.",
4497
- origin: "SFO",
4498
- destination: "LHR",
4499
- departOn: "2026-09-14",
4500
- nights: 4,
4501
- travelers: 2,
4502
- budgetCents: 35e4,
4503
- currency: "USD"
4504
- }
4505
- }
4506
- }
4507
- },
4508
- {
4509
- batchId: "turn-response:run:{submissionId}:1",
4510
- sequence: 3,
4511
- record: {
4512
- recordId: "model-response:run:{submissionId}:1",
4513
- family: "conversation",
4514
- schemaVersion: 1,
4515
- createdAt: "{timestamp}",
4516
- deploymentId: "{deploymentId}",
4517
- payload: {
4518
- _tag: "ModelResponseRecorded",
4519
- runId: "run:{submissionId}",
4520
- turnId: "turn:run:{submissionId}:1",
4521
- turn: 1,
4522
- messages: { content: [
4523
- {
4524
- options: {},
4525
- role: "system",
4526
- content: "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."
4527
- },
4528
- {
4529
- options: {},
4530
- role: "user",
4531
- content: "{\"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\"}"
4532
- },
4533
- {
4534
- options: {},
4535
- role: "assistant",
4536
- content: [
4537
- {
4538
- options: {},
4539
- type: "tool-call",
4540
- id: "flight-call-1",
4541
- name: "search_flights",
4542
- params: {
4543
- origin: "SFO",
4544
- destination: "LHR",
4545
- departOn: "2026-09-14",
4546
- travelers: 2
4547
- },
4548
- providerExecuted: false
4549
- },
4550
- {
4551
- options: {},
4552
- type: "tool-call",
4553
- id: "lodging-call-1",
4554
- name: "search_lodging",
4555
- params: {
4556
- destination: "LHR",
4557
- departOn: "2026-09-14",
4558
- nights: 4,
4559
- travelers: 2
4560
- },
4561
- providerExecuted: false
4562
- },
4563
- {
4564
- options: {},
4565
- type: "tool-call",
4566
- id: "activity-call-1",
4567
- name: "search_activities",
4568
- params: {
4569
- destination: "LHR",
4570
- departOn: "2026-09-14",
4571
- nights: 4,
4572
- travelers: 2
4573
- },
4574
- providerExecuted: false
4575
- }
4576
- ]
4577
- }
4578
- ] },
4579
- messagesDigest: "{digest}"
4580
- }
4581
- }
4582
- },
4583
- {
4584
- batchId: "turn-results:run:{submissionId}:1",
4585
- sequence: 4,
4586
- record: {
4587
- recordId: "tool-settled:run:{submissionId}:1:flight-call-1",
4588
- family: "conversation",
4589
- schemaVersion: 1,
4590
- createdAt: "{timestamp}",
4591
- deploymentId: "{deploymentId}",
4592
- payload: {
4593
- _tag: "ToolCallSettled",
4594
- runId: "run:{submissionId}",
4595
- toolCallId: "flight-call-1",
4596
- toolName: "search_flights",
4597
- result: {
4598
- quoteId: "quote-sfo-lhr-001",
4599
- flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
4600
- estimatedCents: 18e4,
4601
- currency: "USD"
4602
- },
4603
- isFailure: false
4604
- }
4605
- }
4606
- },
4607
- {
4608
- batchId: "turn-results:run:{submissionId}:1",
4609
- sequence: 5,
4610
- record: {
4611
- recordId: "tool-settled:run:{submissionId}:1:lodging-call-1",
4612
- family: "conversation",
4613
- schemaVersion: 1,
4614
- createdAt: "{timestamp}",
4615
- deploymentId: "{deploymentId}",
4616
- payload: {
4617
- _tag: "ToolCallSettled",
4618
- runId: "run:{submissionId}",
4619
- toolCallId: "lodging-call-1",
4620
- toolName: "search_lodging",
4621
- result: {
4622
- lodging: "Bloomsbury House · refundable studio · 4 nights",
4623
- estimatedCents: 104e3,
4624
- currency: "USD"
4625
- },
4626
- isFailure: false
4627
- }
4628
- }
4629
- },
4630
- {
4631
- batchId: "turn-results:run:{submissionId}:1",
4632
- sequence: 6,
4633
- record: {
4634
- recordId: "tool-settled:run:{submissionId}:1:activity-call-1",
4635
- family: "conversation",
4636
- schemaVersion: 1,
4637
- createdAt: "{timestamp}",
4638
- deploymentId: "{deploymentId}",
4639
- payload: {
4640
- _tag: "ToolCallSettled",
4641
- runId: "run:{submissionId}",
4642
- toolCallId: "activity-call-1",
4643
- toolName: "search_activities",
4644
- result: { activities: ["British Museum timed entry", "Thames evening walk"] },
4645
- isFailure: false
4646
- }
4647
- }
4648
- },
4649
- {
4650
- batchId: "turn:run:{submissionId}:2",
4651
- sequence: 7,
4652
- record: {
4653
- recordId: "model-response:run:{submissionId}:2",
4654
- family: "conversation",
4655
- schemaVersion: 1,
4656
- createdAt: "{timestamp}",
4657
- deploymentId: "{deploymentId}",
4658
- payload: {
4659
- _tag: "ModelResponseRecorded",
4660
- runId: "run:{submissionId}",
4661
- turnId: "turn:run:{submissionId}:2",
4662
- turn: 2,
4663
- messages: { content: [{
4664
- options: {},
4665
- role: "assistant",
4666
- content: "{\"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\"}]}"
4667
- }] },
4668
- messagesDigest: "{digest}"
4669
- }
4670
- }
4671
- },
4672
- {
4673
- batchId: "submission-settlement:{submissionId}",
4674
- sequence: 8,
4675
- record: {
4676
- recordId: "settlement:{submissionId}",
4677
- family: "conversation",
4678
- schemaVersion: 1,
4679
- createdAt: "{timestamp}",
4680
- deploymentId: "{deploymentId}",
4681
- payload: {
4682
- _tag: "SubmissionSettled",
4683
- submissionId: "{submissionId}",
4684
- settlementId: "settlement:{submissionId}",
4685
- receiptId: "{receiptId}",
4686
- outcome: "completed",
4687
- runId: "run:{submissionId}",
4688
- result: { itineraries: [{
4689
- title: "Westward light, eastbound overnight",
4690
- route: "San Francisco → London",
4691
- dates: "14–19 September 2026",
4692
- flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
4693
- lodging: "Bloomsbury House · refundable studio · 4 nights",
4694
- activities: ["British Museum timed entry", "Thames evening walk"],
4695
- estimatedTotalCents: 284e3,
4696
- currency: "USD",
4697
- quoteId: "quote-sfo-lhr-001",
4698
- assumptions: ["Two travelers sharing one studio", "Quote is read-only availability, not a reservation"],
4699
- unresolvedConstraints: ["Traveler names and accessibility requests are intentionally omitted"],
4700
- nextAction: "review"
4701
- }] }
4702
- }
4703
- }
4704
- }
4705
- ];
4706
- //#endregion
4707
- //#region src/fixtures/travel-planner/phase7.ts
4708
- /**
4709
- * The P7 dual-profile claim, schema-first so the exact scope of "live
4710
- * integration profiles" is a committed, decodable value:
4711
- *
4712
- * - `offlineConformanceDeterministic` / `offlineRequiresCredentials`: the
4713
- * cumulative conformance suites stay deterministic and credential-free.
4714
- * - `liveProfileOptIn`: live suites are excluded from ordinary gates by the
4715
- * environment predicate (`phase7LiveProfileEnabled`), never by test-runner
4716
- * configuration that could silently drift.
4717
- * - `liveModelLayers` / `liveSupplierLayers`: live profiles exercise real
4718
- * model Layers over the SAME deterministic supplier desk — no claim of a
4719
- * live supplier integration is made anywhere (decision 9).
4720
- * - `structurallyRedactedTranscripts`: transcript evidence a live profile
4721
- * emits passes through the structural `Redactor` first (SEC-008,
4722
- * testing.md §12: "live model and supplier profiles are opt-in smoke or
4723
- * release tests, rate-limited and structurally redacted").
4724
- * - `exactlyOnceExternalEffects`: never claimed at any phase (DUR-003).
4725
- */
4726
- var TravelPlannerPhase7Profile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerPhase7Profile")({
4727
- phase: Schema.Literal("P7"),
4728
- offlineConformanceDeterministic: Schema.Literal(true),
4729
- offlineRequiresCredentials: Schema.Literal(false),
4730
- liveProfileOptIn: Schema.Literal(true),
4731
- liveModelLayers: Schema.Literal(true),
4732
- liveSupplierLayers: Schema.Literal(false),
4733
- structurallyRedactedTranscripts: Schema.Literal(true),
4734
- exactlyOnceExternalEffects: Schema.Literal(false)
4735
- }) {};
4736
- const phase7TravelPlannerProfile = TravelPlannerPhase7Profile.make({
4737
- phase: "P7",
4738
- offlineConformanceDeterministic: true,
4739
- offlineRequiresCredentials: false,
4740
- liveProfileOptIn: true,
4741
- liveModelLayers: true,
4742
- liveSupplierLayers: false,
4743
- structurallyRedactedTranscripts: true,
4744
- exactlyOnceExternalEffects: false
4745
- });
4746
- /**
4747
- * The one opt-in switch for EVERY live profile in this repository. `"1"` is
4748
- * the only enabling value: an unset, empty, or differently-truthy value keeps
4749
- * the suite skipped, so CI and ordinary developer runs stay offline.
4750
- */
4751
- const PHASE7_LIVE_GATE_ENV = "EFFECT_AGENT_LIVE";
4752
- /** The credential a Travel Planner live-model profile additionally requires. */
4753
- const PHASE7_LIVE_CREDENTIAL_ENV = "OPENAI_API_KEY";
4754
- /**
4755
- * The test-side live gate (P7 plan §6: no test-side live-gating pattern
4756
- * existed before this — the demo gates at serve time via
4757
- * `Config.redacted("OPENAI_API_KEY")`). Suites use it as
4758
- * `describe.skipIf(!phase7LiveProfileEnabled(process.env))`, which keeps the
4759
- * live block out of ordinary gates while the SAME file's ungated tests keep
4760
- * pinning the profile schema on every run.
4761
- */
4762
- const phase7LiveProfileEnabled = (env) => env["EFFECT_AGENT_LIVE"] === "1" && (env["OPENAI_API_KEY"] ?? "") !== "";
4763
- //#endregion
4764
- export { ActivityCatalog, ActivityCatalogLayer, ActivityQuery, ActivitySearchResult, ActivityUnavailable, AirportCode, BookFlight, BookItinerary, BookingRef, BoundedSummary, CERTIFICATION_SCENARIOS, CancelBooking, CancelBookingRequest, CancellationConfirmation, CatalogLifecycle, CatalogLifecycleCounts, ChaosApprovalDecision, ChaosConvergenceFailure, ChaosLaneReport, ChaosPlan, ChaosPlanReport, ChaosResolutionKind, ChaosScenarioKind, ChaosSubmissionSpec, CodeExecutorConformanceViolation, DEFAULT_CHAOS_SEED, DestinationBrief, DestinationFacts, DestinationGuide, DestinationGuideLayer, DestinationGuideUnavailable, DestinationQuery, DestinationRecommendation, DestinationReport, DestinationResearchFailed, DestinationResearchFindings, DestinationResearchRequest, DestinationResearchSupportLayer, DestinationResearcher, DestinationResearcherToolkit, DestinationResearcherToolkitLayer, DestinationShortlist, DeterministicIdGeneratorLayer, DocContentToolkit, DocSummarizer, DocsMcpDiscoveryEvidence, DocsResearcher, DocsResearcherToolkit, DocumentLibrary, DocumentQuery, DocumentSummary, DocumentSummaryFailed, DocumentUnavailable, DurableSearchActivities, DurableSearchFlights, DurableSearchLodging, FetchDocument, FlightBookingRequest, FlightCatalog, FlightCatalogLayer, FlightOption, FlightQuery, FlightUnavailable, GuidanceFailure, HoldItinerary, Itinerary, ItineraryBookingRequest, ItineraryConfirmation, ItineraryHold, ItineraryHoldGateway, ItineraryHoldRequest, ItineraryHoldUnavailable, LodgingCatalog, LodgingCatalogLayer, LodgingOption, LodgingQuery, LodgingUnavailable, LookupDestination, PHASE7_LIVE_CREDENTIAL_ENV, PHASE7_LIVE_GATE_ENV, QuoteId, ResearchDigest, ResearchDispatchGate, ResearchDocument, ResearchDocumentId, ResearchMission, ResearchRequest, ReverseCompletionToolkitLayer, ScriptedGeneratePart, ScriptedGenerateTurn, ScriptedModel, ScriptedStreamPart, ScriptedStreamTermination, ScriptedStreamTurn, ScriptedTurn, SearchActivities, SearchFlights, SearchLodging, SummaryBrief, SummaryFinding, SummaryRequest, SupplierBookingConfirmation, SupplierBookingDesk, SupplierBookingRecord, SupplierOperation, SupplierUnavailable, TIER2_UNREACHED_LOCATIONS, TravelBookingReport, TravelCoordinator, TravelCoordinatorToolkit, TravelGuidance, TravelGuidanceLayer, TravelPlan, TravelPlanner, TravelPlannerBookingEvidenceError, TravelPlannerBookingProfile, TravelPlannerCloudflareProfile, TravelPlannerDurabilityProfile, TravelPlannerDurableEvidenceError, TravelPlannerPersistenceProfile, TravelPlannerPhase2, TravelPlannerPhase2Toolkit, TravelPlannerPhase2ToolkitLayer, TravelPlannerPhase4, TravelPlannerPhase4Toolkit, TravelPlannerPhase4ToolkitLayer, TravelPlannerPhase5, TravelPlannerPhase5Toolkit, TravelPlannerPhase5ToolkitLayer, TravelPlannerPhase7Profile, TravelPlannerProjectionError, TravelPlannerRuntimeLayer, TravelPlannerSubagentDurabilityProfile, TravelPlannerToolkit, TravelPlannerToolkitLayer, TravelSupplierReconcilerLayer, TravelerRef, TripRequest, assertDiscoveryMatchesAuthoredToolkit, assertSettledBookingsExistAtSupplier, bookFlightIdempotencyKey, cancelBookingIdempotencyKey, certifyDurableAdapters, chaosSeedFromEnv, codeExecutorConformanceCases, coordinatorConfidentialMarker, coordinatorResearchTurn, coordinatorShortlistTurn, delegateDocumentSummary, destinationLookup, destinationReportFor, destinationResearchDelegation, destinationResearchHandlersLayer, destinationResearchPolicy, docContentToolkitLayer, docsCoordinatorConfidentialMarker, docsCoordinatorDigests, docsDocumentBodySecret, docsMcpConnectorLayer, docsMcpIdentity, docsMcpMismatchedConnectorLayer, docsMcpOversizedConnectorLayer, docsMcpRequest, docsMissionConfidentialMarker, docsResearcherDeploymentId, docsResearcherPrincipal, docsResearcherProducerId, docsResearcherSubmitAgent, docsResearcherSubmitOptions, docsSummarizerDigestStrings, docsSummarizerDigests, docsSummaryHandlersLayer, documentBodyPhrase, documentSummaryFor, documentSummaryPolicy, durableChildLookupCallId, durableDestinationResearchHandlersLayer, durableResearchAllocation, durableResearchCallId, durableResearchFinding, durableResearchShortlist, encodedDestinationFacts, encodedDestinationReport, encodedDocumentSummary, expectedDestinationShortlist, expectedResearchDigest, expectedTravelPlan, fetchCallId, generateChaosPlans, inProcessCodeExecutorImplementation, inProcessCodeExecutorLayer, itineraryStepIdempotencyKey, makeDestinationResearcherModel, makeDocsResearcherHarness, makeDurableResearchHarness, makeInvocationCountingModel, makePhase3TravelPlannerCheckpoint, makePhase4TravelPlannerAgent, makePhase6TravelPlannerBindings, mapResearchChildFailure, mapSummaryChildFailure, missionConfidentialMarker, normalizeCrossPlatformTravelPlannerEvidence, normalizeDurableTravelPlannerEvidence, phase0HappyPathTurns, phase0Trip, phase1HappyPathTurns, phase1Trip, phase3TravelPlannerBatches, phase3TravelPlannerCompletionBatch, phase3TravelPlannerConversationId, phase3TravelPlannerDefinitionDigests, phase3TravelPlannerEncodedFixture, phase3TravelPlannerInitialBatch, phase3TravelPlannerProducerId, phase3TravelPlannerProfile, phase3TravelPlannerRunId, phase4TravelPlannerDefinitionDigests, phase4TravelPlannerDeploymentId, phase4TravelPlannerPrincipal, phase4TravelPlannerProducerId, phase4TravelPlannerProfile, phase4TravelPlannerSubmitOptions, phase4TravelPlannerWorkerLayer, phase5TravelPlannerDefinitionDigests, phase5TravelPlannerDeploymentId, phase5TravelPlannerPrincipal, phase5TravelPlannerProducerId, phase5TravelPlannerProfile, phase5TravelPlannerSubmitOptions, phase5TravelPlannerWorkerLayer, phase6ActivityCallId, phase6BookingModel, phase6BookingRef, phase6BookingToolCallId, phase6BookingTrip, phase6ChildLookupCallId, phase6CoordinatorModel, phase6FlightCallId, phase6GatedPlannerDefinitionDigests, phase6GatedPlannerModel, phase6GatedTrip, phase6GuideInvocationCount, phase6LodgingCallId, phase6PlannerModel, phase6ResearchDestination, phase6ResearchMission, phase6ResearcherModel, phase6SupplierDesk, phase6SupplierDeskLayer, phase6SupplierReconcilerLayer, phase6TravelPlannerDeploymentId, phase6TravelPlannerGoldenEvidence, phase6TravelPlannerProducerId, phase6TravelPlannerProducerPrefix, phase6TravelPlannerProfile, phase7LiveProfileEnabled, phase7TravelPlannerProfile, redactedDocumentPreview, releasePhase6PlannerGate, releasePhase6ResearcherGate, researchCorpusDocumentIds, researchDocumentFor, researchDocumentLookup, researchMission, researchMissionRequest, researcherHappyPathTurns, resetPhase6PlannerGate, resetPhase6ResearcherGate, resolveTierThree, runChaosPlan, s2CoordinatorDigests, s2CoordinatorSubmitAgent, s2ResearcherDigestStrings, s2ResearcherDigests, s2TravelPlannerDeploymentId, s2TravelPlannerPrincipal, s2TravelPlannerProducerId, s2TravelPlannerProfile, s2TravelPlannerSubmitOptions, summarizeCallId, supplierBookingRefFor, tier2NeverFiredLocations, travelPlanFromDurableSettlement, travelPlanFromProjection };
4765
-
4766
- //# sourceMappingURL=index.mjs.map
1
+ import { t as ScriptedModel_exports } from "./ScriptedModel.mjs";
2
+ export { ScriptedModel_exports as ScriptedModel };