@creatornader/agent-bridge 0.6.0 → 0.6.2

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 (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +31 -7
  3. package/ROADMAP.md +32 -9
  4. package/SKILL.md +4 -1
  5. package/dist/bridge.d.ts +1 -1
  6. package/dist/bridge.js +3 -3
  7. package/dist/{chunk-62C63PIE.js → chunk-63JKCBC6.js} +4 -2
  8. package/dist/chunk-63JKCBC6.js.map +1 -0
  9. package/dist/{chunk-WQ4I5XGF.js → chunk-6ZOLE3E3.js} +2 -2
  10. package/dist/chunk-7B3XRRNI.js +27 -0
  11. package/dist/chunk-7B3XRRNI.js.map +1 -0
  12. package/dist/{chunk-IMJ47WO4.js → chunk-IXNQG4SB.js} +2 -2
  13. package/dist/{chunk-AIALYLGQ.js → chunk-JIRNR75D.js} +3 -3
  14. package/dist/{chunk-FGERNG4X.js → chunk-LF37B6KL.js} +5 -3
  15. package/dist/chunk-LF37B6KL.js.map +1 -0
  16. package/dist/cli.js +11 -13
  17. package/dist/cli.js.map +1 -1
  18. package/dist/client-runtime.js +3 -3
  19. package/dist/contracts/generate.js +2 -1
  20. package/dist/contracts/generate.js.map +1 -1
  21. package/dist/{gateway-BqmcKam8.d.ts → gateway-DWZ3pX48.d.ts} +5 -0
  22. package/dist/gateway-main.js +11 -2
  23. package/dist/gateway-main.js.map +1 -1
  24. package/dist/gateway.d.ts +1 -1
  25. package/dist/gateway.js +2 -2
  26. package/dist/index.js +4 -4
  27. package/dist/server.js +4 -4
  28. package/docs/architecture-v2.md +7 -3
  29. package/docs/decisions/0002-canonical-operation-contract-registry.md +5 -0
  30. package/docs/deployment.md +30 -8
  31. package/docs/ecosystem.md +2 -2
  32. package/llms.txt +2 -2
  33. package/openapi/agent-bridge-v2.openapi.json +8 -0
  34. package/package.json +4 -2
  35. package/schemas/agent-bridge-v2.capabilities.json +7 -0
  36. package/schemas/agent-bridge-v2.mcp.json +7 -0
  37. package/schemas/agent-bridge-v2.schema.json +14 -0
  38. package/scripts/gateway-release-check.mjs +92 -0
  39. package/dist/chunk-62C63PIE.js.map +0 -1
  40. package/dist/chunk-FGERNG4X.js.map +0 -1
  41. /package/dist/{chunk-WQ4I5XGF.js.map → chunk-6ZOLE3E3.js.map} +0 -0
  42. /package/dist/{chunk-IMJ47WO4.js.map → chunk-IXNQG4SB.js.map} +0 -0
  43. /package/dist/{chunk-AIALYLGQ.js.map → chunk-JIRNR75D.js.map} +0 -0
@@ -2,14 +2,14 @@
2
2
  import {
3
3
  createClientRuntime,
4
4
  createStore
5
- } from "./chunk-IMJ47WO4.js";
6
- import "./chunk-WQ4I5XGF.js";
5
+ } from "./chunk-IXNQG4SB.js";
6
+ import "./chunk-6ZOLE3E3.js";
7
7
  import "./chunk-ZUZ7TCIH.js";
8
8
  import "./chunk-IVG4XWWS.js";
9
9
  import "./chunk-GTK4KOED.js";
10
10
  import "./chunk-VOQIDTCJ.js";
11
11
  import "./chunk-4V2PFJEF.js";
12
- import "./chunk-62C63PIE.js";
12
+ import "./chunk-63JKCBC6.js";
13
13
  import "./chunk-BZLMF5O5.js";
14
14
  export {
15
15
  createClientRuntime,
@@ -11,7 +11,7 @@ import {
11
11
  SUPPORTED_PROTOCOL_VERSIONS,
12
12
  capabilityDocument,
13
13
  operations
14
- } from "../chunk-62C63PIE.js";
14
+ } from "../chunk-63JKCBC6.js";
15
15
 
16
16
  // src/contracts/generate.ts
