@yielded/agent 0.1.0-beta.178 → 0.1.0-beta.181

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 (40) hide show
  1. package/dist/{AgentRuntime-DrQfy4cL.mjs → AgentRuntime-BAExRlgu.mjs} +5 -4
  2. package/dist/AgentRuntime-BAExRlgu.mjs.map +1 -0
  3. package/dist/{DurableAgentRuntime-CWhu1exp.mjs → DurableAgentRuntime-HH2muFrT.mjs} +4 -4
  4. package/dist/{DurableAgentRuntime-CWhu1exp.mjs.map → DurableAgentRuntime-HH2muFrT.mjs.map} +1 -1
  5. package/dist/{Subagent-C7F7c8Op.mjs → Subagent-D68fe7mr.mjs} +2 -2
  6. package/dist/{Subagent-C7F7c8Op.mjs.map → Subagent-D68fe7mr.mjs.map} +1 -1
  7. package/dist/{ThreadImport-CMKa8U7y.d.mts → ThreadImport-em89zmM-.d.mts} +39 -39
  8. package/dist/{WorkerAdmission-CtX1HRkm.mjs → WorkerAdmission-DrxDrLII.mjs} +2 -2
  9. package/dist/{WorkerAdmission-CtX1HRkm.mjs.map → WorkerAdmission-DrxDrLII.mjs.map} +1 -1
  10. package/dist/{agent-registration-Dt57NAP6.mjs → agent-registration-BovXT8jc.mjs} +2 -2
  11. package/dist/{agent-registration-Dt57NAP6.mjs.map → agent-registration-BovXT8jc.mjs.map} +1 -1
  12. package/dist/capabilities/BrowserUse.d.mts +39 -19
  13. package/dist/capabilities/BrowserUse.mjs +34 -8
  14. package/dist/capabilities/BrowserUse.mjs.map +1 -1
  15. package/dist/capabilities/Subagent.mjs +1 -1
  16. package/dist/durable/AgentRegistration.mjs +1 -1
  17. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  18. package/dist/durable/MessageDeliveryStoreConformance.d.mts +38 -38
  19. package/dist/durable/RecordFormat.mjs +1 -2
  20. package/dist/durable/RecordFormat.mjs.map +1 -1
  21. package/dist/durable/SqlMemoryStore.d.mts +2 -15
  22. package/dist/durable/SqlMemoryStore.mjs +1 -1
  23. package/dist/durable/SqlMemoryStore.mjs.map +1 -1
  24. package/dist/durable/SqlStorageOwner.d.mts +20 -0
  25. package/dist/durable/SqlStorageOwner.mjs +7 -0
  26. package/dist/durable/SqlStorageOwner.mjs.map +1 -0
  27. package/dist/durable/SubscriptionInput.mjs +1 -1
  28. package/dist/durable/ThreadImport.d.mts +1 -1
  29. package/dist/durable/ThreadInvariants.d.mts +1 -1
  30. package/dist/durable/WorkerAdmission.mjs +1 -1
  31. package/dist/engine/AgentRuntime.mjs +1 -1
  32. package/dist/index.d.mts +1 -1
  33. package/dist/index.mjs +4 -4
  34. package/package.json +1 -1
  35. package/src/capabilities/BrowserUse.ts +54 -13
  36. package/src/durable/RecordFormat.ts +2 -2
  37. package/src/durable/SqlMemoryStore.ts +3 -21
  38. package/src/durable/SqlStorageOwner.ts +24 -0
  39. package/src/engine/internal/agent-runtime.ts +13 -2
  40. package/dist/AgentRuntime-DrQfy4cL.mjs.map +0 -1
