@creatornader/agent-bridge 0.4.0 → 0.5.0

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 (76) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +73 -7
  3. package/ROADMAP.md +29 -0
  4. package/SECURITY.md +23 -0
  5. package/SKILL.md +5 -1
  6. package/dist/archive.d.ts +2 -2
  7. package/dist/{bridge-service-YTjGr91A.d.ts → bridge-service-CNBKdYXh.d.ts} +2 -1
  8. package/dist/{bridge-store-Boaj-ZbO.d.ts → bridge-store-ByJ6CaJk.d.ts} +1 -0
  9. package/dist/bridge.d.ts +15 -8
  10. package/dist/bridge.js +10 -8
  11. package/dist/{chunk-PDIHDBP3.js → chunk-7VJI2MXI.js} +116 -26
  12. package/dist/chunk-7VJI2MXI.js.map +1 -0
  13. package/dist/{chunk-4VB44KJU.js → chunk-AWE3DFZV.js} +3 -2
  14. package/dist/chunk-AWE3DFZV.js.map +1 -0
  15. package/dist/{chunk-IHZFI7TH.js → chunk-E4OWHGUE.js} +5 -2
  16. package/dist/chunk-E4OWHGUE.js.map +1 -0
  17. package/dist/{chunk-SYGONYMM.js → chunk-HUHG7XTB.js} +6 -5
  18. package/dist/chunk-HUHG7XTB.js.map +1 -0
  19. package/dist/{chunk-DQOZJJZ2.js → chunk-IVG4XWWS.js} +5 -5
  20. package/dist/{chunk-DQOZJJZ2.js.map → chunk-IVG4XWWS.js.map} +1 -1
  21. package/dist/{chunk-3YHVUPU2.js → chunk-P635FAN4.js} +4 -4
  22. package/dist/chunk-P635FAN4.js.map +1 -0
  23. package/dist/{chunk-6BTJE6D4.js → chunk-QNXHDOJ5.js} +56 -23
  24. package/dist/chunk-QNXHDOJ5.js.map +1 -0
  25. package/dist/{chunk-MCKKVNCE.js → chunk-QPC6JHA3.js} +5 -5
  26. package/dist/{chunk-SV3SVBYS.js → chunk-SN7PIVDF.js} +2 -2
  27. package/dist/{chunk-2DFNOLMO.js → chunk-XDNT6ZNZ.js} +9 -6
  28. package/dist/chunk-XDNT6ZNZ.js.map +1 -0
  29. package/dist/{chunk-LAHNQZDN.js → chunk-Z6JP6MYD.js} +2 -2
  30. package/dist/cli.js +9 -9
  31. package/dist/cli.js.map +1 -1
  32. package/dist/client-runtime.d.ts +3 -3
  33. package/dist/client-runtime.js +6 -6
  34. package/dist/contracts/generate.js +1 -1
  35. package/dist/dr.js +3 -3
  36. package/dist/{gateway-BQHpV-MZ.d.ts → gateway-CW-61lvs.d.ts} +2 -2
  37. package/dist/gateway-main.js +5 -5
  38. package/dist/gateway.d.ts +3 -3
  39. package/dist/gateway.js +3 -3
  40. package/dist/index.js +7 -7
  41. package/dist/{postgres-bridge-store-WASumj26.d.ts → postgres-bridge-store-C9KG9Z69.d.ts} +1 -1
  42. package/dist/postgres-production-preflight.d.ts +32 -0
  43. package/dist/postgres-production-preflight.js +249 -0
  44. package/dist/postgres-production-preflight.js.map +1 -0
  45. package/dist/server.js +7 -7
  46. package/dist/{sqlite-edge-store-Bc15DvpX.d.ts → sqlite-edge-store-CdMIOrho.d.ts} +1 -1
  47. package/dist/sqlite.d.ts +3 -3
  48. package/dist/sqlite.js +2 -2
  49. package/docs/architecture-v2.md +36 -5
  50. package/docs/deployment.md +144 -0
  51. package/llms.txt +2 -1
  52. package/openapi/agent-bridge-v2.openapi.json +5 -1
  53. package/package.json +5 -1
  54. package/schemas/agent-bridge-v2.capabilities.json +2 -1
  55. package/schemas/agent-bridge-v2.mcp.json +5 -1
  56. package/schemas/agent-bridge-v2.schema.json +4 -0
  57. package/sql/migrations/007_runtime_role.sql +8 -4
  58. package/sql/migrations/013_row_isolation.sql +71 -8
  59. package/sql/migrations/014_owner_control_plane.sql +124 -31
  60. package/sql/migrations/015_portable_archives.sql +143 -41
  61. package/sql/migrations/016_native_dr_fence.sql +102 -35
  62. package/sql/migrations/018_endpoint_migration_challenges.sql +36 -10
  63. package/sql/migrations/019_endpoint_migration_same_successor.sql +34 -10
  64. package/sql/migrations/020_managed_authority_compat.sql +698 -0
  65. package/sql/migrations/021_native_backup_reader.sql +421 -0
  66. package/sql/setup.sql +1 -3
  67. package/dist/chunk-2DFNOLMO.js.map +0 -1
  68. package/dist/chunk-3YHVUPU2.js.map +0 -1
  69. package/dist/chunk-4VB44KJU.js.map +0 -1
  70. package/dist/chunk-6BTJE6D4.js.map +0 -1
  71. package/dist/chunk-IHZFI7TH.js.map +0 -1
  72. package/dist/chunk-PDIHDBP3.js.map +0 -1
  73. package/dist/chunk-SYGONYMM.js.map +0 -1
  74. /package/dist/{chunk-MCKKVNCE.js.map → chunk-QPC6JHA3.js.map} +0 -0
  75. /package/dist/{chunk-SV3SVBYS.js.map → chunk-SN7PIVDF.js.map} +0 -0
  76. /package/dist/{chunk-LAHNQZDN.js.map → chunk-Z6JP6MYD.js.map} +0 -0
@@ -368,7 +368,7 @@ var operations = [
368
368
  operation({ id: "publish_message", summary: "Create an immutable Agent Bridge v2 message.", request: MessageDraftSchema, response: Type.Object({ created: Type.Boolean(), message: MessageSchema, disposition: Type.Optional(Type.Enum(["committed", "queued"])), authoritative: OptionalBoolean() }, { additionalProperties: true }), scopes: ["messages:write"], providers: ALL_PROVIDERS, mcp: { name: "send" }, http: { method: "POST", path: "/v2/messages", successStatus: 201 }, cli: { command: "send", aliases: ["post"], options: ["source", "project", "type", "kind", "category", "content", "content-type", "data", "payload", "payload-mime", "payload-ref", "payload-ciphertext", "target", "target-agent", "target-agents", "thread-id", "reply-to-id", "correlation-id", "causation-id", "priority", "expires-at", "idempotency-key", "atrib-receipt-id", "informed-by", "metadata", "delivery-mode", "delivery-policy", "delivery-max-attempts", "retry-base-ms", "retry-max-ms", "retry-jitter", "not-before", "message-id"] } }),
369
369
  operation({ id: "history", summary: "Read visible messages after an opaque cursor.", request: HistoryRequestSchema, response: MessagePageSchema, scopes: ["messages:read"], providers: ALL_PROVIDERS, mcp: { name: "history" }, http: { method: "GET", path: "/v2/history", queryAliases: { unacknowledgedBy: ["unacked_by"] } }, cli: { command: "history", aliases: ["inbox", "sent"], options: HistoryCliOptions, variants: [{ command: "get", condition: { kind: "always" }, routesTo: "history", options: HistoryCliOptions, response: Type.Array(LegacyGetRowSchema) }] } }),
370
370
  operation({ id: "record_receipt", summary: "Record caller-bound inbox read receipts.", request: Type.Object({ messageIds: Type.Array(Type.String(), { minItems: 1, maxItems: 200 }) }, { additionalProperties: false }), response: Type.Object({ recorded: Type.Number() }, { additionalProperties: true }), scopes: ["receipts:write"], providers: ALL_PROVIDERS, http: { method: "POST", path: "/v2/receipts" }, cli: { command: "acknowledge", aliases: ["receipt"], options: ["ids"], response: ReceiptCliResponseSchema, variants: [{ command: "ack", condition: { kind: "option-present", option: "ids" }, routesTo: "record_receipt", options: ["ids"], response: ReceiptCliResponseSchema }] } }),
371
- operation({ id: "claim_delivery", summary: "Atomically claim the next targeted delivery.", request: Type.Object({ leaseMs: OptionalNumber(), maxAttempts: OptionalNumber() }, { additionalProperties: false }), response: ClaimResponseSchema, scopes: ["deliveries:claim"], providers: DELIVERY_PROVIDERS, mcp: { name: "claim" }, http: { method: "POST", path: "/v2/deliveries/claim" }, cli: { command: "claim", options: ["lease-ms", "max-attempts"], response: Type.Union([Type.Object({ delivery: DeliverySchema, leaseToken: Type.String() }, { additionalProperties: true }), Type.Null()]) } }),
371
+ operation({ id: "claim_delivery", summary: "Atomically claim the next targeted delivery, or one eligible message when requested.", request: Type.Object({ leaseMs: OptionalNumber(), messageId: Type.Optional(Type.String({ pattern: UUID_PATTERN })), maxAttempts: OptionalNumber() }, { additionalProperties: false }), response: ClaimResponseSchema, scopes: ["deliveries:claim"], providers: DELIVERY_PROVIDERS, mcp: { name: "claim" }, http: { method: "POST", path: "/v2/deliveries/claim" }, cli: { command: "claim", options: ["lease-ms", "message-id", "max-attempts"], response: Type.Union([Type.Object({ delivery: DeliverySchema, leaseToken: Type.String() }, { additionalProperties: true }), Type.Null()]) } }),
372
372
  operation({ id: "list_deliveries", summary: "List caller-visible deliveries.", request: Type.Object({ cursor: OptionalString(), limit: OptionalNumber(), role: Type.Optional(Type.Enum(["recipient", "publisher", "all"])), messageId: OptionalString(), recipient: OptionalString(), states: Type.Optional(Type.Array(DeliveryStateSchema)) }, { additionalProperties: false }), response: DeliveryPageSchema, scopes: ["deliveries:read"], providers: DELIVERY_PROVIDERS, mcp: { name: "list_deliveries" }, http: { method: "GET", path: "/v2/deliveries" }, cli: { command: "deliveries", aliases: ["dead-letters"], options: ["cursor", "limit", "role", "message-id", "recipient", "state"] } }),
373
373
  operation({ id: "list_delivery_events", summary: "List the append-only event history for a delivery.", request: Type.Object({ deliveryId: Type.String(), cursor: OptionalString(), limit: OptionalNumber() }, { additionalProperties: false }), response: DeliveryEventPageSchema, scopes: ["deliveries:read"], providers: DELIVERY_PROVIDERS, mcp: { name: "list_delivery_events" }, http: { method: "GET", path: "/v2/deliveries/{deliveryId}/events" }, cli: { command: "delivery-events", options: ["delivery-id", "cursor", "limit"] } }),
374
374
  operation({ id: "cancel_delivery", summary: "Cancel a delivery as its publisher.", request: DeliveryIdSchema, response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: ["deliveries:manage"], providers: DELIVERY_PROVIDERS, mcp: { name: "cancel_delivery" }, http: { method: "POST", path: "/v2/deliveries/{deliveryId}/cancel" }, cli: { command: "cancel", options: ["delivery-id"], response: Type.Union([DeliverySchema, Type.Null()]) } }),
@@ -425,6 +425,9 @@ function validateRequestForProtocol(operationId, value, protocolVersion) {
425
425
  const unsupported = ["mailbox", "receiptState", "project"].find((field) => value[field] !== void 0);
426
426
  if (unsupported) throw new ContractValidationError(operationId, [{ path: `/${unsupported}`, message: `Field is not supported by protocol ${LEGACY_PROTOCOL_VERSION}` }]);
427
427
  }
428
+ if (operationId === "claim_delivery" && value && typeof value === "object" && value.messageId !== void 0) {
429
+ throw new ContractValidationError(operationId, [{ path: "/messageId", message: `Field is not supported by protocol ${LEGACY_PROTOCOL_VERSION}` }]);
430
+ }
428
431
  }