17
17
  import { mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -175,6 +175,7 @@ var openapi = {
175
175
  openapi: "3.1.2",
176
176
  info: {
177
177
  title: "Agent Bridge Gateway",
178
+ description: "Let AI agents message each other and hand off work across tools, sessions, and machines.",
178
179
  version: PROTOCOL_VERSION,
179
180
  license: { name: "Apache-2.0", identifier: "Apache-2.0" }
180
181
  },
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/generate.ts","../../src/contracts/artifact-format.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { formatContractArtifact, normalizeContractArtifact } from \"./artifact-format.js\";\nimport {\n capabilityDocument,\n ErrorEnvelopeSchema,\n LegacyDeliverySchema,\n LegacyMessageDraftSchema,\n LegacyMessageSchema,\n LEGACY_PROTOCOL_VERSION,\n operations,\n PROTOCOL_HEADER,\n PROTOCOL_VERSION,\n SCOPE_ENFORCEMENT,\n SUPPORTED_PROTOCOL_HEADER,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"./registry.js\";\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction objectWithout(schema: Record<string, any>, excluded: ReadonlySet<string>): Record<string, any> {\n const result = clone(schema);\n if (!result.properties) return result;\n result.properties = Object.fromEntries(Object.entries(result.properties).filter(([name]) => !excluded.has(name)));\n if (Array.isArray(result.required)) {\n result.required = result.required.filter((name: string) => !excluded.has(name));\n if (!result.required.length) delete result.required;\n }\n return result;\n}\n\nconst scopeEnforcementByProvider = {\n local: false,\n gateway: SCOPE_ENFORCEMENT,\n};\n\nconst schemas = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n $id: \"https://agent-bridge.dev/schemas/v2/operations.json\",\n title: \"Agent Bridge v2 operation contracts\",\n protocolVersion: PROTOCOL_VERSION,\n scopeEnforcementByProvider,\n $defs: {\n ErrorEnvelope: ErrorEnvelopeSchema,\n legacy20MessageDraft: LegacyMessageDraftSchema,\n legacy20Message: LegacyMessageSchema,\n legacy20Delivery: LegacyDeliverySchema,\n ...Object.fromEntries(operations.flatMap((operation) => [\n [`${operation.id}Request`, operation.request],\n [`${operation.id}Response`, operation.response],\n ...(operation.cli ? [[`${operation.id}CliResponse`, operation.cli.response ?? operation.response] as const] : []),\n ...(operation.cli?.variants?.map((variant) => [\n `${operation.id}CliVariant${variant.command.replace(/(^|[-_])(\\w)/g, (_match, _separator, character: string) => character.toUpperCase())}Response`,\n variant.response,\n ] as const) ?? []),\n ])),\n },\n};\n\nconst protocolHeaders = {\n [PROTOCOL_HEADER]: {\n description: \"Selected Agent Bridge protocol version.\",\n required: true,\n schema: { type: \"string\", enum: [...SUPPORTED_PROTOCOL_VERSIONS] },\n },\n [SUPPORTED_PROTOCOL_HEADER]: {\n description: \"Comma-separated protocol versions supported by this gateway.\",\n required: true,\n schema: { type: \"string\" },\n },\n};\n\nfunction errorResponse(description: string) {\n return {\n description,\n headers: protocolHeaders,\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorEnvelope\" } } },\n };\n}\n\nconst canonicalErrors = {\n \"400\": errorResponse(\"The request does not match the operation contract.\"),\n \"401\": errorResponse(\"The bearer credential is missing or invalid.\"),\n \"403\": errorResponse(\"The credential cannot access the requested principal or origin.\"),\n \"404\": errorResponse(\"The route or requested resource does not exist.\"),\n \"409\": errorResponse(\"The request conflicts with current delivery or idempotency state.\"),\n \"413\": errorResponse(\"The request body exceeds the configured limit.\"),\n \"415\": errorResponse(\"The request content type is not application/json.\"),\n \"426\": errorResponse(\"The requested protocol version is unsupported.\"),\n \"429\": errorResponse(\"The gateway has rate-limited the request.\"),\n \"500\": errorResponse(\"The gateway could not complete the request.\"),\n \"502\": errorResponse(\"The upstream response does not match the selected protocol contract.\"),\n \"503\": errorResponse(\"The backing service is unavailable.\"),\n \"504\": errorResponse(\"The request exceeded the gateway deadline.\"),\n};\n\nconst paths: Record<string, Record<string, unknown>> = {};\nfor (const operation of operations.filter((entry) => entry.http)) {\n const http = operation.http!;\n const pathItem = paths[http.path] ??= {};\n const pathNames = [...http.path.matchAll(/\\{([^}]+)\\}/g)].map((match) => match[1]!);\n const pathSet = new Set(pathNames);\n const request = clone(operation.request as Record<string, any>);\n const parameters: Array<Record<string, unknown>> = [{\n name: PROTOCOL_HEADER,\n in: \"header\",\n required: true,\n description: \"This OpenAPI operation describes protocol 2.1. Headerless protocol 2.0 uses the separate schemas named by x-agent-bridge-protocol-2.0.\",\n schema: { type: \"string\", enum: [PROTOCOL_VERSION] },\n }, ...pathNames.map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: request.properties?.[name] ?? { type: \"string\" },\n }))];\n\n if (http.method === \"GET\" && request.properties) {\n for (const [propertyName, propertySchema] of Object.entries(request.properties) as Array<[string, Record<string, any>]>) {\n if (pathSet.has(propertyName)) continue;\n const queryName = propertyName === \"types\" ? \"type\" : propertyName === \"states\" ? \"state\" : propertyName;\n const repeated = propertySchema.type === \"array\";\n parameters.push({\n name: queryName,\n in: \"query\",\n required: request.required?.includes(propertyName) ?? false,\n ...(repeated ? { style: \"form\", explode: true } : {}),\n schema: propertySchema,\n });\n for (const alias of http.queryAliases?.[propertyName] ?? []) {\n parameters.push({\n name: alias,\n in: \"query\",\n required: false,\n deprecated: true,\n description: `Compatibility alias for ${queryName}.`,\n schema: propertySchema,\n });\n }\n }\n }\n\n const contentType = http.responseContentType ?? \"application/json\";\n const successStatus = String(http.successStatus ?? 200);\n const successResponse = {\n description: \"Successful response.\",\n headers: protocolHeaders,\n content: { [contentType]: { schema: clone(operation.response) } },\n };\n const bodySchema = objectWithout(request, pathSet);\n const hasBodyFields = Object.keys(bodySchema.properties ?? {}).length > 0;\n const hasRequiredBodyFields = Array.isArray(bodySchema.required) && bodySchema.required.length > 0;\n pathItem[http.method.toLowerCase()] = {\n operationId: operation.id,\n summary: operation.summary,\n security: [{ bearerAuth: [] }],\n \"x-agent-bridge-required-scopes\": [...operation.scopes],\n \"x-agent-bridge-scope-enforcement\": SCOPE_ENFORCEMENT,\n ...(parameters.length ? { parameters } : {}),\n ...(http.method === \"POST\" && hasBodyFields ? {\n requestBody: {\n required: hasRequiredBodyFields,\n content: { \"application/json\": { schema: bodySchema } },\n },\n } : {}),\n responses: { [successStatus]: successResponse, ...canonicalErrors },\n };\n}\n\nconst openapi = {\n openapi: \"3.1.2\",\n info: {\n title: \"Agent Bridge Gateway\",\n version: PROTOCOL_VERSION,\n license: { name: \"Apache-2.0\", identifier: \"Apache-2.0\" },\n },\n servers: [{ url: \"/\" }],\n \"x-agent-bridge-protocol-versions\": [...SUPPORTED_PROTOCOL_VERSIONS],\n \"x-agent-bridge-openapi-protocol-version\": PROTOCOL_VERSION,\n \"x-agent-bridge-protocol-2.0\": {\n description: \"Limited schema metadata for the released headerless 0.2.0 compatibility contract derived from d8184fe. This is not a complete OpenAPI route description. It does not support project, deliveryPolicy, delivery management/listing, or current delivery bookkeeping fields.\",\n requestSchemas: { publish_message: \"#/x-agent-bridge-schemas-2.0/MessageDraft\" },\n responseSchemas: { message: \"#/x-agent-bridge-schemas-2.0/Message\", delivery: \"#/x-agent-bridge-schemas-2.0/Delivery\" },\n },\n \"x-agent-bridge-schemas-2.0\": {\n MessageDraft: LegacyMessageDraftSchema,\n Message: LegacyMessageSchema,\n Delivery: LegacyDeliverySchema,\n },\n \"x-agent-bridge-scope-enforcement\": SCOPE_ENFORCEMENT,\n paths,\n components: {\n schemas: { ErrorEnvelope: ErrorEnvelopeSchema },\n securitySchemes: { bearerAuth: { type: \"http\", scheme: \"bearer\" } },\n },\n};\n\nconst mcp = {\n schemaVersion: \"agent-bridge-mcp-manifest-v1\",\n protocolVersion: PROTOCOL_VERSION,\n scopeEnforcementByProvider,\n tools: operations.filter((entry) => entry.mcp).map((entry) => ({\n name: entry.mcp!.name,\n description: entry.summary,\n inputSchema: entry.request,\n outputSchema: entry.response,\n requiredScopes: entry.scopes,\n providers: entry.providers,\n })),\n};\n\nconst root = resolve(dirname(fileURLToPath(import.meta.url)), \"../..\");\nconst outputs = new Map([\n [resolve(root, \"schemas/agent-bridge-v2.schema.json\"), formatContractArtifact(schemas)],\n [resolve(root, \"openapi/agent-bridge-v2.openapi.json\"), formatContractArtifact(openapi)],\n [resolve(root, \"schemas/agent-bridge-v2.mcp.json\"), formatContractArtifact(mcp)],\n [resolve(root, \"schemas/agent-bridge-v2.capabilities.json\"), formatContractArtifact(capabilityDocument())],\n]);\nconst check = process.argv.includes(\"--check\");\nconst drift: string[] = [];\nfor (const [path, contents] of outputs) {\n if (check) {\n let current = \"\";\n try { current = readFileSync(path, \"utf8\"); } catch {}\n if (normalizeContractArtifact(current) !== normalizeContractArtifact(contents)) {\n drift.push(path.slice(root.length + 1));\n }\n } else {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n }\n}\nif (drift.length) {\n for (const path of drift) process.stderr.write(`ERROR contract artifact drift: ${path}\\n`);\n process.exitCode = 1;\n} else {\n process.stdout.write(`contracts ${check ? \"match\" : \"generated\"}: ${outputs.size} artifacts, ${operations.length} operations\\n`);\n}\n","export function formatContractArtifact(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nexport function normalizeContractArtifact(contents: string): string {\n return contents.replace(/\\r\\n?/g, \"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;;;ACFvB,SAAS,uBAAuB,OAAwB;AAC7D,SAAO,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA;AAC1C;AAEO,SAAS,0BAA0B,UAA0B;AAClE,SAAO,SAAS,QAAQ,UAAU,IAAI;AACxC;;;ADaA,SAAS,MAAS,OAAa;AAC7B,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEA,SAAS,cAAc,QAA6B,UAAoD;AACtG,QAAM,SAAS,MAAM,MAAM;AAC3B,MAAI,CAAC,OAAO,WAAY,QAAO;AAC/B,SAAO,aAAa,OAAO,YAAY,OAAO,QAAQ,OAAO,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;AAChH,MAAI,MAAM,QAAQ,OAAO,QAAQ,GAAG;AAClC,WAAO,WAAW,OAAO,SAAS,OAAO,CAAC,SAAiB,CAAC,SAAS,IAAI,IA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]}
1
+ {"version":3,"sources":["../../src/contracts/generate.ts","../../src/contracts/artifact-format.ts"],"sourcesContent":["import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { formatContractArtifact, normalizeContractArtifact } from \"./artifact-format.js\";\nimport {\n capabilityDocument,\n ErrorEnvelopeSchema,\n LegacyDeliverySchema,\n LegacyMessageDraftSchema,\n LegacyMessageSchema,\n LEGACY_PROTOCOL_VERSION,\n operations,\n PROTOCOL_HEADER,\n PROTOCOL_VERSION,\n SCOPE_ENFORCEMENT,\n SUPPORTED_PROTOCOL_HEADER,\n SUPPORTED_PROTOCOL_VERSIONS,\n} from \"./registry.js\";\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nfunction objectWithout(schema: Record<string, any>, excluded: ReadonlySet<string>): Record<string, any> {\n const result = clone(schema);\n if (!result.properties) return result;\n result.properties = Object.fromEntries(Object.entries(result.properties).filter(([name]) => !excluded.has(name)));\n if (Array.isArray(result.required)) {\n result.required = result.required.filter((name: string) => !excluded.has(name));\n if (!result.required.length) delete result.required;\n }\n return result;\n}\n\nconst scopeEnforcementByProvider = {\n local: false,\n gateway: SCOPE_ENFORCEMENT,\n};\n\nconst schemas = {\n $schema: \"https://json-schema.org/draft/2020-12/schema\",\n $id: \"https://agent-bridge.dev/schemas/v2/operations.json\",\n title: \"Agent Bridge v2 operation contracts\",\n protocolVersion: PROTOCOL_VERSION,\n scopeEnforcementByProvider,\n $defs: {\n ErrorEnvelope: ErrorEnvelopeSchema,\n legacy20MessageDraft: LegacyMessageDraftSchema,\n legacy20Message: LegacyMessageSchema,\n legacy20Delivery: LegacyDeliverySchema,\n ...Object.fromEntries(operations.flatMap((operation) => [\n [`${operation.id}Request`, operation.request],\n [`${operation.id}Response`, operation.response],\n ...(operation.cli ? [[`${operation.id}CliResponse`, operation.cli.response ?? operation.response] as const] : []),\n ...(operation.cli?.variants?.map((variant) => [\n `${operation.id}CliVariant${variant.command.replace(/(^|[-_])(\\w)/g, (_match, _separator, character: string) => character.toUpperCase())}Response`,\n variant.response,\n ] as const) ?? []),\n ])),\n },\n};\n\nconst protocolHeaders = {\n [PROTOCOL_HEADER]: {\n description: \"Selected Agent Bridge protocol version.\",\n required: true,\n schema: { type: \"string\", enum: [...SUPPORTED_PROTOCOL_VERSIONS] },\n },\n [SUPPORTED_PROTOCOL_HEADER]: {\n description: \"Comma-separated protocol versions supported by this gateway.\",\n required: true,\n schema: { type: \"string\" },\n },\n};\n\nfunction errorResponse(description: string) {\n return {\n description,\n headers: protocolHeaders,\n content: { \"application/json\": { schema: { $ref: \"#/components/schemas/ErrorEnvelope\" } } },\n };\n}\n\nconst canonicalErrors = {\n \"400\": errorResponse(\"The request does not match the operation contract.\"),\n \"401\": errorResponse(\"The bearer credential is missing or invalid.\"),\n \"403\": errorResponse(\"The credential cannot access the requested principal or origin.\"),\n \"404\": errorResponse(\"The route or requested resource does not exist.\"),\n \"409\": errorResponse(\"The request conflicts with current delivery or idempotency state.\"),\n \"413\": errorResponse(\"The request body exceeds the configured limit.\"),\n \"415\": errorResponse(\"The request content type is not application/json.\"),\n \"426\": errorResponse(\"The requested protocol version is unsupported.\"),\n \"429\": errorResponse(\"The gateway has rate-limited the request.\"),\n \"500\": errorResponse(\"The gateway could not complete the request.\"),\n \"502\": errorResponse(\"The upstream response does not match the selected protocol contract.\"),\n \"503\": errorResponse(\"The backing service is unavailable.\"),\n \"504\": errorResponse(\"The request exceeded the gateway deadline.\"),\n};\n\nconst paths: Record<string, Record<string, unknown>> = {};\nfor (const operation of operations.filter((entry) => entry.http)) {\n const http = operation.http!;\n const pathItem = paths[http.path] ??= {};\n const pathNames = [...http.path.matchAll(/\\{([^}]+)\\}/g)].map((match) => match[1]!);\n const pathSet = new Set(pathNames);\n const request = clone(operation.request as Record<string, any>);\n const parameters: Array<Record<string, unknown>> = [{\n name: PROTOCOL_HEADER,\n in: \"header\",\n required: true,\n description: \"This OpenAPI operation describes protocol 2.1. Headerless protocol 2.0 uses the separate schemas named by x-agent-bridge-protocol-2.0.\",\n schema: { type: \"string\", enum: [PROTOCOL_VERSION] },\n }, ...pathNames.map((name) => ({\n name,\n in: \"path\",\n required: true,\n schema: request.properties?.[name] ?? { type: \"string\" },\n }))];\n\n if (http.method === \"GET\" && request.properties) {\n for (const [propertyName, propertySchema] of Object.entries(request.properties) as Array<[string, Record<string, any>]>) {\n if (pathSet.has(propertyName)) continue;\n const queryName = propertyName === \"types\" ? \"type\" : propertyName === \"states\" ? \"state\" : propertyName;\n const repeated = propertySchema.type === \"array\";\n parameters.push({\n name: queryName,\n in: \"query\",\n required: request.required?.includes(propertyName) ?? false,\n ...(repeated ? { style: \"form\", explode: true } : {}),\n schema: propertySchema,\n });\n for (const alias of http.queryAliases?.[propertyName] ?? []) {\n parameters.push({\n name: alias,\n in: \"query\",\n required: false,\n deprecated: true,\n description: `Compatibility alias for ${queryName}.`,\n schema: propertySchema,\n });\n }\n }\n }\n\n const contentType = http.responseContentType ?? \"application/json\";\n const successStatus = String(http.successStatus ?? 200);\n const successResponse = {\n description: \"Successful response.\",\n headers: protocolHeaders,\n content: { [contentType]: { schema: clone(operation.response) } },\n };\n const bodySchema = objectWithout(request, pathSet);\n const hasBodyFields = Object.keys(bodySchema.properties ?? {}).length > 0;\n const hasRequiredBodyFields = Array.isArray(bodySchema.required) && bodySchema.required.length > 0;\n pathItem[http.method.toLowerCase()] = {\n operationId: operation.id,\n summary: operation.summary,\n security: [{ bearerAuth: [] }],\n \"x-agent-bridge-required-scopes\": [...operation.scopes],\n \"x-agent-bridge-scope-enforcement\": SCOPE_ENFORCEMENT,\n ...(parameters.length ? { parameters } : {}),\n ...(http.method === \"POST\" && hasBodyFields ? {\n requestBody: {\n required: hasRequiredBodyFields,\n content: { \"application/json\": { schema: bodySchema } },\n },\n } : {}),\n responses: { [successStatus]: successResponse, ...canonicalErrors },\n };\n}\n\nconst openapi = {\n openapi: \"3.1.2\",\n info: {\n title: \"Agent Bridge Gateway\",\n description: \"Let AI agents message each other and hand off work across tools, sessions, and machines.\",\n version: PROTOCOL_VERSION,\n license: { name: \"Apache-2.0\", identifier: \"Apache-2.0\" },\n },\n servers: [{ url: \"/\" }],\n \"x-agent-bridge-protocol-versions\": [...SUPPORTED_PROTOCOL_VERSIONS],\n \"x-agent-bridge-openapi-protocol-version\": PROTOCOL_VERSION,\n \"x-agent-bridge-protocol-2.0\": {\n description: \"Limited schema metadata for the released headerless 0.2.0 compatibility contract derived from d8184fe. This is not a complete OpenAPI route description. It does not support project, deliveryPolicy, delivery management/listing, or current delivery bookkeeping fields.\",\n requestSchemas: { publish_message: \"#/x-agent-bridge-schemas-2.0/MessageDraft\" },\n responseSchemas: { message: \"#/x-agent-bridge-schemas-2.0/Message\", delivery: \"#/x-agent-bridge-schemas-2.0/Delivery\" },\n },\n \"x-agent-bridge-schemas-2.0\": {\n MessageDraft: LegacyMessageDraftSchema,\n Message: LegacyMessageSchema,\n Delivery: LegacyDeliverySchema,\n },\n \"x-agent-bridge-scope-enforcement\": SCOPE_ENFORCEMENT,\n paths,\n components: {\n schemas: { ErrorEnvelope: ErrorEnvelopeSchema },\n securitySchemes: { bearerAuth: { type: \"http\", scheme: \"bearer\" } },\n },\n};\n\nconst mcp = {\n schemaVersion: \"agent-bridge-mcp-manifest-v1\",\n protocolVersion: PROTOCOL_VERSION,\n scopeEnforcementByProvider,\n tools: operations.filter((entry) => entry.mcp).map((entry) => ({\n name: entry.mcp!.name,\n description: entry.summary,\n inputSchema: entry.request,\n outputSchema: entry.response,\n requiredScopes: entry.scopes,\n providers: entry.providers,\n })),\n};\n\nconst root = resolve(dirname(fileURLToPath(import.meta.url)), \"../..\");\nconst outputs = new Map([\n [resolve(root, \"schemas/agent-bridge-v2.schema.json\"), formatContractArtifact(schemas)],\n [resolve(root, \"openapi/agent-bridge-v2.openapi.json\"), formatContractArtifact(openapi)],\n [resolve(root, \"schemas/agent-bridge-v2.mcp.json\"), formatContractArtifact(mcp)],\n [resolve(root, \"schemas/agent-bridge-v2.capabilities.json\"), formatContractArtifact(capabilityDocument())],\n]);\nconst check = process.argv.includes(\"--check\");\nconst drift: string[] = [];\nfor (const [path, contents] of outputs) {\n if (check) {\n let current = \"\";\n try { current = readFileSync(path, \"utf8\"); } catch {}\n if (normalizeContractArtifact(current) !== normalizeContractArtifact(contents)) {\n drift.push(path.slice(root.length + 1));\n }\n } else {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, contents);\n }\n}\nif (drift.length) {\n for (const path of drift) process.stderr.write(`ERROR contract artifact drift: ${path}\\n`);\n process.exitCode = 1;\n} else {\n process.stdout.write(`contracts ${check ? \"match\" : \"generated\"}: ${outputs.size} artifacts, ${operations.length} operations\\n`);\n}\n","export function formatContractArtifact(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nexport function normalizeContractArtifact(contents: string): string {\n return contents.replace(/\\r\\n?/g, \"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc,qBAAqB;AACvD,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;;;ACFvB,SAAS,uBAAuB,OAAwB;AAC7D,SAAO,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA;AAC1C;AAEO,SAAS,0BAA0B,UAA0B;AAClE,SAAO,SAAS,QAAQ,UAAU,IAAI;AACxC;;;ADaA,SAAS,MAAS,OAAa;AAC7B,SAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEA,SAAS,cAAc,QAA6B,UAAoD;AACtG,QAAM,SAAS,MAAM,MAAM;AAC3B,MAAI,CAAC,OAAO,WAAY,QAAO;AAC/B,SAAO,aAAa,OAAO,YAAY,OAAO,QAAQ,OAAO,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,MAAM,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;AAChH,MAAI,MAAM,QAAQ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L,UAAQ,OAAO,MAAM,aAAa,QAAQ,UAAU,WAAW,KAAK,QAAQ,IAAI,eAAe,WAAW,MAAM;AAAA,CAAe;AACjI;","names":[]}
@@ -96,6 +96,11 @@ interface GatewayOptions {
96
96
  rowIsolationReady?: () => Promise<boolean>;
97
97
  /** Production PostgreSQL request authority. Other providers omit this. */
98
98
  requestAuthority?: RequestAuthority;
99
+ /** Package and source revision for deployment drift checks. */
100
+ implementation?: {
101
+ version: string;
102
+ revision?: string;
103
+ };
99
104
  }
100
105
  declare function createGateway(options: GatewayOptions): node_http.Server<typeof IncomingMessage, typeof ServerResponse>;
101
106
 
@@ -2,6 +2,10 @@
2
2
  import {
3
3
  PostgresBridgeStore
4
4
  } from "./chunk-CVZAJ7TP.js";
5
+ import {
6
+ buildRevision,
7
+ packageVersion
8
+ } from "./chunk-7B3XRRNI.js";
5
9
  import {
6
10
  loadMigrationPlan,
7
11
  migrationsReady,
@@ -12,9 +16,9 @@ import "./chunk-VOQIDTCJ.js";
12
16
  import {
13
17
  PostgresCredentialResolver,
14
18
  createGateway
15
- } from "./chunk-FGERNG4X.js";
19
+ } from "./chunk-LF37B6KL.js";
16
20
  import "./chunk-4V2PFJEF.js";
17
- import "./chunk-62C63PIE.js";
21
+ import "./chunk-63JKCBC6.js";
18
22
  import "./chunk-BZLMF5O5.js";
19
23
 
20
24
  // src/gateway-main.ts
@@ -315,6 +319,10 @@ async function main() {
315
319
  if (!databaseUrl) {
316
320
  throw new Error("AGENT_BRIDGE_RUNTIME_DATABASE_URL is required for the gateway");
317
321
  }
322
+ const implementation = {
323
+ version: packageVersion(),
324
+ revision: buildRevision(process.env.AGENT_BRIDGE_BUILD_REVISION)
325
+ };
318
326
  const deadline = integer(process.env.AGENT_BRIDGE_REQUEST_DEADLINE_MS, 1e4, "request deadline");
319
327
  const databaseTimeout = integer(
320
328
  process.env.AGENT_BRIDGE_DATABASE_TIMEOUT_MS,
@@ -388,6 +396,7 @@ async function main() {
388
396
  allowedOrigins,
389
397
  bodyLimitBytes,
390
398
  requestDeadlineMs: deadline,
399
+ implementation,
391
400
  ready: schemaReady,
392
401
  rowIsolationReady: schemaReady
393
402
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/gateway-main.ts","../src/gateway-security.ts","../src/postgres-request-authority.ts","../src/postgres-runtime-connection.ts"],"sourcesContent":["import { fileURLToPath } from \"node:url\";\nimport pg from \"pg\";\nimport { PostgresCredentialResolver } from \"./gateway-auth.js\";\nimport { PostgresGatewaySecurity } from \"./gateway-security.js\";\nimport { createGateway } from \"./gateway.js\";\nimport {\n loadMigrationPlan,\n migrationsReady,\n runMigrations,\n runtimeSchemaReady,\n} from \"./migrations.js\";\nimport { PostgresBridgeStore } from \"./postgres-bridge-store.js\";\nimport { PostgresRequestAuthority } from \"./postgres-request-authority.js\";\nimport { runtimePostgresConnectionConfig } from \"./postgres-runtime-connection.js\";\n\nfunction integer(value: string | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${name} must be a positive integer`);\n return parsed;\n}\n\nasync function main(): Promise<void> {\n const migrationsDirectory = fileURLToPath(new URL(\"../sql/migrations\", import.meta.url));\n if (process.argv.includes(\"--migrate-only\")) {\n const databaseUrl = process.env.AGENT_BRIDGE_DATABASE_URL;\n if (!databaseUrl) throw new Error(\"AGENT_BRIDGE_DATABASE_URL is required for migrations\");\n const migrationPool = new pg.Pool({\n connectionString: databaseUrl,\n max: 1,\n application_name: \"agent-bridge-migrator\",\n });\n try {\n await runMigrations(migrationPool, migrationsDirectory);\n } finally {\n await migrationPool.end();\n }\n return;\n }\n if (process.env.AGENT_BRIDGE_MIGRATE === \"1\") {\n throw new Error(\"AGENT_BRIDGE_MIGRATE is not supported; run agent-bridge migrate separately\");\n }\n const databaseUrl = process.env.AGENT_BRIDGE_RUNTIME_DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL is required for the gateway\");\n }\n\n const deadline = integer(process.env.AGENT_BRIDGE_REQUEST_DEADLINE_MS, 10_000, \"request deadline\");\n const databaseTimeout = integer(\n process.env.AGENT_BRIDGE_DATABASE_TIMEOUT_MS,\n Math.max(1, Math.floor(deadline / 3)),\n \"database timeout\",\n );\n const poolSize = integer(process.env.AGENT_BRIDGE_DATABASE_POOL_SIZE, 10, \"database pool size\");\n const bodyLimitBytes = integer(\n process.env.AGENT_BRIDGE_BODY_LIMIT_BYTES,\n 128 * 1024,\n \"body limit\",\n );\n const host = process.env.AGENT_BRIDGE_HOST ?? \"127.0.0.1\";\n const port = integer(process.env.AGENT_BRIDGE_PORT, 8787, \"gateway port\");\n const allowedOrigins = process.env.AGENT_BRIDGE_ALLOWED_ORIGINS\n ?.split(\",\")\n .map((origin) => origin.trim())\n .filter(Boolean);\n const migrationPlan = await loadMigrationPlan(migrationsDirectory);\n const runtimeConnection = runtimePostgresConnectionConfig(\n databaseUrl,\n process.env.AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64,\n );\n const pool = new pg.Pool({\n ...runtimeConnection,\n max: poolSize,\n connectionTimeoutMillis: databaseTimeout,\n query_timeout: databaseTimeout,\n statement_timeout: databaseTimeout,\n application_name: \"agent-bridge-gateway\",\n });\n const readinessPool = new pg.Pool({\n ...runtimeConnection,\n max: 1,\n connectionTimeoutMillis: databaseTimeout,\n query_timeout: databaseTimeout,\n statement_timeout: databaseTimeout,\n application_name: \"agent-bridge-gateway-readiness\",\n });\n\n const store = new PostgresBridgeStore(pool);\n let readinessCheckedAt = 0;\n let readinessValue = false;\n let readinessInFlight: Promise<boolean> | undefined;\n const probeSchema = async () =>\n await migrationsReady(readinessPool, migrationPlan) && await runtimeSchemaReady(readinessPool);\n const schemaReady = (force = false): Promise<boolean> => {\n if (!force && Date.now() - readinessCheckedAt < 1_000) {\n return Promise.resolve(readinessValue);\n }\n if (readinessInFlight) return readinessInFlight;\n let current: Promise<boolean>;\n current = probeSchema()\n .then((ready) => {\n readinessValue = ready;\n readinessCheckedAt = Date.now();\n return ready;\n })\n .finally(() => {\n if (readinessInFlight === current) readinessInFlight = undefined;\n });\n readinessInFlight = current;\n return current;\n };\n try {\n if (!await schemaReady(true)) {\n throw new Error(\"runtime database is not ready for enforced row isolation\");\n }\n } catch (error) {\n await Promise.allSettled([pool.end(), readinessPool.end()]);\n throw error;\n }\n const gateway = createGateway({\n store,\n credentials: new PostgresCredentialResolver(pool),\n security: new PostgresGatewaySecurity(pool),\n requestAuthority: new PostgresRequestAuthority(pool),\n allowedOrigins,\n bodyLimitBytes,\n requestDeadlineMs: deadline,\n ready: schemaReady,\n rowIsolationReady: schemaReady,\n });\n\n gateway.listen(port, host, () => {\n process.stderr.write(`Agent Bridge gateway listening on ${host}:${port}\\n`);\n });\n\n let stopping = false;\n async function shutdown(): Promise<void> {\n if (stopping) return;\n stopping = true;\n await new Promise<void>((resolve, reject) => {\n gateway.close((error) => error ? reject(error) : resolve());\n });\n await Promise.all([pool.end(), readinessPool.end()]);\n }\n\n process.once(\"SIGINT\", () => void shutdown());\n process.once(\"SIGTERM\", () => void shutdown());\n}\n\nvoid main().catch((error) => {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n});\n","import type { PgQueryable } from \"./postgres-bridge-store.js\";\nimport type { OperationId } from \"./contracts/registry.js\";\n\nexport interface RateLimitDecision {\n allowed: boolean;\n policyId: string | null;\n limit: number;\n remaining: number;\n retryAfterSeconds: number;\n}\n\nexport interface GatewaySecurity {\n recordScopeDenial(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void>;\n consume(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<RateLimitDecision>;\n}\n\nexport class PostgresGatewaySecurity implements GatewaySecurity {\n constructor(private readonly db: PgQueryable) {}\n\n private functionName(bound: string, unbound: string): string {\n return this.db.inTransaction ? bound : unbound;\n }\n\n async recordScopeDenial(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) throw signal.reason;\n await this.db.query(\n `SELECT agent_bridge.${this.functionName(\"record_scope_denial\", \"record_scope_denial_unbound_011\")}($1::uuid, $2::text, $3::uuid)`,\n [credentialId, operationId, requestId],\n );\n if (signal?.aborted) throw signal.reason;\n }\n\n async consume(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<RateLimitDecision> {\n if (signal?.aborted) throw signal.reason;\n const result = await this.db.query<{\n allowed: boolean;\n limit_value: string | number;\n remaining_value: string | number;\n retry_after_seconds: string | number;\n denied_policy_id: string | null;\n }>(\n `SELECT allowed, limit_value, remaining_value, retry_after_seconds, denied_policy_id\n FROM agent_bridge.${this.functionName(\"consume_rate_limit\", \"consume_rate_limit_unbound_011\")}($1::uuid, $2::text, $3::uuid)`,\n [credentialId, operationId, requestId],\n );\n if (signal?.aborted) throw signal.reason;\n const row = result.rows[0];\n if (!row) throw new Error(\"rate limit policy is missing\");\n return {\n allowed: row.allowed,\n policyId: row.denied_policy_id,\n limit: Math.max(0, Number(row.limit_value)),\n remaining: Math.max(0, Number(row.remaining_value)),\n retryAfterSeconds: Math.max(0, Number(row.retry_after_seconds)),\n };\n }\n}\n","import type pg from \"pg\";\nimport type { BridgePrincipal } from \"./bridge-domain.js\";\nimport type { AuthorizationScope } from \"./contracts/registry.js\";\nimport { PostgresBridgeStore, type PgQueryable } from \"./postgres-bridge-store.js\";\nimport { PostgresGatewaySecurity } from \"./gateway-security.js\";\n\nexport interface RequestAuthorityContext {\n gatewayAuthorityId: string;\n credential: { id: string; principal: BridgePrincipal; scopes: readonly AuthorizationScope[] };\n store: PostgresBridgeStore;\n security: PostgresGatewaySecurity;\n /** Establishes the savepoint separating durable security accounting from domain work. */\n beginDomainWork(): Promise<void>;\n endpointMigrationChallenges?: {\n issue(input: { challenge: string; expectedGatewayAuthorityId: string; verifierCredentialId: string }): Promise<{ gatewayAuthorityId: string; issuerCredentialId: string; verifierCredentialId: string; expiresAt: string }>;\n consume(input: { challenge: string; expectedGatewayAuthorityId: string; issuerCredentialId: string }): Promise<{ gatewayAuthorityId: string; issuerCredentialId: string; verifierCredentialId: string; expiresAt: string | null; consumed: boolean }>;\n };\n}\n\nexport interface RequestAuthority {\n run<T>(credentialId: string, credentialHash: string, requestId: string, signal: AbortSignal, work: (context: RequestAuthorityContext) => Promise<T>): Promise<T>;\n}\n\ntype AuthorityRow = {\n gateway_authority_id: string;\n credential_id: string;\n workspace_id: string;\n principal: string;\n scopes: AuthorizationScope[];\n};\n\nfunction timestamp(value: unknown): string {\n if (value instanceof Date) return value.toISOString();\n return String(value);\n}\n\nfunction endpointMigrationFailure(error: unknown): never {\n const sqlstate = typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code ?? \"\")\n : \"\";\n if (sqlstate === \"28000\") {\n throw Object.assign(new Error(\"endpoint migration binding was rejected\"), {\n status: 409,\n code: \"endpoint_migration_binding_rejected\",\n });\n }\n if (sqlstate === \"23505\") {\n throw Object.assign(new Error(\"endpoint migration challenge conflicts with existing state\"), {\n status: 409,\n code: \"endpoint_migration_challenge_conflict\",\n });\n }\n throw error;\n}\n\nexport class MutationOutcomeUnknownError extends Error {\n readonly status = 503;\n readonly code = \"mutation_outcome_unknown\";\n constructor() { super(\"The database commit outcome is unknown\"); }\n}\n\nexport class PostgresRequestAuthority implements RequestAuthority {\n constructor(private readonly pool: Pick<pg.Pool, \"connect\">) {}\n\n async run<T>(credentialId: string, credentialHash: string, requestId: string, signal: AbortSignal, work: (context: RequestAuthorityContext) => Promise<T>): Promise<T> {\n if (signal.aborted) throw signal.reason;\n const client = await this.pool.connect();\n const db: PgQueryable = { inTransaction: true, query: (sql, values) => client.query(sql, values) };\n let transactionOpen = false;\n let domainSavepoint = false;\n let commitDispatched = false;\n let commitCompleted = false;\n let discard: Error | undefined;\n try {\n if (signal.aborted) throw signal.reason;\n await client.query(\"BEGIN\");\n transactionOpen = true;\n const opened = await client.query<AuthorityRow>(\n `SELECT gateway_authority_id,credential_id,workspace_id,principal,scopes\n FROM agent_bridge.open_request_authority_bound($1::uuid,$2::text,$3::uuid)`,\n [credentialId, credentialHash, requestId],\n );\n const row = opened.rows[0];\n if (!row) {\n await client.query(\"ROLLBACK\");\n transactionOpen = false;\n throw Object.assign(new Error(\"Credential is not active\"), { status: 401, code: \"unauthorized\" });\n }\n if (signal.aborted) throw signal.reason;\n const context: RequestAuthorityContext = {\n gatewayAuthorityId: row.gateway_authority_id,\n credential: { id: row.credential_id, principal: { workspace: row.workspace_id, agent: row.principal }, scopes: row.scopes },\n store: new PostgresBridgeStore(db),\n security: new PostgresGatewaySecurity(db),\n beginDomainWork: async () => {\n if (domainSavepoint) return;\n if (signal.aborted) throw signal.reason;\n await client.query(\"SAVEPOINT agent_bridge_domain_work\");\n if (signal.aborted) throw signal.reason;\n domainSavepoint = true;\n },\n endpointMigrationChallenges: {\n issue: async (input) => {\n let result;\n try {\n result = await client.query<{\n gateway_authority_id: string;\n issuer_credential_id: string;\n verifier_credential_id: string;\n expires_at: string | Date;\n }>(\n `SELECT gateway_authority_id,issuer_credential_id,verifier_credential_id,expires_at\n FROM agent_bridge.issue_endpoint_migration_challenge($1::uuid,$2::uuid,$3::text)`,\n [input.expectedGatewayAuthorityId, input.verifierCredentialId, input.challenge],\n );\n } catch (error) {\n endpointMigrationFailure(error);\n }\n const row = result.rows[0];\n if (!row) throw new Error(\"endpoint migration challenge could not be issued\");\n return {\n gatewayAuthorityId: row.gateway_authority_id,\n issuerCredentialId: row.issuer_credential_id,\n verifierCredentialId: row.verifier_credential_id,\n expiresAt: timestamp(row.expires_at),\n };\n },\n consume: async (input) => {\n let result;\n try {\n result = await client.query<{\n gateway_authority_id: string;\n issuer_credential_id: string;\n verifier_credential_id: string;\n expires_at: string | Date | null;\n consumed: boolean;\n }>(\n `SELECT gateway_authority_id,issuer_credential_id,verifier_credential_id,expires_at,consumed\n FROM agent_bridge.consume_endpoint_migration_challenge($1::uuid,$2::uuid,$3::text)`,\n [input.expectedGatewayAuthorityId, input.issuerCredentialId, input.challenge],\n );\n } catch (error) {\n endpointMigrationFailure(error);\n }\n const row = result.rows[0];\n if (!row) throw new Error(\"endpoint migration challenge could not be consumed\");\n return {\n gatewayAuthorityId: row.gateway_authority_id,\n issuerCredentialId: row.issuer_credential_id,\n verifierCredentialId: row.verifier_credential_id,\n expiresAt: row.expires_at === null ? null : timestamp(row.expires_at),\n consumed: row.consumed,\n };\n },\n },\n };\n try {\n const result = await work(context);\n if (signal.aborted) throw signal.reason;\n await client.query(\"SELECT agent_bridge.close_request_authority()\");\n if (signal.aborted) throw signal.reason;\n commitDispatched = true;\n await client.query(\"COMMIT\");\n commitCompleted = true;\n transactionOpen = false;\n return result;\n } catch (error) {\n if (commitDispatched) throw new MutationOutcomeUnknownError();\n if (signal.aborted) throw error;\n try {\n if (domainSavepoint) {\n await client.query(\"ROLLBACK TO SAVEPOINT agent_bridge_domain_work\");\n }\n await client.query(\"SELECT agent_bridge.close_request_authority()\");\n } catch {\n try {\n await client.query(\"ROLLBACK\");\n } catch (rollbackError) {\n discard = rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError));\n }\n transactionOpen = false;\n throw error;\n }\n if (signal.aborted) throw signal.reason;\n commitDispatched = true;\n await client.query(\"COMMIT\");\n commitCompleted = true;\n transactionOpen = false;\n throw error;\n }\n } catch (error) {\n if (commitDispatched && !commitCompleted) {\n discard = error instanceof Error ? error : new Error(String(error));\n throw error instanceof MutationOutcomeUnknownError ? error : new MutationOutcomeUnknownError();\n }\n if (transactionOpen) {\n try { await client.query(\"ROLLBACK\"); transactionOpen = false; }\n catch (rollbackError) { discard = rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError)); }\n }\n throw error;\n } finally {\n client.release(discard);\n }\n }\n\n}\n","import type { PoolConfig } from \"pg\";\n\nconst MAX_CA_PEM_BYTES = 256 * 1024;\nconst BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;\nconst CERTIFICATE_PATTERN = /-----BEGIN CERTIFICATE-----[\\s\\S]+-----END CERTIFICATE-----/u;\nconst CLIENT_CERTIFICATE_PARAMETERS = [\n \"sslcert\",\n \"sslkey\",\n \"sslpassword\",\n] as const;\n\nfunction decodeCaPem(encoded: string): string {\n const value = encoded.trim();\n if (!value) throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be empty\");\n if (!BASE64_PATTERN.test(value)) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must be canonical base64\");\n }\n const bytes = Buffer.from(value, \"base64\");\n if (bytes.toString(\"base64\") !== value) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must be canonical base64\");\n }\n if (bytes.byteLength > MAX_CA_PEM_BYTES) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 exceeds 256 KiB after decoding\");\n }\n const pem = bytes.toString(\"utf8\").trim();\n if (pem.includes(\"\\0\") || !CERTIFICATE_PATTERN.test(pem)) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must decode to a PEM certificate bundle\");\n }\n return pem;\n}\n\nexport function runtimePostgresConnectionConfig(\n connectionString: string,\n caBase64: string | undefined,\n): Pick<PoolConfig, \"connectionString\" | \"ssl\"> {\n if (caBase64 === undefined) return { connectionString };\n\n let parsed: URL;\n try {\n parsed = new URL(connectionString);\n } catch {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL must be a valid PostgreSQL URL\");\n }\n if (parsed.protocol !== \"postgresql:\" && parsed.protocol !== \"postgres:\") {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL must use postgresql:// or postgres://\");\n }\n\n if (CLIENT_CERTIFICATE_PARAMETERS.some((parameter) => parsed.searchParams.has(parameter))) {\n throw new Error(\n \"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be combined with client certificate URL parameters\",\n );\n }\n if (parsed.searchParams.has(\"ssl\")) {\n throw new Error(\n \"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be combined with the ssl URL parameter\",\n );\n }\n parsed.searchParams.delete(\"sslmode\");\n parsed.searchParams.delete(\"sslrootcert\");\n return {\n connectionString: parsed.toString(),\n ssl: {\n ca: decodeCaPem(caBase64),\n rejectUnauthorized: true,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;;;ACyBR,IAAM,0BAAN,MAAyD;AAAA,EAC9D,YAA6B,IAAiB;AAAjB;AAAA,EAAkB;AAAA,EAEvC,aAAa,OAAe,SAAyB;AAC3D,WAAO,KAAK,GAAG,gBAAgB,QAAQ;AAAA,EACzC;AAAA,EAEA,MAAM,kBACJ,cACA,aACA,WACA,QACe;AACf,QAAI,QAAQ,QAAS,OAAM,OAAO;AAClC,UAAM,KAAK,GAAG;AAAA,MACZ,uBAAuB,KAAK,aAAa,uBAAuB,iCAAiC,CAAC;AAAA,MAClG,CAAC,cAAc,aAAa,SAAS;AAAA,IACvC;AACA,QAAI,QAAQ,QAAS,OAAM,OAAO;AAAA,EACpC;AAAA,EAEA,MAAM,QACJ,cACA,aACA,WACA,QAC4B;AAC5B,QAAI,QAAQ,QAAS,OAAM,OAAO;AAClC,UAAM,SAAS,MAAM,KAAK,GAAG;AAAA,MAO3B;AAAA,2BACqB,KAAK,aAAa,sBAAsB,gCAAgC,CAAC;AAAA,MAC9F,CAAC,cAAc,aAAa,SAAS;AAAA,IACvC;AACA,QAAI,QAAQ,QAAS,OAAM,OAAO;AAClC,UAAM,MAAM,OAAO,KAAK,CAAC;AACzB,QAAI,CAAC,IAAK,OAAM,IAAI,MAAM,8BAA8B;AACxD,WAAO;AAAA,MACL,SAAS,IAAI;A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A,IACA;AAAA,IACA,mBAAmB;AAAA,IACnB,OAAO;AAAA,IACP,mBAAmB;AAAA,EACrB,CAAC;AAED,UAAQ,OAAO,MAAM,MAAM,MAAM;AAC/B,YAAQ,OAAO,MAAM,qCAAqC,IAAI,IAAI,IAAI;AAAA,CAAI;AAAA,EAC5E,CAAC;AAED,MAAI,WAAW;AACf,iBAAe,WAA0B;AACvC,QAAI,SAAU;AACd,eAAW;AACX,UAAM,IAAI,QAAc,CAAC,SAAS,WAAW;AAC3C,cAAQ,MAAM,CAAC,UAAU,QAAQ,OAAO,KAAK,IAAI,QAAQ,CAAC;AAAA,IAC5D,CAAC;AACD,UAAM,QAAQ,IAAI,CAAC,KAAK,IAAI,GAAG,cAAc,IAAI,CAAC,CAAC;AAAA,EACrD;AAEA,UAAQ,KAAK,UAAU,MAAM,KAAK,SAAS,CAAC;AAC5C,UAAQ,KAAK,WAAW,MAAM,KAAK,SAAS,CAAC;AAC/C;AAEA,KAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,UAAQ,OAAO,MAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAClF,UAAQ,WAAW;AACrB,CAAC;","names":["row","databaseUrl"]}
1
+ {"version":3,"sources":["../src/gateway-main.ts","../src/gateway-security.ts","../src/postgres-request-authority.ts","../src/postgres-runtime-connection.ts"],"sourcesContent":["import { fileURLToPath } from \"node:url\";\nimport pg from \"pg\";\nimport { PostgresCredentialResolver } from \"./gateway-auth.js\";\nimport { PostgresGatewaySecurity } from \"./gateway-security.js\";\nimport { createGateway } from \"./gateway.js\";\nimport {\n loadMigrationPlan,\n migrationsReady,\n runMigrations,\n runtimeSchemaReady,\n} from \"./migrations.js\";\nimport { PostgresBridgeStore } from \"./postgres-bridge-store.js\";\nimport { PostgresRequestAuthority } from \"./postgres-request-authority.js\";\nimport { runtimePostgresConnectionConfig } from \"./postgres-runtime-connection.js\";\nimport { buildRevision, packageVersion } from \"./package-metadata.js\";\n\nfunction integer(value: string | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${name} must be a positive integer`);\n return parsed;\n}\n\nasync function main(): Promise<void> {\n const migrationsDirectory = fileURLToPath(new URL(\"../sql/migrations\", import.meta.url));\n if (process.argv.includes(\"--migrate-only\")) {\n const databaseUrl = process.env.AGENT_BRIDGE_DATABASE_URL;\n if (!databaseUrl) throw new Error(\"AGENT_BRIDGE_DATABASE_URL is required for migrations\");\n const migrationPool = new pg.Pool({\n connectionString: databaseUrl,\n max: 1,\n application_name: \"agent-bridge-migrator\",\n });\n try {\n await runMigrations(migrationPool, migrationsDirectory);\n } finally {\n await migrationPool.end();\n }\n return;\n }\n if (process.env.AGENT_BRIDGE_MIGRATE === \"1\") {\n throw new Error(\"AGENT_BRIDGE_MIGRATE is not supported; run agent-bridge migrate separately\");\n }\n const databaseUrl = process.env.AGENT_BRIDGE_RUNTIME_DATABASE_URL;\n if (!databaseUrl) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL is required for the gateway\");\n }\n const implementation = {\n version: packageVersion(),\n revision: buildRevision(process.env.AGENT_BRIDGE_BUILD_REVISION),\n };\n\n const deadline = integer(process.env.AGENT_BRIDGE_REQUEST_DEADLINE_MS, 10_000, \"request deadline\");\n const databaseTimeout = integer(\n process.env.AGENT_BRIDGE_DATABASE_TIMEOUT_MS,\n Math.max(1, Math.floor(deadline / 3)),\n \"database timeout\",\n );\n const poolSize = integer(process.env.AGENT_BRIDGE_DATABASE_POOL_SIZE, 10, \"database pool size\");\n const bodyLimitBytes = integer(\n process.env.AGENT_BRIDGE_BODY_LIMIT_BYTES,\n 128 * 1024,\n \"body limit\",\n );\n const host = process.env.AGENT_BRIDGE_HOST ?? \"127.0.0.1\";\n const port = integer(process.env.AGENT_BRIDGE_PORT, 8787, \"gateway port\");\n const allowedOrigins = process.env.AGENT_BRIDGE_ALLOWED_ORIGINS\n ?.split(\",\")\n .map((origin) => origin.trim())\n .filter(Boolean);\n const migrationPlan = await loadMigrationPlan(migrationsDirectory);\n const runtimeConnection = runtimePostgresConnectionConfig(\n databaseUrl,\n process.env.AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64,\n );\n const pool = new pg.Pool({\n ...runtimeConnection,\n max: poolSize,\n connectionTimeoutMillis: databaseTimeout,\n query_timeout: databaseTimeout,\n statement_timeout: databaseTimeout,\n application_name: \"agent-bridge-gateway\",\n });\n const readinessPool = new pg.Pool({\n ...runtimeConnection,\n max: 1,\n connectionTimeoutMillis: databaseTimeout,\n query_timeout: databaseTimeout,\n statement_timeout: databaseTimeout,\n application_name: \"agent-bridge-gateway-readiness\",\n });\n\n const store = new PostgresBridgeStore(pool);\n let readinessCheckedAt = 0;\n let readinessValue = false;\n let readinessInFlight: Promise<boolean> | undefined;\n const probeSchema = async () =>\n await migrationsReady(readinessPool, migrationPlan) && await runtimeSchemaReady(readinessPool);\n const schemaReady = (force = false): Promise<boolean> => {\n if (!force && Date.now() - readinessCheckedAt < 1_000) {\n return Promise.resolve(readinessValue);\n }\n if (readinessInFlight) return readinessInFlight;\n let current: Promise<boolean>;\n current = probeSchema()\n .then((ready) => {\n readinessValue = ready;\n readinessCheckedAt = Date.now();\n return ready;\n })\n .finally(() => {\n if (readinessInFlight === current) readinessInFlight = undefined;\n });\n readinessInFlight = current;\n return current;\n };\n try {\n if (!await schemaReady(true)) {\n throw new Error(\"runtime database is not ready for enforced row isolation\");\n }\n } catch (error) {\n await Promise.allSettled([pool.end(), readinessPool.end()]);\n throw error;\n }\n const gateway = createGateway({\n store,\n credentials: new PostgresCredentialResolver(pool),\n security: new PostgresGatewaySecurity(pool),\n requestAuthority: new PostgresRequestAuthority(pool),\n allowedOrigins,\n bodyLimitBytes,\n requestDeadlineMs: deadline,\n implementation,\n ready: schemaReady,\n rowIsolationReady: schemaReady,\n });\n\n gateway.listen(port, host, () => {\n process.stderr.write(`Agent Bridge gateway listening on ${host}:${port}\\n`);\n });\n\n let stopping = false;\n async function shutdown(): Promise<void> {\n if (stopping) return;\n stopping = true;\n await new Promise<void>((resolve, reject) => {\n gateway.close((error) => error ? reject(error) : resolve());\n });\n await Promise.all([pool.end(), readinessPool.end()]);\n }\n\n process.once(\"SIGINT\", () => void shutdown());\n process.once(\"SIGTERM\", () => void shutdown());\n}\n\nvoid main().catch((error) => {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`);\n process.exitCode = 1;\n});\n","import type { PgQueryable } from \"./postgres-bridge-store.js\";\nimport type { OperationId } from \"./contracts/registry.js\";\n\nexport interface RateLimitDecision {\n allowed: boolean;\n policyId: string | null;\n limit: number;\n remaining: number;\n retryAfterSeconds: number;\n}\n\nexport interface GatewaySecurity {\n recordScopeDenial(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void>;\n consume(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<RateLimitDecision>;\n}\n\nexport class PostgresGatewaySecurity implements GatewaySecurity {\n constructor(private readonly db: PgQueryable) {}\n\n private functionName(bound: string, unbound: string): string {\n return this.db.inTransaction ? bound : unbound;\n }\n\n async recordScopeDenial(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) throw signal.reason;\n await this.db.query(\n `SELECT agent_bridge.${this.functionName(\"record_scope_denial\", \"record_scope_denial_unbound_011\")}($1::uuid, $2::text, $3::uuid)`,\n [credentialId, operationId, requestId],\n );\n if (signal?.aborted) throw signal.reason;\n }\n\n async consume(\n credentialId: string,\n operationId: OperationId,\n requestId: string,\n signal?: AbortSignal,\n ): Promise<RateLimitDecision> {\n if (signal?.aborted) throw signal.reason;\n const result = await this.db.query<{\n allowed: boolean;\n limit_value: string | number;\n remaining_value: string | number;\n retry_after_seconds: string | number;\n denied_policy_id: string | null;\n }>(\n `SELECT allowed, limit_value, remaining_value, retry_after_seconds, denied_policy_id\n FROM agent_bridge.${this.functionName(\"consume_rate_limit\", \"consume_rate_limit_unbound_011\")}($1::uuid, $2::text, $3::uuid)`,\n [credentialId, operationId, requestId],\n );\n if (signal?.aborted) throw signal.reason;\n const row = result.rows[0];\n if (!row) throw new Error(\"rate limit policy is missing\");\n return {\n allowed: row.allowed,\n policyId: row.denied_policy_id,\n limit: Math.max(0, Number(row.limit_value)),\n remaining: Math.max(0, Number(row.remaining_value)),\n retryAfterSeconds: Math.max(0, Number(row.retry_after_seconds)),\n };\n }\n}\n","import type pg from \"pg\";\nimport type { BridgePrincipal } from \"./bridge-domain.js\";\nimport type { AuthorizationScope } from \"./contracts/registry.js\";\nimport { PostgresBridgeStore, type PgQueryable } from \"./postgres-bridge-store.js\";\nimport { PostgresGatewaySecurity } from \"./gateway-security.js\";\n\nexport interface RequestAuthorityContext {\n gatewayAuthorityId: string;\n credential: { id: string; principal: BridgePrincipal; scopes: readonly AuthorizationScope[] };\n store: PostgresBridgeStore;\n security: PostgresGatewaySecurity;\n /** Establishes the savepoint separating durable security accounting from domain work. */\n beginDomainWork(): Promise<void>;\n endpointMigrationChallenges?: {\n issue(input: { challenge: string; expectedGatewayAuthorityId: string; verifierCredentialId: string }): Promise<{ gatewayAuthorityId: string; issuerCredentialId: string; verifierCredentialId: string; expiresAt: string }>;\n consume(input: { challenge: string; expectedGatewayAuthorityId: string; issuerCredentialId: string }): Promise<{ gatewayAuthorityId: string; issuerCredentialId: string; verifierCredentialId: string; expiresAt: string | null; consumed: boolean }>;\n };\n}\n\nexport interface RequestAuthority {\n run<T>(credentialId: string, credentialHash: string, requestId: string, signal: AbortSignal, work: (context: RequestAuthorityContext) => Promise<T>): Promise<T>;\n}\n\ntype AuthorityRow = {\n gateway_authority_id: string;\n credential_id: string;\n workspace_id: string;\n principal: string;\n scopes: AuthorizationScope[];\n};\n\nfunction timestamp(value: unknown): string {\n if (value instanceof Date) return value.toISOString();\n return String(value);\n}\n\nfunction endpointMigrationFailure(error: unknown): never {\n const sqlstate = typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code ?? \"\")\n : \"\";\n if (sqlstate === \"28000\") {\n throw Object.assign(new Error(\"endpoint migration binding was rejected\"), {\n status: 409,\n code: \"endpoint_migration_binding_rejected\",\n });\n }\n if (sqlstate === \"23505\") {\n throw Object.assign(new Error(\"endpoint migration challenge conflicts with existing state\"), {\n status: 409,\n code: \"endpoint_migration_challenge_conflict\",\n });\n }\n throw error;\n}\n\nexport class MutationOutcomeUnknownError extends Error {\n readonly status = 503;\n readonly code = \"mutation_outcome_unknown\";\n constructor() { super(\"The database commit outcome is unknown\"); }\n}\n\nexport class PostgresRequestAuthority implements RequestAuthority {\n constructor(private readonly pool: Pick<pg.Pool, \"connect\">) {}\n\n async run<T>(credentialId: string, credentialHash: string, requestId: string, signal: AbortSignal, work: (context: RequestAuthorityContext) => Promise<T>): Promise<T> {\n if (signal.aborted) throw signal.reason;\n const client = await this.pool.connect();\n const db: PgQueryable = { inTransaction: true, query: (sql, values) => client.query(sql, values) };\n let transactionOpen = false;\n let domainSavepoint = false;\n let commitDispatched = false;\n let commitCompleted = false;\n let discard: Error | undefined;\n try {\n if (signal.aborted) throw signal.reason;\n await client.query(\"BEGIN\");\n transactionOpen = true;\n const opened = await client.query<AuthorityRow>(\n `SELECT gateway_authority_id,credential_id,workspace_id,principal,scopes\n FROM agent_bridge.open_request_authority_bound($1::uuid,$2::text,$3::uuid)`,\n [credentialId, credentialHash, requestId],\n );\n const row = opened.rows[0];\n if (!row) {\n await client.query(\"ROLLBACK\");\n transactionOpen = false;\n throw Object.assign(new Error(\"Credential is not active\"), { status: 401, code: \"unauthorized\" });\n }\n if (signal.aborted) throw signal.reason;\n const context: RequestAuthorityContext = {\n gatewayAuthorityId: row.gateway_authority_id,\n credential: { id: row.credential_id, principal: { workspace: row.workspace_id, agent: row.principal }, scopes: row.scopes },\n store: new PostgresBridgeStore(db),\n security: new PostgresGatewaySecurity(db),\n beginDomainWork: async () => {\n if (domainSavepoint) return;\n if (signal.aborted) throw signal.reason;\n await client.query(\"SAVEPOINT agent_bridge_domain_work\");\n if (signal.aborted) throw signal.reason;\n domainSavepoint = true;\n },\n endpointMigrationChallenges: {\n issue: async (input) => {\n let result;\n try {\n result = await client.query<{\n gateway_authority_id: string;\n issuer_credential_id: string;\n verifier_credential_id: string;\n expires_at: string | Date;\n }>(\n `SELECT gateway_authority_id,issuer_credential_id,verifier_credential_id,expires_at\n FROM agent_bridge.issue_endpoint_migration_challenge($1::uuid,$2::uuid,$3::text)`,\n [input.expectedGatewayAuthorityId, input.verifierCredentialId, input.challenge],\n );\n } catch (error) {\n endpointMigrationFailure(error);\n }\n const row = result.rows[0];\n if (!row) throw new Error(\"endpoint migration challenge could not be issued\");\n return {\n gatewayAuthorityId: row.gateway_authority_id,\n issuerCredentialId: row.issuer_credential_id,\n verifierCredentialId: row.verifier_credential_id,\n expiresAt: timestamp(row.expires_at),\n };\n },\n consume: async (input) => {\n let result;\n try {\n result = await client.query<{\n gateway_authority_id: string;\n issuer_credential_id: string;\n verifier_credential_id: string;\n expires_at: string | Date | null;\n consumed: boolean;\n }>(\n `SELECT gateway_authority_id,issuer_credential_id,verifier_credential_id,expires_at,consumed\n FROM agent_bridge.consume_endpoint_migration_challenge($1::uuid,$2::uuid,$3::text)`,\n [input.expectedGatewayAuthorityId, input.issuerCredentialId, input.challenge],\n );\n } catch (error) {\n endpointMigrationFailure(error);\n }\n const row = result.rows[0];\n if (!row) throw new Error(\"endpoint migration challenge could not be consumed\");\n return {\n gatewayAuthorityId: row.gateway_authority_id,\n issuerCredentialId: row.issuer_credential_id,\n verifierCredentialId: row.verifier_credential_id,\n expiresAt: row.expires_at === null ? null : timestamp(row.expires_at),\n consumed: row.consumed,\n };\n },\n },\n };\n try {\n const result = await work(context);\n if (signal.aborted) throw signal.reason;\n await client.query(\"SELECT agent_bridge.close_request_authority()\");\n if (signal.aborted) throw signal.reason;\n commitDispatched = true;\n await client.query(\"COMMIT\");\n commitCompleted = true;\n transactionOpen = false;\n return result;\n } catch (error) {\n if (commitDispatched) throw new MutationOutcomeUnknownError();\n if (signal.aborted) throw error;\n try {\n if (domainSavepoint) {\n await client.query(\"ROLLBACK TO SAVEPOINT agent_bridge_domain_work\");\n }\n await client.query(\"SELECT agent_bridge.close_request_authority()\");\n } catch {\n try {\n await client.query(\"ROLLBACK\");\n } catch (rollbackError) {\n discard = rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError));\n }\n transactionOpen = false;\n throw error;\n }\n if (signal.aborted) throw signal.reason;\n commitDispatched = true;\n await client.query(\"COMMIT\");\n commitCompleted = true;\n transactionOpen = false;\n throw error;\n }\n } catch (error) {\n if (commitDispatched && !commitCompleted) {\n discard = error instanceof Error ? error : new Error(String(error));\n throw error instanceof MutationOutcomeUnknownError ? error : new MutationOutcomeUnknownError();\n }\n if (transactionOpen) {\n try { await client.query(\"ROLLBACK\"); transactionOpen = false; }\n catch (rollbackError) { discard = rollbackError instanceof Error ? rollbackError : new Error(String(rollbackError)); }\n }\n throw error;\n } finally {\n client.release(discard);\n }\n }\n\n}\n","import type { PoolConfig } from \"pg\";\n\nconst MAX_CA_PEM_BYTES = 256 * 1024;\nconst BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;\nconst CERTIFICATE_PATTERN = /-----BEGIN CERTIFICATE-----[\\s\\S]+-----END CERTIFICATE-----/u;\nconst CLIENT_CERTIFICATE_PARAMETERS = [\n \"sslcert\",\n \"sslkey\",\n \"sslpassword\",\n] as const;\n\nfunction decodeCaPem(encoded: string): string {\n const value = encoded.trim();\n if (!value) throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be empty\");\n if (!BASE64_PATTERN.test(value)) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must be canonical base64\");\n }\n const bytes = Buffer.from(value, \"base64\");\n if (bytes.toString(\"base64\") !== value) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must be canonical base64\");\n }\n if (bytes.byteLength > MAX_CA_PEM_BYTES) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 exceeds 256 KiB after decoding\");\n }\n const pem = bytes.toString(\"utf8\").trim();\n if (pem.includes(\"\\0\") || !CERTIFICATE_PATTERN.test(pem)) {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 must decode to a PEM certificate bundle\");\n }\n return pem;\n}\n\nexport function runtimePostgresConnectionConfig(\n connectionString: string,\n caBase64: string | undefined,\n): Pick<PoolConfig, \"connectionString\" | \"ssl\"> {\n if (caBase64 === undefined) return { connectionString };\n\n let parsed: URL;\n try {\n parsed = new URL(connectionString);\n } catch {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL must be a valid PostgreSQL URL\");\n }\n if (parsed.protocol !== \"postgresql:\" && parsed.protocol !== \"postgres:\") {\n throw new Error(\"AGENT_BRIDGE_RUNTIME_DATABASE_URL must use postgresql:// or postgres://\");\n }\n\n if (CLIENT_CERTIFICATE_PARAMETERS.some((parameter) => parsed.searchParams.has(parameter))) {\n throw new Error(\n \"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be combined with client certificate URL parameters\",\n );\n }\n if (parsed.searchParams.has(\"ssl\")) {\n throw new Error(\n \"AGENT_BRIDGE_RUNTIME_DATABASE_CA_BASE64 cannot be combined with the ssl URL parameter\",\n );\n }\n parsed.searchParams.delete(\"sslmode\");\n parsed.searchParams.delete(\"sslrootcert\");\n return {\n connectionString: parsed.toString(),\n ssl: {\n ca: decodeCaPem(caBase64),\n rejectUnauthorized: true,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;;;ACyBR,IAAM,0BAAN,MAAyD;AAAA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,OAAO,KAAK,IAAI,QAAQ,CAAC;AAAA,IAC5D,CAAC;AACD,UAAM,QAAQ,IAAI,CAAC,KAAK,IAAI,GAAG,cAAc,IAAI,CAAC,CAAC;AAAA,EACrD;AAEA,UAAQ,KAAK,UAAU,MAAM,KAAK,SAAS,CAAC;AAC5C,UAAQ,KAAK,WAAW,MAAM,KAAK,SAAS,CAAC;AAC/C;AAEA,KAAK,KAAK,EAAE,MAAM,CAAC,UAAU;AAC3B,UAAQ,OAAO,MAAM,GAAG,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAClF,UAAQ,WAAW;AACrB,CAAC;","names":["row","databaseUrl"]}
package/dist/gateway.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import 'node:http';
2
2
  import './bridge-store-Bi_LCX8e.js';
3
- export { G as GatewayOptions, c as createGateway } from './gateway-BqmcKam8.js';
3
+ export { G as GatewayOptions, c as createGateway } from './gateway-DWZ3pX48.js';
4
4
  import './bridge-domain-CBX3IVqC.js';
5
5
  import './postgres-bridge-store-ChoOuFEY.js';
package/dist/gateway.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createGateway
4
- } from "./chunk-FGERNG4X.js";
4
+ } from "./chunk-LF37B6KL.js";
5
5
  import "./chunk-4V2PFJEF.js";
6
- import "./chunk-62C63PIE.js";
6
+ import "./chunk-63JKCBC6.js";
7
7
  import "./chunk-BZLMF5O5.js";
8
8
  export {
9
9
  createGateway
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  startServer
4
- } from "./chunk-AIALYLGQ.js";
4
+ } from "./chunk-JIRNR75D.js";
5
5
  import "./chunk-23UDQZMT.js";
6
6
  import "./chunk-UKFRCP6X.js";
7
- import "./chunk-IMJ47WO4.js";
8
- import "./chunk-WQ4I5XGF.js";
7
+ import "./chunk-IXNQG4SB.js";
8
+ import "./chunk-6ZOLE3E3.js";
9
9
  import "./chunk-ZUZ7TCIH.js";
10
10
  import "./chunk-IVG4XWWS.js";
11
11
  import "./chunk-GTK4KOED.js";
12
12
  import "./chunk-VOQIDTCJ.js";
13
13
  import "./chunk-4V2PFJEF.js";
14
- import "./chunk-62C63PIE.js";
14
+ import "./chunk-63JKCBC6.js";
15
15
  import "./chunk-BZLMF5O5.js";
16
16
 
17
17
  // src/index.ts
package/dist/server.js CHANGED
@@ -4,17 +4,17 @@ import {
4
4
  configFromEnv,
5
5
  createAgentBridgeServer,
6
6
  startServer
7
- } from "./chunk-AIALYLGQ.js";
7
+ } from "./chunk-JIRNR75D.js";
8
8
  import "./chunk-23UDQZMT.js";
9
9
  import "./chunk-UKFRCP6X.js";
10
- import "./chunk-IMJ47WO4.js";
11
- import "./chunk-WQ4I5XGF.js";
10
+ import "./chunk-IXNQG4SB.js";
11
+ import "./chunk-6ZOLE3E3.js";
12
12
  import "./chunk-ZUZ7TCIH.js";
13
13
  import "./chunk-IVG4XWWS.js";
14
14
  import "./chunk-GTK4KOED.js";
15
15
  import "./chunk-VOQIDTCJ.js";
16
16
  import "./chunk-4V2PFJEF.js";
17
- import "./chunk-62C63PIE.js";
17
+ import "./chunk-63JKCBC6.js";
18
18
  import "./chunk-BZLMF5O5.js";
19
19
  export {
20
20
  MCP_IMPLEMENTATION_VERSION,
@@ -4,9 +4,9 @@ Status: living architecture for the 0.6.x package line.
4
4
 
5
5
  ## Product boundary
6
6
 
7
- Agent Bridge lets agents exchange messages and hand off work across clients, processes,
8
- sessions, and machines. It supports two operating modes: local SQLite and the
9
- authenticated PostgreSQL gateway.
7
+ Agent Bridge lets AI agents message each other and hand off work across clients,
8
+ processes, sessions, and machines. It supports two operating modes: local SQLite and
9
+ the authenticated PostgreSQL gateway.
10
10
 
11
11
  History visibility is caller-relative. `inbox` is the default and preserves broadcast-plus-targeted visibility; `sent` is source equal to the caller; `all` is their union. Receipt state (`any`, `unread`, `read`) is valid only for inbox and is always evaluated for the authenticated caller. Opaque v2 cursors bind workspace, caller, mailbox, and normalized filters. Readers temporarily accept v1 sequence cursors but emit only v2. After an edge cache contract upgrade, the gateway resets the authoritative pull cursor and replays `all` visibility; the publication outbox is never treated as sent history.
12
12
 
@@ -17,6 +17,10 @@ These authorization guarantees apply to local v2 and the authenticated gateway.
17
17
 
18
18
  The protocol must support informational context and executable work without treating them as the same thing. A2A and application task semantics sit above Agent Bridge. MCP, CLI, HTTPS, and the Node library are access surfaces. Agent harnesses and host applications use those surfaces through host adapters or direct integration. Optional transports may sit below the core, but they cannot replace authoritative cursor replay or durable delivery state.
19
19
 
20
+ Authenticated gateway capabilities identify the running package version. Production
21
+ images also report the Git revision supplied at build time. Deployment checks compare
22
+ both values with the intended release before client rollout or production proof.
23
+
20
24
  [ADR-0001](decisions/0001-protocol-layers-and-acknowledgment-semantics.md) defines these layers and the distinct meanings of receipts, claims, leases, delivery settlement, and external task completion.
21
25
 
22
26
  [ADR-0002](decisions/0002-canonical-operation-contract-registry.md) defines the canonical cross-surface operation contract, deterministic artifacts, capability discovery, and protocol negotiation.
@@ -32,6 +32,11 @@ declared by the registry, while local mode uses process identity and reports sco
32
32
  enforcement as false. [ADR-0005](0005-retire-direct-supabase-runtime.md) removed the
33
33
  legacy runtime provider from this contract.
34
34
 
35
+ Authenticated gateway capability documents may also identify the running package
36
+ version and image Git revision. These implementation fields are independent of the
37
+ HTTP protocol version. Deployment gates compare them with the intended release so a
38
+ healthy but stale gateway cannot pass release proof.
39
+
35
40
  Package version, MCP implementation version, Agent Bridge protocol version, and migration version remain independent. The MCP server reports the explicit `MCP_IMPLEMENTATION_VERSION` constant instead of the npm package version.
36
41
 
37
42
  ## Consequences
@@ -229,11 +229,29 @@ repository does not perform them:
229
229
  match the recorded runtime contract. It never adopts a restored `NOLOGIN` shell.
230
230
  6. Construct the restricted runtime URL. Import it and the base64-encoded PostgreSQL CA
231
231
  as the two runtime secrets shown above, then run the app-aware read-only preflight.
232
- 7. Deploy the immutable image with `fly deploy --config deploy/fly.toml --app <app>`.
232
+ 7. Deploy the immutable image with its source revision:
233
+
234
+ ```bash
235
+ fly deploy --config deploy/fly.toml --app <app> \
236
+ --build-arg AGENT_BRIDGE_BUILD_REVISION="$(git rev-parse HEAD)"
237
+ ```
238
+
233
239
  Require `/readyz` before routing clients.
234
- 8. Run authenticated capability and status probes, then publish, pull, claim, and
240
+ 8. Check the running package and source revision with a principal-bound credential:
241
+
242
+ ```bash
243
+ AGENT_BRIDGE_URL="https://<app>.fly.dev" AGENT_BRIDGE_TOKEN="..." \
244
+ npm run verify:gateway:release -- \
245
+ --version "$(node -p "require('./package.json').version")" \
246
+ --revision "$(git rev-parse HEAD)"
247
+ ```
248
+
249
+ The check also requires protocol 2.1, request authority, and row isolation. It
250
+ fails if the deployed image omits its revision or differs from the intended
251
+ release.
252
+ 9. Run authenticated status, publication, pull, claim, and
235
253
  settle a disposable targeted delivery.
236
- 9. Move clients only after the gateway proof passes. Preserve every source edge store
254
+ 10. Move clients only after the gateway proof passes. Preserve every source edge store
237
255
  until its outbox is empty.
238
256
 
239
257
  App creation, database provisioning, secret writes, migration, bootstrap, deployment,
@@ -257,9 +275,12 @@ The manual `gateway production proof` GitHub Actions workflow runs this acceptan
257
275
  proof against an existing HTTPS gateway. GitHub restricts it to `main`, and every job
258
276
  uses the approval-protected `agent-bridge-production-proof` environment. Configure
259
277
  `PROOF_SENDER_TOKEN`, `PROOF_RECEIVER_TOKEN`, `PROOF_HOST_SALT`, and `FLY_API_TOKEN` as
260
- environment secrets. The sender and receiver credentials must bind the requested
261
- workspace to the dedicated `proof-sender` and `proof-receiver` principals. The
262
- sender credential needs `messages:write` and `messages:read`. The receiver needs
278
+ environment secrets. Use a release-specific proof workspace for every run. Owner
279
+ provisioning refuses a second agent with the same principal in one workspace, and a
280
+ revoked credential cannot serve as a rotation predecessor. The sender and receiver
281
+ credentials must bind the requested workspace to the dedicated `proof-sender` and
282
+ `proof-receiver` principals. The sender credential needs `messages:write` and
283
+ `messages:read`. The receiver needs
263
284
  `messages:read`, `deliveries:claim`, `deliveries:settle`, and `deliveries:read`.
264
285
 
265
286
  Run the workflow only when the Fly app has exactly one gateway machine. The cycle job
@@ -318,8 +339,9 @@ owner-control state, or security events.
318
339
  5. Stop schema-changing jobs other than the selected migration job.
319
340
  6. Run the new image's migration command once with schema-owner authority.
320
341
  7. Run the runtime bootstrap with separate runtime-login credentials.
321
- 8. Start the new gateway and require `/readyz`, an authenticated capability probe, and
322
- an authenticated status probe.
342
+ 8. Start the new gateway and require `/readyz`. Run
343
+ `npm run verify:gateway:release` against the expected package version and Git
344
+ revision, then run an authenticated status probe.
323
345
  9. Send, read, claim, and settle a disposable targeted delivery.
324
346
  10. Roll clients forward only after the gateway proof passes.
325
347
  11. Keep the previous authority available but inactive until the observation window
package/docs/ecosystem.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Agent Bridge in the agent ecosystem
2
2
 
3
- Agent Bridge lets agents exchange messages and hand off work across tools, sessions,
4
- and machines. It preserves each inbox through disconnections and restarts. It stores
3
+ Agent Bridge lets AI agents message each other and hand off work across tools,
4
+ sessions, and machines. Messages wait through disconnections and restarts. It stores
5
5
  immutable messages, read receipts, delivery claims, leases, retries, and replay state.
6
6
  It does not own the full agent stack.
7
7
 
package/llms.txt CHANGED
@@ -3,7 +3,7 @@
3
3
  Repository: https://github.com/creatornader/agent-bridge
4
4
  Package: @creatornader/agent-bridge
5
5
 
6
- Agent Bridge lets AI agents send messages and hand off work across tools, sessions, and machines. Messages survive restarts and offline periods, and each agent resumes from its own inbox.
6
+ Agent Bridge lets AI agents message each other and hand off work across tools, sessions, and machines. Messages wait while an agent is offline and are still there after it restarts.
7
7
  History uses mailbox `inbox` (default), `sent`, or `all`. Receipt state is `any` (default), `unread`, or `read`; it is caller-relative and inbox-only. CLI: `inbox`, `sent`, and `history --mailbox/--receipt-state`. Deprecated unacked-principal arguments must equal the configured identity.
8
8
 
9
9
  ## Install
@@ -122,7 +122,7 @@ one logical authority across restore but does not fence a live clone.
122
122
 
123
123
  ## MCP tools
124
124
 
125
- - `capabilities`: return operations, required scopes, provider-specific enforcement, and supported protocol versions. Gateway access needs an active credential but no named scope for this operation.
125
+ - `capabilities`: return operations, required scopes, provider-specific enforcement, supported protocol versions, and optional implementation version and revision metadata. Gateway access needs an active credential but no named scope for this operation.
126
126
  - Production gateway capabilities report `requestAuthority: true` and `rowIsolation: true` only after the migration and live catalog, role, policy, privilege, and function checks pass. PostgreSQL forces RLS on messages, receipts, deliveries, delivery events, and presence. Lease transitions and target-to-delivery membership remain service-enforced.
127
127
  - Authenticated gateway `/v2/status` returns optional `gatewayAuthorityId` and
128
128
  `credentialId` fields when PostgreSQL request authority is active. They are additive
@@ -2,6 +2,7 @@
2
2
  "openapi": "3.1.2",
3
3
  "info": {
4
4
  "title": "Agent Bridge Gateway",
5
+ "description": "Let AI agents message each other and hand off work across tools, sessions, and machines.",
5
6
  "version": "2.1",
6
7
  "license": {
7
8
  "name": "Apache-2.0",
@@ -347,6 +348,13 @@
347
348
  "gateway"
348
349
  ]
349
350
  },
351
+ "implementationVersion": {
352
+ "type": "string"
353
+ },
354
+ "implementationRevision": {
355
+ "type": "string",
356
+ "pattern": "^[0-9a-f]{7,40}$"
357
+ },
350
358
  "grantedScopes": {
351
359
  "type": "array",
352
360
  "items": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@creatornader/agent-bridge",
3
- "version": "0.6.0",
4
- "description": "Messaging and work delivery for AI agents across tools, sessions, and machines.",
3
+ "version": "0.6.2",
4
+ "description": "Let AI agents message each other and hand off work across tools, sessions, and machines.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "author": "Nader Helmy",
@@ -29,6 +29,7 @@
29
29
  "schemas",
30
30
  "openapi",
31
31
  "docs",
32
+ "scripts/gateway-release-check.mjs",
32
33
  "sql/migrations",
33
34
  "sql/setup.sql",
34
35
  "llms.txt",
@@ -93,6 +94,7 @@
93
94
  "preflight:postgres:production": "npm run build --silent && node dist/postgres-production-preflight.js",
94
95
  "preflight:fly": "node scripts/fly-production-preflight.mjs",
95
96
  "proof:gateway:production": "node scripts/gateway-production-proof.mjs",
97
+ "verify:gateway:release": "node scripts/gateway-release-check.mjs",
96
98
  "test:gateway:production-proof": "vitest run test/gateway-production-proof.test.ts",
97
99
  "test:windows:contract": "vitest run test/private-path.test.ts test/windows-native-smoke.test.ts --maxWorkers=1 --testTimeout=180000 -t \"applies and verifies native Windows file and directory ACLs|recovers an (enrollment|client-operation) subsystem lock\" && vitest run test/client-maintenance.test.ts --maxWorkers=1 --testTimeout=180000",
98
100
  "typecheck": "tsc --noEmit",
@@ -86,6 +86,13 @@
86
86
  "gateway"
87
87
  ]
88
88
  },
89
+ "implementationVersion": {
90
+ "type": "string"
91
+ },
92
+ "implementationRevision": {
93
+ "type": "string",
94
+ "pattern": "^[0-9a-f]{7,40}$"
95
+ },
89
96
  "grantedScopes": {
90
97
  "type": "array",
91
98
  "items": {
@@ -74,6 +74,13 @@
74
74
  "gateway"
75
75
  ]
76
76
  },
77
+ "implementationVersion": {
78
+ "type": "string"
79
+ },
80
+ "implementationRevision": {
81
+ "type": "string",
82
+ "pattern": "^[0-9a-f]{7,40}$"
83
+ },
77
84
  "grantedScopes": {
78
85
  "type": "array",
79
86
  "items": {
@@ -335,6 +335,13 @@
335
335
  "gateway"
336
336
  ]
337
337
  },
338
+ "implementationVersion": {
339
+ "type": "string"
340
+ },
341
+ "implementationRevision": {
342
+ "type": "string",
343
+ "pattern": "^[0-9a-f]{7,40}$"
344
+ },
338
345
  "grantedScopes": {
339
346
  "type": "array",
340
347
  "items": {
@@ -433,6 +440,13 @@
433
440
  "gateway"
434
441
  ]
435
442
  },
443
+ "implementationVersion": {
444
+ "type": "string"
445
+ },
446
+ "implementationRevision": {
447
+ "type": "string",
448
+ "pattern": "^[0-9a-f]{7,40}$"
449
+ },
436
450
  "grantedScopes": {
437
451
  "type": "array",
438
452
  "items": {