@@ -483,25 +483,6 @@ declare const prepareImportPage: (state: ThreadImportProgress, input: {
483
483
  readonly reportKind?: "update" | undefined;
484
484
  } | undefined;
485
485
  readonly messageAdmission?: {
486
- readonly schemaVersion: 1;
487
- readonly message: {
488
- readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
489
- readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
490
- };
491
- readonly peerName: string;
492
- readonly sender: {
493
- readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
494
- readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
495
- };
496
- readonly returnAddress: {
497
- readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
498
- readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
499
- };
500
- readonly inReplyTo?: {
501
- readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
502
- readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
503
- } | undefined;
504
- } | {
505
486
  readonly _tag: "WorkerCompletion";
506
487
  readonly budgetExhausted: boolean;
507
488
  readonly schemaVersion: 1;
@@ -542,6 +523,25 @@ declare const prepareImportPage: (state: ThreadImportProgress, input: {
542
523
  readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
543
524
  };
544
525
  readonly update: Update;
526
+ } | {
527
+ readonly schemaVersion: 1;
528
+ readonly message: {
529
+ readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
530
+ readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
531
+ };
532
+ readonly peerName: string;
533
+ readonly sender: {
534
+ readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
535
+ readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
536
+ };
537
+ readonly returnAddress: {
538
+ readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
539
+ readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
540
+ };
541
+ readonly inReplyTo?: {
542
+ readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
543
+ readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
544
+ } | undefined;
545
545
  } | undefined;
546
546
  };
547
547
  readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
@@ -723,25 +723,6 @@ declare const prepareImportPage: (state: ThreadImportProgress, input: {
723
723
  readonly reportKind?: "update" | undefined;
724
724
  } | undefined;
725
725
  readonly messageAdmission?: {
726
- readonly schemaVersion: 1;
727
- readonly message: {
728
- readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
729
- readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
730
- };
731
- readonly peerName: string;
732
- readonly sender: {
733
- readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
734
- readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
735
- };
736
- readonly returnAddress: {
737
- readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
738
- readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
739
- };
740
- readonly inReplyTo?: {
741
- readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
742
- readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
743
- } | undefined;
744
- } | {
745
726
  readonly _tag: "WorkerCompletion";
746
727
  readonly budgetExhausted: boolean;
747
728
  readonly schemaVersion: 1;
@@ -782,6 +763,25 @@ declare const prepareImportPage: (state: ThreadImportProgress, input: {
782
763
  readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
783
764
  };
784
765
  readonly update: Update;
766
+ } | {
767
+ readonly schemaVersion: 1;
768
+ readonly message: {
769
+ readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
770
+ readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
771
+ };
772
+ readonly peerName: string;
773
+ readonly sender: {
774
+ readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
775
+ readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
776
+ };
777
+ readonly returnAddress: {
778
+ readonly threadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
779
+ readonly agentId: string & import("effect/Brand").Brand<"@effect-agent/core/AgentId">;
780
+ };
781
+ readonly inReplyTo?: {
782
+ readonly ownerThreadId: string & import("effect/Brand").Brand<"@effect-agent/core/ThreadId">;
783
+ readonly messageId: string & import("effect/Brand").Brand<"@effect-agent/thread/IdempotencyKey">;
784
+ } | undefined;
785
785
  } | undefined;
786
786
  };
787
787
  readonly envelopeDigest: string & import("effect/Brand").Brand<"@effect-agent/thread/Digest">;
@@ -840,4 +840,4 @@ declare const rebuildClosedSubmission: (admission: ThreadAdmission) => Effect.Ef
840
840
  declare const reencodeThread: <E, R>(source: Stream.Stream<ThreadExport, E, R>) => Effect.Effect<ThreadImportResult, E | ThreadImportRejected | ThreadStoreError, R | ThreadImport>;
841
841
  //#endregion
842
842
  export { ThreadDeliveryImportReader as C, verifyImportedReferences as S, reencodeThread as _, ThreadImport as a, validateImportedRunExecution as b, ThreadImportResult as c, finishThreadImport as d, invalidThreadArchive as f, rebuildImportedSubmission as g, rebuildClosedSubmission as h, ThreadArchive as i, ThreadImport_d_exports as l, prepareImportPage as m, PreparedImportPage as n, ThreadImportProgress as o, makeThreadImportProgress as p, RebuiltSubmission as r, ThreadImportRejected as s, PreparedImportBatch as t, captureImportSource as u, validateClosedRun as v, ThreadImportReader as w, verifyImportedInputOrder as x, validateImportedExecution as y };
843
- //# sourceMappingURL=ThreadImport-CMKa8U7y.d.mts.map
843
+ //# sourceMappingURL=ThreadImport-em89zmM-.d.mts.map
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { c as WorkerError } from "./Worker-CtuUwYOK.mjs";
3
3
  import { It as WorkerOrigin, Lt as WorkerOriginRecorded, W as ProducerId, X as RecordEnvelope, Z as RecordId, c as CanonicalBatch, i as BatchId, jt as WorkerAdmission, yt as ThreadCreated } from "./Records-CZRedCE7.mjs";
4
4
  import { AdmissionConflict, AdmissionPolicyError, AdmissionRequest, LedgerError, MarkReadyRequest, SubmissionLedger } from "./durable/SubmissionLedger.mjs";
5
- import { o as definitionDigestsEqual } from "./agent-registration-Dt57NAP6.mjs";
5
+ import { o as definitionDigestsEqual } from "./agent-registration-BovXT8jc.mjs";
6
6
  import { X as workerOriginRecordId } from "./RunJournal-oJLo-pjS.mjs";
7
7
  import { I as ThreadIdentityRequest, L as ThreadMaterialization, R as ThreadNotMaterialized, Y as ThreadStore, Z as ThreadStoreError, et as ThreadTailRequest, n as AppendRequest, t as AppendConflict } from "./ThreadStore-D2rqtt7k.mjs";
8
8
  import { DurableRuntimeFailpoint, DurableRuntimeFailpointError } from "./durable/DurableFailpoint.mjs";
@@ -158,4 +158,4 @@ const WorkerAdmissionPort = Context.Reference("@effect-agent/thread/WorkerAdmiss
158
158
  //#endregion
159
159
  export { admitWorker as a, threadCreatedBatchId as c, WorkerAdmission_exports as i, threadCreatedRecordId as l, WorkerAdmissionPort as n, ensureThreadCreated as o, WorkerAdmissionRequest as r, ensureWorkerOrigin as s, WorkerAdmissionFailure as t };
160
160
 
161
- //# sourceMappingURL=WorkerAdmission-CtX1HRkm.mjs.map
161
+ //# sourceMappingURL=WorkerAdmission-DrxDrLII.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"WorkerAdmission-CtX1HRkm.mjs","names":[],"sources":["../src/durable/internal/thread-initialization.ts","../src/durable/WorkerAdmission.ts"],"sourcesContent":["import { DateTime, Effect, Schema } from \"effect\";\n\nimport type { AgentId, ThreadId } from \"../../core/Identifiers.ts\";\nimport { WorkerError } from \"../../core/Worker.ts\";\nimport { DurableRuntimeFailpoint } from \"../DurableFailpoint.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n RecordEnvelope,\n RecordId,\n ThreadCreated,\n WorkerOrigin,\n WorkerOriginRecorded,\n type DefinitionDigests,\n type DeploymentId,\n type ProducerId,\n} from \"../Records.ts\";\nimport { workerOriginRecordId } from \"../RunJournal.ts\";\nimport type { OwnershipLost } from \"../SubmissionLedger.ts\";\nimport type { AppendConflict, ThreadNotMaterialized, ThreadStoreError } from \"../ThreadStore.ts\";\nimport {\n AppendRequest,\n ThreadIdentityRequest,\n ThreadTailRequest,\n ThreadStore,\n} from \"../ThreadStore.ts\";\nimport { WakeScheduler } from \"../WakeScheduler.ts\";\nimport { definitionDigestsEqual } from \"./agent-registration.ts\";\n\ninterface InitializationConfig {\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n}\n\n/** Stable identities retained across admission retries and recovery. */\nexport const threadCreatedBatchId = (threadId: ThreadId): BatchId =>\n Schema.decodeSync(BatchId)(`thread-created:${threadId}`);\n\nexport const threadCreatedRecordId = (threadId: ThreadId): RecordId =>\n Schema.decodeSync(RecordId)(`thread-created:${threadId}`);\n\n/**\n * Coordinator invariant: every Thread's first canonical record is `ThreadCreated`,\n * so `tailSequence >= 1` is the deterministic already-created check. Concurrent admissions\n * re-read this invariant after a tail conflict before considering initialization complete.\n */\nexport const ensureThreadCreated = Effect.fnUntraced(\n function* (\n config: InitializationConfig,\n threadId: ThreadId,\n agentId: AgentId,\n definitions: DefinitionDigests,\n ): Effect.fn.Return<\n void,\n ThreadStoreError | ThreadNotMaterialized | AppendConflict | OwnershipLost,\n ThreadStore | WakeScheduler\n > {\n const store = yield* ThreadStore;\n const wake = yield* WakeScheduler;\n const tail = yield* store.inspectTail(ThreadTailRequest.make({ threadId }));\n\n if (tail.tailSequence > 0) return;\n\n const record = yield* Effect.map(DateTime.now, (createdAt) =>\n RecordEnvelope.make({\n recordId: threadCreatedRecordId(threadId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt,\n deploymentId: config.deploymentId,\n payload: ThreadCreated.make({ agentId, definitions }),\n }),\n );\n\n yield* store\n .append(\n AppendRequest.make({\n threadId,\n batch: CanonicalBatch.make({\n batchId: threadCreatedBatchId(threadId),\n producerId: config.producerId,\n records: [record],\n }),\n expectedTailSequence: tail.tailSequence,\n }),\n )\n .pipe(\n Effect.catchTag(\"AppendConflict\", (error) =>\n store\n .inspectTail(ThreadTailRequest.make({ threadId }))\n .pipe(\n Effect.flatMap((current) =>\n current.tailSequence > 0 ? Effect.void : Effect.fail(error),\n ),\n ),\n ),\n Effect.andThen(wake.notify(threadId)),\n Effect.asVoid,\n );\n },\n (effect) =>\n effect.pipe(\n Effect.retry({\n times: 7,\n while: (error) => error._tag === \"AppendConflict\",\n }),\n ),\n);\n\nconst sameOrigin = Schema.toEquivalence(WorkerOrigin);\n\nexport const ensureWorkerOrigin = Effect.fnUntraced(\n function* (config: InitializationConfig, origin: WorkerOrigin) {\n const store = yield* ThreadStore;\n const failpoint = yield* DurableRuntimeFailpoint;\n\n for (let attempt = 0; attempt < 16; attempt++) {\n const current = yield* store.readIdentity(\n ThreadIdentityRequest.make({ threadId: origin.worker.threadId }),\n );\n\n const existing = current.records.find(\n ({ record }) => record.payload._tag === \"WorkerOriginRecorded\",\n )?.record.payload;\n\n if (existing?._tag === \"WorkerOriginRecorded\") {\n if (!sameOrigin(existing.origin, origin))\n return yield* WorkerError.make({ operation: \"start\", reason: \"worker-mismatch\" });\n\n return;\n }\n const first = current.records[0]?.record.payload;\n\n if (\n first?._tag !== \"ThreadCreated\" ||\n first.agentId !== origin.worker.targetAgentId ||\n !definitionDigestsEqual(first.definitions, origin.targetDigests) ||\n current.records.some(({ record }) => record.payload._tag === \"SubagentLineageRecorded\")\n )\n return yield* WorkerError.make({ operation: \"start\", reason: \"worker-mismatch\" });\n const id = workerOriginRecordId(origin.worker.threadId);\n\n yield* failpoint.hit(\"worker:before-origin-append\");\n\n const appended = yield* store\n .append(\n AppendRequest.make({\n threadId: origin.worker.threadId,\n expectedTailSequence: current.tailSequence,\n\n batch: CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(id),\n producerId: config.producerId,\n records: [\n RecordEnvelope.make({\n recordId: id,\n family: \"thread\",\n schemaVersion: 1,\n createdAt: DateTime.makeUnsafe(origin.createdAtMillis),\n deploymentId: config.deploymentId,\n payload: WorkerOriginRecorded.make({ origin }),\n }),\n ],\n }),\n }),\n )\n .pipe(\n Effect.as(true),\n Effect.catchTag(\"AppendConflict\", () => Effect.succeed(false)),\n );\n\n if (appended) {\n yield* failpoint.hit(\"worker:after-origin-append\");\n\n return;\n }\n }\n\n return yield* WorkerError.make({ operation: \"start\", reason: \"storage\" });\n },\n Effect.mapError((cause) =>\n cause._tag === \"WorkerError\"\n ? cause\n : WorkerError.make({ operation: \"start\", reason: \"storage\", cause }),\n ),\n);\n","import { Context, Effect, Schema } from \"effect\";\n\nimport { DurableRuntimeFailpoint, DurableRuntimeFailpointError } from \"./DurableFailpoint.ts\";\nimport { ensureThreadCreated, ensureWorkerOrigin } from \"./internal/thread-initialization.ts\";\nimport { ProducerId, WorkerAdmission } from \"./Records.ts\";\nimport {\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionRequest,\n LedgerError,\n MarkReadyRequest,\n SubmissionLedger,\n} from \"./SubmissionLedger.ts\";\nimport {\n AppendConflict,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n} from \"./ThreadStore.ts\";\nimport { WakeScheduler } from \"./WakeScheduler.ts\";\n\n/**\n * Storage admission after source authorization, input validation and capacity reservation.\n * This is an internal host port, not an authorization entrypoint. Hosts route the whole\n * operation to the destination owner and enroll recovery before executing it.\n */\nexport class WorkerAdmissionRequest extends Schema.Class<WorkerAdmissionRequest>(\n \"@effect-agent/thread/WorkerAdmissionRequest\",\n)({\n ...AdmissionRequest.fields,\n workerAdmission: WorkerAdmission,\n producerId: ProducerId,\n}) {}\n\nexport const WorkerAdmissionFailure = Schema.Union([\n AdmissionConflict,\n AdmissionPolicyError,\n LedgerError,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n]);\n\n/** Local implementation shared by every host; retries finish the same admitted row. */\nexport const admitWorker = Effect.fnUntraced(function* (request: WorkerAdmissionRequest) {\n const origin = request.workerAdmission.origin;\n\n if (\n origin.worker.threadId !== request.threadId ||\n origin.worker.targetAgentId !== request.agentId ||\n request.parentLinkage !== undefined\n )\n return yield* LedgerError.make({\n operation: \"admit worker\",\n message: \"Worker admission does not belong to the destination Thread\",\n });\n\n const ledger = yield* SubmissionLedger;\n const store = yield* ThreadStore;\n const wake = yield* WakeScheduler;\n const failpoint = yield* DurableRuntimeFailpoint;\n const admitted = yield* ledger.admit(AdmissionRequest.make(request));\n\n yield* failpoint.hit(\"submit:after-admit\");\n if (admitted.replayed && admitted.state !== \"admitted\") return admitted;\n\n yield* store.materialize(\n ThreadMaterialization.make({\n threadId: request.threadId,\n }),\n );\n\n const config = {\n producerId: request.producerId,\n deploymentId: request.deploymentId,\n };\n\n yield* ensureThreadCreated(config, request.threadId, request.agentId, request.agentDigests);\n yield* ensureWorkerOrigin(config, origin).pipe(\n Effect.mapError((cause) =>\n LedgerError.make({ operation: \"worker-origin\", message: cause.reason, cause }),\n ),\n );\n yield* failpoint.hit(\"submit:after-materialize\");\n yield* ledger.markReady(MarkReadyRequest.make({ submissionId: admitted.submissionId }));\n yield* wake.notify(request.threadId);\n\n return admitted;\n});\n\n/** Placement adapter for the composite operation; local hosts use the same implementation. */\nexport const WorkerAdmissionPort = Context.Reference<{ readonly admit: typeof admitWorker }>(\n \"@effect-agent/thread/WorkerAdmissionPort\",\n { defaultValue: () => ({ admit: admitWorker }) },\n);\n"],"mappings":";;;;;;;;;;;;AAmCA,MAAa,wBAAwB,aACnC,OAAO,WAAW,OAAO,CAAC,CAAC,kBAAkB,UAAU;AAEzD,MAAa,yBAAyB,aACpC,OAAO,WAAW,QAAQ,CAAC,CAAC,kBAAkB,UAAU;;;;;;AAO1D,MAAa,sBAAsB,OAAO,WACxC,WACE,QACA,UACA,SACA,aAKA;CACA,MAAM,QAAQ,OAAO;CACrB,MAAM,OAAO,OAAO;CACpB,MAAM,OAAO,OAAO,MAAM,YAAY,kBAAkB,KAAK,EAAE,SAAS,CAAC,CAAC;CAE1E,IAAI,KAAK,eAAe,GAAG;CAE3B,MAAM,SAAS,OAAO,OAAO,IAAI,SAAS,MAAM,cAC9C,eAAe,KAAK;EAClB,UAAU,sBAAsB,QAAQ;EACxC,QAAQ;EACR,eAAe;EACf;EACA,cAAc,OAAO;EACrB,SAAS,cAAc,KAAK;GAAE;GAAS;EAAY,CAAC;CACtD,CAAC,CACH;CAEA,OAAO,MACJ,OACC,cAAc,KAAK;EACjB;EACA,OAAO,eAAe,KAAK;GACzB,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,QAAQ,WACxC,QAAQ,kBAAkB,KAAA,GAE1B,OAAO,OAAO,YAAY,KAAK;EAC7B,WAAW;EACX,SAAS;CACX,CAAC;CAEH,MAAM,SAAS,OAAO;CACtB,MAAM,QAAQ,OAAO;CACrB,MAAM,OAAO,OAAO;CACpB,MAAM,YAAY,OAAO;CACzB,MAAM,WAAW,OAAO,OAAO,MAAM,iBAAiB,KAAK,OAAO,CAAC;CAEnE,OAAO,UAAU,IAAI,oBAAoB;CACzC,IAAI,SAAS,YAAY,SAAS,UAAU,YAAY,OAAO;CAE/D,OAAO,MAAM,YACX,sBAAsB,KAAK,EACzB,UAAU,QAAQ,SACpB,CAAC,CACH;CAEA,MAAM,SAAS;EACb,YAAY,QAAQ;EACpB,cAAc,QAAQ;CACxB;CAEA,OAAO,oBAAoB,QAAQ,QAAQ,UAAU,QAAQ,SAAS,QAAQ,YAAY;CAC1F,OAAO,mBAAmB,QAAQ,MAAM,CAAC,CAAC,KACxC,OAAO,UAAU,UACf,YAAY,KAAK;EAAE,WAAW;EAAiB,SAAS,MAAM;EAAQ;CAAM,CAAC,CAC/E,CACF;CACA,OAAO,UAAU,IAAI,0BAA0B;CAC/C,OAAO,OAAO,UAAU,iBAAiB,KAAK,EAAE,cAAc,SAAS,aAAa,CAAC,CAAC;CACtF,OAAO,KAAK,OAAO,QAAQ,QAAQ;CAEnC,OAAO;AACT,CAAC;;AAGD,MAAa,sBAAsB,QAAQ,UACzC,4CACA,EAAE,qBAAqB,EAAE,OAAO,YAAY,GAAG,CACjD"}
1
+ {"version":3,"file":"WorkerAdmission-DrxDrLII.mjs","names":[],"sources":["../src/durable/internal/thread-initialization.ts","../src/durable/WorkerAdmission.ts"],"sourcesContent":["import { DateTime, Effect, Schema } from \"effect\";\n\nimport type { AgentId, ThreadId } from \"../../core/Identifiers.ts\";\nimport { WorkerError } from \"../../core/Worker.ts\";\nimport { DurableRuntimeFailpoint } from \"../DurableFailpoint.ts\";\nimport {\n BatchId,\n CanonicalBatch,\n RecordEnvelope,\n RecordId,\n ThreadCreated,\n WorkerOrigin,\n WorkerOriginRecorded,\n type DefinitionDigests,\n type DeploymentId,\n type ProducerId,\n} from \"../Records.ts\";\nimport { workerOriginRecordId } from \"../RunJournal.ts\";\nimport type { OwnershipLost } from \"../SubmissionLedger.ts\";\nimport type { AppendConflict, ThreadNotMaterialized, ThreadStoreError } from \"../ThreadStore.ts\";\nimport {\n AppendRequest,\n ThreadIdentityRequest,\n ThreadTailRequest,\n ThreadStore,\n} from \"../ThreadStore.ts\";\nimport { WakeScheduler } from \"../WakeScheduler.ts\";\nimport { definitionDigestsEqual } from \"./agent-registration.ts\";\n\ninterface InitializationConfig {\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n}\n\n/** Stable identities retained across admission retries and recovery. */\nexport const threadCreatedBatchId = (threadId: ThreadId): BatchId =>\n Schema.decodeSync(BatchId)(`thread-created:${threadId}`);\n\nexport const threadCreatedRecordId = (threadId: ThreadId): RecordId =>\n Schema.decodeSync(RecordId)(`thread-created:${threadId}`);\n\n/**\n * Coordinator invariant: every Thread's first canonical record is `ThreadCreated`,\n * so `tailSequence >= 1` is the deterministic already-created check. Concurrent admissions\n * re-read this invariant after a tail conflict before considering initialization complete.\n */\nexport const ensureThreadCreated = Effect.fnUntraced(\n function* (\n config: InitializationConfig,\n threadId: ThreadId,\n agentId: AgentId,\n definitions: DefinitionDigests,\n ): Effect.fn.Return<\n void,\n ThreadStoreError | ThreadNotMaterialized | AppendConflict | OwnershipLost,\n ThreadStore | WakeScheduler\n > {\n const store = yield* ThreadStore;\n const wake = yield* WakeScheduler;\n const tail = yield* store.inspectTail(ThreadTailRequest.make({ threadId }));\n\n if (tail.tailSequence > 0) return;\n\n const record = yield* Effect.map(DateTime.now, (createdAt) =>\n RecordEnvelope.make({\n recordId: threadCreatedRecordId(threadId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt,\n deploymentId: config.deploymentId,\n payload: ThreadCreated.make({ agentId, definitions }),\n }),\n );\n\n yield* store\n .append(\n AppendRequest.make({\n threadId,\n batch: CanonicalBatch.make({\n batchId: threadCreatedBatchId(threadId),\n producerId: config.producerId,\n records: [record],\n }),\n expectedTailSequence: tail.tailSequence,\n }),\n )\n .pipe(\n Effect.catchTag(\"AppendConflict\", (error) =>\n store\n .inspectTail(ThreadTailRequest.make({ threadId }))\n .pipe(\n Effect.flatMap((current) =>\n current.tailSequence > 0 ? Effect.void : Effect.fail(error),\n ),\n ),\n ),\n Effect.andThen(wake.notify(threadId)),\n Effect.asVoid,\n );\n },\n (effect) =>\n effect.pipe(\n Effect.retry({\n times: 7,\n while: (error) => error._tag === \"AppendConflict\",\n }),\n ),\n);\n\nconst sameOrigin = Schema.toEquivalence(WorkerOrigin);\n\nexport const ensureWorkerOrigin = Effect.fnUntraced(\n function* (config: InitializationConfig, origin: WorkerOrigin) {\n const store = yield* ThreadStore;\n const failpoint = yield* DurableRuntimeFailpoint;\n\n for (let attempt = 0; attempt < 16; attempt++) {\n const current = yield* store.readIdentity(\n ThreadIdentityRequest.make({ threadId: origin.worker.threadId }),\n );\n\n const existing = current.records.find(\n ({ record }) => record.payload._tag === \"WorkerOriginRecorded\",\n )?.record.payload;\n\n if (existing?._tag === \"WorkerOriginRecorded\") {\n if (!sameOrigin(existing.origin, origin))\n return yield* WorkerError.make({ operation: \"start\", reason: \"worker-mismatch\" });\n\n return;\n }\n const first = current.records[0]?.record.payload;\n\n if (\n first?._tag !== \"ThreadCreated\" ||\n first.agentId !== origin.worker.targetAgentId ||\n !definitionDigestsEqual(first.definitions, origin.targetDigests) ||\n current.records.some(({ record }) => record.payload._tag === \"SubagentLineageRecorded\")\n )\n return yield* WorkerError.make({ operation: \"start\", reason: \"worker-mismatch\" });\n const id = workerOriginRecordId(origin.worker.threadId);\n\n yield* failpoint.hit(\"worker:before-origin-append\");\n\n const appended = yield* store\n .append(\n AppendRequest.make({\n threadId: origin.worker.threadId,\n expectedTailSequence: current.tailSequence,\n\n batch: CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(id),\n producerId: config.producerId,\n records: [\n RecordEnvelope.make({\n recordId: id,\n family: \"thread\",\n schemaVersion: 1,\n createdAt: DateTime.makeUnsafe(origin.createdAtMillis),\n deploymentId: config.deploymentId,\n payload: WorkerOriginRecorded.make({ origin }),\n }),\n ],\n }),\n }),\n )\n .pipe(\n Effect.as(true),\n Effect.catchTag(\"AppendConflict\", () => Effect.succeed(false)),\n );\n\n if (appended) {\n yield* failpoint.hit(\"worker:after-origin-append\");\n\n return;\n }\n }\n\n return yield* WorkerError.make({ operation: \"start\", reason: \"storage\" });\n },\n Effect.mapError((cause) =>\n cause._tag === \"WorkerError\"\n ? cause\n : WorkerError.make({ operation: \"start\", reason: \"storage\", cause }),\n ),\n);\n","import { Context, Effect, Schema } from \"effect\";\n\nimport { DurableRuntimeFailpoint, DurableRuntimeFailpointError } from \"./DurableFailpoint.ts\";\nimport { ensureThreadCreated, ensureWorkerOrigin } from \"./internal/thread-initialization.ts\";\nimport { ProducerId, WorkerAdmission } from \"./Records.ts\";\nimport {\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionRequest,\n LedgerError,\n MarkReadyRequest,\n SubmissionLedger,\n} from \"./SubmissionLedger.ts\";\nimport {\n AppendConflict,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n} from \"./ThreadStore.ts\";\nimport { WakeScheduler } from \"./WakeScheduler.ts\";\n\n/**\n * Storage admission after source authorization, input validation and capacity reservation.\n * This is an internal host port, not an authorization entrypoint. Hosts route the whole\n * operation to the destination owner and enroll recovery before executing it.\n */\nexport class WorkerAdmissionRequest extends Schema.Class<WorkerAdmissionRequest>(\n \"@effect-agent/thread/WorkerAdmissionRequest\",\n)({\n ...AdmissionRequest.fields,\n workerAdmission: WorkerAdmission,\n producerId: ProducerId,\n}) {}\n\nexport const WorkerAdmissionFailure = Schema.Union([\n AdmissionConflict,\n AdmissionPolicyError,\n LedgerError,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n]);\n\n/** Local implementation shared by every host; retries finish the same admitted row. */\nexport const admitWorker = Effect.fnUntraced(function* (request: WorkerAdmissionRequest) {\n const origin = request.workerAdmission.origin;\n\n if (\n origin.worker.threadId !== request.threadId ||\n origin.worker.targetAgentId !== request.agentId ||\n request.parentLinkage !== undefined\n )\n return yield* LedgerError.make({\n operation: \"admit worker\",\n message: \"Worker admission does not belong to the destination Thread\",\n });\n\n const ledger = yield* SubmissionLedger;\n const store = yield* ThreadStore;\n const wake = yield* WakeScheduler;\n const failpoint = yield* DurableRuntimeFailpoint;\n const admitted = yield* ledger.admit(AdmissionRequest.make(request));\n\n yield* failpoint.hit(\"submit:after-admit\");\n if (admitted.replayed && admitted.state !== \"admitted\") return admitted;\n\n yield* store.materialize(\n ThreadMaterialization.make({\n threadId: request.threadId,\n }),\n );\n\n const config = {\n producerId: request.producerId,\n deploymentId: request.deploymentId,\n };\n\n yield* ensureThreadCreated(config, request.threadId, request.agentId, request.agentDigests);\n yield* ensureWorkerOrigin(config, origin).pipe(\n Effect.mapError((cause) =>\n LedgerError.make({ operation: \"worker-origin\", message: cause.reason, cause }),\n ),\n );\n yield* failpoint.hit(\"submit:after-materialize\");\n yield* ledger.markReady(MarkReadyRequest.make({ submissionId: admitted.submissionId }));\n yield* wake.notify(request.threadId);\n\n return admitted;\n});\n\n/** Placement adapter for the composite operation; local hosts use the same implementation. */\nexport const WorkerAdmissionPort = Context.Reference<{ readonly admit: typeof admitWorker }>(\n \"@effect-agent/thread/WorkerAdmissionPort\",\n { defaultValue: () => ({ admit: admitWorker }) },\n);\n"],"mappings":";;;;;;;;;;;;AAmCA,MAAa,wBAAwB,aACnC,OAAO,WAAW,OAAO,CAAC,CAAC,kBAAkB,UAAU;AAEzD,MAAa,yBAAyB,aACpC,OAAO,WAAW,QAAQ,CAAC,CAAC,kBAAkB,UAAU;;;;;;AAO1D,MAAa,sBAAsB,OAAO,WACxC,WACE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,aAAa,CAAC,CAAC;CACtF,OAAO,KAAK,OAAO,QAAQ,QAAQ;CAEnC,OAAO;AACT,CAAC;;AAGD,MAAa,sBAAsB,QAAQ,UACzC,4CACA,EAAE,qBAAqB,EAAE,OAAO,YAAY,GAAG,CACjD"}
@@ -3,7 +3,7 @@ import { n as getToolExecutionClass } from "./tool-execution-Ba7tO7Pt.mjs";
3
3
  import { getToolExecutionKind } from "./core/SubagentContract.mjs";
4
4
  import { a as PinnedTool, l as ToolNamespace, n as DiscoveryTool, r as IncludesCatalogDocumentation, t as AdditionalToolCatalog } from "./ToolExposure-hTJT2ekj.mjs";
5
5
  import { BackgroundReporting, WorkerReportPreparationFailure } from "./engine/SubagentHost.mjs";
6
- import { S as withAttempt } from "./AgentRuntime-DrQfy4cL.mjs";
6
+ import { S as withAttempt } from "./AgentRuntime-BAExRlgu.mjs";
7
7
  import { ContextRolloverTool } from "./engine/ContextWindow.mjs";
8
8
  import { tt as ReplayContract, v as DefinitionDigests } from "./Records-CZRedCE7.mjs";
9
9
  import { o as digestDefinitions, s as digestJson, t as DigestError } from "./Digest-ft4ku9pj.mjs";
@@ -259,4 +259,4 @@ const compileRegistrations = (entries) => {
259
259
  //#endregion
260
260
  export { compileRegistrations as a, resolveDefinitionBinding as c, compileBindingContracts as i, resolveWorkerBinding as l, CurrentBindingSelection as n, definitionDigestsEqual as o, DurableWorkerBinding as r, makeLegacyWorkerBinding as s, BindingUnavailable as t, toolReplayContracts as u };
261
261
 
262
- //# sourceMappingURL=agent-registration-Dt57NAP6.mjs.map
262
+ //# sourceMappingURL=agent-registration-BovXT8jc.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-registration-Dt57NAP6.mjs","names":["withProvisionalTextAttempt","run"],"sources":["../src/durable/internal/agent-registration.ts"],"sourcesContent":["import { Crypto, Option, Scope, Context, Effect, Layer, References, Schema, Tracer } from \"effect\";\nimport { Tool } from \"effect/ai\";\n\nimport type * as Agent from \"../../core/Agent.ts\";\nimport {\n type InputPromptSource,\n type InstructionSource,\n type ModelServices,\n type RunDispositionDeclaration,\n} from \"../../core/Agent.ts\";\nimport { type ThreadId, AgentId } from \"../../core/Identifiers.ts\";\nimport { getToolExecutionKind } from \"../../core/SubagentContract.ts\";\nimport {\n AdditionalToolCatalog,\n DiscoveryTool,\n IncludesCatalogDocumentation,\n PinnedTool,\n ToolNamespace,\n} from \"../../core/ToolExposure.ts\";\nimport { type RuntimeBinding } from \"../../engine/AgentRuntime.ts\";\nimport { ContextRolloverTool } from \"../../engine/ContextWindow.ts\";\nimport { getToolExecutionClass } from \"../../engine/DurableStep.ts\";\nimport { withAttempt as withProvisionalTextAttempt } from \"../../engine/internal/provisional-text.ts\";\nimport {\n BackgroundReporting,\n WorkerReportPreparationFailure,\n type WorkerReporting,\n} from \"../../engine/SubagentHost.ts\";\nimport { digestDefinitions, digestJson, DigestError } from \"../Digest.ts\";\nimport type { DurableWorkerFailure, DurableWorkerRequirements } from \"../DurableAgentRuntime.ts\";\nimport type { DefinitionDigestInput, Digest, PersistedJson } from \"../Records.ts\";\nimport { DefinitionDigests, ReplayContract } from \"../Records.ts\";\nimport type { Claim, Settlement, SubmissionSnapshot } from \"../SubmissionLedger.ts\";\n\n/** No unique current Binding can execute the stable Agent identity or decode its accepted input. */\nexport class BindingUnavailable extends Schema.TaggedError<BindingUnavailable>()(\n \"BindingUnavailable\",\n { agentId: AgentId, message: Schema.String },\n) {}\n\nexport type DurableBindingFailure = BindingUnavailable;\n\n/**\n * Submission execution/recovery routing for stable identities shared by current Definitions.\n * Worker declarations and peer-messaging endpoints still require unique Agent identities.\n */\nexport interface BindingSelection {\n /** Change when routing changes, so hosts can retry parked work without rewriting admission. */\n readonly key: string;\n /**\n * Select an exact registered Definition using the canonical Submission and authoritative host\n * state. Undefined retains unique-identity resolution. Never grant authority or mutate here;\n * input decoding, replay contracts and current Tool authorization still apply after selection.\n */\n readonly select: (\n submission: SubmissionSnapshot,\n ) => Effect.Effect<Agent.AnyDefinition | undefined, DurableWorkerFailure | BindingUnavailable>;\n}\n\n/** Captured at runtime construction; callers cannot replace routing during an Attempt. */\nexport const CurrentBindingSelection = Context.Reference<BindingSelection | undefined>(\n \"@effect-agent/thread/CurrentBindingSelection\",\n { defaultValue: () => undefined },\n);\n\n/** Exact immutable admission, lineage and delivery evidence; never an executable-code gate. */\nexport const definitionDigestsEqual = (\n left: DefinitionDigests,\n right: DefinitionDigests,\n): boolean =>\n left.agent === right.agent &&\n left.model === right.model &&\n left.tools === right.tools &&\n Schema.toEquivalence(Schema.UndefinedOr(ReplayContract))(left.replay, right.replay);\n\n/**\n * Explicit versions must cover every current Tool. Change a version when handler meaning,\n * durable Step names/codecs, external idempotency keys, authorization, completion projection,\n * or child/report protocols change. JSON Schema cannot detect handler or codec-transform changes.\n */\nexport interface ReplayVersions {\n readonly tools: Readonly<Record<string, PersistedJson>>;\n}\n\n// These are immutable declaration projections, never model or admission contexts.\nconst replaySchemaProjections = new WeakMap<Schema.Top, Schema.Json>();\n\ntype CachedFallbackContracts = {\n readonly tools: ReadonlyArray<Tool.Any>;\n readonly completionTool: string | undefined;\n readonly completionFromTools: ReadonlyArray<string>;\n readonly version: PersistedJson;\n readonly contracts: Record<string, Digest>;\n};\n\nconst fallbackContracts = new WeakMap<Crypto.Crypto, WeakMap<object, CachedFallbackContracts>>();\n\n/** Hash current operation contracts; no historical definitions or schemas are retained. */\nexport const toolReplayContracts = Effect.fnUntraced(function* (\n definition: Agent.AnyDefinition,\n versions?: ReplayVersions,\n fallbackVersion: PersistedJson = null,\n) {\n // Optional lookup preserves validation before a missing-service defect. A\n // different host Crypto service must never inherit another host's digest map.\n const crypto = Option.getOrUndefined(yield* Effect.serviceOption(Crypto.Crypto));\n\n const invalidContracts = () =>\n DigestError.make({\n message: \"Operation contracts require serializable codecs and a version for every Tool\",\n });\n\n const prepared = yield* Effect.try({\n try: () => {\n const tools = Object.values(definition.toolkit.tools);\n const completionTool = definition.completion?.tool;\n const completionFromTools = definition.completionFromTools?.map(({ tool }) => tool) ?? [];\n // Object-valued versions may be mutable caller data. Only primitive fallback\n // versions can reuse a result, and only one result is retained per toolkit.\n\n const cacheable =\n versions === undefined && (fallbackVersion === null || typeof fallbackVersion !== \"object\");\n\n const cached =\n cacheable && crypto !== undefined\n ? fallbackContracts.get(crypto)?.get(definition.toolkit.tools)\n : undefined;\n\n if (\n cached !== undefined &&\n cached.version === fallbackVersion &&\n cached.completionTool === completionTool &&\n cached.completionFromTools.length === completionFromTools.length &&\n cached.completionFromTools.every((tool, index) => tool === completionFromTools[index]) &&\n cached.tools.length === tools.length &&\n cached.tools.every((tool, index) => tool === tools[index])\n )\n return { _tag: \"Cached\" as const, contracts: { ...cached.contracts } };\n\n const jsonSchema = (schema: Schema.Top) => {\n const cached = replaySchemaProjections.get(schema);\n\n if (cached !== undefined) return cached;\n\n const projection = Schema.decodeUnknownSync(Schema.Json)(\n Tool.getJsonSchemaFromSchema(schema),\n );\n\n replaySchemaProjections.set(schema, projection);\n\n return projection;\n };\n\n return {\n _tag: \"Compile\" as const,\n jsonSchema,\n cacheable,\n tools,\n completionTool,\n completionFromTools,\n };\n },\n catch: () =>\n DigestError.make({\n message: \"Operation contracts require serializable codecs and a version for every Tool\",\n }),\n });\n\n if (prepared._tag === \"Cached\") return prepared.contracts;\n\n const declarations = yield* Effect.forEach(\n prepared.tools,\n Effect.fnUntraced(function* (tool) {\n const { version, present } = yield* Effect.try({\n try: () => ({\n version: versions === undefined ? fallbackVersion : versions.tools[tool.name],\n present: versions === undefined || Object.hasOwn(versions.tools, tool.name),\n }),\n catch: invalidContracts,\n });\n\n if (version === undefined || !present) return yield* invalidContracts();\n\n return yield* Effect.try({\n try: () => ({\n name: tool.name,\n contract: {\n version,\n ...(Tool.isProviderDefined(tool)\n ? {\n provider: {\n id: tool.id,\n providerName: tool.providerName,\n args: Schema.decodeUnknownSync(Schema.Json)(tool.args ?? null),\n requiresHandler: tool.requiresHandler,\n },\n readonly: Context.get(tool.annotations, Tool.Readonly),\n }\n : {}),\n parameters: prepared.jsonSchema(tool.parametersSchema),\n success: prepared.jsonSchema(tool.successSchema),\n failure: prepared.jsonSchema(tool.failureSchema),\n failureMode: tool.failureMode,\n needsApproval:\n typeof tool.needsApproval === \"function\" ? \"dynamic\" : (tool.needsApproval ?? false),\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n contextRollover: Context.get(tool.annotations, ContextRolloverTool),\n completion: definition.completion?.tool === tool.name,\n completionFromTool:\n definition.completionFromTools?.some(\n (declaration) => declaration.tool === tool.name,\n ) ?? false,\n },\n }),\n catch: invalidContracts,\n });\n }),\n );\n\n const contracts = Object.fromEntries(\n yield* Effect.forEach(declarations, ({ name, contract }) =>\n digestJson(contract).pipe(Effect.map((digest) => [name, digest] as const)),\n ),\n );\n\n if (prepared.cacheable && crypto !== undefined) {\n const cache = fallbackContracts.get(crypto) ?? new WeakMap<object, CachedFallbackContracts>();\n\n cache.set(definition.toolkit.tools, {\n tools: prepared.tools,\n completionTool: prepared.completionTool,\n completionFromTools: prepared.completionFromTools,\n version: fallbackVersion,\n contracts: { ...contracts },\n });\n fallbackContracts.set(crypto, cache);\n }\n\n return contracts;\n});\n\n/** Compile current metadata without acquiring executable services. */\nexport const compileBindingContracts = Effect.fnUntraced(function* (\n definition: Agent.AnyDefinition,\n definitions: DefinitionDigestInput,\n versions?: ReplayVersions,\n): Effect.fn.Return<Pick<ResolvedBinding, \"digests\">, DigestError, Crypto.Crypto> {\n const digests = yield* digestDefinitions(definitions);\n const tools = yield* toolReplayContracts(definition, versions, definitions.tools);\n\n return {\n digests: DefinitionDigests.make({\n ...digests,\n replay: ReplayContract.make({ agent: digests.agent, tools }),\n }),\n };\n});\n\ntype ExecutableDefinition = Agent.AnyDefinition & {\n readonly instructions: InstructionSource<never, unknown, unknown>;\n readonly inputPrompt?: InputPromptSource<never, unknown, unknown> | undefined;\n};\n\n/** Executable model Binding accepted by durable registration descriptors. */\nexport type ExecutableAgentBinding = {\n readonly definition: ExecutableDefinition;\n readonly model: Layer.Layer<ModelServices, never, unknown>;\n};\n\n/**\n * Internal coordinator entry point for one fenced Attempt over an already-granted claim.\n * The generic signature matches `runAttempt` and is specialized for each captured Agent.\n */\ntype ResolvedAttemptDriver = <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue extends\n | RunDispositionDeclaration<OutputSchema[\"Type\"], Schema.Top>\n | undefined,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined,\n>(\n agent: RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n threadId: ThreadId,\n claim: Claim,\n) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n DurableWorkerRequirements<\n RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n InstructionRequirements\n >\n>;\n\ntype CapturedAttempt<A extends ExecutableAgentBinding> = (\n agent: A,\n threadId: ThreadId,\n claim: Claim,\n) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n DurableWorkerRequirements<A>\n>;\n\n/**\n * An Agent with its worker services captured, ready to drive a fenced Attempt.\n * Concrete Schema and model types stay inside this closure when registrations are collected.\n */\ninterface CapturedBinding {\n readonly agentId: AgentId;\n /** Exact immutable definition whose codecs and behavior the worker captured. */\n readonly definition: Agent.AnyDefinition;\n /** Captured independently from per-Attempt services: report preparation has no fenced Claim. */\n readonly reporting?: ReadonlyArray<WorkerReporting<WorkerReportPreparationFailure>>;\n readonly attempt: (\n driver: ResolvedAttemptDriver,\n threadId: ThreadId,\n claim: Claim,\n ) => Effect.Effect<Option.Option<Settlement>, DurableWorkerFailure | DurableBindingFailure>;\n}\n\n// Registrations outlive their construction span. Dependencies remain captured,\n// while every attempt/report inherits the invoking fiber's tracing state.\nconst omitTraceContext = Context.omit(\n Scope.Scope,\n Tracer.ParentSpan,\n Tracer.Tracer,\n Tracer.MinimumTraceLevel,\n Tracer.CurrentTraceLevel,\n References.TracerEnabled,\n References.TracerTimingEnabled,\n References.TracerSpanAnnotations,\n References.TracerSpanLinks,\n References.CurrentLoggers,\n References.CurrentLogLevel,\n References.MinimumLogLevel,\n References.CurrentStackFrame,\n References.CurrentLogAnnotations,\n References.CurrentLogSpans,\n);\n\n// R describes captured application services; ParentSpan is supplied by the\n// live invocation rather than stored as a registration dependency.\nconst withoutTraceContext = <R>(context: Context.Context<R>): Context.Context<R> =>\n omitTraceContext(context) as Context.Context<R>;\n\nconst captureReporting = <E, R>(reports: ReadonlyArray<WorkerReporting<E, R>>) =>\n Effect.map(\n Effect.context<Exclude<R, Scope.Scope>>().pipe(Effect.map(withoutTraceContext)),\n (context) =>\n reports.map((report): WorkerReporting<WorkerReportPreparationFailure> => ({\n ...report,\n prepare: (value) =>\n Effect.scoped(Effect.suspend(() => report.prepare(value))).pipe(\n Effect.provide(context),\n Effect.mapError((error) =>\n Schema.is(WorkerReportPreparationFailure)(error)\n ? error\n : WorkerReportPreparationFailure.make({ stage: \"preparation\" }),\n ),\n ),\n })),\n );\n\nconst backgroundReports = (definition: Agent.AnyDefinition) => [\n ...new Set(\n Object.values(definition.toolkit.tools).flatMap((tool) => {\n const report = Context.get(tool.annotations, BackgroundReporting);\n\n return report === undefined ? [] : [report];\n }),\n ),\n];\n\n/** One exact executable registration used by durable claim-time resolution. */\nexport interface ResolvedBinding extends CapturedBinding {\n readonly digests: DefinitionDigests;\n}\n\n/** Trusted claim identity for resolving per-Attempt application services. Not model input. */\nexport interface AgentAttemptContext {\n readonly threadId: ThreadId;\n readonly submissionId: Claim[\"submissionId\"];\n readonly attemptId: Claim[\"attemptId\"];\n}\n\nconst capture = <A extends ExecutableAgentBinding, Requires>(\n agent: A,\n prepare: (\n execute: ReturnType<CapturedAttempt<A>>,\n context: AgentAttemptContext,\n ) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n Requires\n >,\n): Effect.Effect<CapturedBinding, never, Requires> =>\n Effect.map(\n Effect.context<Requires>().pipe(Effect.map(withoutTraceContext)),\n (context): CapturedBinding => ({\n agentId: agent.definition.id,\n definition: agent.definition,\n attempt: (driver, threadId, claim) => {\n // Registration closes one concrete Binding before heterogeneous registrations are\n // collected. TypeScript cannot instantiate the higher-rank RuntimeBinding parameters\n // from the intentionally erased public shape, so specialize the driver back to A here.\n const run = driver as unknown as CapturedAttempt<A>;\n\n const execute = withProvisionalTextAttempt(\n run(agent, threadId, claim),\n threadId,\n claim.submissionId,\n claim.attemptId,\n );\n\n return prepare(execute, {\n threadId,\n submissionId: claim.submissionId,\n attemptId: claim.attemptId,\n }).pipe(Effect.provide(context));\n },\n }),\n );\n\nconst captureWithAttemptLayer = <A extends ExecutableAgentBinding, Provides, Requires>(\n agent: A,\n attemptLayer: (context: AgentAttemptContext) => Layer.Layer<Provides, never, Requires>,\n) =>\n capture(agent, (execute, context) =>\n execute.pipe(Effect.provide(Layer.fresh(attemptLayer(context)))),\n );\n\n/**\n * Build one exact worker registration from an executable Agent Binding and\n * its already-computed definition digests.\n *\n * `make(agent, digests)` captures the binding plus its worker-requirement\n * Context at Layer/effect construction time. Hosts that start from application\n * version declarations should use `compileRegistrations`; low-level fixtures\n * may supply a previously computed digest triple directly.\n */\nexport const DurableWorkerBinding = {\n make: <A extends ExecutableAgentBinding>(\n agent: A,\n digests: DefinitionDigests,\n ): Effect.Effect<ResolvedBinding, never, DurableWorkerRequirements<A>> =>\n Effect.gen(function* () {\n const binding = yield* capture(agent, (execute) => execute);\n const reporting = yield* captureReporting(backgroundReports(agent.definition));\n\n return { ...binding, digests, reporting };\n }),\n} as const;\n\n/** INTERNAL identity-only capture retained for the legacy direct worker path. */\nexport const makeLegacyWorkerBinding = <A extends ExecutableAgentBinding>(agent: A) =>\n capture(agent, (execute) => execute);\n\nexport const resolveWorkerBinding = Effect.fnUntraced(function* (\n bindings: ReadonlyArray<ResolvedBinding>,\n submission: SubmissionSnapshot,\n) {\n const selection = yield* CurrentBindingSelection;\n const definition = selection === undefined ? undefined : yield* selection.select(submission);\n\n const registered = bindings.filter(\n (binding) =>\n binding.agentId === submission.agentId &&\n (definition === undefined || Object.is(binding.definition, definition)),\n );\n\n const binding = registered[0];\n\n if (registered.length !== 1 || binding === undefined)\n return yield* BindingUnavailable.make({\n agentId: submission.agentId,\n message: \"Exactly one current Agent Binding must match the accepted Submission\",\n });\n\n return binding;\n});\n\n/** Resolve authoring-time admission through exact host registration, never by identity alone. */\nexport const resolveDefinitionBinding = (\n bindings: ReadonlyArray<ResolvedBinding>,\n definition: Pick<Agent.AnyDefinition, \"id\">,\n): Effect.Effect<ResolvedBinding, BindingUnavailable> => {\n const candidates = bindings.filter(\n (binding) => binding.agentId === definition.id && Object.is(binding.definition, definition),\n );\n\n const binding = candidates[0];\n\n return candidates.length === 1 && binding !== undefined\n ? Effect.succeed(binding)\n : Effect.fail(\n BindingUnavailable.make({\n agentId: definition.id,\n message:\n \"Registered admission requires exactly one registration of the exact Agent Definition\",\n }),\n );\n};\n\n/** Application versions and a model Layer, supplied directly or through an existing Binding. */\nexport type AgentRegistration<A extends ExecutableAgentBinding = ExecutableAgentBinding> = (\n | { readonly agent: A; readonly model?: never; readonly definitions: DefinitionDigestInput }\n | {\n readonly agent: A[\"definition\"];\n readonly model: A[\"model\"];\n readonly definitions: DefinitionDigestInput;\n }\n) & {\n /** Explicit operation versions let unchanged unfinished handlers survive toolbox changes. */\n readonly continuity?: {\n readonly versions: ReplayVersions;\n };\n /**\n * Build fresh services for exactly one fenced Attempt, across all its Tool/model turns.\n * Finalizes on completion, suspension, failure and interruption. Never reused after eviction.\n * Resolve invocation authority from the trusted claim identity, not captured caller state.\n * Keep fallible resource acquisition lazy in typed Tool operations; this Layer cannot fail.\n * Provide DurableApprovalSuspension here when resources need retention before approval waits.\n */\n readonly attemptLayer?: (context: AgentAttemptContext) => Layer.Layer<never, never, unknown>;\n};\n\ntype EntryWorkerRequirements<Entry> = Entry extends {\n readonly agent: infer A extends ExecutableAgentBinding;\n}\n ? DurableWorkerRequirements<A>\n : Entry extends {\n readonly agent: infer D extends ExecutableDefinition;\n readonly model: infer M extends ExecutableAgentBinding[\"model\"];\n }\n ? DurableWorkerRequirements<{ readonly definition: D; readonly model: M }>\n : never;\n\ntype AttemptLayerRequirements<Requirements, AttemptLayer> = AttemptLayer extends (\n context: AgentAttemptContext,\n) => Layer.Layer<infer Provides, never, infer Requires>\n ? Exclude<Requirements, Provides> | Requires\n : Requirements;\n\n// Conditional options retain every service they may consume. An absent attempt Layer\n// still needs the original worker services; only a definite Layer can remove them.\ntype EntryRequirements<Entry> = Entry extends unknown\n ? AttemptLayerRequirements<\n EntryWorkerRequirements<Entry>,\n \"attemptLayer\" extends keyof Entry ? Entry[\"attemptLayer\"] : undefined\n >\n : never;\n\ntype RegistrationRequirements<Entries extends ReadonlyArray<AgentRegistration>> = EntryRequirements<\n Entries[number]\n>;\n\nconst registrationDefinitions = (entry: AgentRegistration): DefinitionDigestInput => {\n const definition = entry.model === undefined ? entry.agent.definition : entry.agent;\n const automatic = backgroundReports(definition);\n\n const declaredDefinitions =\n definition.updates === undefined\n ? entry.definitions\n : {\n ...entry.definitions,\n agent: {\n declaration: entry.definitions.agent,\n updates: Schema.decodeUnknownSync(Schema.Json)(\n Tool.getJsonSchemaFromSchema(definition.updates),\n ),\n updateProtocol: { schemaVersion: 1, tool: \"emit_update\" },\n },\n };\n\n const definitions =\n automatic.length === 0\n ? declaredDefinitions\n : {\n ...declaredDefinitions,\n agent: {\n declaration: declaredDefinitions.agent,\n backgroundReporting: automatic.map((report) => ({\n delegationId: report.delegationId,\n targetAgentId: report.target.id,\n mode: \"standard\",\n // Preserve the fingerprint of existing standard registrations.\n destinationDelegationId: null,\n })),\n },\n };\n\n const exposure = definition.toolExposure;\n\n if (\n exposure === undefined &&\n !Object.values(definition.toolkit.tools).some(\n (tool) =>\n Context.get(tool.annotations, DiscoveryTool) || Context.get(tool.annotations, PinnedTool),\n )\n )\n return definitions;\n\n return {\n ...definitions,\n agent: {\n declaration: definitions.agent,\n toolExposure: {\n initialToolNames: exposure === undefined ? null : [...(exposure.initialToolNames ?? [])],\n maxTools: exposure?.maxTools ?? 64,\n maxSchemaBytes: exposure?.maxSchemaBytes ?? 262_144,\n requiredCompletion:\n definition.completion?.required === true ? definition.completion.tool : null,\n tools: Object.values(definition.toolkit.tools).map((tool) => ({\n name: tool.name,\n pinned: Context.get(tool.annotations, PinnedTool),\n discovery: Context.get(tool.annotations, DiscoveryTool),\n namespace: Context.get(tool.annotations, ToolNamespace) ?? null,\n includesCatalogDocumentation: Context.get(tool.annotations, IncludesCatalogDocumentation),\n additional: Context.get(tool.annotations, AdditionalToolCatalog).map((entry) => ({\n name: entry.tool.name,\n namespace: entry.namespace,\n method: entry.method,\n })),\n })),\n },\n },\n };\n};\n\n// The public signature distributes over descriptors, including optional attempt Layers.\n// The implementation consumes their erased union and captures the selected Layer's context.\nfunction compileRegistration<Entry extends AgentRegistration>(\n entry: Entry,\n): Effect.Effect<ResolvedBinding, DigestError, Crypto.Crypto | EntryRequirements<Entry>>;\nfunction compileRegistration(entry: AgentRegistration) {\n return Effect.flatMap(\n Effect.try({\n try: () => registrationDefinitions(entry),\n catch: () =>\n DigestError.make({ message: \"Agent update schema has no serializable wire contract\" }),\n }),\n (definitions) =>\n Effect.gen(function* () {\n const agent =\n // The heterogeneous descriptor erases model services; the overload retains EntryRequirements.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n entry.model === undefined ? entry.agent : { definition: entry.agent, model: entry.model };\n\n // Omitted attempt services need no Layer construction or provisioning scope.\n const binding = yield* entry.attemptLayer === undefined\n ? // Capture closes the erased requirements over the registration's actual Context.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n capture(agent, (execute) => execute)\n : // The selected Layer discharges its services before the remaining Context is captured.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n captureWithAttemptLayer(agent, entry.attemptLayer);\n\n const reporting = yield* captureReporting(backgroundReports(binding.definition));\n\n return {\n ...binding,\n ...(yield* compileBindingContracts(\n binding.definition,\n definitions,\n entry.continuity?.versions,\n )),\n reporting,\n };\n }),\n );\n}\n\n/** Compile heterogeneous Agent descriptors into exact, dependency-closed worker registrations. */\nexport const compileRegistrations = <const Entries extends ReadonlyArray<AgentRegistration>>(\n entries: Entries,\n): Effect.Effect<\n ReadonlyArray<ResolvedBinding>,\n DigestError,\n Crypto.Crypto | RegistrationRequirements<Entries>\n> => {\n return Effect.forEach(entries, compileRegistration<Entries[number]>);\n};\n"],"mappings":";;;;;;;;;;;;;AAmCA,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CAAE,SAAS;CAAS,SAAS,OAAO;AAAO,CAC7C,CAAC,CAAC,CAAC;;AAsBH,MAAa,0BAA0B,QAAQ,UAC7C,gDACA,EAAE,oBAAoB,KAAA,EAAU,CAClC;;AAGA,MAAa,0BACX,MACA,UAEA,KAAK,UAAU,MAAM,SACrB,KAAK,UAAU,MAAM,SACrB,KAAK,UAAU,MAAM,SACrB,OAAO,cAAc,OAAO,YAAY,cAAc,CAAC,CAAC,CAAC,KAAK,QAAQ,MAAM,MAAM;AAYpF,MAAM,0CAA0B,IAAI,QAAiC;AAUrE,MAAM,oCAAoB,IAAI,QAAiE;;AAG/F,MAAa,sBAAsB,OAAO,WAAW,WACnD,YACA,UACA,kBAAiC,MACjC;CAGA,MAAM,SAAS,OAAO,eAAe,OAAO,OAAO,cAAc,OAAO,MAAM,CAAC;CA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AAU,CAAC;EAE/E,OAAO;GACL,GAAG;GACH,GAAI,OAAO,wBACT,QAAQ,YACR,aACA,MAAM,YAAY,QACpB;GACA;EACF;CACF,CAAC,CACL;AACF;;AAGA,MAAa,wBACX,YAKG;CACH,OAAO,OAAO,QAAQ,SAAS,mBAAoC;AACrE"}
1
+ {"version":3,"file":"agent-registration-BovXT8jc.mjs","names":["withProvisionalTextAttempt","run"],"sources":["../src/durable/internal/agent-registration.ts"],"sourcesContent":["import { Crypto, Option, Scope, Context, Effect, Layer, References, Schema, Tracer } from \"effect\";\nimport { Tool } from \"effect/ai\";\n\nimport type * as Agent from \"../../core/Agent.ts\";\nimport {\n type InputPromptSource,\n type InstructionSource,\n type ModelServices,\n type RunDispositionDeclaration,\n} from \"../../core/Agent.ts\";\nimport { type ThreadId, AgentId } from \"../../core/Identifiers.ts\";\nimport { getToolExecutionKind } from \"../../core/SubagentContract.ts\";\nimport {\n AdditionalToolCatalog,\n DiscoveryTool,\n IncludesCatalogDocumentation,\n PinnedTool,\n ToolNamespace,\n} from \"../../core/ToolExposure.ts\";\nimport { type RuntimeBinding } from \"../../engine/AgentRuntime.ts\";\nimport { ContextRolloverTool } from \"../../engine/ContextWindow.ts\";\nimport { getToolExecutionClass } from \"../../engine/DurableStep.ts\";\nimport { withAttempt as withProvisionalTextAttempt } from \"../../engine/internal/provisional-text.ts\";\nimport {\n BackgroundReporting,\n WorkerReportPreparationFailure,\n type WorkerReporting,\n} from \"../../engine/SubagentHost.ts\";\nimport { digestDefinitions, digestJson, DigestError } from \"../Digest.ts\";\nimport type { DurableWorkerFailure, DurableWorkerRequirements } from \"../DurableAgentRuntime.ts\";\nimport type { DefinitionDigestInput, Digest, PersistedJson } from \"../Records.ts\";\nimport { DefinitionDigests, ReplayContract } from \"../Records.ts\";\nimport type { Claim, Settlement, SubmissionSnapshot } from \"../SubmissionLedger.ts\";\n\n/** No unique current Binding can execute the stable Agent identity or decode its accepted input. */\nexport class BindingUnavailable extends Schema.TaggedError<BindingUnavailable>()(\n \"BindingUnavailable\",\n { agentId: AgentId, message: Schema.String },\n) {}\n\nexport type DurableBindingFailure = BindingUnavailable;\n\n/**\n * Submission execution/recovery routing for stable identities shared by current Definitions.\n * Worker declarations and peer-messaging endpoints still require unique Agent identities.\n */\nexport interface BindingSelection {\n /** Change when routing changes, so hosts can retry parked work without rewriting admission. */\n readonly key: string;\n /**\n * Select an exact registered Definition using the canonical Submission and authoritative host\n * state. Undefined retains unique-identity resolution. Never grant authority or mutate here;\n * input decoding, replay contracts and current Tool authorization still apply after selection.\n */\n readonly select: (\n submission: SubmissionSnapshot,\n ) => Effect.Effect<Agent.AnyDefinition | undefined, DurableWorkerFailure | BindingUnavailable>;\n}\n\n/** Captured at runtime construction; callers cannot replace routing during an Attempt. */\nexport const CurrentBindingSelection = Context.Reference<BindingSelection | undefined>(\n \"@effect-agent/thread/CurrentBindingSelection\",\n { defaultValue: () => undefined },\n);\n\n/** Exact immutable admission, lineage and delivery evidence; never an executable-code gate. */\nexport const definitionDigestsEqual = (\n left: DefinitionDigests,\n right: DefinitionDigests,\n): boolean =>\n left.agent === right.agent &&\n left.model === right.model &&\n left.tools === right.tools &&\n Schema.toEquivalence(Schema.UndefinedOr(ReplayContract))(left.replay, right.replay);\n\n/**\n * Explicit versions must cover every current Tool. Change a version when handler meaning,\n * durable Step names/codecs, external idempotency keys, authorization, completion projection,\n * or child/report protocols change. JSON Schema cannot detect handler or codec-transform changes.\n */\nexport interface ReplayVersions {\n readonly tools: Readonly<Record<string, PersistedJson>>;\n}\n\n// These are immutable declaration projections, never model or admission contexts.\nconst replaySchemaProjections = new WeakMap<Schema.Top, Schema.Json>();\n\ntype CachedFallbackContracts = {\n readonly tools: ReadonlyArray<Tool.Any>;\n readonly completionTool: string | undefined;\n readonly completionFromTools: ReadonlyArray<string>;\n readonly version: PersistedJson;\n readonly contracts: Record<string, Digest>;\n};\n\nconst fallbackContracts = new WeakMap<Crypto.Crypto, WeakMap<object, CachedFallbackContracts>>();\n\n/** Hash current operation contracts; no historical definitions or schemas are retained. */\nexport const toolReplayContracts = Effect.fnUntraced(function* (\n definition: Agent.AnyDefinition,\n versions?: ReplayVersions,\n fallbackVersion: PersistedJson = null,\n) {\n // Optional lookup preserves validation before a missing-service defect. A\n // different host Crypto service must never inherit another host's digest map.\n const crypto = Option.getOrUndefined(yield* Effect.serviceOption(Crypto.Crypto));\n\n const invalidContracts = () =>\n DigestError.make({\n message: \"Operation contracts require serializable codecs and a version for every Tool\",\n });\n\n const prepared = yield* Effect.try({\n try: () => {\n const tools = Object.values(definition.toolkit.tools);\n const completionTool = definition.completion?.tool;\n const completionFromTools = definition.completionFromTools?.map(({ tool }) => tool) ?? [];\n // Object-valued versions may be mutable caller data. Only primitive fallback\n // versions can reuse a result, and only one result is retained per toolkit.\n\n const cacheable =\n versions === undefined && (fallbackVersion === null || typeof fallbackVersion !== \"object\");\n\n const cached =\n cacheable && crypto !== undefined\n ? fallbackContracts.get(crypto)?.get(definition.toolkit.tools)\n : undefined;\n\n if (\n cached !== undefined &&\n cached.version === fallbackVersion &&\n cached.completionTool === completionTool &&\n cached.completionFromTools.length === completionFromTools.length &&\n cached.completionFromTools.every((tool, index) => tool === completionFromTools[index]) &&\n cached.tools.length === tools.length &&\n cached.tools.every((tool, index) => tool === tools[index])\n )\n return { _tag: \"Cached\" as const, contracts: { ...cached.contracts } };\n\n const jsonSchema = (schema: Schema.Top) => {\n const cached = replaySchemaProjections.get(schema);\n\n if (cached !== undefined) return cached;\n\n const projection = Schema.decodeUnknownSync(Schema.Json)(\n Tool.getJsonSchemaFromSchema(schema),\n );\n\n replaySchemaProjections.set(schema, projection);\n\n return projection;\n };\n\n return {\n _tag: \"Compile\" as const,\n jsonSchema,\n cacheable,\n tools,\n completionTool,\n completionFromTools,\n };\n },\n catch: () =>\n DigestError.make({\n message: \"Operation contracts require serializable codecs and a version for every Tool\",\n }),\n });\n\n if (prepared._tag === \"Cached\") return prepared.contracts;\n\n const declarations = yield* Effect.forEach(\n prepared.tools,\n Effect.fnUntraced(function* (tool) {\n const { version, present } = yield* Effect.try({\n try: () => ({\n version: versions === undefined ? fallbackVersion : versions.tools[tool.name],\n present: versions === undefined || Object.hasOwn(versions.tools, tool.name),\n }),\n catch: invalidContracts,\n });\n\n if (version === undefined || !present) return yield* invalidContracts();\n\n return yield* Effect.try({\n try: () => ({\n name: tool.name,\n contract: {\n version,\n ...(Tool.isProviderDefined(tool)\n ? {\n provider: {\n id: tool.id,\n providerName: tool.providerName,\n args: Schema.decodeUnknownSync(Schema.Json)(tool.args ?? null),\n requiresHandler: tool.requiresHandler,\n },\n readonly: Context.get(tool.annotations, Tool.Readonly),\n }\n : {}),\n parameters: prepared.jsonSchema(tool.parametersSchema),\n success: prepared.jsonSchema(tool.successSchema),\n failure: prepared.jsonSchema(tool.failureSchema),\n failureMode: tool.failureMode,\n needsApproval:\n typeof tool.needsApproval === \"function\" ? \"dynamic\" : (tool.needsApproval ?? false),\n executionClass: getToolExecutionClass(tool),\n executionKind: getToolExecutionKind(tool.annotations),\n contextRollover: Context.get(tool.annotations, ContextRolloverTool),\n completion: definition.completion?.tool === tool.name,\n completionFromTool:\n definition.completionFromTools?.some(\n (declaration) => declaration.tool === tool.name,\n ) ?? false,\n },\n }),\n catch: invalidContracts,\n });\n }),\n );\n\n const contracts = Object.fromEntries(\n yield* Effect.forEach(declarations, ({ name, contract }) =>\n digestJson(contract).pipe(Effect.map((digest) => [name, digest] as const)),\n ),\n );\n\n if (prepared.cacheable && crypto !== undefined) {\n const cache = fallbackContracts.get(crypto) ?? new WeakMap<object, CachedFallbackContracts>();\n\n cache.set(definition.toolkit.tools, {\n tools: prepared.tools,\n completionTool: prepared.completionTool,\n completionFromTools: prepared.completionFromTools,\n version: fallbackVersion,\n contracts: { ...contracts },\n });\n fallbackContracts.set(crypto, cache);\n }\n\n return contracts;\n});\n\n/** Compile current metadata without acquiring executable services. */\nexport const compileBindingContracts = Effect.fnUntraced(function* (\n definition: Agent.AnyDefinition,\n definitions: DefinitionDigestInput,\n versions?: ReplayVersions,\n): Effect.fn.Return<Pick<ResolvedBinding, \"digests\">, DigestError, Crypto.Crypto> {\n const digests = yield* digestDefinitions(definitions);\n const tools = yield* toolReplayContracts(definition, versions, definitions.tools);\n\n return {\n digests: DefinitionDigests.make({\n ...digests,\n replay: ReplayContract.make({ agent: digests.agent, tools }),\n }),\n };\n});\n\ntype ExecutableDefinition = Agent.AnyDefinition & {\n readonly instructions: InstructionSource<never, unknown, unknown>;\n readonly inputPrompt?: InputPromptSource<never, unknown, unknown> | undefined;\n};\n\n/** Executable model Binding accepted by durable registration descriptors. */\nexport type ExecutableAgentBinding = {\n readonly definition: ExecutableDefinition;\n readonly model: Layer.Layer<ModelServices, never, unknown>;\n};\n\n/**\n * Internal coordinator entry point for one fenced Attempt over an already-granted claim.\n * The generic signature matches `runAttempt` and is specialized for each captured Agent.\n */\ntype ResolvedAttemptDriver = <\n InputSchema extends Schema.Top,\n OutputSchema extends Schema.Top,\n Instructions,\n Tools extends Record<string, Tool.Any>,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue extends\n | RunDispositionDeclaration<OutputSchema[\"Type\"], Schema.Top>\n | undefined,\n InputPromptValue extends InputPromptSource<InputSchema[\"Type\"], unknown, unknown> | undefined,\n UpdatesSchema extends Schema.Top | undefined,\n>(\n agent: RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n threadId: ThreadId,\n claim: Claim,\n) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n DurableWorkerRequirements<\n RuntimeBinding<\n InputSchema,\n OutputSchema,\n Instructions,\n Tools,\n Provider,\n ModelProvides,\n ModelRequires,\n InstructionError,\n InstructionRequirements,\n RunDispositionValue,\n InputPromptValue,\n UpdatesSchema\n >,\n InstructionRequirements\n >\n>;\n\ntype CapturedAttempt<A extends ExecutableAgentBinding> = (\n agent: A,\n threadId: ThreadId,\n claim: Claim,\n) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n DurableWorkerRequirements<A>\n>;\n\n/**\n * An Agent with its worker services captured, ready to drive a fenced Attempt.\n * Concrete Schema and model types stay inside this closure when registrations are collected.\n */\ninterface CapturedBinding {\n readonly agentId: AgentId;\n /** Exact immutable definition whose codecs and behavior the worker captured. */\n readonly definition: Agent.AnyDefinition;\n /** Captured independently from per-Attempt services: report preparation has no fenced Claim. */\n readonly reporting?: ReadonlyArray<WorkerReporting<WorkerReportPreparationFailure>>;\n readonly attempt: (\n driver: ResolvedAttemptDriver,\n threadId: ThreadId,\n claim: Claim,\n ) => Effect.Effect<Option.Option<Settlement>, DurableWorkerFailure | DurableBindingFailure>;\n}\n\n// Registrations outlive their construction span. Dependencies remain captured,\n// while every attempt/report inherits the invoking fiber's tracing state.\nconst omitTraceContext = Context.omit(\n Scope.Scope,\n Tracer.ParentSpan,\n Tracer.Tracer,\n Tracer.MinimumTraceLevel,\n Tracer.CurrentTraceLevel,\n References.TracerEnabled,\n References.TracerTimingEnabled,\n References.TracerSpanAnnotations,\n References.TracerSpanLinks,\n References.CurrentLoggers,\n References.CurrentLogLevel,\n References.MinimumLogLevel,\n References.CurrentStackFrame,\n References.CurrentLogAnnotations,\n References.CurrentLogSpans,\n);\n\n// R describes captured application services; ParentSpan is supplied by the\n// live invocation rather than stored as a registration dependency.\nconst withoutTraceContext = <R>(context: Context.Context<R>): Context.Context<R> =>\n omitTraceContext(context) as Context.Context<R>;\n\nconst captureReporting = <E, R>(reports: ReadonlyArray<WorkerReporting<E, R>>) =>\n Effect.map(\n Effect.context<Exclude<R, Scope.Scope>>().pipe(Effect.map(withoutTraceContext)),\n (context) =>\n reports.map((report): WorkerReporting<WorkerReportPreparationFailure> => ({\n ...report,\n prepare: (value) =>\n Effect.scoped(Effect.suspend(() => report.prepare(value))).pipe(\n Effect.provide(context),\n Effect.mapError((error) =>\n Schema.is(WorkerReportPreparationFailure)(error)\n ? error\n : WorkerReportPreparationFailure.make({ stage: \"preparation\" }),\n ),\n ),\n })),\n );\n\nconst backgroundReports = (definition: Agent.AnyDefinition) => [\n ...new Set(\n Object.values(definition.toolkit.tools).flatMap((tool) => {\n const report = Context.get(tool.annotations, BackgroundReporting);\n\n return report === undefined ? [] : [report];\n }),\n ),\n];\n\n/** One exact executable registration used by durable claim-time resolution. */\nexport interface ResolvedBinding extends CapturedBinding {\n readonly digests: DefinitionDigests;\n}\n\n/** Trusted claim identity for resolving per-Attempt application services. Not model input. */\nexport interface AgentAttemptContext {\n readonly threadId: ThreadId;\n readonly submissionId: Claim[\"submissionId\"];\n readonly attemptId: Claim[\"attemptId\"];\n}\n\nconst capture = <A extends ExecutableAgentBinding, Requires>(\n agent: A,\n prepare: (\n execute: ReturnType<CapturedAttempt<A>>,\n context: AgentAttemptContext,\n ) => Effect.Effect<\n Option.Option<Settlement>,\n DurableWorkerFailure | DurableBindingFailure,\n Requires\n >,\n): Effect.Effect<CapturedBinding, never, Requires> =>\n Effect.map(\n Effect.context<Requires>().pipe(Effect.map(withoutTraceContext)),\n (context): CapturedBinding => ({\n agentId: agent.definition.id,\n definition: agent.definition,\n attempt: (driver, threadId, claim) => {\n // Registration closes one concrete Binding before heterogeneous registrations are\n // collected. TypeScript cannot instantiate the higher-rank RuntimeBinding parameters\n // from the intentionally erased public shape, so specialize the driver back to A here.\n const run = driver as unknown as CapturedAttempt<A>;\n\n const execute = withProvisionalTextAttempt(\n run(agent, threadId, claim),\n threadId,\n claim.submissionId,\n claim.attemptId,\n );\n\n return prepare(execute, {\n threadId,\n submissionId: claim.submissionId,\n attemptId: claim.attemptId,\n }).pipe(Effect.provide(context));\n },\n }),\n );\n\nconst captureWithAttemptLayer = <A extends ExecutableAgentBinding, Provides, Requires>(\n agent: A,\n attemptLayer: (context: AgentAttemptContext) => Layer.Layer<Provides, never, Requires>,\n) =>\n capture(agent, (execute, context) =>\n execute.pipe(Effect.provide(Layer.fresh(attemptLayer(context)))),\n );\n\n/**\n * Build one exact worker registration from an executable Agent Binding and\n * its already-computed definition digests.\n *\n * `make(agent, digests)` captures the binding plus its worker-requirement\n * Context at Layer/effect construction time. Hosts that start from application\n * version declarations should use `compileRegistrations`; low-level fixtures\n * may supply a previously computed digest triple directly.\n */\nexport const DurableWorkerBinding = {\n make: <A extends ExecutableAgentBinding>(\n agent: A,\n digests: DefinitionDigests,\n ): Effect.Effect<ResolvedBinding, never, DurableWorkerRequirements<A>> =>\n Effect.gen(function* () {\n const binding = yield* capture(agent, (execute) => execute);\n const reporting = yield* captureReporting(backgroundReports(agent.definition));\n\n return { ...binding, digests, reporting };\n }),\n} as const;\n\n/** INTERNAL identity-only capture retained for the legacy direct worker path. */\nexport const makeLegacyWorkerBinding = <A extends ExecutableAgentBinding>(agent: A) =>\n capture(agent, (execute) => execute);\n\nexport const resolveWorkerBinding = Effect.fnUntraced(function* (\n bindings: ReadonlyArray<ResolvedBinding>,\n submission: SubmissionSnapshot,\n) {\n const selection = yield* CurrentBindingSelection;\n const definition = selection === undefined ? undefined : yield* selection.select(submission);\n\n const registered = bindings.filter(\n (binding) =>\n binding.agentId === submission.agentId &&\n (definition === undefined || Object.is(binding.definition, definition)),\n );\n\n const binding = registered[0];\n\n if (registered.length !== 1 || binding === undefined)\n return yield* BindingUnavailable.make({\n agentId: submission.agentId,\n message: \"Exactly one current Agent Binding must match the accepted Submission\",\n });\n\n return binding;\n});\n\n/** Resolve authoring-time admission through exact host registration, never by identity alone. */\nexport const resolveDefinitionBinding = (\n bindings: ReadonlyArray<ResolvedBinding>,\n definition: Pick<Agent.AnyDefinition, \"id\">,\n): Effect.Effect<ResolvedBinding, BindingUnavailable> => {\n const candidates = bindings.filter(\n (binding) => binding.agentId === definition.id && Object.is(binding.definition, definition),\n );\n\n const binding = candidates[0];\n\n return candidates.length === 1 && binding !== undefined\n ? Effect.succeed(binding)\n : Effect.fail(\n BindingUnavailable.make({\n agentId: definition.id,\n message:\n \"Registered admission requires exactly one registration of the exact Agent Definition\",\n }),\n );\n};\n\n/** Application versions and a model Layer, supplied directly or through an existing Binding. */\nexport type AgentRegistration<A extends ExecutableAgentBinding = ExecutableAgentBinding> = (\n | { readonly agent: A; readonly model?: never; readonly definitions: DefinitionDigestInput }\n | {\n readonly agent: A[\"definition\"];\n readonly model: A[\"model\"];\n readonly definitions: DefinitionDigestInput;\n }\n) & {\n /** Explicit operation versions let unchanged unfinished handlers survive toolbox changes. */\n readonly continuity?: {\n readonly versions: ReplayVersions;\n };\n /**\n * Build fresh services for exactly one fenced Attempt, across all its Tool/model turns.\n * Finalizes on completion, suspension, failure and interruption. Never reused after eviction.\n * Resolve invocation authority from the trusted claim identity, not captured caller state.\n * Keep fallible resource acquisition lazy in typed Tool operations; this Layer cannot fail.\n * Provide DurableApprovalSuspension here when resources need retention before approval waits.\n */\n readonly attemptLayer?: (context: AgentAttemptContext) => Layer.Layer<never, never, unknown>;\n};\n\ntype EntryWorkerRequirements<Entry> = Entry extends {\n readonly agent: infer A extends ExecutableAgentBinding;\n}\n ? DurableWorkerRequirements<A>\n : Entry extends {\n readonly agent: infer D extends ExecutableDefinition;\n readonly model: infer M extends ExecutableAgentBinding[\"model\"];\n }\n ? DurableWorkerRequirements<{ readonly definition: D; readonly model: M }>\n : never;\n\ntype AttemptLayerRequirements<Requirements, AttemptLayer> = AttemptLayer extends (\n context: AgentAttemptContext,\n) => Layer.Layer<infer Provides, never, infer Requires>\n ? Exclude<Requirements, Provides> | Requires\n : Requirements;\n\n// Conditional options retain every service they may consume. An absent attempt Layer\n// still needs the original worker services; only a definite Layer can remove them.\ntype EntryRequirements<Entry> = Entry extends unknown\n ? AttemptLayerRequirements<\n EntryWorkerRequirements<Entry>,\n \"attemptLayer\" extends keyof Entry ? Entry[\"attemptLayer\"] : undefined\n >\n : never;\n\ntype RegistrationRequirements<Entries extends ReadonlyArray<AgentRegistration>> = EntryRequirements<\n Entries[number]\n>;\n\nconst registrationDefinitions = (entry: AgentRegistration): DefinitionDigestInput => {\n const definition = entry.model === undefined ? entry.agent.definition : entry.agent;\n const automatic = backgroundReports(definition);\n\n const declaredDefinitions =\n definition.updates === undefined\n ? entry.definitions\n : {\n ...entry.definitions,\n agent: {\n declaration: entry.definitions.agent,\n updates: Schema.decodeUnknownSync(Schema.Json)(\n Tool.getJsonSchemaFromSchema(definition.updates),\n ),\n updateProtocol: { schemaVersion: 1, tool: \"emit_update\" },\n },\n };\n\n const definitions =\n automatic.length === 0\n ? declaredDefinitions\n : {\n ...declaredDefinitions,\n agent: {\n declaration: declaredDefinitions.agent,\n backgroundReporting: automatic.map((report) => ({\n delegationId: report.delegationId,\n targetAgentId: report.target.id,\n mode: \"standard\",\n // Preserve the fingerprint of existing standard registrations.\n destinationDelegationId: null,\n })),\n },\n };\n\n const exposure = definition.toolExposure;\n\n if (\n exposure === undefined &&\n !Object.values(definition.toolkit.tools).some(\n (tool) =>\n Context.get(tool.annotations, DiscoveryTool) || Context.get(tool.annotations, PinnedTool),\n )\n )\n return definitions;\n\n return {\n ...definitions,\n agent: {\n declaration: definitions.agent,\n toolExposure: {\n initialToolNames: exposure === undefined ? null : [...(exposure.initialToolNames ?? [])],\n maxTools: exposure?.maxTools ?? 64,\n maxSchemaBytes: exposure?.maxSchemaBytes ?? 262_144,\n requiredCompletion:\n definition.completion?.required === true ? definition.completion.tool : null,\n tools: Object.values(definition.toolkit.tools).map((tool) => ({\n name: tool.name,\n pinned: Context.get(tool.annotations, PinnedTool),\n discovery: Context.get(tool.annotations, DiscoveryTool),\n namespace: Context.get(tool.annotations, ToolNamespace) ?? null,\n includesCatalogDocumentation: Context.get(tool.annotations, IncludesCatalogDocumentation),\n additional: Context.get(tool.annotations, AdditionalToolCatalog).map((entry) => ({\n name: entry.tool.name,\n namespace: entry.namespace,\n method: entry.method,\n })),\n })),\n },\n },\n };\n};\n\n// The public signature distributes over descriptors, including optional attempt Layers.\n// The implementation consumes their erased union and captures the selected Layer's context.\nfunction compileRegistration<Entry extends AgentRegistration>(\n entry: Entry,\n): Effect.Effect<ResolvedBinding, DigestError, Crypto.Crypto | EntryRequirements<Entry>>;\nfunction compileRegistration(entry: AgentRegistration) {\n return Effect.flatMap(\n Effect.try({\n try: () => registrationDefinitions(entry),\n catch: () =>\n DigestError.make({ message: \"Agent update schema has no serializable wire contract\" }),\n }),\n (definitions) =>\n Effect.gen(function* () {\n const agent =\n // The heterogeneous descriptor erases model services; the overload retains EntryRequirements.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n entry.model === undefined ? entry.agent : { definition: entry.agent, model: entry.model };\n\n // Omitted attempt services need no Layer construction or provisioning scope.\n const binding = yield* entry.attemptLayer === undefined\n ? // Capture closes the erased requirements over the registration's actual Context.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n capture(agent, (execute) => execute)\n : // The selected Layer discharges its services before the remaining Context is captured.\n // @effect-diagnostics-next-line anyUnknownInErrorContext:off\n captureWithAttemptLayer(agent, entry.attemptLayer);\n\n const reporting = yield* captureReporting(backgroundReports(binding.definition));\n\n return {\n ...binding,\n ...(yield* compileBindingContracts(\n binding.definition,\n definitions,\n entry.continuity?.versions,\n )),\n reporting,\n };\n }),\n );\n}\n\n/** Compile heterogeneous Agent descriptors into exact, dependency-closed worker registrations. */\nexport const compileRegistrations = <const Entries extends ReadonlyArray<AgentRegistration>>(\n entries: Entries,\n): Effect.Effect<\n ReadonlyArray<ResolvedBinding>,\n DigestError,\n Crypto.Crypto | RegistrationRequirements<Entries>\n> => {\n return Effect.forEach(entries, compileRegistration<Entries[number]>);\n};\n"],"mappings":";;;;;;;;;;;;;AAmCA,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CAAE,SAAS;CAAS,SAAS,OAAO;AAAO,CAC7C,CAAC,CAAC,CAAC;;AAsBH,MAAa,0BAA0B,QAAQ,UAC7C,gDACA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CACrD,OAAO,OAAO,QACZ,OAAO,IAAI;EACT,WAAW,wBAAwB,KAAK;EACxC,aACE,YAAY,KAAK,EAAE,SAAS,wDAAwD,CAAC;CACzF,CAAC,IACA,gBACC,OAAO,IAAI,aAAa;EACtB,MAAM,QAGJ,MAAM,UAAU,KAAA,IAAY,MAAM,QAAQ;GAAE,YAAY,MAAM;GAAO,OAAO,MAAM;EAAM;EAG1F,MAAM,UAAU,OAAO,MAAM,iBAAiB,KAAA,IAG1C,QAAQ,QAAQ,YAAY,OAAO,IAGnC,wBAAwB,OAAO,MAAM,YAAY;EAErD,MAAM,YAAY,OAAO,iBAAiB,kBAAkB,QAAQ,UAAU,CAAC;EAE/E,OAAO;GACL,GAAG;GACH,GAAI,OAAO,wBACT,QAAQ,YACR,aACA,MAAM,YAAY,QACpB;GACA;EACF;CACF,CAAC,CACL;AACF;;AAGA,MAAa,wBACX,YAKG;CACH,OAAO,OAAO,QAAQ,SAAS,mBAAoC;AACrE"}
@@ -3,7 +3,7 @@ import { CodeModeDefinition, t as CodeMode_d_exports } from "./CodeMode.mjs";
3
3
  import { Context, Effect, Schema } from "effect";
4
4
  import { Tool } from "effect/ai";
5
5
  declare namespace BrowserUse_d_exports {
6
- export { BrowserCdp, BrowserUseError, CloseTabRequest, FrameInfo, FramesRequest, SendRequest, Tab, TargetId, layer, make };
6
+ export { BrowserCdp, BrowserUseError, BrowserUseFailure, BrowserUsePolicyError, CloseTabRequest, FrameInfo, FramesRequest, SendRequest, Tab, TargetId, layer, make };
7
7
  }
8
8
  export declare const TargetId: Schema.NonEmptyString;
9
9
  export declare const SendRequest: Schema.Struct<{
@@ -11,7 +11,9 @@ export declare const SendRequest: Schema.Struct<{
11
11
  readonly params: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
12
12
  /** Omit to address the session's original page. Discover other pages with cdp.tabs(). */
13
13
  readonly targetId: Schema.optionalKey<Schema.NonEmptyString>;
14
- /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames(). */
14
+ /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames().
15
+ * The model toolkit requires this for world creation and context-scoped evaluation.
16
+ */
15
17
  readonly frameId: Schema.optionalKey<Schema.NonEmptyString>;
16
18
  }>;
17
19
  export declare const Tab: Schema.Struct<{
@@ -37,12 +39,26 @@ declare const BrowserUseError_base: Schema.Class<BrowserUseError, Schema.TaggedS
37
39
  }>, import("effect/Cause").YieldableError>;
38
40
  /** A command may have changed the website even when its response is unavailable. Never replay it automatically. */
39
41
  export declare class BrowserUseError extends BrowserUseError_base {}
42
+ declare const BrowserUsePolicyError_base: Schema.Class<BrowserUsePolicyError, Schema.TaggedStruct<"BrowserUsePolicyError", {
43
+ readonly reason: Schema.Literal<"observation-required">;
44
+ readonly dispatch: Schema.Literal<"not-dispatched">;
45
+ readonly nextStep: Schema.Literal<"fresh-observation">;
46
+ readonly message: Schema.Literal<"Inspect the current page before attempting this browser action.">;
47
+ }>, import("effect/Cause").YieldableError>;
48
+ /**
49
+ * A host-confirmed policy refusal before dispatch. Hosts must establish that the
50
+ * entire Cause is expected before using this error; never hide mixed failures,
51
+ * defects or interruption behind it. Fields contain no provider or page content.
52
+ */
53
+ export declare class BrowserUsePolicyError extends BrowserUsePolicyError_base {}
54
+ export declare const BrowserUseFailure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
55
+ export type BrowserUseFailure = typeof BrowserUseFailure.Type;
40
56
  declare const BrowserCdp_base: Context.ServiceClass<BrowserCdp, "@effect-agent/BrowserUse/BrowserCdp", {
41
- readonly send: (request: typeof SendRequest.Type) => Effect.Effect<Schema.Json, BrowserUseError>;
42
- readonly tabs: Effect.Effect<ReadonlyArray<typeof Tab.Type>, BrowserUseError>;
43
- readonly frames: (request: typeof FramesRequest.Type) => Effect.Effect<ReadonlyArray<typeof FrameInfo.Type>, BrowserUseError>;
44
- readonly newTab: Effect.Effect<typeof Tab.Type, BrowserUseError>;
45
- readonly closeTab: (request: typeof CloseTabRequest.Type) => Effect.Effect<void, BrowserUseError>;
57
+ readonly send: (request: typeof SendRequest.Type) => Effect.Effect<Schema.Json, BrowserUseFailure>;
58
+ readonly tabs: Effect.Effect<ReadonlyArray<typeof Tab.Type>, BrowserUseFailure>;
59
+ readonly frames: (request: typeof FramesRequest.Type) => Effect.Effect<ReadonlyArray<typeof FrameInfo.Type>, BrowserUseFailure>;
60
+ readonly newTab: Effect.Effect<typeof Tab.Type, BrowserUseFailure>;
61
+ readonly closeTab: (request: typeof CloseTabRequest.Type) => Effect.Effect<void, BrowserUseFailure>;
46
62
  }>;
47
63
  /** Host-owned CDP transport. The host authorizes every call and owns browser lifetime and limits. */
48
64
  export declare class BrowserCdp extends BrowserCdp_base {}
@@ -58,11 +74,13 @@ export declare const layer: import("effect/Layer").Layer<Tool.HandlersFor<{
58
74
  readonly params: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
59
75
  /** Omit to address the session's original page. Discover other pages with cdp.tabs(). */
60
76
  readonly targetId: Schema.optionalKey<Schema.NonEmptyString>;
61
- /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames(). */
77
+ /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames().
78
+ * The model toolkit requires this for world creation and context-scoped evaluation.
79
+ */
62
80
  readonly frameId: Schema.optionalKey<Schema.NonEmptyString>;
63
81
  }>;
64
82
  readonly success: Schema.Codec<Schema.Json, Schema.Json, never, never>;
65
- readonly failure: typeof BrowserUseError;
83
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
66
84
  readonly failureMode: "return";
67
85
  }, never>;
68
86
  readonly browser_close_tab: Tool.Tool<"browser_close_tab", {
@@ -70,7 +88,7 @@ export declare const layer: import("effect/Layer").Layer<Tool.HandlersFor<{
70
88
  readonly targetId: Schema.NonEmptyString;
71
89
  }>;
72
90
  readonly success: Schema.Null;
73
- readonly failure: typeof BrowserUseError;
91
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
74
92
  readonly failureMode: "return";
75
93
  }, never>;
76
94
  readonly browser_frames: Tool.Tool<"browser_frames", {
@@ -82,7 +100,7 @@ export declare const layer: import("effect/Layer").Layer<Tool.HandlersFor<{
82
100
  readonly parentFrameId: Schema.NullOr<Schema.NonEmptyString>;
83
101
  readonly url: Schema.String;
84
102
  }>>;
85
- readonly failure: typeof BrowserUseError;
103
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
86
104
  readonly failureMode: "return";
87
105
  }, never>;
88
106
  readonly browser_new_tab: Tool.Tool<"browser_new_tab", {
@@ -92,7 +110,7 @@ export declare const layer: import("effect/Layer").Layer<Tool.HandlersFor<{
92
110
  readonly url: Schema.String;
93
111
  readonly title: Schema.String;
94
112
  }>;
95
- readonly failure: typeof BrowserUseError;
113
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
96
114
  readonly failureMode: "return";
97
115
  }, never>;
98
116
  readonly browser_tabs: Tool.Tool<"browser_tabs", {
@@ -102,7 +120,7 @@ export declare const layer: import("effect/Layer").Layer<Tool.HandlersFor<{
102
120
  readonly url: Schema.String;
103
121
  readonly title: Schema.String;
104
122
  }>>;
105
- readonly failure: typeof BrowserUseError;
123
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
106
124
  readonly failureMode: "return";
107
125
  }, never>;
108
126
  }>, never, BrowserCdp>;
@@ -118,11 +136,13 @@ export declare const make: (options?: {
118
136
  readonly params: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
119
137
  /** Omit to address the session's original page. Discover other pages with cdp.tabs(). */
120
138
  readonly targetId: Schema.optionalKey<Schema.NonEmptyString>;
121
- /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames(). */
139
+ /** Route to a frame's CDP session, including out-of-process frames. Obtain IDs with cdp.frames().
140
+ * The model toolkit requires this for world creation and context-scoped evaluation.
141
+ */
122
142
  readonly frameId: Schema.optionalKey<Schema.NonEmptyString>;
123
143
  }>;
124
144
  readonly success: Schema.Codec<Schema.Json, Schema.Json, never, never>;
125
- readonly failure: typeof BrowserUseError;
145
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
126
146
  readonly failureMode: "return";
127
147
  }, never>;
128
148
  tabs: Tool.Tool<"browser_tabs", {
@@ -132,7 +152,7 @@ export declare const make: (options?: {
132
152
  readonly url: Schema.String;
133
153
  readonly title: Schema.String;
134
154
  }>>;
135
- readonly failure: typeof BrowserUseError;
155
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
136
156
  readonly failureMode: "return";
137
157
  }, never>;
138
158
  frames: Tool.Tool<"browser_frames", {
@@ -144,7 +164,7 @@ export declare const make: (options?: {
144
164
  readonly parentFrameId: Schema.NullOr<Schema.NonEmptyString>;
145
165
  readonly url: Schema.String;
146
166
  }>>;
147
- readonly failure: typeof BrowserUseError;
167
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
148
168
  readonly failureMode: "return";
149
169
  }, never>;
150
170
  newTab: Tool.Tool<"browser_new_tab", {
@@ -154,7 +174,7 @@ export declare const make: (options?: {
154
174
  readonly url: Schema.String;
155
175
  readonly title: Schema.String;
156
176
  }>;
157
- readonly failure: typeof BrowserUseError;
177
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
158
178
  readonly failureMode: "return";
159
179
  }, never>;
160
180
  closeTab: Tool.Tool<"browser_close_tab", {
@@ -162,7 +182,7 @@ export declare const make: (options?: {
162
182
  readonly targetId: Schema.NonEmptyString;
163
183
  }>;
164
184
  readonly success: Schema.Null;
165
- readonly failure: typeof BrowserUseError;
185
+ readonly failure: Schema.Union<readonly [typeof BrowserUseError, typeof BrowserUsePolicyError]>;
166
186
  readonly failureMode: "return";
167
187
  }, never>;
168
188
  };