429
432
  if (operationId !== "negative_acknowledge_delivery" || protocolVersion !== LEGACY_PROTOCOL_VERSION) {
430
433
  return validateRequest(operationId, value);
@@ -532,4 +535,4 @@ export {
532
535
  capabilityDocument,
533
536
  negotiateProtocolVersion
534
537
  };
535
- //# sourceMappingURL=chunk-IHZFI7TH.js.map
538
+ //# sourceMappingURL=chunk-E4OWHGUE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/contracts/registry.ts"],"sourcesContent":["import Type, { type TSchema } from \"@sinclair/typebox\";\nimport { Check, Errors } from \"@sinclair/typebox/value\";\n\nexport const PROTOCOL_VERSION = \"2.1\";\nexport const LEGACY_PROTOCOL_VERSION = \"2.0\";\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LEGACY_PROTOCOL_VERSION, PROTOCOL_VERSION] as const;\nexport const SUPPORTED_PROTOCOL_RANGE = SUPPORTED_PROTOCOL_VERSIONS.join(\",\");\nexport const PROTOCOL_HEADER = \"x-agent-bridge-protocol-version\";\nexport const SUPPORTED_PROTOCOL_HEADER = \"x-agent-bridge-supported-protocol-versions\";\nexport const SCOPE_ENFORCEMENT = true;\n\nconst StringArray = Type.Array(Type.String());\nconst Empty = Type.Object({}, { additionalProperties: false });\nconst OptionalString = () => Type.Optional(Type.String());\nconst OptionalNumber = (options: Record<string, unknown> = {}) => Type.Optional(Type.Number(options));\nconst OptionalBoolean = () => Type.Optional(Type.Boolean());\nconst NullableString = () => Type.Union([Type.String(), Type.Null()]);\nconst NullableNumber = () => Type.Union([Type.Number(), Type.Null()]);\nconst UUID_PATTERN = \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$\";\nconst UUID_V7_PATTERN = \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-7[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$\";\n\nexport const ErrorIssueSchema = Type.Object({\n path: Type.String(),\n message: Type.String(),\n}, { additionalProperties: true });\n\nexport const ErrorEnvelopeSchema = Type.Object({\n error: Type.Object({\n code: Type.String(),\n requestId: Type.String(),\n message: OptionalString(),\n operation: OptionalString(),\n issues: Type.Optional(Type.Array(ErrorIssueSchema)),\n details: Type.Optional(Type.Any()),\n supportedProtocolVersions: Type.Optional(StringArray),\n }, { additionalProperties: true }),\n}, { additionalProperties: true });\n\nconst DeliveryPolicySchema = Type.Union([\n Type.Object({ mode: Type.Literal(\"mailbox\") }, { additionalProperties: false }),\n Type.Object({\n mode: Type.Literal(\"leased\"),\n maxAttempts: Type.Number(),\n retryBaseDelayMs: Type.Number(),\n retryMaxDelayMs: Type.Number(),\n retryJitterRatio: Type.Number(),\n notBefore: OptionalString(),\n }, { additionalProperties: false }),\n]);\n\nconst DeliveryPolicyInputSchema = Type.Object({\n mode: Type.Optional(Type.Enum([\"mailbox\", \"leased\"])),\n maxAttempts: OptionalNumber(),\n retryBaseDelayMs: OptionalNumber(),\n retryMaxDelayMs: OptionalNumber(),\n retryJitterRatio: OptionalNumber(),\n notBefore: OptionalString(),\n}, { additionalProperties: false });\n\nconst MessageDraftSchema = Type.Object({\n id: Type.Optional(Type.String({ pattern: UUID_V7_PATTERN })),\n source: OptionalString(),\n project: OptionalString(),\n type: Type.String(),\n content: Type.String(),\n contentType: OptionalString(),\n data: Type.Optional(Type.Any()),\n targets: Type.Optional(StringArray),\n threadId: OptionalString(),\n replyToId: OptionalString(),\n correlationId: OptionalString(),\n causationId: OptionalString(),\n priority: Type.Optional(Type.Enum([\"info\", \"high\", \"urgent\"])),\n expiresAt: OptionalString(),\n idempotencyKey: OptionalString(),\n atribReceiptId: OptionalString(),\n informedBy: Type.Optional(StringArray),\n metadata: Type.Optional(Type.Any()),\n deliveryPolicy: Type.Optional(DeliveryPolicyInputSchema),\n}, { additionalProperties: false });\n\n// Exact field set released by package 0.2.0 at d8184fe. A headerless\n// gateway response selects this wire contract, not the current one.\nexport const LegacyMessageDraftSchema = Type.Object({\n id: OptionalString(), source: OptionalString(), type: Type.String(), content: Type.String(),\n contentType: OptionalString(), data: Type.Optional(Type.Any()), targets: Type.Optional(StringArray),\n threadId: OptionalString(), replyToId: OptionalString(), correlationId: OptionalString(),\n causationId: OptionalString(), priority: Type.Optional(Type.Enum([\"info\", \"high\", \"urgent\"])),\n expiresAt: OptionalString(), idempotencyKey: OptionalString(), atribReceiptId: OptionalString(),\n informedBy: Type.Optional(StringArray), metadata: Type.Optional(Type.Any()),\n}, { additionalProperties: false });\n\nconst MessageSchema = Type.Object({\n id: Type.String(),\n workspace: Type.String(),\n project: OptionalString(),\n source: Type.String(),\n type: Type.String(),\n content: Type.String(),\n contentType: Type.String(),\n sequence: Type.String(),\n createdAt: Type.String(),\n data: Type.Optional(Type.Any()),\n targets: StringArray,\n threadId: OptionalString(),\n replyToId: OptionalString(),\n correlationId: OptionalString(),\n causationId: OptionalString(),\n priority: Type.Enum([\"info\", \"high\", \"urgent\"]),\n expiresAt: OptionalString(),\n idempotencyKey: OptionalString(),\n atribReceiptId: OptionalString(),\n informedBy: Type.Optional(StringArray),\n metadata: Type.Optional(Type.Any()),\n deliveryPolicy: DeliveryPolicySchema,\n}, { additionalProperties: true });\n\nexport const LegacyMessageSchema = Type.Object({\n id: Type.String(), workspace: Type.String(), source: Type.String(), type: Type.String(),\n content: Type.String(), contentType: Type.String(), sequence: Type.String(), createdAt: Type.String(),\n data: Type.Optional(Type.Any()), targets: StringArray, threadId: OptionalString(), replyToId: OptionalString(),\n correlationId: OptionalString(), causationId: OptionalString(), priority: Type.Enum([\"info\", \"high\", \"urgent\"]),\n expiresAt: OptionalString(), idempotencyKey: OptionalString(), atribReceiptId: OptionalString(),\n informedBy: Type.Optional(StringArray), metadata: Type.Optional(Type.Any()),\n}, { additionalProperties: true });\n\nconst DeliveryStateSchema = Type.Enum([\"pending\", \"claimed\", \"acked\", \"retrying\", \"dead\", \"cancelled\"]);\nconst DeliveryActionSchema = Type.Enum([\"created\", \"claim\", \"ack\", \"nack_retry\", \"nack_dead\", \"lease_expired\", \"attempts_exhausted\", \"message_expired\", \"cancel\", \"requeue\"]);\nconst DeliverySchema = Type.Object({\n id: Type.String(),\n messageId: Type.String(),\n workspace: Type.String(),\n recipient: Type.String(),\n state: DeliveryStateSchema,\n attempt: Type.Number(),\n cycleAttempt: Type.Number(),\n requeueCount: Type.Number(),\n createdAt: Type.String(),\n priorityRank: Type.Number(),\n availableAt: Type.String(),\n leaseToken: OptionalString(),\n leaseOwner: OptionalString(),\n leaseExpiresAt: OptionalString(),\n lastError: OptionalString(),\n lastActor: OptionalString(),\n lastAction: DeliveryActionSchema,\n}, { additionalProperties: true });\n\nexport const LegacyDeliverySchema = Type.Object({\n id: Type.String(), messageId: Type.String(), workspace: Type.String(), recipient: Type.String(),\n state: Type.Enum([\"pending\", \"claimed\", \"acked\", \"retrying\", \"dead\"]), attempt: Type.Number(),\n availableAt: Type.String(), leaseToken: OptionalString(), leaseOwner: OptionalString(),\n leaseExpiresAt: OptionalString(), lastError: OptionalString(),\n}, { additionalProperties: true });\n\nconst DeliveryEventSchema = Type.Object({\n sequence: Type.String(),\n deliveryId: Type.String(),\n messageId: Type.String(),\n workspace: Type.String(),\n recipient: Type.String(),\n fromState: Type.Optional(DeliveryStateSchema),\n toState: DeliveryStateSchema,\n attempt: Type.Number(),\n cycleAttempt: Type.Number(),\n requeueCount: Type.Number(),\n leaseOwner: OptionalString(),\n error: OptionalString(),\n actor: Type.String(),\n action: DeliveryActionSchema,\n createdAt: Type.String(),\n}, { additionalProperties: true });\n\nconst PresenceSchema = Type.Object({\n workspace: Type.String(),\n agent: Type.String(),\n instance: Type.String(),\n runtimeType: OptionalString(),\n capabilities: StringArray,\n leaseExpiresAt: Type.String(),\n lastSeenAt: Type.String(),\n}, { additionalProperties: true });\n\nconst DeliveryDiagnosticsProperties = {\n schemaVersion: Type.Enum([\"local-v2\", \"postgres-v2\", \"legacy-v1\"]),\n deliverySupported: Type.Boolean(),\n pending: NullableNumber(),\n claimed: NullableNumber(),\n retrying: NullableNumber(),\n dead: NullableNumber(),\n cancelled: Type.Optional(NullableNumber()),\n oldestAvailableAt: OptionalString(),\n due: Type.Optional(NullableNumber()),\n scheduled: Type.Optional(NullableNumber()),\n expiredLeases: Type.Optional(NullableNumber()),\n oldestDueAt: OptionalString(),\n queueLagMs: Type.Optional(NullableNumber()),\n gatewayAuthorityId: OptionalString(),\n credentialId: OptionalString(),\n principal: Type.Optional(Type.Object({ workspace: Type.String(), agent: Type.String() }, { additionalProperties: true })),\n} as const;\n\nconst DiagnosticsSchema = Type.Object(DeliveryDiagnosticsProperties, { additionalProperties: true });\n\nconst ClientDiagnosticsSchema = Type.Object({\n ...DeliveryDiagnosticsProperties,\n remoteReachable: Type.Optional(Type.Union([Type.Boolean(), Type.Null()])),\n outboxPending: OptionalNumber(),\n outboxBlocked: OptionalNumber(),\n cachedMessages: OptionalNumber(),\n lastSyncAt: OptionalString(),\n lastSyncError: OptionalString(),\n outboxDue: OptionalNumber(),\n outboxScheduled: OptionalNumber(),\n outboxLeased: OptionalNumber(),\n outboxOldestDueAt: OptionalString(),\n outboxQueueLagMs: OptionalNumber(),\n outboxOldestBlockedAt: OptionalString(),\n outboxBlockedAgeMs: Type.Optional(NullableNumber()),\n outboxBlockedMaxAttempts: OptionalNumber(),\n outboxBlockedLastError: OptionalString(),\n outboxNextRetryAt: OptionalString(),\n lastOutboundSyncAt: OptionalString(),\n lastInboundSyncAt: OptionalString(),\n lastSyncAttemptAt: OptionalString(),\n syncLoopState: Type.Optional(Type.Enum([\"disabled\", \"idle\", \"running\", \"backoff\", \"paused\", \"stopped\", \"failed\"])),\n syncLoopError: OptionalString(),\n remoteError: OptionalString(),\n migrationState: Type.Optional(Type.Enum([\"active\", \"draining\", \"retired\"])),\n migrationOperationId: OptionalString(),\n migrationLeaseExpiresAt: OptionalString(),\n}, { additionalProperties: true });\n\nconst ClientStatusSchema = Type.Object({\n status: Type.Enum([\"ok\", \"unknown\", \"degraded\", \"failed\"]),\n localHealthy: Type.Boolean(),\n connected: Type.Boolean(),\n remoteReachable: Type.Union([Type.Boolean(), Type.Null()]),\n provider: Type.Enum([\"local\", \"gateway\", \"legacy-supabase\"]),\n workspace: Type.String(),\n agent: Type.String(),\n instance: Type.Union([Type.String(), Type.Null()]),\n schemaVersion: Type.Enum([\"local-v2\", \"postgres-v2\", \"legacy-v1\"]),\n endpoint: Type.Union([Type.String(), Type.Null()]),\n database: Type.Union([Type.String(), Type.Null()]),\n cursorPath: Type.String(),\n lastCursor: Type.Union([Type.String(), Type.Null()]),\n queue: ClientDiagnosticsSchema,\n checks: Type.Array(Type.Object({\n name: Type.String(),\n status: Type.Enum([\"ok\", \"unknown\", \"degraded\", \"failed\"]),\n message: Type.String(),\n }, { additionalProperties: false })),\n}, { additionalProperties: true });\n\nconst HistoryRequestSchema = Type.Object({\n cursor: OptionalString(),\n limit: OptionalNumber({ minimum: 1, maximum: 200 }),\n types: Type.Optional(StringArray),\n mailbox: Type.Optional(Type.Enum([\"inbox\", \"sent\", \"all\"])),\n receiptState: Type.Optional(Type.Enum([\"any\", \"unread\", \"read\"])),\n includeExpired: OptionalBoolean(),\n source: OptionalString(),\n project: OptionalString(),\n since: OptionalString(),\n unacknowledgedBy: OptionalString(),\n threadId: OptionalString(),\n latest: OptionalBoolean(),\n}, { additionalProperties: false });\n\nconst MessagePageSchema = Type.Object({\n messages: Type.Array(MessageSchema),\n cursor: OptionalString(),\n source: Type.Optional(Type.Enum([\"remote\", \"cache\"])),\n stale: OptionalBoolean(),\n degraded: OptionalBoolean(),\n acknowledgements: Type.Optional(Type.Enum([\"authoritative\", \"unknown\"])),\n lastSyncedAt: OptionalString(),\n}, { additionalProperties: true });\n\nconst DeliveryPageSchema = Type.Object({ deliveries: Type.Array(DeliverySchema), cursor: OptionalString() }, { additionalProperties: true });\nconst DeliveryEventPageSchema = Type.Object({ events: Type.Array(DeliveryEventSchema), cursor: OptionalString() }, { additionalProperties: true });\nconst DeliveryIdSchema = Type.Object({ deliveryId: Type.String() }, { additionalProperties: false });\nconst LeaseSchema = Type.Object({ deliveryId: Type.String(), leaseToken: Type.String() }, { additionalProperties: false });\nconst RetryPolicySchema = Type.Object({\n maxAttempts: OptionalNumber(),\n baseDelayMs: OptionalNumber(),\n maxDelayMs: OptionalNumber(),\n jitterRatio: OptionalNumber(),\n}, { additionalProperties: false });\n\nconst NegativeAcknowledgeRequestSchema = Type.Object({\n deliveryId: Type.String(),\n leaseToken: Type.String(),\n error: Type.String(),\n disposition: Type.Optional(Type.Enum([\"retry\", \"dead\"])),\n dead: OptionalBoolean(),\n retryPolicy: Type.Optional(RetryPolicySchema),\n}, { additionalProperties: false });\n\nconst LegacyNegativeAcknowledgeRequestSchema = Type.Object({\n deliveryId: Type.String(),\n leaseToken: Type.String(),\n error: OptionalString(),\n disposition: Type.Optional(Type.Enum([\"retry\", \"dead\"])),\n dead: OptionalBoolean(),\n retryPolicy: Type.Optional(RetryPolicySchema),\n}, { additionalProperties: false });\n\nconst SyncResponseSchema = Type.Object({\n online: Type.Boolean(),\n pushed: Type.Number(),\n deduplicated: Type.Number(),\n pulled: Type.Number(),\n pending: Type.Number(),\n blocked: Type.Number(),\n cached: Type.Number(),\n cursor: Type.Optional(NullableString()),\n lastSyncedAt: Type.Optional(NullableString()),\n lastError: Type.Optional(NullableString()),\n failureRetryable: OptionalBoolean(),\n}, { additionalProperties: true });\n\nconst ClaimResponseSchema = Type.Object({\n delivery: Type.Union([DeliverySchema, Type.Null()]),\n leaseToken: OptionalString(),\n}, {\n additionalProperties: true,\n oneOf: [\n { properties: { delivery: { type: \"null\" }, leaseToken: false }, required: [\"delivery\"] },\n { properties: { delivery: DeliverySchema, leaseToken: { type: \"string\" } }, required: [\"delivery\", \"leaseToken\"] },\n ],\n});\n\nexport const AUTHORIZATION_SCOPES = [\n \"deliveries:claim\",\n \"deliveries:manage\",\n \"deliveries:read\",\n \"deliveries:settle\",\n \"gateway:metrics\",\n \"messages:read\",\n \"messages:write\",\n \"presence:read\",\n \"presence:write\",\n \"receipts:write\",\n \"status:read\",\n] as const;\n\nexport type AuthorizationScope = typeof AUTHORIZATION_SCOPES[number];\n\nexport type ContractProvider = \"local\" | \"gateway\" | \"legacy-supabase\";\nexport type ContractSurface = \"mcp\" | \"http\" | \"cli\";\nexport type OperationId =\n | \"capabilities\" | \"status\" | \"client_status\" | \"gateway_metrics\" | \"publish_message\" | \"history\"\n | \"issue_endpoint_migration_challenge\" | \"consume_endpoint_migration_challenge\"\n | \"record_receipt\" | \"claim_delivery\" | \"list_deliveries\" | \"list_delivery_events\"\n | \"cancel_delivery\" | \"requeue_delivery\" | \"extend_delivery\" | \"acknowledge_delivery\"\n | \"negative_acknowledge_delivery\" | \"heartbeat\" | \"presence\" | \"sync\";\n\nexport interface HttpContract {\n method: \"GET\" | \"POST\";\n path: string;\n successStatus?: 200 | 201;\n responseContentType?: \"application/json\" | \"text/plain\";\n queryAliases?: Readonly<Record<string, readonly string[]>>;\n}\n\nexport interface CliContract {\n command: string;\n aliases?: readonly string[];\n options: readonly string[];\n response?: TSchema;\n variants?: readonly CliCompatibilityVariant[];\n}\n\nexport interface CliCompatibilityVariant {\n command: string;\n condition: { kind: \"always\" } | { kind: \"option-present\"; option: string };\n routesTo: OperationId;\n options: readonly string[];\n response: TSchema;\n}\n\nexport interface OperationContract {\n id: OperationId;\n summary: string;\n request: TSchema;\n response: TSchema;\n scopes: readonly AuthorizationScope[];\n providers: readonly ContractProvider[];\n mcp?: { name: string };\n http?: HttpContract;\n cli?: CliContract;\n}\n\nconst ALL_PROVIDERS = [\"local\", \"gateway\", \"legacy-supabase\"] as const;\nconst DELIVERY_PROVIDERS = [\"local\", \"gateway\"] as const;\nconst GATEWAY_PROVIDER = [\"gateway\"] as const;\nconst operation = (entry: OperationContract): OperationContract => entry;\nconst HistoryCliOptions = [\"cursor\", \"limit\", \"type\", \"category\", \"mailbox\", \"receipt-state\", \"source\", \"project\", \"since\", \"unacked-by\", \"thread-id\", \"latest\"] as const;\nconst LegacyGetRowSchema = Type.Object({\n id: Type.Union([Type.String(), Type.Number()]),\n source: Type.String(),\n category: Type.String(),\n content: Type.String(),\n priority: Type.Enum([\"info\", \"high\", \"urgent\"]),\n project: NullableString(),\n metadata: Type.Any(),\n created_at: Type.String(),\n}, { additionalProperties: false });\nconst ReceiptCliResponseSchema = Type.Object({\n acknowledged: Type.Number(),\n agent: Type.String(),\n}, { additionalProperties: true });\n\nexport const operations: readonly OperationContract[] = [\n operation({ id: \"capabilities\", summary: \"Discover operations available on the current surface.\", request: Empty, response: Type.Object({ protocolVersion: Type.String(), currentProtocolVersion: Type.String(), selectedProtocolVersion: Type.String(), supportedProtocolVersions: StringArray, scopeEnforcement: Type.Boolean(), requestAuthority: Type.Boolean(), rowIsolation: Type.Boolean(), authorizationModel: Type.Enum([\"scoped-credential\", \"credential-wide\", \"process-identity\", \"legacy-key\"]), surface: Type.Enum([\"mcp\", \"http\", \"cli\"]), provider: Type.Enum([\"local\", \"gateway\", \"legacy-supabase\"]), grantedScopes: Type.Optional(StringArray), operations: Type.Array(Type.Object({ id: Type.String(), summary: Type.String(), requiredScopes: StringArray, mcp: Type.Optional(Type.Any()), http: Type.Optional(Type.Any()), cli: Type.Optional(Type.Any()) }, { additionalProperties: true })) }, { additionalProperties: true }), scopes: [], providers: ALL_PROVIDERS, mcp: { name: \"capabilities\" }, http: { method: \"GET\", path: \"/v2/capabilities\" }, cli: { command: \"capabilities\", options: [] } }),\n operation({ id: \"status\", summary: \"Read gateway delivery diagnostics.\", request: Empty, response: DiagnosticsSchema, scopes: [\"status:read\"], providers: ALL_PROVIDERS, http: { method: \"GET\", path: \"/v2/status\" } }),\n operation({ id: \"issue_endpoint_migration_challenge\", summary: \"Issue a short-lived endpoint migration challenge commitment.\", request: Type.Object({ challenge: Type.String({ pattern: \"^[0-9a-f]{64}$\" }), expectedGatewayAuthorityId: Type.String({ pattern: UUID_PATTERN }), verifierCredentialId: Type.String({ pattern: UUID_PATTERN }) }, { additionalProperties: false }), response: Type.Object({ gatewayAuthorityId: Type.String(), issuerCredentialId: Type.String(), verifierCredentialId: Type.String(), expiresAt: Type.String() }, { additionalProperties: false }), scopes: [], providers: GATEWAY_PROVIDER, http: { method: \"POST\", path: \"/v2/endpoint-migration-challenges\" } }),\n operation({ id: \"consume_endpoint_migration_challenge\", summary: \"Consume a short-lived endpoint migration challenge commitment.\", request: Type.Object({ challenge: Type.String({ pattern: \"^[0-9a-f]{64}$\" }), expectedGatewayAuthorityId: Type.String({ pattern: UUID_PATTERN }), issuerCredentialId: Type.String({ pattern: UUID_PATTERN }) }, { additionalProperties: false }), response: Type.Object({ gatewayAuthorityId: Type.String(), issuerCredentialId: Type.String(), verifierCredentialId: Type.String(), expiresAt: Type.Union([Type.String(), Type.Null()]), consumed: Type.Boolean() }, { additionalProperties: false }), scopes: [], providers: GATEWAY_PROVIDER, http: { method: \"POST\", path: \"/v2/endpoint-migration-challenges/consume\" } }),\n operation({ id: \"client_status\", summary: \"Read client connectivity and provider diagnostics.\", request: Empty, response: ClientStatusSchema, scopes: [\"status:read\"], providers: ALL_PROVIDERS, cli: { command: \"status\", aliases: [\"doctor\"], options: [] } }),\n operation({ id: \"gateway_metrics\", summary: \"Read Prometheus gateway counters.\", request: Empty, response: Type.String(), scopes: [\"gateway:metrics\"], providers: GATEWAY_PROVIDER, http: { method: \"GET\", path: \"/metrics\", responseContentType: \"text/plain\" } }),\n operation({ id: \"publish_message\", summary: \"Create an immutable Agent Bridge v2 message.\", request: MessageDraftSchema, response: Type.Object({ created: Type.Boolean(), message: MessageSchema, disposition: Type.Optional(Type.Enum([\"committed\", \"queued\"])), authoritative: OptionalBoolean() }, { additionalProperties: true }), scopes: [\"messages:write\"], providers: ALL_PROVIDERS, mcp: { name: \"send\" }, http: { method: \"POST\", path: \"/v2/messages\", successStatus: 201 }, cli: { command: \"send\", aliases: [\"post\"], options: [\"source\", \"project\", \"type\", \"kind\", \"category\", \"content\", \"content-type\", \"data\", \"payload\", \"payload-mime\", \"payload-ref\", \"payload-ciphertext\", \"target\", \"target-agent\", \"target-agents\", \"thread-id\", \"reply-to-id\", \"correlation-id\", \"causation-id\", \"priority\", \"expires-at\", \"idempotency-key\", \"atrib-receipt-id\", \"informed-by\", \"metadata\", \"delivery-mode\", \"delivery-policy\", \"delivery-max-attempts\", \"retry-base-ms\", \"retry-max-ms\", \"retry-jitter\", \"not-before\", \"message-id\"] } }),\n operation({ id: \"history\", summary: \"Read visible messages after an opaque cursor.\", request: HistoryRequestSchema, response: MessagePageSchema, scopes: [\"messages:read\"], providers: ALL_PROVIDERS, mcp: { name: \"history\" }, http: { method: \"GET\", path: \"/v2/history\", queryAliases: { unacknowledgedBy: [\"unacked_by\"] } }, cli: { command: \"history\", aliases: [\"inbox\", \"sent\"], options: HistoryCliOptions, variants: [{ command: \"get\", condition: { kind: \"always\" }, routesTo: \"history\", options: HistoryCliOptions, response: Type.Array(LegacyGetRowSchema) }] } }),\n operation({ id: \"record_receipt\", summary: \"Record caller-bound inbox read receipts.\", request: Type.Object({ messageIds: Type.Array(Type.String(), { minItems: 1, maxItems: 200 }) }, { additionalProperties: false }), response: Type.Object({ recorded: Type.Number() }, { additionalProperties: true }), scopes: [\"receipts:write\"], providers: ALL_PROVIDERS, http: { method: \"POST\", path: \"/v2/receipts\" }, cli: { command: \"acknowledge\", aliases: [\"receipt\"], options: [\"ids\"], response: ReceiptCliResponseSchema, variants: [{ command: \"ack\", condition: { kind: \"option-present\", option: \"ids\" }, routesTo: \"record_receipt\", options: [\"ids\"], response: ReceiptCliResponseSchema }] } }),\n operation({ id: \"claim_delivery\", summary: \"Atomically claim the next targeted delivery, or one eligible message when requested.\", request: Type.Object({ leaseMs: OptionalNumber(), messageId: Type.Optional(Type.String({ pattern: UUID_PATTERN })), maxAttempts: OptionalNumber() }, { additionalProperties: false }), response: ClaimResponseSchema, scopes: [\"deliveries:claim\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"claim\" }, http: { method: \"POST\", path: \"/v2/deliveries/claim\" }, cli: { command: \"claim\", options: [\"lease-ms\", \"message-id\", \"max-attempts\"], response: Type.Union([Type.Object({ delivery: DeliverySchema, leaseToken: Type.String() }, { additionalProperties: true }), Type.Null()]) } }),\n operation({ id: \"list_deliveries\", summary: \"List caller-visible deliveries.\", request: Type.Object({ cursor: OptionalString(), limit: OptionalNumber(), role: Type.Optional(Type.Enum([\"recipient\", \"publisher\", \"all\"])), messageId: OptionalString(), recipient: OptionalString(), states: Type.Optional(Type.Array(DeliveryStateSchema)) }, { additionalProperties: false }), response: DeliveryPageSchema, scopes: [\"deliveries:read\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"list_deliveries\" }, http: { method: \"GET\", path: \"/v2/deliveries\" }, cli: { command: \"deliveries\", aliases: [\"dead-letters\"], options: [\"cursor\", \"limit\", \"role\", \"message-id\", \"recipient\", \"state\"] } }),\n operation({ id: \"list_delivery_events\", summary: \"List the append-only event history for a delivery.\", request: Type.Object({ deliveryId: Type.String(), cursor: OptionalString(), limit: OptionalNumber() }, { additionalProperties: false }), response: DeliveryEventPageSchema, scopes: [\"deliveries:read\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"list_delivery_events\" }, http: { method: \"GET\", path: \"/v2/deliveries/{deliveryId}/events\" }, cli: { command: \"delivery-events\", options: [\"delivery-id\", \"cursor\", \"limit\"] } }),\n operation({ id: \"cancel_delivery\", summary: \"Cancel a delivery as its publisher.\", request: DeliveryIdSchema, response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: [\"deliveries:manage\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"cancel_delivery\" }, http: { method: \"POST\", path: \"/v2/deliveries/{deliveryId}/cancel\" }, cli: { command: \"cancel\", options: [\"delivery-id\"], response: Type.Union([DeliverySchema, Type.Null()]) } }),\n operation({ id: \"requeue_delivery\", summary: \"Requeue a delivery as its publisher.\", request: DeliveryIdSchema, response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: [\"deliveries:manage\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"requeue_delivery\" }, http: { method: \"POST\", path: \"/v2/deliveries/{deliveryId}/requeue\" }, cli: { command: \"requeue\", options: [\"delivery-id\"], response: Type.Union([DeliverySchema, Type.Null()]) } }),\n operation({ id: \"extend_delivery\", summary: \"Extend a claimed delivery lease.\", request: Type.Object({ deliveryId: Type.String(), leaseToken: Type.String(), leaseMs: Type.Number() }, { additionalProperties: false }), response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: [\"deliveries:settle\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"extend\" }, http: { method: \"POST\", path: \"/v2/deliveries/{deliveryId}/extend\" }, cli: { command: \"extend\", options: [\"delivery-id\", \"lease-token\", \"lease-ms\"], response: Type.Union([DeliverySchema, Type.Null()]) } }),\n operation({ id: \"acknowledge_delivery\", summary: \"Settle a claimed delivery successfully.\", request: LeaseSchema, response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: [\"deliveries:settle\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"acknowledge\" }, http: { method: \"POST\", path: \"/v2/deliveries/{deliveryId}/ack\" }, cli: { command: \"ack\", options: [\"delivery-id\", \"lease-token\"], response: Type.Union([DeliverySchema, Type.Null()]) } }),\n operation({ id: \"negative_acknowledge_delivery\", summary: \"Settle a claimed delivery for retry or dead letter.\", request: NegativeAcknowledgeRequestSchema, response: Type.Object({ delivery: Type.Union([DeliverySchema, Type.Null()]) }, { additionalProperties: true }), scopes: [\"deliveries:settle\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"negative_acknowledge\" }, http: { method: \"POST\", path: \"/v2/deliveries/{deliveryId}/nack\" }, cli: { command: \"nack\", options: [\"delivery-id\", \"lease-token\", \"error\", \"disposition\", \"dead\"], response: Type.Union([DeliverySchema, Type.Null()]) } }),\n operation({ id: \"heartbeat\", summary: \"Publish a leased runtime presence record.\", request: Type.Object({ leaseMs: OptionalNumber({ minimum: 1000, maximum: 900000 }), runtimeType: OptionalString(), capabilities: Type.Optional(StringArray) }, { additionalProperties: false }), response: PresenceSchema, scopes: [\"presence:write\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"heartbeat\" }, http: { method: \"POST\", path: \"/v2/presence/heartbeat\" }, cli: { command: \"join\", options: [\"lease-ms\", \"runtime\", \"capability\"] } }),\n operation({ id: \"presence\", summary: \"List active agent runtime instances.\", request: Empty, response: Type.Object({ agents: Type.Array(PresenceSchema) }, { additionalProperties: true }), scopes: [\"presence:read\"], providers: DELIVERY_PROVIDERS, mcp: { name: \"presence\" }, http: { method: \"GET\", path: \"/v2/presence\" }, cli: { command: \"presence\", options: [] } }),\n operation({ id: \"sync\", summary: \"Replay a gateway outbox and refresh its inbox cache.\", request: Type.Object({ maxPush: OptionalNumber(), maxPages: OptionalNumber() }, { additionalProperties: false }), response: SyncResponseSchema, scopes: [\"messages:write\", \"messages:read\"], providers: GATEWAY_PROVIDER, mcp: { name: \"sync\" }, cli: { command: \"sync\", options: [\"max-push\", \"max-pages\", \"limit\"] } }),\n];\n\nconst byId = new Map(operations.map((entry) => [entry.id, entry]));\n\nexport class ContractValidationError extends Error {\n readonly code = \"invalid_input\";\n readonly status = 400;\n constructor(readonly operation: string, readonly issues: readonly { path: string; message: string }[]) {\n super(`Request does not match the ${operation} schema`);\n }\n}\n\nexport class ContractResponseError extends Error {\n readonly code = \"protocol_mismatch\";\n readonly status = 502;\n constructor(readonly operation: string, readonly issues: readonly { path: string; message: string }[]) {\n super(`Response does not match the ${operation} schema`);\n }\n}\n\nfunction issues(schema: TSchema, value: unknown): readonly { path: string; message: string }[] {\n return [...Errors(schema, value)].map((entry) => ({ path: entry.instancePath || \"/\", message: entry.message }));\n}\n\nexport function operationContract(operationId: string): OperationContract {\n const contract = byId.get(operationId as OperationId);\n if (!contract) throw new Error(`Unknown operation contract: ${operationId}`);\n return contract;\n}\n\nexport function validateRequest(operationId: string, value: unknown): Record<string, unknown> {\n const contract = operationContract(operationId);\n if (!Check(contract.request, value)) throw new ContractValidationError(operationId, issues(contract.request, value));\n return value as Record<string, unknown>;\n}\n\nexport function validateRequestForProtocol(operationId: string, value: unknown, protocolVersion: string): Record<string, unknown> {\n if (protocolVersion === LEGACY_PROTOCOL_VERSION) {\n if (operationId === \"publish_message\") {\n if (!Check(LegacyMessageDraftSchema, value)) throw new ContractValidationError(operationId, issues(LegacyMessageDraftSchema, value));\n return value as Record<string, unknown>;\n }\n if ([\"list_deliveries\", \"list_delivery_events\", \"cancel_delivery\", \"requeue_delivery\", \"capabilities\"].includes(operationId)) {\n throw new ContractValidationError(operationId, [{ path: \"/\", message: `Operation is not supported by protocol ${LEGACY_PROTOCOL_VERSION}` }]);\n }\n if (operationId === \"history\" && value && typeof value === \"object\") {\n const unsupported = [\"mailbox\", \"receiptState\", \"project\"].find((field) => (value as Record<string, unknown>)[field] !== undefined);\n if (unsupported) throw new ContractValidationError(operationId, [{ path: `/${unsupported}`, message: `Field is not supported by protocol ${LEGACY_PROTOCOL_VERSION}` }]);\n }\n if (operationId === \"claim_delivery\" && value && typeof value === \"object\"\n && (value as Record<string, unknown>).messageId !== undefined) {\n throw new ContractValidationError(operationId, [{ path: \"/messageId\", message: `Field is not supported by protocol ${LEGACY_PROTOCOL_VERSION}` }]);\n }\n }\n if (operationId !== \"negative_acknowledge_delivery\" || protocolVersion !== LEGACY_PROTOCOL_VERSION) {\n return validateRequest(operationId, value);\n }\n if (!Check(LegacyNegativeAcknowledgeRequestSchema, value)) {\n throw new ContractValidationError(operationId, issues(LegacyNegativeAcknowledgeRequestSchema, value));\n }\n return value as Record<string, unknown>;\n}\n\nexport function parseResponse(operationId: string, value: unknown): unknown {\n const contract = operationContract(operationId);\n const serialized = JSON.stringify(value);\n const wireValue = serialized === undefined ? value : JSON.parse(serialized);\n if (!Check(contract.response, wireValue)) throw new ContractResponseError(operationId, issues(contract.response, wireValue));\n return wireValue;\n}\n\nexport function parseResponseForProtocol(operationId: string, value: unknown, protocolVersion: string): unknown {\n if (protocolVersion !== LEGACY_PROTOCOL_VERSION) return parseResponse(operationId, value);\n let schema: TSchema | undefined;\n let normalized = value;\n if (operationId === \"publish_message\") schema = Type.Object({ created: Type.Boolean(), message: LegacyMessageSchema }, { additionalProperties: true });\n else if (operationId === \"history\") schema = Type.Object({ messages: Type.Array(LegacyMessageSchema), cursor: OptionalString() }, { additionalProperties: true });\n else if (operationId === \"claim_delivery\") {\n schema = Type.Union([Type.Object({ delivery: LegacyDeliverySchema, leaseToken: Type.String() }, { additionalProperties: true }), Type.Null()]);\n normalized = value === null ? { delivery: null } : value;\n } else if ([\"extend_delivery\", \"acknowledge_delivery\", \"negative_acknowledge_delivery\"].includes(operationId)) {\n schema = LegacyDeliverySchema;\n normalized = { delivery: value };\n }\n if (!schema) return parseResponse(operationId, value);\n if (!Check(schema, value)) throw new ContractResponseError(operationId, issues(schema, value));\n return normalized;\n}\n\nexport function parseCliResponse(\n operationId: string,\n value: unknown,\n invocation?: { command: string; optionNames?: readonly string[] },\n): unknown {\n const contract = operationContract(operationId);\n const optionNames = new Set(invocation?.optionNames ?? []);\n const variant = contract.cli?.variants?.find((entry) =>\n entry.command === invocation?.command && cliVariantMatches(entry, optionNames));\n const schema = variant?.response ?? contract.cli?.response ?? contract.response;\n const serialized = JSON.stringify(value);\n const wireValue = serialized === undefined ? value : JSON.parse(serialized);\n if (!Check(schema, wireValue)) throw new ContractResponseError(operationId, issues(schema, wireValue));\n return wireValue;\n}\n\nexport function availableOperations(context: { surface: ContractSurface; provider: ContractProvider }): readonly OperationContract[] {\n return operations.filter((entry) => entry.providers.includes(context.provider) && Boolean(entry[context.surface]));\n}\n\nexport function operationForMcp(name: string, provider: ContractProvider): OperationContract | undefined {\n return availableOperations({ surface: \"mcp\", provider }).find((entry) => entry.mcp?.name === name);\n}\n\nexport function operationForHttp(method: string, path: string): OperationContract | undefined {\n return availableOperations({ surface: \"http\", provider: \"gateway\" }).find((entry) => entry.http?.method === method && entry.http.path === path);\n}\n\nfunction cliVariantMatches(\n variant: CliCompatibilityVariant,\n optionNames: ReadonlySet<string>,\n): boolean {\n return variant.condition.kind === \"always\" || optionNames.has(variant.condition.option);\n}\n\nexport function operationForCli(\n command: string,\n provider: ContractProvider,\n optionNames: readonly string[] = [],\n): OperationContract | undefined {\n const selectedOptions = new Set(optionNames);\n return availableOperations({ surface: \"cli\", provider }).find((entry) =>\n entry.cli?.command === command ||\n entry.cli?.aliases?.includes(command) ||\n entry.cli?.variants?.some((variant) =>\n variant.command === command && cliVariantMatches(variant, selectedOptions)));\n}\n\nexport function capabilityDocument(context: { surface: ContractSurface; provider: ContractProvider; selectedProtocolVersion?: string; requestAuthority?: boolean; rowIsolation?: boolean } = { surface: \"http\", provider: \"gateway\" }) {\n const selectedProtocolVersion = context.selectedProtocolVersion ?? PROTOCOL_VERSION;\n return {\n protocolVersion: selectedProtocolVersion,\n currentProtocolVersion: PROTOCOL_VERSION,\n selectedProtocolVersion,\n supportedProtocolVersions: [...SUPPORTED_PROTOCOL_VERSIONS],\n scopeEnforcement: context.provider === \"gateway\" ? SCOPE_ENFORCEMENT : false,\n requestAuthority: context.provider === \"gateway\" && context.requestAuthority === true,\n rowIsolation: context.provider === \"gateway\" && context.requestAuthority === true && context.rowIsolation === true,\n authorizationModel: context.provider === \"gateway\"\n ? \"scoped-credential\"\n : context.provider === \"local\"\n ? \"process-identity\"\n : \"legacy-key\",\n surface: context.surface,\n provider: context.provider,\n operations: availableOperations(context).map(({ request: _request, response, providers: _providers, scopes, cli, ...entry }) => ({\n ...entry,\n ...(cli ? {\n cli: {\n command: cli.command,\n ...(cli.aliases ? { aliases: cli.aliases } : {}),\n options: cli.options,\n outputSchema: cli.response ?? response,\n ...(cli.variants ? {\n variants: cli.variants.map((variant) => ({\n command: variant.command,\n condition: variant.condition,\n routesTo: variant.routesTo,\n options: variant.options,\n outputSchema: variant.response,\n })),\n } : {}),\n },\n } : {}),\n requiredScopes: [...scopes],\n })),\n };\n}\n\nexport function negotiateProtocolVersion(value: string | string[] | undefined): string {\n const requested = Array.isArray(value) ? value[0] : value;\n if (requested === undefined || requested.trim() === \"\") return LEGACY_PROTOCOL_VERSION;\n if ((SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(requested.trim())) return requested.trim();\n const error = new Error(\"Unsupported Agent Bridge protocol version\") as Error & { status: number; code: string; supported: string };\n error.status = 426;\n error.code = \"unsupported_protocol_version\";\n error.supported = SUPPORTED_PROTOCOL_RANGE;\n throw error;\n}\n"],"mappings":";;;AAAA,OAAO,UAA4B;AACnC,SAAS,OAAO,cAAc;AAEvB,IAAM,mBAAmB;AACzB,IAAM,0BAA0B;AAChC,IAAM,8BAA8B,CAAC,yBAAyB,gBAAgB;AAC9E,IAAM,2BAA2B,4BAA4B,KAAK,GAAG;AACrE,IAAM,kBAAkB;AACxB,IAAM,4BAA4B;AAClC,IAAM,oBAAoB;AAEjC,IAAM,cAAc,KAAK,MAAM,KAAK,OAAO,CAAC;AAC5C,IAAM,QAAQ,KAAK,OAAO,CAAC,GAAG,EAAE,sBAAsB,MAAM,CAAC;AAC7D,IAAM,iBAAiB,MAAM,KAAK,SAAS,KAAK,OAAO,CAAC;AACxD,IAAM,iBAAiB,CAAC,UAAmC,CAAC,MAAM,KAAK,SAAS,KAAK,OAAO,OAAO,CAAC;AACpG,IAAM,kBAAkB,MAAM,KAAK,SAAS,KAAK,QAAQ,CAAC;AAC1D,IAAM,iBAAiB,MAAM,KAAK,MAAM,CAAC,KAAK,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC;AACpE,IAAM,iBAAiB,MAAM,KAAK,MAAM,CAAC,KAAK,OAAO,GAAG,KAAK,KAAK,CAAC,CAAC;AACpE,IAAM,eAAe;AACrB,IAAM,kBAAkB;AAEjB,IAAM,mBAAmB,KAAK,OAAO;AAAA,EAC1C,MAAM,KAAK,OAAO;AAAA,EAClB,S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QACR,KAAK;AAAA,UACH,SAAS,IAAI;AAAA,UACb,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;AAAA,UAC9C,SAAS,IAAI;AAAA,UACb,cAAc,IAAI,YAAY;AAAA,UAC9B,GAAI,IAAI,WAAW;AAAA,YACjB,UAAU,IAAI,SAAS,IAAI,CAAC,aAAa;AAAA,cACvC,SAAS,QAAQ;AAAA,cACjB,WAAW,QAAQ;AAAA,cACnB,UAAU,QAAQ;AAAA,cAClB,SAAS,QAAQ;AAAA,cACjB,cAAc,QAAQ;AAAA,YACxB,EAAE;AAAA,UACJ,IAAI,CAAC;AAAA,QACP;AAAA,MACF,IAAI,CAAC;AAAA,MACL,gBAAgB,CAAC,GAAG,MAAM;AAAA,IAC5B,EAAE;AAAA,EACJ;AACF;AAEO,SAAS,yBAAyB,OAA8C;AACrF,QAAM,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,CAAC,IAAI;AACpD,MAAI,cAAc,UAAa,UAAU,KAAK,MAAM,GAAI,QAAO;AAC/D,MAAK,4BAAkD,SAAS,UAAU,KAAK,CAAC,EAAG,QAAO,UAAU,KAAK;AACzG,QAAM,QAAQ,IAAI,MAAM,2CAA2C;AACnE,QAAM,SAAS;AACf,QAAM,OAAO;AACb,QAAM,YAAY;AAClB,QAAM;AACR;","names":["operation","issues"]}
@@ -5,21 +5,21 @@ import {
5
5
  } from "./chunk-2EVLG3YA.js";
6
6
  import {
7
7
  createStore
8
- } from "./chunk-MCKKVNCE.js";
8
+ } from "./chunk-QPC6JHA3.js";
9
9
  import {
10
10
  legacyContextMetadata,
11
11
  legacyNumericMessageId
12
- } from "./chunk-LAHNQZDN.js";
12
+ } from "./chunk-Z6JP6MYD.js";
13
13
  import {
14
14
  BridgeService
15
- } from "./chunk-4VB44KJU.js";
15
+ } from "./chunk-AWE3DFZV.js";
16
16
  import {
17
17
  ContractValidationError,
18
18
  availableOperations,
19
19
  capabilityDocument,
20
20
  parseResponse,
21
21
  validateRequest
22
- } from "./chunk-IHZFI7TH.js";
22
+ } from "./chunk-E4OWHGUE.js";
23
23
  import {
24
24
  BridgePrincipalMismatchError,
25
25
  BridgeValidationError,
@@ -693,6 +693,7 @@ function createAgentBridgeServer(config) {
693
693
  const input = validateRequest("claim_delivery", args ?? {});
694
694
  const result = await service.claim(principal, {
695
695
  leaseMs: input.leaseMs,
696
+ messageId: input.messageId,
696
697
  maxAttempts: input.maxAttempts
697
698
  });
698
699
  return canonicalResult("claim_delivery", result ?? { delivery: null });
@@ -795,4 +796,4 @@ export {
795
796
  createAgentBridgeServer,
796
797
  startServer
797
798
  };
798
- //# sourceMappingURL=chunk-SYGONYMM.js.map
799
+ //# sourceMappingURL=chunk-HUHG7XTB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/message-envelope.ts","../src/source-identity.ts"],"sourcesContent":["import { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n ErrorCode,\n ListToolsRequestSchema,\n McpError,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { normalizeReceiptId } from \"./atrib-receipt.js\";\nimport {\n buildMessageEnvelope,\n filterContextRows,\n mergeEnvelopeMetadata,\n} from \"./message-envelope.js\";\nimport { resolveAgentIdentity, resolvePostSource } from \"./source-identity.js\";\nimport { BridgeService } from \"./bridge-service.js\";\nimport {\n BridgePrincipalMismatchError,\n BridgeValidationError,\n validateProject,\n validateMessageDraft,\n type BridgePrincipal,\n type MessageDraft,\n} from \"./bridge-domain.js\";\nimport { createStore } from \"./client-runtime.js\";\nimport { legacyContextMetadata, legacyNumericMessageId } from \"./legacy-compat.js\";\nimport {\n readClientConfigFile,\n resolveClientConfig,\n type ClientConfig,\n type ClientEnvironment,\n type ClientProvider,\n} from \"./client-config.js\";\nimport {\n availableOperations,\n capabilityDocument,\n ContractValidationError,\n parseResponse,\n validateRequest,\n} from \"./contracts/registry.js\";\n\nexport interface AgentBridgeServerConfig {\n supabaseUrl?: string;\n supabaseKey?: string;\n agent?: string;\n provider?: ClientProvider;\n workspace?: string;\n instance?: string;\n databasePath?: string;\n edgeDatabasePath?: string;\n cursorPath?: string;\n gatewayUrl?: string;\n gatewayToken?: string;\n}\n\nexport const MCP_IMPLEMENTATION_VERSION = \"2.0.0\";\n\nexport interface AgentBridgeServerEnv {\n AGENT_BRIDGE_URL?: string;\n AGENT_BRIDGE_KEY?: string;\n AGENT_BRIDGE_AGENT?: string;\n AGENT_BRIDGE_CONFIG?: string;\n HOME?: string;\n AGENT_BRIDGE_PROVIDER?: string;\n AGENT_BRIDGE_TOKEN?: string;\n AGENT_BRIDGE_WORKSPACE?: string;\n AGENT_BRIDGE_INSTANCE?: string;\n AGENT_BRIDGE_DB?: string;\n}\n\nfunction normalizedConfigValue(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed || undefined;\n}\n\nfunction defaultConfigPath(env: AgentBridgeServerEnv): string {\n return (\n normalizedConfigValue(env.AGENT_BRIDGE_CONFIG) ??\n join(normalizedConfigValue(env.HOME) ?? homedir(), \".agent-bridge\", \"config\")\n );\n}\n\nexport function configFromEnv(\n env: AgentBridgeServerEnv = process.env,\n): AgentBridgeServerConfig {\n const sharedFile = readClientConfigFile(defaultConfigPath(env));\n const value = (key: keyof AgentBridgeServerEnv) =>\n normalizedConfigValue(env[key]) ?? normalizedConfigValue(sharedFile[key]);\n const runtimeAgent = normalizedConfigValue(env.AGENT_BRIDGE_AGENT);\n const rawProvider = normalizedConfigValue(env.AGENT_BRIDGE_PROVIDER) ??\n normalizedConfigValue(sharedFile.AGENT_BRIDGE_PROVIDER);\n const provider = rawProvider === \"legacy\" || rawProvider === \"supabase\"\n ? \"legacy-supabase\"\n : rawProvider ?? (value(\"AGENT_BRIDGE_TOKEN\") ? \"gateway\" : \"legacy-supabase\");\n if (!([\"local\", \"gateway\", \"legacy-supabase\"] as string[]).includes(provider)) {\n throw new Error(`Unsupported AGENT_BRIDGE_PROVIDER: ${rawProvider}`);\n }\n if (provider === \"local\" || provider === \"gateway\") {\n const client = resolveClientConfig(env as ClientEnvironment);\n return {\n provider: client.provider,\n agent: client.principal.agent,\n workspace: client.principal.workspace,\n instance: client.principal.instance,\n databasePath: client.databasePath,\n edgeDatabasePath: client.edgeDatabasePath,\n cursorPath: client.cursorPath,\n gatewayUrl: client.provider === \"gateway\" ? client.url : undefined,\n gatewayToken: client.provider === \"gateway\" ? client.credential : undefined,\n };\n }\n const supabaseUrl =\n value(\"AGENT_BRIDGE_URL\");\n const supabaseKey =\n value(\"AGENT_BRIDGE_KEY\");\n if (!supabaseUrl || !supabaseKey) {\n throw new Error(\n \"Missing AGENT_BRIDGE_URL or AGENT_BRIDGE_KEY environment variables or ~/.agent-bridge/config\",\n );\n }\n return {\n supabaseUrl,\n supabaseKey,\n agent: runtimeAgent,\n provider: provider as ClientProvider,\n workspace: value(\"AGENT_BRIDGE_WORKSPACE\") ?? \"*\",\n instance: normalizedConfigValue(env.AGENT_BRIDGE_INSTANCE),\n };\n}\n\nfunction buildSupabaseRequest(config: AgentBridgeServerConfig & { supabaseUrl: string; supabaseKey: string }) {\n const parsed = new URL(config.supabaseUrl);\n const loopback = parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\" || parsed.hostname === \"[::1]\";\n if (parsed.protocol !== \"https:\" && !(parsed.protocol === \"http:\" && loopback)) {\n throw new Error(\"Agent Bridge requires HTTPS for non-loopback legacy providers\");\n }\n const restUrl = `${config.supabaseUrl.replace(/\\/$/, \"\")}/rest/v1`;\n const headers = {\n apikey: config.supabaseKey,\n Authorization: `Bearer ${config.supabaseKey}`,\n \"Content-Type\": \"application/json\",\n Prefer: \"return=representation\",\n };\n\n return async function supabaseRequest(\n path: string,\n options: RequestInit = {},\n ): Promise<unknown> {\n const url = `${restUrl}${path}`;\n const res = await fetch(url, {\n ...options,\n signal: options.signal ?? AbortSignal.timeout(10_000),\n headers: { ...headers, ...(options.headers as Record<string, string>) },\n });\n if (!res.ok) {\n throw new Error(`Supabase request failed (${res.status})`);\n }\n const text = await res.text();\n return text ? JSON.parse(text) : null;\n };\n}\n\nexport function createAgentBridgeServer(\n config: AgentBridgeServerConfig,\n): Server {\n const supabaseRequest = config.supabaseUrl && config.supabaseKey ? buildSupabaseRequest(config as AgentBridgeServerConfig & { supabaseUrl: string; supabaseKey: string }) : undefined;\n const provider = config.provider ?? (config.gatewayToken ? \"gateway\" : config.supabaseUrl ? \"legacy-supabase\" : \"local\");\n const principal: BridgePrincipal | undefined = config.agent ? {\n workspace: provider === \"legacy-supabase\" ? \"*\" : config.workspace ?? \"default\",\n agent: config.agent,\n instance: config.instance,\n } : undefined;\n const clientConfig: ClientConfig | undefined = principal ? {\n provider, principal,\n url: config.gatewayUrl ?? config.supabaseUrl, credential: config.gatewayToken ?? config.supabaseKey,\n databasePath: config.databasePath ?? \":memory:\", edgeDatabasePath: config.edgeDatabasePath ?? config.databasePath ?? \":memory:\", cursorPath: config.cursorPath ?? \"\", configPath: \"\",\n } : undefined;\n const store = clientConfig ? createStore(clientConfig) : undefined;\n const service = store ? new BridgeService(store) : undefined;\n const server = new Server(\n { name: \"agent-bridge\", version: MCP_IMPLEMENTATION_VERSION },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const legacyTools = [\n {\n name: \"post_context\",\n description:\n \"Post a shared context entry visible to all agents. Categories: operational, config-change, goal-update, flag, bridge-meta (for suggesting improvements to the Agent Bridge itself).\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n source: {\n type: \"string\",\n description:\n \"Optional posting agent. Defaults to AGENT_BRIDGE_AGENT when configured; an explicit value must match it.\",\n },\n category: {\n type: \"string\",\n description:\n \"Entry type: operational | config-change | goal-update | flag | bridge-meta\",\n },\n content: {\n type: \"string\",\n description: \"The context message\",\n },\n priority: {\n type: \"string\",\n description: \"info (default) | high | urgent\",\n },\n project: {\n type: \"string\",\n description:\n \"Optional immutable message label. Omit for an unlabeled message.\",\n },\n metadata: {\n type: \"object\",\n description: \"Arbitrary structured data\",\n },\n message_id: {\n type: \"string\",\n description:\n \"Stable message id. Generated by the bridge when omitted.\",\n },\n target_agents: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Optional target agent names. Empty or omitted means broadcast.\",\n },\n thread_id: {\n type: \"string\",\n description: \"Optional conversation/thread id.\",\n },\n reply_to_id: {\n type: \"string\",\n description: \"Optional parent message id for reply threading.\",\n },\n kind: {\n type: \"string\",\n description:\n \"Message kind: operational | config-change | goal-update | flag | bridge-meta | handoff | request | result\",\n },\n payload_mime: {\n type: \"string\",\n description:\n \"Payload MIME type. Defaults to text/plain for the content column.\",\n },\n payload: {\n anyOf: [\n { type: \"object\" },\n { type: \"array\" },\n { type: \"string\" },\n { type: \"number\" },\n { type: \"boolean\" },\n { type: \"null\" },\n ],\n description:\n \"Optional structured payload stored in metadata.message_envelope.\",\n },\n payload_ref: {\n type: \"string\",\n description: \"Optional external blob pointer for large payloads.\",\n },\n payload_ciphertext: {\n type: \"string\",\n description:\n \"Optional inline encrypted payload for small encrypted messages.\",\n },\n informed_by: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Optional atrib record hashes (sha256:<64-hex>) this message depends on.\",\n },\n expires_at: {\n type: \"string\",\n description: \"Optional ISO timestamp retention boundary.\",\n },\n atrib_receipt_id: {\n type: \"string\",\n description:\n \"Optional. Signed atrib record receipt_id for the wrapper that signed this post_context call. Set automatically by an atrib-signing wrapper; consumers reading the row use this as the informed_by anchor for cross-process causal edges.\",\n },\n },\n required: [\"category\", \"content\"],\n },\n },\n {\n name: \"get_context\",\n description:\n \"Read shared context entries, newest first. Filter by source, category, project, or unacknowledged entries.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n since: {\n type: \"string\",\n description: \"ISO timestamp. Only entries after this time\",\n },\n source: {\n type: \"string\",\n description: \"Filter by posting agent\",\n },\n category: {\n type: \"string\",\n description: \"Filter by category\",\n },\n project: {\n type: \"string\",\n description: \"Filter by an exact project label\",\n },\n unacked_by: {\n type: \"string\",\n description:\n \"Only entries NOT yet acknowledged by this agent name. Defaults to AGENT_BRIDGE_AGENT when configured.\",\n },\n limit: {\n type: \"number\",\n description: \"Max entries to return (default 20)\",\n minimum: 1,\n maximum: 200,\n },\n target_agent: {\n type: \"string\",\n description:\n \"Return broadcast entries plus entries targeted to this agent.\",\n },\n thread_id: {\n type: \"string\",\n description: \"Filter by metadata.message_envelope.thread_id.\",\n },\n kind: {\n type: \"string\",\n description: \"Filter by metadata.message_envelope.kind.\",\n },\n },\n },\n outputSchema: {\n type: \"object\" as const,\n properties: {\n entries: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n source: { type: \"string\", enum: [\"remote\", \"cache\"] },\n stale: { type: \"boolean\" }, degraded: { type: \"boolean\" },\n acknowledgements: { type: \"string\", enum: [\"authoritative\", \"unknown\"] },\n lastSyncedAt: { type: [\"string\", \"null\"] },\n },\n required: [\"entries\"],\n additionalProperties: false,\n },\n },\n {\n name: \"ack_context\",\n description:\n \"Acknowledge context entries so they won't appear in unacked queries for this agent.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n ids: {\n type: \"array\",\n items: { anyOf: [{ type: \"number\" }, { type: \"string\" }] },\n description: \"Legacy numeric entry IDs or v2 UUID message IDs to acknowledge\",\n },\n agent: {\n type: \"string\",\n description:\n \"Optional acknowledging agent. Defaults to AGENT_BRIDGE_AGENT when configured; an explicit value must match it.\",\n },\n },\n required: [\"ids\"],\n },\n },\n ];\n const canonical = service ? availableOperations({ surface: \"mcp\", provider }).map((operation) => ({\n name: operation.mcp!.name,\n description: operation.summary,\n inputSchema: operation.request,\n outputSchema: operation.response,\n })) : [];\n return { tools: [...legacyTools, ...canonical] as any };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const { name, arguments: args } = request.params;\n const canonicalResult = (operationId: string, value: unknown) => {\n const parsed = parseResponse(operationId, value);\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(parsed) }],\n ...(parsed !== null && typeof parsed === \"object\"\n ? { structuredContent: parsed as Record<string, unknown> }\n : {}),\n };\n };\n\n try {\n switch (name) {\n case \"capabilities\": {\n validateRequest(\"capabilities\", args ?? {});\n return canonicalResult(\"capabilities\", capabilityDocument({ surface: \"mcp\", provider }));\n }\n case \"post_context\": {\n let source: string | undefined;\n try {\n source = resolvePostSource(args?.source, config.agent);\n if (!source) {\n throw new Error(\n \"source is required when AGENT_BRIDGE_AGENT is not configured\",\n );\n }\n } catch (e) {\n throw new McpError(\n ErrorCode.InvalidParams,\n e instanceof Error ? e.message : \"source identity mismatch\",\n );\n }\n const project = validateProject(args?.project);\n const postArgs = { ...(args ?? {}), source, project };\n const receiptId = normalizeReceiptId(args?.atrib_receipt_id);\n const envelope = buildMessageEnvelope(postArgs, receiptId);\n const draft = validateMessageDraft({\n id: String(envelope.message_id),\n project,\n type: String(args?.kind ?? args?.category),\n content: String(args?.content ?? \"\"),\n contentType: String(args?.payload_mime ?? \"text/plain\"),\n data: args?.payload as MessageDraft[\"data\"],\n targets: Array.isArray(args?.target_agents) ? args.target_agents.map(String) : [],\n threadId: args?.thread_id as string | undefined,\n replyToId: args?.reply_to_id as string | undefined,\n priority: (args?.priority ?? \"info\") as MessageDraft[\"priority\"],\n expiresAt: args?.expires_at as string | undefined,\n atribReceiptId: receiptId,\n informedBy: Array.isArray(args?.informed_by) ? args.informed_by.map(String) : [],\n metadata: mergeEnvelopeMetadata(args?.metadata, envelope) as MessageDraft[\"metadata\"],\n });\n const body: Record<string, unknown> = {\n source,\n category: draft.type,\n content: draft.content,\n priority: draft.priority,\n project: draft.project ?? null,\n metadata: draft.metadata,\n };\n // Optional cross-tool causal anchor; written when an atrib-signing\n // wrapper signs this call before forwarding. Format-validated so\n // unexpected producers cannot pollute the column with garbage.\n if (receiptId) {\n body.atrib_receipt_id = receiptId;\n }\n if (!supabaseRequest) {\n if (!service || !principal) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n const result = await service.publish(principal, draft);\n return { content: [{ type: \"text\", text: JSON.stringify(result) }], structuredContent: result as unknown as Record<string, unknown> };\n }\n if (!supabaseRequest) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n const data = await supabaseRequest(\"/shared_context\", {\n method: \"POST\",\n body: JSON.stringify(body),\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(data, null, 2) }],\n };\n }\n\n case \"get_context\": {\n const project = validateProject(args?.project);\n const contextArgs = { ...(args ?? {}), project };\n const rawLimit = args?.limit;\n if (\n rawLimit !== undefined &&\n (typeof rawLimit !== \"number\" || !Number.isSafeInteger(rawLimit) || rawLimit < 1 || rawLimit > 200)\n ) {\n throw new McpError(ErrorCode.InvalidParams, \"limit must be between 1 and 200\");\n }\n const requestedLimit = rawLimit ?? 20;\n if (args?.unacked_by !== undefined && String(args.unacked_by) !== config.agent) {\n throw new McpError(ErrorCode.InvalidParams, \"unacked_by must equal the configured principal\");\n }\n if (service && principal) {\n if (!service || !principal) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n if (args?.target_agent && String(args.target_agent) !== principal.agent) {\n return { content: [{ type: \"text\", text: \"[]\" }], structuredContent: { entries: [] } };\n }\n const result = await service.history(principal, {\n limit: requestedLimit,\n types: args?.kind ? [String(args.kind)] : args?.category ? [String(args.category)] : undefined,\n source: args?.source ? String(args.source) : undefined,\n project,\n since: args?.since ? String(args.since) : undefined,\n receiptState: \"unread\",\n threadId: args?.thread_id ? String(args.thread_id) : undefined,\n latest: true,\n });\n const entries = result.messages\n .slice(0, requestedLimit)\n .map((message) => ({\n id: clientConfig?.provider === \"legacy-supabase\" && /^\\d+$/.test(message.sequence)\n ? Number.isSafeInteger(Number(message.sequence)) ? Number(message.sequence) : message.sequence\n : message.id,\n source: message.source,\n category: message.type,\n content: message.content,\n priority: message.priority,\n project: message.project ?? null,\n metadata: legacyContextMetadata(message),\n atrib_receipt_id: message.atribReceiptId ?? null,\n created_at: message.createdAt,\n }));\n const cachedResult = result as typeof result & {\n source?: \"remote\" | \"cache\";\n stale?: boolean;\n degraded?: boolean;\n acknowledgements?: \"authoritative\" | \"unknown\";\n lastSyncedAt?: string;\n };\n const cacheMetadata = cachedResult.source\n ? {\n source: cachedResult.source,\n stale: Boolean(cachedResult.stale),\n degraded: Boolean(cachedResult.degraded),\n acknowledgements: cachedResult.acknowledgements ?? \"authoritative\",\n lastSyncedAt: cachedResult.lastSyncedAt ?? null,\n }\n : {};\n return {\n content: [\n { type: \"text\", text: JSON.stringify(entries, null, 2) },\n ...(cachedResult.stale || cachedResult.degraded ? [{\n type: \"text\" as const,\n text: `WARNING: cached Agent Bridge context is ${cachedResult.stale ? \"stale\" : \"degraded\"}; acknowledgement authority is ${cachedResult.acknowledgements ?? \"unknown\"}.`,\n }] : []),\n ],\n structuredContent: { entries, ...cacheMetadata },\n };\n }\n const hasEnvelopeFilter = Boolean(\n args?.target_agent || args?.thread_id || args?.kind,\n );\n const fetchLimit = hasEnvelopeFilter\n ? Math.min(Math.max(requestedLimit * 5, 50), 200)\n : requestedLimit;\n const params: string[] = [\n \"order=created_at.desc\",\n `limit=${fetchLimit}`,\n ];\n if (args?.since)\n params.push(\n `created_at=gte.${encodeURIComponent(String(args.since))}`,\n );\n if (args?.source)\n params.push(`source=eq.${encodeURIComponent(String(args.source))}`);\n if (args?.category)\n params.push(\n `category=eq.${encodeURIComponent(String(args.category))}`,\n );\n if (project)\n params.push(`project=eq.${encodeURIComponent(project)}`);\n const unackedBy = args?.unacked_by ?? config.agent;\n if (unackedBy)\n params.push(\n `acked_by=not.cs.%7B${encodeURIComponent(String(unackedBy))}%7D`,\n );\n\n if (!supabaseRequest) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n const data = await supabaseRequest(\n `/shared_context?${params.join(\"&\")}`,\n );\n const filtered = filterContextRows(data, contextArgs, requestedLimit);\n return {\n content: [{ type: \"text\", text: JSON.stringify(filtered, null, 2) }],\n structuredContent: { entries: filtered },\n };\n }\n\n case \"ack_context\": {\n const ids = args?.ids as unknown[];\n let agent: string | undefined;\n try {\n agent = resolveAgentIdentity(args?.agent, config.agent);\n } catch (e) {\n throw new McpError(\n ErrorCode.InvalidParams,\n e instanceof Error ? e.message : \"agent identity mismatch\",\n );\n }\n if (!ids?.length || !agent) {\n throw new McpError(\n ErrorCode.InvalidParams,\n \"ids are required; agent is required when AGENT_BRIDGE_AGENT is not configured\",\n );\n }\n if (service && principal) {\n if (!service || !principal) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n const rawIds = ids.map(String);\n const acknowledged = clientConfig?.provider === \"legacy-supabase\" &&\n store?.recordLegacyReceipt && rawIds.every((id) => /^\\d+$/.test(id))\n ? await store.recordLegacyReceipt(rawIds, principal.agent)\n : await service.acknowledge(\n principal,\n ids.map((id) => legacyNumericMessageId(id as string | number)),\n );\n return { content: [{ type: \"text\", text: JSON.stringify({ acknowledged, agent }) }], structuredContent: { acknowledged, agent } };\n }\n if (!supabaseRequest) throw new McpError(ErrorCode.InternalError, \"bridge provider is not configured\");\n const data = await supabaseRequest(\"/rpc/ack_context\", {\n method: \"POST\",\n body: JSON.stringify({ entry_ids: ids.map(String), agent_name: agent }),\n });\n return {\n content: [\n {\n type: \"text\",\n text: JSON.stringify({ acknowledged: data, agent }),\n },\n ],\n };\n }\n\n case \"send\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n const input = validateRequest(\"publish_message\", args ?? {});\n try { resolvePostSource(input.source, principal.agent); } catch (error) { throw new McpError(ErrorCode.InvalidParams, error instanceof Error ? error.message : \"source identity mismatch\"); }\n const { source: _source, ...draft } = input;\n return canonicalResult(\"publish_message\", await service.publish(principal, draft as unknown as MessageDraft));\n }\n case \"history\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n const input = validateRequest(\"history\", args ?? {});\n return canonicalResult(\"history\", await service.history(principal, input));\n }\n case \"sync\": {\n if (!store?.sync) throw new McpError(ErrorCode.InvalidParams, \"sync is available only with the gateway provider\");\n const input = validateRequest(\"sync\", args ?? {});\n const result = await store.sync({\n maxPush: input.maxPush as number | undefined,\n maxPages: input.maxPages as number | undefined,\n signal: extra.signal,\n });\n return canonicalResult(\"sync\", result);\n }\n case \"claim\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n const input = validateRequest(\"claim_delivery\", args ?? {});\n const result = await service.claim(principal, {\n leaseMs: input.leaseMs as number | undefined,\n messageId: input.messageId as string | undefined,\n maxAttempts: input.maxAttempts as number | undefined,\n });\n return canonicalResult(\"claim_delivery\", result ?? { delivery: null });\n }\n case \"list_deliveries\": case \"list_delivery_events\": case \"cancel_delivery\": case \"requeue_delivery\": {\n if(!service||!principal) throw new McpError(ErrorCode.InvalidParams,\"AGENT_BRIDGE_AGENT is required\");\n const operationId = name === \"list_deliveries\" ? \"list_deliveries\" : name === \"list_delivery_events\" ? \"list_delivery_events\" : name === \"cancel_delivery\" ? \"cancel_delivery\" : \"requeue_delivery\";\n const input = validateRequest(operationId, args ?? {});\n const result=name===\"list_deliveries\"?await service.deliveries(principal,input as any):name===\"list_delivery_events\"?await service.deliveryEvents(principal,String(input.deliveryId),input as any):name===\"cancel_delivery\"?await service.cancel(principal,String(input.deliveryId)):await service.requeue(principal,String(input.deliveryId));\n return canonicalResult(operationId, name === \"list_deliveries\" || name === \"list_delivery_events\" ? result : { delivery: result });\n }\n case \"extend\": case \"acknowledge\": case \"negative_acknowledge\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n const operationId = name === \"extend\" ? \"extend_delivery\" : name === \"acknowledge\" ? \"acknowledge_delivery\" : \"negative_acknowledge_delivery\";\n const input = validateRequest(operationId, args ?? {});\n const id = String(input.deliveryId), token = String(input.leaseToken);\n const result = name === \"extend\" ? await service.extend(principal, id, token, input.leaseMs as number | undefined)\n : name === \"acknowledge\" ? await service.ack(principal, id, token)\n : await service.nack(\n principal,\n id,\n token,\n input.error as string,\n (input.disposition ?? input.dead ?? \"retry\") as \"retry\" | \"dead\" | boolean,\n input.retryPolicy,\n );\n return canonicalResult(operationId, { delivery: result });\n }\n case \"heartbeat\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n const input = validateRequest(\"heartbeat\", args ?? {});\n const result = await service.heartbeat(principal, {\n leaseMs: input.leaseMs as number | undefined,\n runtimeType: input.runtimeType as string | undefined,\n capabilities: input.capabilities as string[] | undefined,\n });\n return canonicalResult(\"heartbeat\", result);\n }\n case \"presence\": {\n if (!service || !principal) throw new McpError(ErrorCode.InvalidParams, \"AGENT_BRIDGE_AGENT is required\");\n validateRequest(\"presence\", args ?? {});\n const result = { agents: await service.presence(principal) };\n return canonicalResult(\"presence\", result);\n }\n\n default:\n throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);\n }\n } catch (error) {\n if (error instanceof McpError) throw error;\n if (error instanceof ContractValidationError || error instanceof BridgeValidationError || error instanceof BridgePrincipalMismatchError) {\n throw new McpError(ErrorCode.InvalidParams, error.message);\n }\n throw error;\n }\n });\n\n let initialization: Promise<void> | undefined;\n const initializeStore = () => initialization ??= clientConfig?.provider === \"gateway\"\n ? store?.initialize() ?? Promise.resolve()\n : Promise.resolve();\n let closure: Promise<void> | undefined;\n const closeStore = () => closure ??= store?.close?.() ?? Promise.resolve();\n const connect = server.connect.bind(server);\n server.connect = async (transport) => {\n await initializeStore();\n await connect(transport);\n };\n const close = server.close.bind(server);\n server.close = async () => {\n let transportError: unknown;\n try { await close(); } catch (error) { transportError = error; }\n try { await closeStore(); } catch (error) {\n if (transportError) throw Object.assign(new Error(\"failed to close Agent Bridge server\"), {\n errors: [transportError, error],\n });\n throw error;\n }\n if (transportError) throw transportError;\n };\n server.onclose = () => {\n void closeStore().catch((error) => server.onerror?.(error instanceof Error ? error : new Error(String(error))));\n };\n\n return server;\n}\n\nexport async function startServer(\n config: AgentBridgeServerConfig = configFromEnv(),\n) {\n const server = createAgentBridgeServer(config);\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import { uuidv7 } from \"./bridge-domain.js\";\n\nexport const MESSAGE_ENVELOPE_SCHEMA = \"agent-bridge.message-envelope.v1\";\n\nconst RECORD_HASH_RE = /^sha256:[a-f0-9]{64}$/i;\n\ntype JsonRecord = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction normalizeString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed ? trimmed : undefined;\n}\n\nfunction normalizeStringList(value: unknown): string[] | undefined {\n const raw = Array.isArray(value)\n ? value\n : typeof value === \"string\"\n ? value.split(\",\")\n : [];\n const seen = new Set<string>();\n for (const item of raw) {\n const normalized = normalizeString(item);\n if (normalized) seen.add(normalized);\n }\n return seen.size ? [...seen] : undefined;\n}\n\nfunction normalizeRecordHashes(value: unknown): string[] | undefined {\n const raw = Array.isArray(value)\n ? value\n : typeof value === \"string\"\n ? value.split(\",\")\n : [];\n const seen = new Set<string>();\n for (const item of raw) {\n const normalized = normalizeString(item);\n if (normalized && RECORD_HASH_RE.test(normalized)) {\n seen.add(normalized.toLowerCase());\n }\n }\n return seen.size ? [...seen] : undefined;\n}\n\nfunction normalizeIsoTimestamp(value: unknown): string | undefined {\n const text = normalizeString(value);\n if (!text) return undefined;\n const parsed = Date.parse(text);\n if (Number.isNaN(parsed)) return undefined;\n return new Date(parsed).toISOString();\n}\n\nexport function normalizeMetadata(value: unknown): JsonRecord {\n return isRecord(value) ? { ...value } : {};\n}\n\nexport function buildMessageEnvelope(\n args: JsonRecord | undefined,\n receiptId?: string\n): JsonRecord {\n const source = normalizeString(args?.source) ?? \"unknown\";\n const category = normalizeString(args?.category);\n const kind = normalizeString(args?.kind) ?? category ?? \"operational\";\n const messageId = normalizeString(args?.message_id) ?? uuidv7();\n\n const envelope: JsonRecord = {\n schema: MESSAGE_ENVELOPE_SCHEMA,\n message_id: messageId,\n source_agent: source,\n kind,\n priority: normalizeString(args?.priority) ?? \"info\",\n payload_mime: normalizeString(args?.payload_mime) ?? \"text/plain\",\n };\n\n const targetAgents = normalizeStringList(args?.target_agents);\n if (targetAgents) envelope.target_agents = targetAgents;\n\n const project = normalizeString(args?.project);\n if (project) envelope.project = project;\n\n const threadId = normalizeString(args?.thread_id);\n if (threadId) envelope.thread_id = threadId;\n\n const replyToId = normalizeString(args?.reply_to_id);\n if (replyToId) envelope.reply_to_id = replyToId;\n\n if (Object.prototype.hasOwnProperty.call(args ?? {}, \"payload\")) {\n envelope.payload = args?.payload;\n }\n\n const payloadRef = normalizeString(args?.payload_ref);\n if (payloadRef) envelope.payload_ref = payloadRef;\n\n const payloadCiphertext = normalizeString(args?.payload_ciphertext);\n if (payloadCiphertext) envelope.payload_ciphertext = payloadCiphertext;\n\n if (receiptId) envelope.atrib_receipt_id = receiptId;\n\n const informedBy = normalizeRecordHashes(args?.informed_by);\n if (informedBy) envelope.informed_by = informedBy;\n\n const expiresAt = normalizeIsoTimestamp(args?.expires_at);\n if (expiresAt) envelope.expires_at = expiresAt;\n\n return envelope;\n}\n\nexport function mergeEnvelopeMetadata(\n metadataInput: unknown,\n envelope: JsonRecord\n): JsonRecord {\n return {\n ...normalizeMetadata(metadataInput),\n message_envelope: envelope,\n };\n}\n\nfunction getEnvelope(row: unknown): JsonRecord | undefined {\n if (!isRecord(row)) return undefined;\n const metadata = row.metadata;\n if (!isRecord(metadata)) return undefined;\n const envelope = metadata.message_envelope;\n return isRecord(envelope) ? envelope : undefined;\n}\n\nexport function rowMatchesMessageFilters(\n row: unknown,\n filters: JsonRecord | undefined\n): boolean {\n const targetAgent = normalizeString(filters?.target_agent);\n const threadId = normalizeString(filters?.thread_id);\n const kind = normalizeString(filters?.kind);\n\n if (!targetAgent && !threadId && !kind) return true;\n\n const envelope = getEnvelope(row);\n if (!envelope) {\n return !threadId && !kind;\n }\n\n if (targetAgent) {\n const targets = normalizeStringList(envelope.target_agents);\n if (targets && !targets.includes(targetAgent)) return false;\n }\n\n if (threadId && normalizeString(envelope.thread_id) !== threadId) {\n return false;\n }\n\n if (kind && normalizeString(envelope.kind) !== kind) {\n return false;\n }\n\n return true;\n}\n\nexport function filterContextRows(\n rows: unknown,\n filters: JsonRecord | undefined,\n limit: number\n): unknown {\n if (!Array.isArray(rows)) return rows;\n return rows.filter((row) => rowMatchesMessageFilters(row, filters)).slice(0, limit);\n}\n","function normalizeSource(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed ? trimmed : undefined;\n}\n\nexport function resolveAgentIdentity(\n requestedAgent: unknown,\n configuredAgent: unknown,\n field = \"agent\",\n): string | undefined {\n const requested = normalizeSource(requestedAgent);\n const configured = normalizeSource(configuredAgent);\n\n if (requested && configured && requested !== configured) {\n throw new Error(\n `${field} must match AGENT_BRIDGE_AGENT (${configured}); got ${requested}`,\n );\n }\n\n return requested ?? configured;\n}\n\nexport function resolvePostSource(\n requestedSource: unknown,\n configuredAgent: unknown,\n): string | undefined {\n return resolveAgentIdentity(requestedSource, configuredAgent, \"source\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,YAAY;;;ACPd,IAAM,0BAA0B;AAEvC,IAAM,iBAAiB;AAIvB,SAAS,SAAS,OAAqC;AACrD,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,gBAAgB,OAAoC;AAC3D,MAAI,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R;AAAA,EACF,CAAC;AAED,MAAI;AACJ,QAAM,kBAAkB,MAAM,oCAAmB,cAAc,aAAa,YACxE,OAAO,WAAW,KAAK,QAAQ,QAAQ,IACvC,QAAQ,QAAQ;AACpB,MAAI;AACJ,QAAM,aAAa,MAAM,sBAAY,OAAO,QAAQ,KAAK,QAAQ,QAAQ;AACzE,QAAM,UAAU,OAAO,QAAQ,KAAK,MAAM;AAC1C,SAAO,UAAU,OAAO,cAAc;AACpC,UAAM,gBAAgB;AACtB,UAAM,QAAQ,SAAS;AAAA,EACzB;AACA,QAAM,QAAQ,OAAO,MAAM,KAAK,MAAM;AACtC,SAAO,QAAQ,YAAY;AACzB,QAAI;AACJ,QAAI;AAAE,YAAM,MAAM;AAAA,IAAG,SAAS,OAAO;AAAE,uBAAiB;AAAA,IAAO;AAC/D,QAAI;AAAE,YAAM,WAAW;AAAA,IAAG,SAAS,OAAO;AACxC,UAAI,eAAgB,OAAM,OAAO,OAAO,IAAI,MAAM,qCAAqC,GAAG;AAAA,QACxF,QAAQ,CAAC,gBAAgB,KAAK;AAAA,MAChC,CAAC;AACD,YAAM;AAAA,IACR;AACA,QAAI,eAAgB,OAAM;AAAA,EAC5B;AACA,SAAO,UAAU,MAAM;AACrB,SAAK,WAAW,EAAE,MAAM,CAAC,UAAU,OAAO,UAAU,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC,CAAC;AAAA,EAChH;AAEA,SAAO;AACT;AAEA,eAAsB,YACpB,SAAkC,cAAc,GAChD;AACA,QAAM,SAAS,wBAAwB,MAAM;AAC7C,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;","names":[]}
@@ -797,10 +797,10 @@ var SQLiteBridgeStore = class {
797
797
  const owner = principal.instance ?? principal.agent;
798
798
  this.db.exec("BEGIN IMMEDIATE");
799
799
  try {
800
- this.db.prepare("UPDATE bridge_deliveries SET state='dead',last_error='message expired',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='message_expired' WHERE workspace=? AND recipient=? AND state IN ('pending','retrying','claimed') AND EXISTS (SELECT 1 FROM bridge_messages message WHERE message.workspace=bridge_deliveries.workspace AND message.id=bridge_deliveries.message_id AND message.expires_at IS NOT NULL AND message.expires_at<=?)").run(principal.workspace, principal.agent, nowText);
801
- this.db.prepare("UPDATE bridge_deliveries SET state='dead',last_error='maximum attempts reached',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='attempts_exhausted' WHERE workspace=? AND recipient=? AND cycle_attempt>=(SELECT json_extract(delivery_policy,'$.maxAttempts') FROM bridge_messages WHERE workspace=bridge_deliveries.workspace AND id=bridge_deliveries.message_id) AND (state IN ('pending','retrying') OR (state='claimed' AND lease_expires_at<=?))").run(principal.workspace, principal.agent, nowText);
802
- this.db.prepare("UPDATE bridge_deliveries SET state='retrying',available_at=?,last_error='lease expired',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='lease_expired' WHERE workspace=? AND recipient=? AND state='claimed' AND lease_expires_at<=? AND cycle_attempt<(SELECT json_extract(delivery_policy,'$.maxAttempts') FROM bridge_messages WHERE workspace=bridge_deliveries.workspace AND id=bridge_deliveries.message_id)").run(nowText, principal.workspace, principal.agent, nowText);
803
- const candidate = this.db.prepare("SELECT delivery.id FROM bridge_deliveries delivery JOIN bridge_messages message ON message.workspace=delivery.workspace AND message.id=delivery.message_id WHERE delivery.workspace=? AND delivery.recipient=? AND delivery.state IN ('pending','retrying') AND delivery.available_at<=? AND delivery.cycle_attempt<json_extract(message.delivery_policy,'$.maxAttempts') AND (message.expires_at IS NULL OR message.expires_at>?) ORDER BY delivery.priority_rank,delivery.available_at,delivery.created_at,delivery.id LIMIT 1").get(principal.workspace, principal.agent, nowText, nowText);
800
+ this.db.prepare("UPDATE bridge_deliveries SET state='dead',last_error='message expired',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='message_expired' WHERE workspace=? AND recipient=? AND (? IS NULL OR message_id=?) AND state IN ('pending','retrying','claimed') AND EXISTS (SELECT 1 FROM bridge_messages message WHERE message.workspace=bridge_deliveries.workspace AND message.id=bridge_deliveries.message_id AND message.expires_at IS NOT NULL AND message.expires_at<=?)").run(principal.workspace, principal.agent, options.messageId ?? null, options.messageId ?? null, nowText);
801
+ this.db.prepare("UPDATE bridge_deliveries SET state='dead',last_error='maximum attempts reached',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='attempts_exhausted' WHERE workspace=? AND recipient=? AND (? IS NULL OR message_id=?) AND cycle_attempt>=(SELECT json_extract(delivery_policy,'$.maxAttempts') FROM bridge_messages WHERE workspace=bridge_deliveries.workspace AND id=bridge_deliveries.message_id) AND (state IN ('pending','retrying') OR (state='claimed' AND lease_expires_at<=?))").run(principal.workspace, principal.agent, options.messageId ?? null, options.messageId ?? null, nowText);
802
+ this.db.prepare("UPDATE bridge_deliveries SET state='retrying',available_at=?,last_error='lease expired',lease_token=NULL,lease_owner=NULL,lease_expires_at=NULL,last_actor='agent-bridge',last_action='lease_expired' WHERE workspace=? AND recipient=? AND (? IS NULL OR message_id=?) AND state='claimed' AND lease_expires_at<=? AND cycle_attempt<(SELECT json_extract(delivery_policy,'$.maxAttempts') FROM bridge_messages WHERE workspace=bridge_deliveries.workspace AND id=bridge_deliveries.message_id)").run(nowText, principal.workspace, principal.agent, options.messageId ?? null, options.messageId ?? null, nowText);
803
+ const candidate = this.db.prepare("SELECT delivery.id FROM bridge_deliveries delivery JOIN bridge_messages message ON message.workspace=delivery.workspace AND message.id=delivery.message_id WHERE delivery.workspace=? AND delivery.recipient=? AND (? IS NULL OR delivery.message_id=?) AND delivery.state IN ('pending','retrying') AND delivery.available_at<=? AND delivery.cycle_attempt<json_extract(message.delivery_policy,'$.maxAttempts') AND (message.expires_at IS NULL OR message.expires_at>?) ORDER BY delivery.priority_rank,delivery.available_at,delivery.created_at,delivery.id LIMIT 1").get(principal.workspace, principal.agent, options.messageId ?? null, options.messageId ?? null, nowText, nowText);
804
804
  if (!candidate) {
805
805
  this.db.exec("COMMIT");
806
806
  return null;
@@ -1022,4 +1022,4 @@ export {
1022
1022
  verifySqliteHealth,
1023
1023
  SQLiteBridgeStore
1024
1024
  };
1025
- //# sourceMappingURL=chunk-DQOZJJZ2.js.map
1025
+ //# sourceMappingURL=chunk-IVG4XWWS.js.map